code
stringlengths
38
801k
repo_path
stringlengths
6
263
const FrameBuffer = @import("framebuffer.zig").FrameBuffer; const Position = @import("framebuffer.zig").Position; const Color = @import("framebuffer.zig").Color; const assert = @import("std").debug.assert; pub const Direction = enum { Horizontal, Vertical }; const stdout = @import("std").io.getStdOut().writer(); //TODO: Move to framebuffer and rename to BufferWindow pub const RenderTarget = struct { frameBuffer: *FrameBuffer, topLeft: Position, width: u32, height: u32, pub inline fn setPixel(self: *RenderTarget, x: u32, y: u32, color: Color) void { //_ = stdout.print("Set Pixel w/o Offset {}/{} = {}\n", .{ x, y, color }) catch unreachable; self.frameBuffer.setPixel(topLeft.x + x, topLeft.y + y, color); } pub inline fn setPixelAtOffset(self: *RenderTarget, offset: u32, color: Color) void { var y = offset / self.width; var x = offset % self.width; //_ = stdout.print("Set Pixel with Offset at Render Target {} = {}\n", .{ offset, color }) catch unreachable; self.frameBuffer.setPixel(self.topLeft.x + x, self.topLeft.y + y, color); } }; pub const Renderer = struct { framebuffer: FrameBuffer, pub fn drawRectangle(self: *Renderer, topLeft: Position, width: u32, height: u32, color: Color) void { self.drawLine(topLeft, width, Direction.Horizontal, color); self.drawLine(topLeft, height, Direction.Vertical, color); self.drawLine(topLeft.offsetY(height), width, Direction.Horizontal, color); self.drawLine(topLeft.offsetX(width), height, Direction.Vertical, color); } pub inline fn drawLine(self: *Renderer, start: Position, length: u32, direction: Direction, color: Color) void { switch (direction) { .Horizontal => { var x = start.x; while (x < start.x + length) : (x += 1) { self.framebuffer.setPixel(x, start.y, color); } }, .Vertical => { var y = start.y; while (y < start.y + length) : (y += 1) { self.framebuffer.setPixel(start.x, y, color); } }, } } pub fn fillRectangle(self: *Renderer, topLeft: Position, width: u32, height: u32, color: Color) void { var y: u32 = 0; while (y < height) : (y += 1) { self.drawLine(topLeft.offsetY(y), width, Direction.Horizontal, color); } } pub fn getTarget(self: *Renderer, topLeft: Position, width: u32, height: u32) RenderTarget { return RenderTarget{ .frameBuffer = &self.framebuffer, .topLeft = topLeft, .width = width, .height = height }; } };
kernel/renderer.zig
const std = @import("std"); const DW = std.dwarf; const testing = std.testing; /// The condition field specifies the flags neccessary for an /// Instruction to be executed pub const Condition = enum(u4) { /// equal eq, /// not equal ne, /// unsigned higher or same cs, /// unsigned lower cc, /// negative mi, /// positive or zero pl, /// overflow vs, /// no overflow vc, /// unsigned higer hi, /// unsigned lower or same ls, /// greater or equal ge, /// less than lt, /// greater than gt, /// less than or equal le, /// always al, }; /// Represents a register in the ARM instruction set architecture pub const Register = enum(u5) { r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, /// Argument / result / scratch register 1 a1, /// Argument / result / scratch register 2 a2, /// Argument / scratch register 3 a3, /// Argument / scratch register 4 a4, /// Variable-register 1 v1, /// Variable-register 2 v2, /// Variable-register 3 v3, /// Variable-register 4 v4, /// Variable-register 5 v5, /// Platform register v6, /// Variable-register 7 v7, /// Frame pointer or Variable-register 8 fp, /// Intra-Procedure-call scratch register ip, /// Stack pointer sp, /// Link register lr, /// Program counter pc, /// Returns the unique 4-bit ID of this register which is used in /// the machine code pub fn id(self: Register) u4 { return @truncate(u4, @enumToInt(self)); } /// Returns the index into `callee_preserved_regs`. pub fn allocIndex(self: Register) ?u4 { inline for (callee_preserved_regs) |cpreg, i| { if (self.id() == cpreg.id()) return i; } return null; } pub fn dwarfLocOp(self: Register) u8 { return @as(u8, self.id()) + DW.OP_reg0; } }; test "Register.id" { testing.expectEqual(@as(u4, 15), Register.r15.id()); testing.expectEqual(@as(u4, 15), Register.pc.id()); } pub const callee_preserved_regs = [_]Register{ .r0, .r1, .r2, .r3, .r4, .r5, .r6, .r7, .r8, .r10 }; pub const c_abi_int_param_regs = [_]Register{ .r0, .r1, .r2, .r3 }; pub const c_abi_int_return_regs = [_]Register{ .r0, .r1 }; /// Represents an instruction in the ARM instruction set architecture pub const Instruction = union(enum) { DataProcessing: packed struct { // Note to self: The order of the fields top-to-bottom is // right-to-left in the actual 32-bit int representation op2: u12, rd: u4, rn: u4, s: u1, opcode: u4, i: u1, fixed: u2 = 0b00, cond: u4, }, SingleDataTransfer: packed struct { offset: u12, rd: u4, rn: u4, l: u1, w: u1, b: u1, u: u1, p: u1, i: u1, fixed: u2 = 0b01, cond: u4, }, Branch: packed struct { offset: u24, link: u1, fixed: u3 = 0b101, cond: u4, }, BranchExchange: packed struct { rn: u4, fixed_1: u1 = 0b1, link: u1, fixed_2: u22 = 0b0001_0010_1111_1111_1111_00, cond: u4, }, SupervisorCall: packed struct { comment: u24, fixed: u4 = 0b1111, cond: u4, }, Breakpoint: packed struct { imm4: u4, fixed_1: u4 = 0b0111, imm12: u12, fixed_2_and_cond: u12 = 0b1110_0001_0010, }, /// Represents the possible operations which can be performed by a /// DataProcessing instruction const Opcode = enum(u4) { // Rd := Op1 AND Op2 @"and", // Rd := Op1 EOR Op2 eor, // Rd := Op1 - Op2 sub, // Rd := Op2 - Op1 rsb, // Rd := Op1 + Op2 add, // Rd := Op1 + Op2 + C adc, // Rd := Op1 - Op2 + C - 1 sbc, // Rd := Op2 - Op1 + C - 1 rsc, // set condition codes on Op1 AND Op2 tst, // set condition codes on Op1 EOR Op2 teq, // set condition codes on Op1 - Op2 cmp, // set condition codes on Op1 + Op2 cmn, // Rd := Op1 OR Op2 orr, // Rd := Op2 mov, // Rd := Op1 AND NOT Op2 bic, // Rd := NOT Op2 mvn, }; /// Represents the second operand to a data processing instruction /// which can either be content from a register or an immediate /// value pub const Operand = union(enum) { Register: packed struct { rm: u4, shift: u8, }, Immediate: packed struct { imm: u8, rotate: u4, }, /// Represents multiple ways a register can be shifted. A /// register can be shifted by a specific immediate value or /// by the contents of another register pub const Shift = union(enum) { Immediate: packed struct { fixed: u1 = 0b0, typ: u2, amount: u5, }, Register: packed struct { fixed_1: u1 = 0b1, typ: u2, fixed_2: u1 = 0b0, rs: u4, }, const Type = enum(u2) { LogicalLeft, LogicalRight, ArithmeticRight, RotateRight, }; const none = Shift{ .Immediate = .{ .amount = 0, .typ = 0, }, }; pub fn toU8(self: Shift) u8 { return switch (self) { .Register => |v| @bitCast(u8, v), .Immediate => |v| @bitCast(u8, v), }; } pub fn reg(rs: Register, typ: Type) Shift { return Shift{ .Register = .{ .rs = rs.id(), .typ = @enumToInt(typ), }, }; } pub fn imm(amount: u5, typ: Type) Shift { return Shift{ .Immediate = .{ .amount = amount, .typ = @enumToInt(typ), }, }; } }; pub fn toU12(self: Operand) u12 { return switch (self) { .Register => |v| @bitCast(u12, v), .Immediate => |v| @bitCast(u12, v), }; } pub fn reg(rm: Register, shift: Shift) Operand { return Operand{ .Register = .{ .rm = rm.id(), .shift = shift.toU8(), }, }; } pub fn imm(immediate: u8, rotate: u4) Operand { return Operand{ .Immediate = .{ .imm = immediate, .rotate = rotate, }, }; } }; /// Represents the offset operand of a load or store /// instruction. Data can be loaded from memory with either an /// immediate offset or an offset that is stored in some register. pub const Offset = union(enum) { Immediate: u12, Register: packed struct { rm: u4, shift: u8, }, pub const none = Offset{ .Immediate = 0, }; pub fn toU12(self: Offset) u12 { return switch (self) { .Register => |v| @bitCast(u12, v), .Immediate => |v| v, }; } pub fn reg(rm: Register, shift: u8) Offset { return Offset{ .Register = .{ .rm = rm.id(), .shift = shift, }, }; } pub fn imm(immediate: u8) Offset { return Offset{ .Immediate = immediate, }; } }; pub fn toU32(self: Instruction) u32 { return switch (self) { .DataProcessing => |v| @bitCast(u32, v), .SingleDataTransfer => |v| @bitCast(u32, v), .Branch => |v| @bitCast(u32, v), .BranchExchange => |v| @bitCast(u32, v), .SupervisorCall => |v| @bitCast(u32, v), .Breakpoint => |v| @intCast(u32, v.imm4) | (@intCast(u32, v.fixed_1) << 4) | (@intCast(u32, v.imm12) << 8) | (@intCast(u32, v.fixed_2_and_cond) << 20), }; } // Helper functions for the "real" functions below fn dataProcessing( cond: Condition, opcode: Opcode, s: u1, rd: Register, rn: Register, op2: Operand, ) Instruction { return Instruction{ .DataProcessing = .{ .cond = @enumToInt(cond), .i = if (op2 == .Immediate) 1 else 0, .opcode = @enumToInt(opcode), .s = s, .rn = rn.id(), .rd = rd.id(), .op2 = op2.toU12(), }, }; } fn singleDataTransfer( cond: Condition, rd: Register, rn: Register, offset: Offset, pre_post: u1, up_down: u1, byte_word: u1, writeback: u1, load_store: u1, ) Instruction { return Instruction{ .SingleDataTransfer = .{ .cond = @enumToInt(cond), .rn = rn.id(), .rd = rd.id(), .offset = offset.toU12(), .l = load_store, .w = writeback, .b = byte_word, .u = up_down, .p = pre_post, .i = if (offset == .Immediate) 0 else 1, }, }; } fn branch(cond: Condition, offset: i24, link: u1) Instruction { return Instruction{ .Branch = .{ .cond = @enumToInt(cond), .link = link, .offset = @bitCast(u24, offset), }, }; } fn branchExchange(cond: Condition, rn: Register, link: u1) Instruction { return Instruction{ .BranchExchange = .{ .cond = @enumToInt(cond), .link = link, .rn = rn.id(), }, }; } fn supervisorCall(cond: Condition, comment: u24) Instruction { return Instruction{ .SupervisorCall = .{ .cond = @enumToInt(cond), .comment = comment, }, }; } fn breakpoint(imm: u16) Instruction { return Instruction{ .Breakpoint = .{ .imm12 = @truncate(u12, imm >> 4), .imm4 = @truncate(u4, imm), }, }; } // Public functions replicating assembler syntax as closely as // possible // Data processing pub fn @"and"(cond: Condition, s: u1, rd: Register, rn: Register, op2: Operand) Instruction { return dataProcessing(cond, .@"and", s, rd, rn, op2); } pub fn eor(cond: Condition, s: u1, rd: Register, rn: Register, op2: Operand) Instruction { return dataProcessing(cond, .eor, s, rd, rn, op2); } pub fn sub(cond: Condition, s: u1, rd: Register, rn: Register, op2: Operand) Instruction { return dataProcessing(cond, .sub, s, rd, rn, op2); } pub fn rsb(cond: Condition, s: u1, rd: Register, rn: Register, op2: Operand) Instruction { return dataProcessing(cond, .rsb, s, rd, rn, op2); } pub fn add(cond: Condition, s: u1, rd: Register, rn: Register, op2: Operand) Instruction { return dataProcessing(cond, .add, s, rd, rn, op2); } pub fn adc(cond: Condition, s: u1, rd: Register, rn: Register, op2: Operand) Instruction { return dataProcessing(cond, .adc, s, rd, rn, op2); } pub fn sbc(cond: Condition, s: u1, rd: Register, rn: Register, op2: Operand) Instruction { return dataProcessing(cond, .sbc, s, rd, rn, op2); } pub fn rsc(cond: Condition, s: u1, rd: Register, rn: Register, op2: Operand) Instruction { return dataProcessing(cond, .rsc, s, rd, rn, op2); } pub fn tst(cond: Condition, rn: Register, op2: Operand) Instruction { return dataProcessing(cond, .tst, 1, .r0, rn, op2); } pub fn teq(cond: Condition, rn: Register, op2: Operand) Instruction { return dataProcessing(cond, .teq, 1, .r0, rn, op2); } pub fn cmp(cond: Condition, rn: Register, op2: Operand) Instruction { return dataProcessing(cond, .cmp, 1, .r0, rn, op2); } pub fn cmn(cond: Condition, rn: Register, op2: Operand) Instruction { return dataProcessing(cond, .cmn, 1, .r0, rn, op2); } pub fn orr(cond: Condition, s: u1, rd: Register, rn: Register, op2: Operand) Instruction { return dataProcessing(cond, .orr, s, rd, rn, op2); } pub fn mov(cond: Condition, s: u1, rd: Register, op2: Operand) Instruction { return dataProcessing(cond, .mov, s, rd, .r0, op2); } pub fn bic(cond: Condition, s: u1, rd: Register, op2: Operand) Instruction { return dataProcessing(cond, .bic, s, rd, rn, op2); } pub fn mvn(cond: Condition, s: u1, rd: Register, op2: Operand) Instruction { return dataProcessing(cond, .mvn, s, rd, .r0, op2); } // Single data transfer pub fn ldr(cond: Condition, rd: Register, rn: Register, offset: Offset) Instruction { return singleDataTransfer(cond, rd, rn, offset, 1, 1, 0, 0, 1); } pub fn str(cond: Condition, rd: Register, rn: Register, offset: Offset) Instruction { return singleDataTransfer(cond, rd, rn, offset, 1, 1, 0, 0, 0); } // Branch pub fn b(cond: Condition, offset: i24) Instruction { return branch(cond, offset, 0); } pub fn bl(cond: Condition, offset: i24) Instruction { return branch(cond, offset, 1); } // Branch and exchange pub fn bx(cond: Condition, rn: Register) Instruction { return branchExchange(cond, rn, 0); } pub fn blx(cond: Condition, rn: Register) Instruction { return branchExchange(cond, rn, 1); } // Supervisor Call pub const swi = svc; pub fn svc(cond: Condition, comment: u24) Instruction { return supervisorCall(cond, comment); } // Breakpoint pub fn bkpt(imm: u16) Instruction { return breakpoint(imm); } }; test "serialize instructions" { const Testcase = struct { inst: Instruction, expected: u32, }; const testcases = [_]Testcase{ .{ // add r0, r0, r0 .inst = Instruction.add(.al, 0, .r0, .r0, Instruction.Operand.reg(.r0, Instruction.Operand.Shift.none)), .expected = 0b1110_00_0_0100_0_0000_0000_00000000_0000, }, .{ // mov r4, r2 .inst = Instruction.mov(.al, 0, .r4, Instruction.Operand.reg(.r2, Instruction.Operand.Shift.none)), .expected = 0b1110_00_0_1101_0_0000_0100_00000000_0010, }, .{ // mov r0, #42 .inst = Instruction.mov(.al, 0, .r0, Instruction.Operand.imm(42, 0)), .expected = 0b1110_00_1_1101_0_0000_0000_0000_00101010, }, .{ // ldr r0, [r2, #42] .inst = Instruction.ldr(.al, .r0, .r2, Instruction.Offset.imm(42)), .expected = 0b1110_01_0_1_1_0_0_1_0010_0000_000000101010, }, .{ // str r0, [r3] .inst = Instruction.str(.al, .r0, .r3, Instruction.Offset.none), .expected = 0b1110_01_0_1_1_0_0_0_0011_0000_000000000000, }, .{ // b #12 .inst = Instruction.b(.al, 12), .expected = 0b1110_101_0_0000_0000_0000_0000_0000_1100, }, .{ // bl #-4 .inst = Instruction.bl(.al, -4), .expected = 0b1110_101_1_1111_1111_1111_1111_1111_1100, }, .{ // bx lr .inst = Instruction.bx(.al, .lr), .expected = 0b1110_0001_0010_1111_1111_1111_0001_1110, }, .{ // svc #0 .inst = Instruction.svc(.al, 0), .expected = 0b1110_1111_0000_0000_0000_0000_0000_0000, }, .{ // bkpt #42 .inst = Instruction.bkpt(42), .expected = 0b1110_0001_0010_000000000010_0111_1010, }, }; for (testcases) |case| { const actual = case.inst.toU32(); testing.expectEqual(case.expected, actual); } }
src-self-hosted/codegen/arm.zig
const std = @import("std"); const expect = std.testing.expect; const Allocator = std.mem.Allocator; const Error = Allocator.Error; //Experiment with different degrees. //Exercise: why can't `t = 1`? const t = 2; pub fn Node(comptime T: type) type { return struct { n: usize, leaf: bool, key: [2 * t]T, c: [2 * t]?*Node(T) }; } pub fn SearchTuple(comptime T: type) type { return struct { node: *Node(T), index: usize, }; } /// References: Introduction to algorithms / <NAME>...[et al.]. -3rd ed. /// To make things simpler diskWrite and diskRead are not implemented here but /// the code contains comments when these would be performed. pub fn Tree(comptime T: type) type { return struct { root: ?*Node(T) = null, pub fn create(self: *Tree(T), allocator: *Allocator) !void { var x = try allocator.create(Node(T)); //Here we would write to disk -> diskWrite(x) x.n = 0; x.leaf = true; for (x.c) |_, i| { x.c[i] = null; x.key[i] = 0; } self.root = x; } pub fn insert(self: *Tree(T), k: T, allocator: *Allocator) !void { var r = self.root; if (r == null) { return; } if (r.?.n == 2 * t - 1) { var s = try allocator.create(Node(T)); self.root = s; s.leaf = false; s.n = 0; for (s.c) |_, i| { s.c[i] = null; s.key[i] = 0; } s.c[0] = r; try Tree(T).splitChild(s, 1, allocator); try Tree(T).insertNonfull(s, k, allocator); } else { try Tree(T).insertNonfull(r.?, k, allocator); } } fn splitChild(x: *Node(T), i: usize, allocator: *Allocator) Error!void { var z = try allocator.create(Node(T)); for (z.c) |_, index| { z.c[index] = null; z.key[index] = 0; } var y = x.c[i - 1].?; z.leaf = y.leaf; z.n = t - 1; var j: usize = 1; while (j <= t - 1) : (j += 1) { z.key[j - 1] = y.key[j - 1 + t]; } if (!y.leaf) { j = 1; while (j <= t) : (j += 1) { z.c[j - 1] = y.c[j - 1 + t]; } } y.n = t - 1; j = x.n + 1; while (j >= i + 1) : (j -= 1) { x.c[j] = x.c[j - 1]; } x.c[i] = z; j = x.n; while (j >= i) : (j -= 1) { x.key[j] = x.key[j - 1]; } x.key[i - 1] = y.key[t - 1]; x.n = x.n + 1; //diskWrite(y) //diskWrite(z) //diskWrite(x) } fn insertNonfull(x: *Node(T), k: T, allocator: *Allocator) Error!void { var i = x.n; if (x.leaf) { while (i >= 1 and k < x.key[i - 1]) : (i -= 1) { x.key[i] = x.key[i - 1]; } x.key[i] = k; x.n = x.n + 1; //Here we would write to disk -> diskWrite(x) } else { while (i >= 1 and k < x.key[i - 1]) : (i -= 1) {} i = i + 1; //Here we would read from disk -> diskRead(x.c[i-1]) if (x.c[i - 1].?.n == 2 * t - 1) { try splitChild(x, i, allocator); if (k > x.key[i - 1]) { i = i + 1; } } try insertNonfull(x.c[i - 1].?, k, allocator); } } pub fn search(node: ?*Node(T), k: T) ?SearchTuple(T) { if (node) |x| { var i: usize = 1; while (i <= x.n and k > x.key[i - 1]) : (i += 1) {} if (i <= x.n and k == x.key[i - 1]) { return SearchTuple(T){ .node = x, .index = i - 1 }; } else if (x.leaf) { return null; } else { //Here we would read from disk -> diskRead(x.c[i-1]) return Tree(T).search(x.c[i - 1], k); } } else { return null; } } }; } pub fn main() !void {} test "search empty tree" { var tree = Tree(i32){}; var result = Tree(i32).search(tree.root, 3); try expect(result == null); } test "verify tree creation" { var tree = Tree(i32){}; var arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_allocator.deinit(); const allocator = &arena_allocator.allocator; try tree.create(allocator); try expect(tree.root.?.n == 0); try expect(tree.root.?.leaf); } test "search non-existent element" { var tree = Tree(i32){}; var arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_allocator.deinit(); const allocator = &arena_allocator.allocator; try tree.create(allocator); try tree.insert(3, allocator); var result = Tree(i32).search(tree.root, 4); try expect(result == null); } test "search an existing element" { var tree = Tree(i32){}; var arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_allocator.deinit(); const allocator = &arena_allocator.allocator; try tree.create(allocator); try tree.insert(3, allocator); var result = Tree(i32).search(tree.root, 3); const index = result.?.index; const node = result.?.node; try expect(index == 0); try expect(node.key[index] == 3); } test "search with u8 as key" { var tree = Tree(u8){}; var arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_allocator.deinit(); const allocator = &arena_allocator.allocator; try tree.create(allocator); try tree.insert('F', allocator); try tree.insert('S', allocator); try tree.insert('Q', allocator); try tree.insert('K', allocator); var result = Tree(u8).search(tree.root, 'F'); const index = result.?.index; const node = result.?.node; try expect(index == 0); try expect(node.key[index] == 'F'); } test "search for an element with multiple nodes" { var tree = Tree(i32){}; var arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_allocator.deinit(); const allocator = &arena_allocator.allocator; try tree.create(allocator); const values = [_]i32{ 15, 18, 17, 6, 7, 20, 3, 13, 2, 4, 9 }; for (values) |v| { try tree.insert(v, allocator); } var result = Tree(i32).search(tree.root, 9); const index = result.?.index; const node = result.?.node; try expect(result != null); try expect(index == 0); try expect(node.key[index] == 9); }
search_trees/b_tree_search.zig
const std = @import("std"); var a: *std.mem.Allocator = undefined; const stdout = std.io.getStdOut().writer(); //prepare stdout to write in const Op = enum { acc, jmp, nop, invalid, pub fn init(op: []const u8) Op { if (std.mem.eql(u8, op, "acc")) { return Op.acc; } else if (std.mem.eql(u8, op, "jmp")) { return Op.jmp; } else if (std.mem.eql(u8, op, "nop")) { return Op.nop; } return Op.invalid; } }; const Instruction = struct { op: Op, arg: i32 }; fn run_code(program: [700]?Instruction, swap_idx: usize) ?i64 { var seen_pc: [700]bool = [_]bool{false} ** 700; var PC: usize = 0; var ACC: i64 = 0; while (true) { //std.debug.print("PC: {}\t", .{PC}); if (seen_pc[PC]) { return null; } seen_pc[PC] = true; if (program[PC]) |instruction| { //std.debug.print("{}\n", .{instruction}); switch (instruction.op) { .acc => { ACC += instruction.arg; PC += 1; }, .jmp => { if (PC == swap_idx) { PC += 1; } else { PC = @intCast(usize, @intCast(i32, PC) + instruction.arg); } }, .nop => { if (PC == swap_idx) { PC = @intCast(usize, @intCast(i32, PC) + instruction.arg); } else { PC += 1; } }, .invalid => { break; }, } } else { break; } } //std.debug.print("RETURNING {}\n", .{ACC}); return ACC; } fn run(input: [:0]u8) i64 { var instructions = [_]?Instruction{null} ** 700; var swaps = [_]?usize{null} ** 700; var instruction_counter: usize = 0; var swap_counter: usize = 0; var all_lines_it = std.mem.split(input, "\n"); while (all_lines_it.next()) |line| { var tokenizer = std.mem.tokenize(line, " "); const op = Op.init(tokenizer.next().?); if (op == Op.jmp or op == Op.nop) { swaps[swap_counter] = instruction_counter; swap_counter += 1; } instructions[instruction_counter] = Instruction{ .op = op, .arg = std.fmt.parseInt(i32, tokenizer.next().?, 10) catch unreachable, // I like to live dangerously }; instruction_counter += 1; } for (swaps) |swap_opt| { if (swap_opt) |swap_idx| { if (run_code(instructions, swap_idx)) |retval| { return retval; } } else { break; } } return 0; } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); // create memory allocator for strings defer arena.deinit(); // clear memory var arg_it = std.process.args(); _ = arg_it.skip(); // skip over exe name a = &arena.allocator; // get ref to allocator const input: [:0]u8 = try (arg_it.next(a)).?; // get the first argument const start: i128 = std.time.nanoTimestamp(); // start time const answer = run(input); // compute answer const elapsed_nano: f128 = @intToFloat(f128, std.time.nanoTimestamp() - start); const elapsed_milli: f64 = @floatCast(f64, @divFloor(elapsed_nano, 1_000_000)); try stdout.print("_duration:{d}\n{}\n", .{ elapsed_milli, answer }); // emit actual lines parsed by AOC } test "aoc input 1" { const i = \\nop +0 \\acc +1 \\jmp +4 \\acc +3 \\jmp -3 \\acc -99 \\acc +1 \\jmp -4 \\acc +6 ; var b = i.*; std.testing.expect(run(&b) == 8); }
day-08/part-2/lelithium.zig
pub nakedcc fn _aullrem() void { @setRuntimeSafety(false); asm volatile ( \\.intel_syntax noprefix \\ \\ push ebx \\ mov eax,dword ptr [esp+14h] \\ or eax,eax \\ jne L1a \\ mov ecx,dword ptr [esp+10h] \\ mov eax,dword ptr [esp+0Ch] \\ xor edx,edx \\ div ecx \\ mov eax,dword ptr [esp+8] \\ div ecx \\ mov eax,edx \\ xor edx,edx \\ jmp L2a \\ L1a: \\ mov ecx,eax \\ mov ebx,dword ptr [esp+10h] \\ mov edx,dword ptr [esp+0Ch] \\ mov eax,dword ptr [esp+8] \\ L3a: \\ shr ecx,1 \\ rcr ebx,1 \\ shr edx,1 \\ rcr eax,1 \\ or ecx,ecx \\ jne L3a \\ div ebx \\ mov ecx,eax \\ mul dword ptr [esp+14h] \\ xchg eax,ecx \\ mul dword ptr [esp+10h] \\ add edx,ecx \\ jb L4a \\ cmp edx,dword ptr [esp+0Ch] \\ ja L4a \\ jb L5a \\ cmp eax,dword ptr [esp+8] \\ jbe L5a \\ L4a: \\ sub eax,dword ptr [esp+10h] \\ sbb edx,dword ptr [esp+14h] \\ L5a: \\ sub eax,dword ptr [esp+8] \\ sbb edx,dword ptr [esp+0Ch] \\ neg edx \\ neg eax \\ sbb edx,0 \\ L2a: \\ pop ebx \\ ret 10h ); }
std/special/compiler_rt/aullrem.zig
const std = @import("std"); const res = @import("resources.zig"); const mem = std.mem; const Logo = res.Logo; const OsEnum = res.OsEnum; pub fn getlogo(allocator: *mem.Allocator, os_id: anytype, colorset: res.Colors) !Logo { const ansi: res.Colors = colorset; var id: OsEnum = undefined; if (@TypeOf(os_id) == []u8) { id = std.meta.stringToEnum(OsEnum, os_id) orelse OsEnum.generic; } else { id = os_id orelse OsEnum.generic; } const logo = switch (id) { .arch => Logo{ .motif = ansi.bb, .logo = [8][]const u8{ try std.fmt.allocPrint( // 0 allocator, " {s}.{s} ", .{ ansi.b, ansi.x }, ), try std.fmt.allocPrint( // 1 allocator, " {s}/^\\{s} ", .{ ansi.b, ansi.x }, ), try std.fmt.allocPrint( // 2 allocator, " {s}/, ,\\{s} ", .{ ansi.b, ansi.x }, ), try std.fmt.allocPrint( // 3 allocator, " {s}/, {s}{s}v{s}{s} ,\\{s} ", .{ ansi.b, ansi.c, ansi.z, ansi.x, ansi.b, ansi.x, }, ), try std.fmt.allocPrint( // 4 allocator, " {s}/, {s}{s}({s} {s}{s}){s}{s} ,\\{s} ", .{ ansi.b, ansi.c, ansi.z, ansi.x, ansi.c, ansi.z, ansi.x, ansi.b, ansi.x, }, ), try std.fmt.allocPrint( // 5 allocator, " {s}/,{s} {s}> <{s} {s},\\{s} ", .{ ansi.b, ansi.x, ansi.b, ansi.x, ansi.b, ansi.x, }, ), try std.fmt.allocPrint( // 6 allocator, " {s}/.>{s} {s}<.\\{s} ", .{ ansi.b, ansi.x, ansi.b, ansi.x, }, ), try std.fmt.allocPrint( // 7 allocator, "{s}/>{s} {s}<\\{s}", .{ ansi.b, ansi.x, ansi.b, ansi.x, }, ), }, }, .artix => Logo{ .motif = ansi.b, .logo = [8][]const u8{ try std.fmt.allocPrint( // 0 allocator, " {s}.{s} ", .{ ansi.b, ansi.x }, ), try std.fmt.allocPrint( // 1 allocator, " {s}/{s}{s}#\\{s} ", .{ ansi.b, ansi.bb, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 2 allocator, " {s}/,{s}{s}+,\\{s} ", .{ ansi.b, ansi.bb, ansi.z, ansi.x, }, ), try std.fmt.allocPrint( // 3 allocator, " {s}`<{s}{s}n,\\{s} ", .{ ansi.b, ansi.bb, ansi.z, ansi.x, }, ), try std.fmt.allocPrint( // 4 allocator, " {s}{s}/{s}{s}, {s}`{s}{s},\\{s} ", .{ ansi.bb, ansi.z, ansi.x, ansi.b, ansi.b, ansi.bb, ansi.z, ansi.x, }, ), try std.fmt.allocPrint( // 5 allocator, " {s}{s}/,hK{s}{s}+> {s},{s} ", .{ ansi.bb, ansi.z, ansi.x, ansi.b, ansi.b, ansi.x, }, ), try std.fmt.allocPrint( // 6 allocator, " {s}{s}/.b{s}{s}>` {s}<H{s}{s}.\\{s} ", .{ ansi.bb, ansi.z, ansi.x, ansi.b, ansi.b, ansi.bb, ansi.z, ansi.x, }, ), try std.fmt.allocPrint( // 7 allocator, "{s}{s}/{s}{s}>` {s}`<{s}{s}\\{s}", .{ ansi.bb, ansi.z, ansi.x, ansi.b, ansi.b, ansi.bb, ansi.z, ansi.x, }, ), }, }, .gentoo => Logo{ .motif = ansi.mm, .logo = [8][]const u8{ try std.fmt.allocPrint( // 0 allocator, " {s}{s}.ggg.{s} ", .{ ansi.m, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 1 allocator, " {s}{s}.dGGGGG$b.{s} ", .{ ansi.m, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 2 allocator, " {s}{s}$GGG( )GGGb{s} ", .{ ansi.m, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 3 allocator, " {s}{s}Q$GGGGGGGGG){s}", .{ ansi.m, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 4 allocator, " {s}{s}'GGGGGGGP{s} ", .{ ansi.m, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 5 allocator, " {s}{s}dGGGGG$P'{s} ", .{ ansi.m, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 6 allocator, "{s}{s}$$GGGG$P{s} ", .{ ansi.m, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 7 allocator, "{s}{s}`qG$$P'{s} ", .{ ansi.m, ansi.z, ansi.x }, ), }, }, .parabola => Logo{ .motif = ansi.bb, .logo = [8][]const u8{ try std.fmt.allocPrint( // 0 allocator, " {s}{s}_.__{s} ", .{ ansi.b, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 1 allocator, " {s}{s}_.,;\"[ZAMW:+{s} ", .{ ansi.b, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 2 allocator, "{s}{s},;\"'` @#;:{s}", .{ ansi.b, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 3 allocator, " {s}{s}.$#;/{s} ", .{ ansi.b, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 4 allocator, " {s}{s},/;/{s} ", .{ ansi.b, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 5 allocator, " {s}{s}/;/{s} ", .{ ansi.b, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 6 allocator, " {s}{s};/>{s} ", .{ ansi.b, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 7 allocator, " {s}{s},/{s} ", .{ ansi.b, ansi.z, ansi.x }, ), }, }, .qubes => Logo{ .motif = ansi.bb, .logo = [8][]const u8{ try std.fmt.allocPrint( // 0 allocator, " {s}{s}.<>.{s} ", .{ ansi.b, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 1 allocator, " {s}{s}.<^>''<^>.{s} ", .{ ansi.b, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 2 allocator, "{s}{s}<^>< ><^>{s}", .{ ansi.b, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 3 allocator, "{s}{s}[:] [:]{s}", .{ ansi.b, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 4 allocator, "{s}{s}[:] [:]{s}", .{ ansi.b, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 5 allocator, "{s}{s}<:>< ><:>{s}", .{ ansi.b, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 6 allocator, " {s}{s}<.>..<.>>{s} ", .{ ansi.b, ansi.z, ansi.x }, ), try std.fmt.allocPrint( // 7 allocator, " {s}{s}`<>` </>{s}", .{ ansi.b, ansi.z, ansi.x }, ), }, }, else => Logo{ .motif = ansi.yy, .logo = [8][]const u8{ try std.fmt.allocPrint( // 0 allocator, " {s}XXXX{s} ", .{ ansi.dd, ansi.x }, ), try std.fmt.allocPrint( // 1 allocator, " {s}X{s}{s}^{s}{s}XX{s}{s}^{s}{s}X{s} ", .{ ansi.dd, ansi.x, ansi.z, ansi.x, ansi.dd, ansi.x, ansi.z, ansi.x, ansi.dd, ansi.x, }, ), try std.fmt.allocPrint( // 2 allocator, " {s}X{s}{s}<XX>{s}{s}X{s} ", .{ ansi.dd, ansi.x, ansi.y, ansi.x, ansi.dd, ansi.x, }, ), try std.fmt.allocPrint( // 3 allocator, " {s}XX{s}X{s}XXXX{s}X{s}XX{s} ", .{ ansi.dd, ansi.x, ansi.dd, ansi.x, ansi.dd, ansi.x, }, ), try std.fmt.allocPrint( // 4 allocator, " {s}XX{s}XXXXXXXX{s}XX{s} ", .{ ansi.dd, ansi.x, ansi.dd, ansi.x, }, ), try std.fmt.allocPrint( // 5 allocator, " {s}XX{s}XXXXXXXXXX{s}XX{s} ", .{ ansi.dd, ansi.x, ansi.dd, ansi.x, }, ), try std.fmt.allocPrint( // 6 allocator, "{s}I{s}{s}XXX{s}XXXXXXXX{s}XXX{s}{s}I{s}", .{ ansi.y, ansi.x, ansi.dd, ansi.x, ansi.dd, ansi.x, ansi.y, ansi.x, }, ), try std.fmt.allocPrint( // 7 allocator, "{s}IL>{s}{s}XX{s}XXXXXX{s}XX{s}{s}<JI{s}", .{ ansi.y, ansi.x, ansi.dd, ansi.x, ansi.dd, ansi.x, ansi.y, ansi.x, }, ), }, }, }; return logo; }
src/logos.zig
const std = @import("std"); const time = @import("../time.zig"); const platform = @import("../platform.zig"); const vfs = @import("../vfs.zig"); const util = @import("../util.zig"); const RefCount = util.RefCount; const Node = vfs.Node; const File = vfs.File; const FileList = std.ArrayList(?File); // These **MUST** be inlined. inline fn myFsImpl(self: *Node) *FsImpl { return self.file_system.?.cookie.?.as(FsImpl); } inline fn myImpl(self: *Node) *NodeImpl { return self.cookie.?.as(NodeImpl); } const NodeImpl = struct { const ops: Node.Ops = .{ .open = NodeImpl.open, .close = NodeImpl.close, .read = NodeImpl.read, .write = NodeImpl.write, .find = NodeImpl.find, .create = NodeImpl.create, .link = NodeImpl.link, .unlink = NodeImpl.unlink, .readDir = NodeImpl.readDir, .unlink_me = NodeImpl.unlink_me, }; children: ?FileList = null, data: ?[]u8 = null, n_links: RefCount = .{}, pub fn init(file_system: *vfs.FileSystem, typ: Node.Type, initial_stat: Node.Stat) !*Node { var fs_impl = file_system.cookie.?.as(FsImpl); var node_impl = try fs_impl.file_allocator.create(NodeImpl); errdefer fs_impl.file_allocator.destroy(node_impl); if (typ == .directory) { node_impl.children = FileList.init(fs_impl.file_allocator); } else if (typ == .file) { node_impl.data = try fs_impl.file_allocator.alloc(u8, 0); } else { unreachable; } var node = try fs_impl.file_allocator.create(Node); errdefer fs_impl.file_allocator.destroy(node); var true_initial_stat = initial_stat; true_initial_stat.inode = fs_impl.inode_count; true_initial_stat.type = typ; true_initial_stat.size = @sizeOf(NodeImpl) + @sizeOf(Node); fs_impl.inode_count += 1; node.* = Node.init(NodeImpl.ops, util.asCookie(node_impl), true_initial_stat, file_system); return node; } // This function destroys a properly allocated and initialized Node object. You should almost never need to call this directly. pub fn deinit(self: *Node) void { var node_impl = myImpl(self); var fs_impl = myFsImpl(self); if (node_impl.children != null) { node_impl.children.?.deinit(); } if (node_impl.data != null) { fs_impl.file_allocator.free(node_impl.data.?); } fs_impl.file_allocator.destroy(node_impl); fs_impl.file_allocator.destroy(self); } // Returns the true reference count (number of opens + number of hard links). We can't deinit until this reaches 0, or bad things will happen. fn trueRefCount(self: *Node) usize { return self.opens.refs + myImpl(self).n_links.refs; } pub fn open(self: *Node) !void { // I don't think this can fail? } pub fn close(self: *Node) !void { if (NodeImpl.trueRefCount(self) == 0) NodeImpl.deinit(self); } pub fn read(self: *Node, offset: u64, buffer: []u8) !usize { var node_impl = myImpl(self); if (node_impl.data) |data| { var trueEnd = @truncate(usize, if (offset + buffer.len > data.len) data.len else offset + buffer.len); var trueOff = @truncate(usize, offset); std.mem.copy(u8, buffer, data[trueOff..trueEnd]); self.stat.access_time = time.getClockNano(.real); return trueEnd - trueOff; } return vfs.Error.NotFile; } pub fn write(self: *Node, offset: u64, buffer: []const u8) !usize { var node_impl = myImpl(self); var fs_impl = myFsImpl(self); if (node_impl.data) |data| { var trueData = data; var trueEnd = @truncate(usize, offset + buffer.len); var trueOff = @truncate(usize, offset); if (trueEnd > data.len) trueData = try fs_impl.file_allocator.realloc(trueData, trueEnd); std.mem.copy(u8, trueData[trueOff..trueEnd], buffer); var now = time.getClockNano(.real); self.stat.access_time = now; self.stat.modify_time = now; self.stat.size = trueData.len; self.stat.blocks = trueData.len + @sizeOf(NodeImpl) + @sizeOf(Node); node_impl.data = trueData; return buffer.len; } return vfs.Error.NotFile; } pub fn find(self: *Node, name: []const u8) !File { var node_impl = myImpl(self); if (node_impl.children) |children| { for (children.items) |child| { if (child == null) continue; if (std.mem.eql(u8, child.?.name(), name)) { try child.?.open(); return child.?; } } return vfs.Error.NoSuchFile; } return vfs.Error.NotDirectory; } pub fn create(self: *Node, name: []const u8, typ: Node.Type, mode: Node.Mode) !File { var fs_impl = myFsImpl(self); var node_impl = myImpl(self); if (node_impl.children) |children| { for (children.items) |child| { if (std.mem.eql(u8, child.?.name(), name)) return vfs.Error.FileExists; } var now = time.getClockNano(.real); var new_node = try NodeImpl.init(self.file_system.?, typ, .{ .mode = mode, .links = 1, .access_time = now, .create_time = now, .modify_time = now }); errdefer NodeImpl.deinit(new_node); var new_file: File = undefined; std.mem.copy(u8, new_file.name_buf[0..], name); new_file.name_len = name.len; new_file.node = new_node; try node_impl.children.?.append(new_file); myImpl(new_node).n_links.ref(); try new_node.open(); return new_file; } return vfs.Error.NotDirectory; } pub fn link(self: *Node, name: []const u8, new_node: *Node) !File { var node_impl = myImpl(self); if (node_impl.children != null) { if (NodeImpl.find(self, name) catch null != null) return vfs.Error.FileExists; var new_file: File = undefined; std.mem.copy(u8, new_file.name_buf[0..], name); new_file.name_len = name.len; new_file.node = new_node; if (new_node.file_system == self.file_system) { myImpl(new_node).n_links.ref(); } else if (new_node.stat.flags.mount_point) { try new_node.open(); } try node_impl.children.?.append(new_file); return new_file; } return vfs.Error.NotDirectory; } pub fn unlink(self: *Node, name: []const u8) !void { var node_impl = myImpl(self); if (node_impl.children) |children| { for (children.items) |child, i| { if (std.mem.eql(u8, child.?.name(), name)) { if (child.?.node.ops.unlink_me) |unlink_me_fn| { try unlink_me_fn(child.?.node); } _ = node_impl.children.?.swapRemove(i); return; } } return vfs.Error.NoSuchFile; } return vfs.Error.NotDirectory; } pub fn readDir(self: *Node, offset: u64, files: []vfs.File) !usize { var node_impl = myImpl(self); if (node_impl.children) |children| { var total: usize = 0; for (children.items) |child, i| { if (i < offset) continue; if (total == files.len) break; files[total] = child.?; total += 1; } return total; } return vfs.Error.NotDirectory; } pub fn unlink_me(self: *Node) !void { var node_impl = myImpl(self); if (node_impl.children) |children| { if (children.items.len != 0) return vfs.Error.NotEmpty; } node_impl.n_links.unref(); var fs = self.file_system.?; if (NodeImpl.trueRefCount(self) == 0) { NodeImpl.deinit(self); } } }; const FsImpl = struct { const ops: vfs.FileSystem.Ops = .{ .mount = FsImpl.mount, }; file_allocator: *std.mem.Allocator, maybe_fba: std.heap.FixedBufferAllocator, maybe_fba_data: []u8, inode_count: u64, pub fn mount(self: *vfs.FileSystem, unused: ?*Node, args: ?[]const u8) !*Node { var fs_impl = try self.allocator.create(FsImpl); errdefer self.allocator.destroy(fs_impl); fs_impl.inode_count = 1; fs_impl.maybe_fba_data = try self.allocator.alloc(u8, 4 * 1024 * 1024); errdefer self.allocator.free(fs_impl.maybe_fba_data); fs_impl.maybe_fba = std.heap.FixedBufferAllocator.init(fs_impl.maybe_fba_data); fs_impl.file_allocator = &fs_impl.maybe_fba.allocator; self.cookie = util.asCookie(fs_impl); var now = time.getClockNano(.real); var root_node = try NodeImpl.init(self, .directory, .{ .flags = .{ .mount_point = true }, .create_time = now, .access_time = now, .modify_time = now }); return root_node; } }; pub const Fs = vfs.FileSystem.init("tmpfs", FsImpl.ops);
kernel/fs/tmpfs.zig
const std = @import("std"); const util = @import("util"); pub fn Grid(comptime grid: anytype) type { comptime std.debug.assert(grid.len > 0 and grid[0].len > 0); comptime std.debug.assert(@TypeOf(grid) == [grid.len][grid[0].len]u8); return struct { buf: [2][height][width]u8 = comptime blk: { @setEvalBranchQuota(height * 10); var buf: [height][width]u8 = undefined; buf[0] = [_]u8{'.'} ** width; buf[height - 1] = buf[0]; for (buf[1..(height - 1)]) |*bytes, y| bytes.* = [_]u8{'.'} ++ grid[y] ++ [_]u8{'.'}; break :blk [_][height][width]u8{ buf, buf }; }, const width = grid[0].len + 2; const height = grid.len + 2; pub fn update( self: *@This(), idx: u1, comptime updateFn: fn ( buf: *const [height][width]u8, x: usize, y: usize, ) bool, ) ?usize { const src = &self.buf[idx]; const dest = &self.buf[idx ^ 1]; var num_occupied: ?usize = 0; var y: usize = 1; while (y < height - 1) : (y += 1) { var x: usize = 1; while (x < width - 1) : (x += 1) { if (src[y][x] == '.') continue; dest[y][x] = if (updateFn(src, x, y)) '#' else 'L'; if (src[y][x] != dest[y][x]) { num_occupied = null; } if (dest[y][x] == '#' and num_occupied != null) { num_occupied.? += 1; } } } return num_occupied; } pub fn adjacentRule(buf: *const [height][width]u8, x: usize, y: usize) bool { var num_adjacent: usize = 0; inline for (.{ -1, 0, 1 }) |dx| { inline for (.{ -1, 0, 1 }) |dy| { if (dx == 0 and dy == 0) continue; const new_x = if (dx == -1) x - 1 else x + dx; const new_y = if (dy == -1) y - 1 else y + dy; if (buf[new_y][new_x] == '#') { num_adjacent += 1; } } } return switch (num_adjacent) { 0 => true, 4...8 => false, else => buf[y][x] == '#', }; } pub fn visibleRule(buf: *const [height][width]u8, x: usize, y: usize) bool { var num_visible: usize = 0; inline for (.{ -1, 0, 1 }) |dx| { inline for (.{ -1, 0, 1 }) |dy| { if (dx == 0 and dy == 0) continue; var new_x = x; var new_y = y; while (new_x > 0 and new_x < width - 1 and new_y > 0 and new_y < height - 1) { new_x = if (dx == -1) new_x - 1 else new_x + dx; new_y = if (dy == -1) new_y - 1 else new_y + dy; if (buf[new_y][new_x] == '#') num_visible += 1; if (buf[new_y][new_x] != '.') break; } } } return switch (num_visible) { 0 => true, 5...8 => false, else => buf[y][x] == '#', }; } }; }
2020/seat_grid.zig
const std = @import("std"); const expect = std.testing.expect; // Try toggling these const simulate_fail_download = false; const simulate_fail_file = false; const suspend_download = true; const suspend_file = true; pub fn main() void { _ = async amainWrap(); // This simulates an event loop if (suspend_file) { resume global_file_frame; } if (suspend_download) { resume global_download_frame; } } fn amainWrap() void { if (amain()) |_| { expect(!simulate_fail_download); expect(!simulate_fail_file); } else |e| switch (e) { error.NoResponse => expect(simulate_fail_download), error.FileNotFound => expect(simulate_fail_file), else => @panic("test failure"), } } fn amain() !void { const allocator = std.heap.page_allocator; var download_frame = async fetchUrl(allocator, "https://example.com/"); var download_awaited = false; errdefer if (!download_awaited) { if (await download_frame) |x| allocator.free(x) else |_| {} }; var file_frame = async readFile(allocator, "something.txt"); var file_awaited = false; errdefer if (!file_awaited) { if (await file_frame) |x| allocator.free(x) else |_| {} }; download_awaited = true; const download_text = try await download_frame; defer allocator.free(download_text); file_awaited = true; const file_text = try await file_frame; defer allocator.free(file_text); expect(std.mem.eql(u8, "expected download text", download_text)); expect(std.mem.eql(u8, "expected file text", file_text)); std.debug.warn("OK!\n", .{}); } var global_download_frame: anyframe = undefined; fn fetchUrl(allocator: *std.mem.Allocator, url: []const u8) anyerror![]u8 { const result = try std.mem.dupe(allocator, u8, "expected download text"); errdefer allocator.free(result); if (suspend_download) { suspend { global_download_frame = @frame(); } } if (simulate_fail_download) return error.NoResponse; std.debug.warn("fetchUrl returning\n", .{}); return result; } var global_file_frame: anyframe = undefined; fn readFile(allocator: *std.mem.Allocator, filename: []const u8) anyerror![]u8 { const result = try std.mem.dupe(allocator, u8, "expected file text"); errdefer allocator.free(result); if (suspend_file) { suspend { global_file_frame = @frame(); } } if (simulate_fail_file) return error.FileNotFound; std.debug.warn("readFile returning\n", .{}); return result; }
examples/async_functions/typical_async_await_original.zig
const std = @import("std"); const debug_enabled = std.meta.globalOption("zpng_debug", bool) orelse (@import("builtin").mode == .Debug); fn debug(comptime level: @TypeOf(.x), comptime format: []const u8, args: anytype) void { if (debug_enabled) { @field(std.log.scoped(.zpng), @tagName(level))(format, args); } } pub const Image = struct { width: u32, height: u32, pixels: [][4]u16, // If the PNG is invalid or corrupt, error.InvalidPng is returned. // If the PNG may be valid, but uses features not supported by this implementation, error.UnsupportedPng is returned. pub fn read(allocator: std.mem.Allocator, r: anytype) !Image { var dec = Decoder(@TypeOf(r)){ .allocator = allocator, .r = r }; return dec.decode(); } pub fn deinit(self: Image, allocator: std.mem.Allocator) void { allocator.free(self.pixels); } /// Return the X coordinate of the pixel at index pub fn x(self: Image, index: usize) u32 { return @intCast(u32, index % self.width); } /// Return the Y coordinate of the pixel at index pub fn y(self: Image, index: usize) u32 { return @intCast(u32, index / self.height); } /// Return the pixel at the given X and Y coordinates pub fn pix(self: Image, px: u32, py: u32) [4]u16 { return self.pixels[px + py * self.width]; } }; fn Decoder(comptime Reader: type) type { return struct { allocator: std.mem.Allocator, r: Reader, const Self = @This(); fn decode(self: *Self) !Image { // Read magic bytes if (!try self.r.isBytes("\x89PNG\r\n\x1a\n")) { return error.InvalidPng; } // Read IHDR chunk const ihdr = self.readIhdr() catch |err| return switch (err) { error.InvalidEnumTag => error.InvalidPng, else => |e| e, }; // TODO: interlacing if (ihdr.interlace_method != .none) { return error.UnsupportedPng; } // Read data chunks var data: ?std.ArrayList(u8) = null; defer if (data) |l| l.deinit(); var palette: ?[][4]u16 = null; defer if (palette) |p| self.allocator.free(p); var transparent_color: ?[3]u16 = null; // Not normalized. If greyscale, only first value is used while (true) { const chunk = try self.readChunk(); var free = true; defer if (free) self.allocator.free(chunk.data); switch (chunk.ctype) { .ihdr => return error.InvalidPng, // Duplicate IHDR .iend => { if (chunk.data.len != 0) { return error.InvalidPng; // Non-empty IEND } break; }, .plte => { if (ihdr.colour_type != .indexed) { return error.InvalidPng; // Unexpected PLTE } if (palette != null) { return error.InvalidPng; // Duplicate PLTE } if (chunk.data.len % 3 != 0) { return error.InvalidPng; // PLTE length not a multiple of three } const rgb_palette = std.mem.bytesAsSlice([3]u8, chunk.data); const rgba_palette = try self.allocator.alloc([4]u16, rgb_palette.len); for (rgb_palette) |entry, i| { for (entry) |c, j| { rgba_palette[i][j] = @as(u16, 257) * c; } rgba_palette[i][3] = std.math.maxInt(u16); } palette = rgba_palette; }, // TODO: streaming .idat => if (data) |*l| { try l.appendSlice(chunk.data); } else { data = std.ArrayList(u8).fromOwnedSlice(self.allocator, chunk.data); free = false; }, .trns => { switch (ihdr.colour_type) { .greyscale_alpha, .truecolour_alpha => { return error.InvalidPng; // tRNS invalid with alpha channel }, .greyscale => { if (chunk.data.len != 2) { return error.InvalidPng; // tRNS data of incorrect length } transparent_color = .{ std.mem.readIntSliceBig(u16, chunk.data), 0, 0 }; }, .truecolour => { if (chunk.data.len != 6) { return error.InvalidPng; // tRNS data of incorrect length } transparent_color = .{ std.mem.readIntSliceBig(u16, chunk.data), std.mem.readIntSliceBig(u16, chunk.data[2..]), std.mem.readIntSliceBig(u16, chunk.data[4..]), }; }, .indexed => { const plte = palette orelse { return error.InvalidPng; // tRNS before PLTE }; for (chunk.data) |trns, i| { plte[i][3] = trns; } }, } }, _ => { const cname = chunkName(chunk.ctype); debug(.warn, "Unsupported chunk: {s}", .{cname}); if (cname[0] & 32 == 0) { // Ancillary bit is unset, this chunk is critical return error.UnsupportedPng; } }, } } // Read pixel data if (data == null) { return error.InvalidPng; // Missing IDAT } const pixels = try readPixels( self.allocator, ihdr, palette orelse null, // ziglang/zig#4907 transparent_color, data.?.items, ); return Image{ .width = ihdr.width, .height = ihdr.height, .pixels = pixels, }; } fn readIhdr(self: *Self) !Ihdr { // Read chunk const chunk = try self.readChunk(); defer self.allocator.free(chunk.data); if (chunk.ctype != .ihdr) { return error.InvalidPng; } var stream = std.io.fixedBufferStream(chunk.data); const r = stream.reader(); // Read and validate width and height const width = try r.readIntBig(u32); const height = try r.readIntBig(u32); if (width == 0 or height == 0) { return error.InvalidPng; } // Read and validate colour type and bit depth const bit_depth = try r.readIntBig(u8); const colour_type = try std.meta.intToEnum(ColourType, try r.readIntBig(u8)); const allowed_bit_depths: []const u5 = switch (colour_type) { .greyscale => &.{ 1, 2, 4, 8, 16 }, .truecolour, .greyscale_alpha, .truecolour_alpha => &.{ 8, 16 }, .indexed => &.{ 1, 2, 4, 8 }, }; for (allowed_bit_depths) |depth| { if (depth == bit_depth) break; } else { return error.InvalidPng; } // Read and validate compression method and filter method const compression_method = try r.readIntBig(u8); const filter_method = try r.readIntBig(u8); if (compression_method != 0 or filter_method != 0) { return error.InvalidPng; } // Read and validate interlace method const interlace_method = try std.meta.intToEnum(InterlaceMethod, try r.readIntBig(u8)); return Ihdr{ .width = width, .height = height, .bit_depth = @intCast(u5, bit_depth), .colour_type = colour_type, .compression_method = compression_method, .filter_method = filter_method, .interlace_method = interlace_method, }; } fn readChunk(self: *Self) !Chunk { var crc = std.hash.Crc32.init(); const len = try self.r.readIntBig(u32); var ctype = try self.r.readBytesNoEof(4); crc.update(&ctype); const data = try self.allocator.alloc(u8, len); errdefer self.allocator.free(data); try self.r.readNoEof(data); crc.update(data); if (crc.final() != try self.r.readIntBig(u32)) { return error.InvalidPng; } return Chunk{ .ctype = chunkType(ctype), .data = data, }; } }; } fn readPixels( allocator: std.mem.Allocator, ihdr: Ihdr, palette: ?[]const [4]u16, transparent_color: ?[3]u16, // Not normalized. If greyscale, only first value is used data: []const u8, ) ![][4]u16 { var compressed_stream = std.io.fixedBufferStream(data); var data_stream = try std.compress.zlib.zlibStream(allocator, compressed_stream.reader()); defer data_stream.deinit(); const datar = data_stream.reader(); // TODO: interlacing var pixels = try allocator.alloc([4]u16, ihdr.width * ihdr.height); errdefer allocator.free(pixels); const components: u3 = switch (ihdr.colour_type) { .indexed => 1, .greyscale => 1, .greyscale_alpha => 2, .truecolour => 3, .truecolour_alpha => 4, }; const line_bytes = (ihdr.width * ihdr.bit_depth * components - 1) / 8 + 1; var line = try allocator.alloc(u8, line_bytes); defer allocator.free(line); var prev_line = try allocator.alloc(u8, line_bytes); defer allocator.free(prev_line); std.mem.set(u8, prev_line, 0); // Zero prev_line // Number of bits in actual colour components const component_bits = switch (ihdr.colour_type) { .indexed => blk: { if (palette == null) { return error.InvalidPng; // Missing PLTE } break :blk 16; }, else => ihdr.bit_depth, }; // Max component_bits-bit value const component_max = @intCast(u16, (@as(u17, 1) << component_bits) - 1); // Multiply each colour component by this to produce a normalized u16 const component_coef = @divExact( std.math.maxInt(u16), component_max, ); var y: u32 = 0; while (y < ihdr.height) : (y += 1) { const filter = std.meta.intToEnum(FilterType, try datar.readByte()) catch { return error.InvalidPng; }; try datar.readNoEof(line); filterScanline(filter, ihdr.bit_depth, components, prev_line, line); var line_stream = std.io.fixedBufferStream(line); var bits = std.io.bitReader(.Big, line_stream.reader()); var x: u32 = 0; while (x < ihdr.width) : (x += 1) { var pix: [4]u16 = switch (ihdr.colour_type) { .greyscale => blk: { const v = try bits.readBitsNoEof(u16, ihdr.bit_depth); break :blk .{ v, v, v, component_max }; }, .greyscale_alpha => blk: { const v = try bits.readBitsNoEof(u16, ihdr.bit_depth); const a = try bits.readBitsNoEof(u16, ihdr.bit_depth); break :blk .{ v, v, v, a }; }, .truecolour => .{ try bits.readBitsNoEof(u16, ihdr.bit_depth), try bits.readBitsNoEof(u16, ihdr.bit_depth), try bits.readBitsNoEof(u16, ihdr.bit_depth), component_max, }, .truecolour_alpha => .{ try bits.readBitsNoEof(u16, ihdr.bit_depth), try bits.readBitsNoEof(u16, ihdr.bit_depth), try bits.readBitsNoEof(u16, ihdr.bit_depth), try bits.readBitsNoEof(u16, ihdr.bit_depth), }, .indexed => palette.?[try bits.readBitsNoEof(u8, ihdr.bit_depth)], }; if (transparent_color) |trns| { const n: u2 = switch (ihdr.colour_type) { .greyscale => 1, .truecolour => 3, else => unreachable, }; if (std.mem.eql(u16, pix[0..n], &trns)) { pix[3] = 0; } } const idx = x + y * ihdr.width; for (pix) |c, i| { pixels[idx][i] = component_coef * c; } } std.debug.assert(line_stream.pos == line_stream.buffer.len); std.mem.swap([]u8, &line, &prev_line); } var buf: [1]u8 = undefined; if (0 != try datar.readAll(&buf)) { return error.InvalidPng; // Excess IDAT data } return pixels; } const Ihdr = struct { width: u32, height: u32, bit_depth: u5, colour_type: ColourType, compression_method: u8, filter_method: u8, interlace_method: InterlaceMethod, }; const ColourType = enum(u8) { greyscale = 0, truecolour = 2, indexed = 3, greyscale_alpha = 4, truecolour_alpha = 6, }; const InterlaceMethod = enum(u8) { none = 0, adam7 = 1, }; const FilterType = enum(u8) { none = 0, sub = 1, up = 2, average = 3, paeth = 4, }; const Chunk = struct { ctype: ChunkType, data: []u8, }; const ChunkType = blk: { const types = [_]*const [4]u8{ "IHDR", "PLTE", "IDAT", "IEND", "tRNS", }; var fields: [types.len]std.builtin.TypeInfo.EnumField = undefined; for (types) |name, i| { var field_name: [4]u8 = undefined; fields[i] = .{ .name = std.ascii.lowerString(&field_name, name), .value = std.mem.readIntNative(u32, name), }; } break :blk @Type(.{ .Enum = .{ .layout = .Auto, .tag_type = u32, .fields = &fields, .decls = &.{}, .is_exhaustive = false, } }); }; fn chunkType(name: [4]u8) ChunkType { return @intToEnum(ChunkType, std.mem.readIntNative(u32, &name)); } fn chunkName(ctype: ChunkType) [4]u8 { var name: [4]u8 = undefined; std.mem.writeIntNative(u32, &name, @enumToInt(ctype)); return name; } // TODO: use optional prev_line, so we can avoid zeroing fn filterScanline(filter: FilterType, bit_depth: u5, components: u4, prev_line: []const u8, line: []u8) void { if (filter == .none) return; const byte_rewind = switch (bit_depth) { 1, 2, 4 => 1, 8 => components, 16 => components * 2, else => unreachable, }; for (line) |*x, i| { const a = if (i < byte_rewind) 0 else line[i - byte_rewind]; const b = prev_line[i]; const c = if (i < byte_rewind) 0 else prev_line[i - byte_rewind]; x.* +%= switch (filter) { .none => unreachable, .sub => a, .up => b, .average => @intCast(u8, (@as(u9, a) + b) / 2), .paeth => paeth(a, b, c), }; } } fn paeth(a: u8, b: u8, c: u8) u8 { const p = @as(i10, a) + b - c; 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; return if (pa <= pb and pa <= pc) a else if (pb <= pc) b else c; } test "red/blue" { var dir = try std.fs.cwd().openDir("test/red_blue", .{ .iterate = true }); defer dir.close(); var it = dir.iterate(); while (try it.next()) |entry| { const f = try dir.openFile(entry.name, .{}); defer f.close(); var buf = std.io.bufferedReader(f.reader()); const img = try Image.read(std.testing.allocator, buf.reader()); defer img.deinit(std.testing.allocator); for (img.pixels) |pix, i| { const r: u16 = if (img.x(i) < 32) 0 else 65535; const b: u16 = if (img.y(i) < 32) 0 else 65535; try std.testing.expectEqual([4]u16{ r, 0, b, 65535 }, pix); } } } test "green/alpha" { var dir = try std.fs.cwd().openDir("test/green_alpha", .{ .iterate = true }); defer dir.close(); var it = dir.iterate(); while (try it.next()) |entry| { const f = try dir.openFile(entry.name, .{}); defer f.close(); var buf = std.io.bufferedReader(f.reader()); const img = try Image.read(std.testing.allocator, buf.reader()); defer img.deinit(std.testing.allocator); for (img.pixels) |pix, i| { const g: u16 = if (img.x(i) < 32) 0 else 65535; const a: u16 = if (img.y(i) < 32) 0 else 65535; try std.testing.expectEqual([4]u16{ 0, g, 0, a }, pix); } } }
zpng.zig
const std = @import("std"); const interop = @import("../interop.zig"); const iup = @import("../iup.zig"); const Impl = @import("../impl.zig").Impl; const CallbackHandler = @import("../callback_handler.zig").CallbackHandler; const debug = std.debug; const trait = std.meta.trait; const Element = iup.Element; const Handle = iup.Handle; const Error = iup.Error; const ChildrenIterator = iup.ChildrenIterator; const Size = iup.Size; const Margin = iup.Margin; /// /// Creates the Message Dialog element. /// It is a predefined dialog for displaying a message. /// The dialog can be shown with the IupPopup function only. pub const MessageDlg = opaque { pub const CLASS_NAME = "messagedlg"; pub const NATIVE_TYPE = iup.NativeType.Dialog; const Self = @This(); pub const OnFocusFn = fn (self: *Self, arg0: i32) anyerror!void; /// /// K_ANY K_ANY Action generated when a keyboard event occurs. /// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) -> /// (ret: number) [in Lua] ih: identifier of the element that activated the event. /// c: identifier of typed key. /// Please refer to the Keyboard Codes table for a list of possible values. /// Returns: If IUP_IGNORE is returned the key is ignored and not processed by /// the control and not propagated. /// If returns IUP_CONTINUE, the key will be processed and the event will be /// propagated to the parent of the element receiving it, this is the default behavior. /// If returns IUP_DEFAULT the key is processed but it is not propagated. /// IUP_CLOSE will be processed. /// Notes Keyboard callbacks depend on the keyboard usage of the control with /// the focus. /// So if you return IUP_IGNORE the control will usually not process the key. /// But be aware that sometimes the control process the key in another event so /// even returning IUP_IGNORE the key can get processed. /// Although it will not be propagated. /// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on /// the IUP_CONTINUE return value to work while the control is in focus. /// If the callback does not exists it is automatically propagated to the /// parent of the element. /// K_* callbacks All defined keys are also callbacks of any element, called /// when the respective key is activated. /// For example: "K_cC" is also a callback activated when the user press /// Ctrl+C, when the focus is at the element or at a children with focus. /// This is the way an application can create shortcut keys, also called hot keys. /// These callbacks are not available in IupLua. /// Affects All elements with keyboard interaction. pub const OnKAnyFn = fn (self: *Self, arg0: i32) anyerror!void; /// /// HELP_CB HELP_CB Action generated when the user press F1 at a control. /// In Motif is also activated by the Help button in some workstations keyboard. /// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Returns: IUP_CLOSE will be processed. /// Affects All elements with user interaction. pub const OnHelpFn = fn (self: *Self) anyerror!void; /// /// CLOSE_CB CLOSE_CB Called just before a dialog is closed when the user /// clicks the close button of the title bar or an equivalent action. /// Callback int function(Ihandle *ih); [in C] ih:close_cb() -> (ret: number) /// [in Lua] ih: identifies the element that activated the event. /// Returns: if IUP_IGNORE, it prevents the dialog from being closed. /// If you destroy the dialog in this callback, you must return IUP_IGNORE. /// IUP_CLOSE will be processed. /// Affects IupDialog pub const OnCloseFn = fn (self: *Self) anyerror!void; pub const OnDropMotionFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: [:0]const u8) anyerror!void; pub const OnDragEndFn = fn (self: *Self, arg0: i32) anyerror!void; pub const OnDragBeginFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void; /// /// MAP_CB MAP_CB Called right after an element is mapped and its attributes /// updated in IupMap. /// When the element is a dialog, it is called after the layout is updated. /// For all other elements is called before the layout is updated, so the /// element current size will still be 0x0 during MAP_CB (since 3.14). /// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub const OnMapFn = fn (self: *Self) anyerror!void; /// /// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also LEAVEWINDOW_CB pub const OnEnterWindowFn = fn (self: *Self) anyerror!void; /// /// DESTROY_CB DESTROY_CB Called right before an element is destroyed. /// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Notes If the dialog is visible then it is hidden before it is destroyed. /// The callback will be called right after it is hidden. /// The callback will be called before all other destroy procedures. /// For instance, if the element has children then it is called before the /// children are destroyed. /// For language binding implementations use the callback name "LDESTROY_CB" to /// release memory allocated by the binding for the element. /// Also the callback will be called before the language callback. /// Affects All. pub const OnDestroyFn = fn (self: *Self) anyerror!void; pub const OnDropDataFn = fn (self: *Self, arg0: [:0]const u8, arg1: *iup.Unknow, arg2: i32, arg3: i32, arg4: i32) anyerror!void; /// /// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus. /// This callback is called before the GETFOCUS_CB of the element that gets the focus. /// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Affects All elements with user interaction, except menus. /// In Windows, there are restrictions when using this callback. /// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any /// function calls that display or activate a window. /// This causes the thread to yield control and can cause the application to /// stop responding to messages. /// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus pub const OnKillFocusFn = fn (self: *Self) anyerror!void; pub const OnDragDataFn = fn (self: *Self, arg0: [:0]const u8, arg1: *iup.Unknow, arg2: i32) anyerror!void; pub const OnDragDataSizeFn = fn (self: *Self, arg0: [:0]const u8) anyerror!void; /// /// SHOW_CB SHOW_CB Called right after the dialog is showed, hidden, maximized, /// minimized or restored from minimized/maximized. /// This callback is called when those actions were performed by the user or /// programmatically by the application. /// Callback int function(Ihandle *ih, int state); [in C] ih:show_cb(state: /// number) -> (ret: number) [in Lua] ih: identifier of the element that /// activated the event. /// state: indicates which of the following situations generated the event: /// IUP_HIDE (since 3.0) IUP_SHOW IUP_RESTORE (was minimized or maximized) /// IUP_MINIMIZE IUP_MAXIMIZE (since 3.0) (not received in Motif when activated /// from the maximize button) Returns: IUP_CLOSE will be processed. /// Affects IupDialog pub const OnShowFn = fn (self: *Self, arg0: i32) anyerror!void; /// /// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control. /// When several files are dropped at once, the callback is called several /// times, once for each file. /// If defined after the element is mapped then the attribute DROPFILESTARGET /// must be set to YES. /// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const /// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename: /// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the /// element that activated the event. /// filename: Name of the dropped file. /// num: Number index of the dropped file. /// If several files are dropped, num is the index of the dropped file starting /// from "total-1" to "0". /// x: X coordinate of the point where the user released the mouse button. /// y: Y coordinate of the point where the user released the mouse button. /// Returns: If IUP_IGNORE is returned the callback will NOT be called for the /// next dropped files, and the processing of dropped files will be interrupted. /// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList pub const OnDropFilesFn = fn (self: *Self, arg0: [:0]const u8, arg1: i32, arg2: i32, arg3: i32) anyerror!void; /// /// RESIZE_CB RESIZE_CB Action generated when the canvas or dialog size is changed. /// Callback int function(Ihandle *ih, int width, int height); [in C] /// ih:resize_cb(width, height: number) -> (ret: number) [in Lua] ih: /// identifier of the element that activated the event. /// width: the width of the internal element size in pixels not considering the /// decorations (client size) height: the height of the internal element size /// in pixels not considering the decorations (client size) Notes For the /// dialog, this action is also generated when the dialog is mapped, after the /// map and before the show. /// When XAUTOHIDE=Yes or YAUTOHIDE=Yes, if the canvas scrollbar is /// hidden/shown after changing the DX or DY attributes from inside the /// callback, the size of the drawing area will immediately change, so the /// parameters with and height will be invalid. /// To update the parameters consult the DRAWSIZE attribute. /// Also activate the drawing toolkit only after updating the DX or DY attributes. /// Affects IupCanvas, IupGLCanvas, IupDialog pub const OnResizeFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void; /// /// UNMAP_CB UNMAP_CB Called right before an element is unmapped. /// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub const OnUnmapFn = fn (self: *Self) anyerror!void; pub const OnTrayClickFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: i32) anyerror!void; /// /// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus. /// This callback is called after the KILLFOCUS_CB of the element that loosed /// the focus. /// The IupGetFocus function during the callback returns the element that /// loosed the focus. /// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that received keyboard focus. /// Affects All elements with user interaction, except menus. /// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus pub const OnGetFocusFn = fn (self: *Self) anyerror!void; pub const OnLDestroyFn = fn (self: *Self) anyerror!void; /// /// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also ENTERWINDOW_CB pub const OnLeaveWindowFn = fn (self: *Self) anyerror!void; pub const OnPostMessageFn = fn (self: *Self, arg0: [:0]const u8, arg1: i32, arg2: f64, arg3: *iup.Unknow) anyerror!void; /// /// DIALOGTYPE: Type of dialog defines which icon will be displayed besides the /// message text. /// Can have values: "MESSAGE" (No Icon), "ERROR" (Stop-sign), "WARNING" /// (Exclamation-point), "QUESTION" (Question-mark) or "INFORMATION" (Letter "i"). /// Default: "MESSAGE". pub const DialogType = enum { Error, Warning, Information, Question, }; pub const ZOrder = enum { Top, Bottom, }; /// /// BUTTONS: Buttons configuration. /// Can have values: "OK", "OKCANCEL", "RETRYCANCEL", "YESNO", or "YESNOCANCEL". /// Default: "OK". /// Additionally the "Help" button is displayed if the HELP_CB callback is defined. /// (RETRYCANCEL and YESNOCANCEL since 3.16) pub const Buttons = enum { OkCanCel, RetrYCanCel, YesNo, YesNoCanCel, Ok, }; pub const Expand = enum { Yes, Horizontal, Vertical, HorizontalFree, VerticalFree, No, }; /// /// BUTTONRESPONSE: Number of the pressed button. /// Can be "1", "2" or "3". /// Default: "1". pub const ButtonResponse = enum(i32) { Button1 = 1, Button2 = 2, Button3 = 3, }; pub const Placement = enum { Maximized, Minimized, Full, }; /// /// BUTTONDEFAULT: Number of the default button. /// Can be "1", "2" or "3". /// "2" is valid only for "RETRYCANCEL", "OKCANCEL" and "YESNO" button configurations. /// "3" is valid only for "YESNOCANCEL". /// Default: "1". pub const ButtonDefault = enum(i32) { Button1 = 1, Button2 = 2, Button3 = 3, }; pub const Floating = enum { Yes, Ignore, No, }; pub const Initializer = struct { last_error: ?anyerror = null, ref: *Self, /// /// Returns a pointer to IUP element or an error. /// Only top-level or detached elements needs to be unwraped, pub fn unwrap(self: Initializer) !*Self { if (self.last_error) |e| { return e; } else { return self.ref; } } /// /// Captures a reference into a external variable /// Allows to capture some references even using full declarative API pub fn capture(self: *Initializer, ref: **Self) Initializer { ref.* = self.ref; return self.*; } pub fn setStrAttribute(self: *Initializer, attributeName: [:0]const u8, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; Self.setStrAttribute(self.ref, attributeName, arg); return self.*; } pub fn setIntAttribute(self: *Initializer, attributeName: [:0]const u8, arg: i32) Initializer { if (self.last_error) |_| return self.*; Self.setIntAttribute(self.ref, attributeName, arg); return self.*; } pub fn setBoolAttribute(self: *Initializer, attributeName: [:0]const u8, arg: bool) Initializer { if (self.last_error) |_| return self.*; Self.setBoolAttribute(self.ref, attributeName, arg); return self.*; } pub fn setPtrAttribute(self: *Initializer, comptime T: type, attributeName: [:0]const u8, value: ?*T) Initializer { if (self.last_error) |_| return self.*; Self.setPtrAttribute(self.ref, T, attributeName, value); return self.*; } pub fn setHandle(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setHandle(self.ref, arg); return self.*; } pub fn setHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "HANDLENAME", .{}, arg); return self.*; } pub fn setTipBgColor(self: *Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self.*; interop.setRgb(self.ref, "TIPBGCOLOR", .{}, rgb); return self.*; } pub fn setMdiClient(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "MDICLIENT", .{}, arg); return self.*; } pub fn setControl(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "CONTROL", .{}, arg); return self.*; } pub fn setTipIcon(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TIPICON", .{}, arg); return self.*; } pub fn setMenu(self: *Initializer, arg: *iup.Menu) Initializer { if (self.last_error) |_| return self.*; interop.setHandleAttribute(self.ref, "MENU", .{}, arg); return self.*; } pub fn setMenuHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "MENU", .{}, arg); return self.*; } pub fn setNoFlush(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "NOFLUSH", .{}, arg); return self.*; } pub fn setMaxSize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "MAXSIZE", .{}, value); return self.*; } pub fn setOpacityImage(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "OPACITYIMAGE", .{}, arg); return self.*; } pub fn setHelpButton(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "HELPBUTTON", .{}, arg); return self.*; } pub fn setShowNoFocus(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "SHOWNOFOCUS", .{}, arg); return self.*; } pub fn setOpacity(self: *Initializer, arg: i32) Initializer { if (self.last_error) |_| return self.*; interop.setIntAttribute(self.ref, "OPACITY", .{}, arg); return self.*; } pub fn setPosition(self: *Initializer, x: i32, y: i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = iup.XYPos.intIntToString(&buffer, x, y, ','); interop.setStrAttribute(self.ref, "POSITION", .{}, value); return self.*; } pub fn setComposited(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "COMPOSITED", .{}, arg); return self.*; } pub fn setDropFilesTarget(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "DROPFILESTARGET", .{}, arg); return self.*; } pub fn setTip(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TIP", .{}, arg); return self.*; } pub fn setCanFocus(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "CANFOCUS", .{}, arg); return self.*; } pub fn setDragSourceMove(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "DRAGSOURCEMOVE", .{}, arg); return self.*; } pub fn setIcon(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "ICON", .{}, arg); return self.*; } pub fn setVisible(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "VISIBLE", .{}, arg); return self.*; } pub fn setCursor(self: *Initializer, arg: anytype) Initializer { if (self.last_error) |_| return self.*; if (interop.validateHandle(.Image, arg)) { interop.setHandleAttribute(self.ref, "CURSOR", .{}, arg); } else |err| { self.last_error = err; } return self.*; } pub fn setCursorHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "CURSOR", .{}, arg); return self.*; } pub fn setMenuBox(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "MENUBOX", .{}, arg); return self.*; } /// /// DIALOGTYPE: Type of dialog defines which icon will be displayed besides the /// message text. /// Can have values: "MESSAGE" (No Icon), "ERROR" (Stop-sign), "WARNING" /// (Exclamation-point), "QUESTION" (Question-mark) or "INFORMATION" (Letter "i"). /// Default: "MESSAGE". pub fn setDialogType(self: *Initializer, arg: ?DialogType) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| switch (value) { .Error => interop.setStrAttribute(self.ref, "DIALOGTYPE", .{}, "ERROR"), .Warning => interop.setStrAttribute(self.ref, "DIALOGTYPE", .{}, "WARNING"), .Information => interop.setStrAttribute(self.ref, "DIALOGTYPE", .{}, "INFORMATION"), .Question => interop.setStrAttribute(self.ref, "DIALOGTYPE", .{}, "QUESTION"), } else { interop.clearAttribute(self.ref, "DIALOGTYPE", .{}); } return self.*; } pub fn zOrder(self: *Initializer, arg: ?ZOrder) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| switch (value) { .Top => interop.setStrAttribute(self.ref, "ZORDER", .{}, "TOP"), .Bottom => interop.setStrAttribute(self.ref, "ZORDER", .{}, "BOTTOM"), } else { interop.clearAttribute(self.ref, "ZORDER", .{}); } return self.*; } pub fn setHideTitleBar(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "HIDETITLEBAR", .{}, arg); return self.*; } pub fn setMaxBox(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "MAXBOX", .{}, arg); return self.*; } pub fn setDragDrop(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "DRAGDROP", .{}, arg); return self.*; } pub fn setDialogHint(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "DIALOGHINT", .{}, arg); return self.*; } pub fn setDialogFrame(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "DIALOGFRAME", .{}, arg); return self.*; } pub fn setNActive(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "NACTIVE", .{}, arg); return self.*; } pub fn setTheme(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "THEME", .{}, arg); return self.*; } pub fn setSaveUnder(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "SAVEUNDER", .{}, arg); return self.*; } pub fn setTray(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "TRAY", .{}, arg); return self.*; } /// /// BUTTONS: Buttons configuration. /// Can have values: "OK", "OKCANCEL", "RETRYCANCEL", "YESNO", or "YESNOCANCEL". /// Default: "OK". /// Additionally the "Help" button is displayed if the HELP_CB callback is defined. /// (RETRYCANCEL and YESNOCANCEL since 3.16) pub fn setButtons(self: *Initializer, arg: ?Buttons) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| switch (value) { .OkCanCel => interop.setStrAttribute(self.ref, "BUTTONS", .{}, "OKCANCEL"), .RetrYCanCel => interop.setStrAttribute(self.ref, "BUTTONS", .{}, "RETRYCANCEL"), .YesNo => interop.setStrAttribute(self.ref, "BUTTONS", .{}, "YESNO"), .YesNoCanCel => interop.setStrAttribute(self.ref, "BUTTONS", .{}, "YESNOCANCEL"), .Ok => interop.setStrAttribute(self.ref, "BUTTONS", .{}, "OK"), } else { interop.clearAttribute(self.ref, "BUTTONS", .{}); } return self.*; } pub fn setChildOffset(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "CHILDOFFSET", .{}, value); return self.*; } pub fn setExpand(self: *Initializer, arg: ?Expand) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self.ref, "EXPAND", .{}, "YES"), .Horizontal => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTAL"), .Vertical => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICAL"), .HorizontalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTALFREE"), .VerticalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICALFREE"), .No => interop.setStrAttribute(self.ref, "EXPAND", .{}, "NO"), } else { interop.clearAttribute(self.ref, "EXPAND", .{}); } return self.*; } pub fn setSize(self: *Initializer, width: ?iup.ScreenSize, height: ?iup.ScreenSize) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var str = iup.DialogSize.screenSizeToString(&buffer, width, height); interop.setStrAttribute(self.ref, "SIZE", .{}, str); return self.*; } pub fn setTipMarkup(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TIPMARKUP", .{}, arg); return self.*; } /// /// BUTTONRESPONSE: Number of the pressed button. /// Can be "1", "2" or "3". /// Default: "1". pub fn setButtonResponse(self: *Initializer, arg: ?ButtonResponse) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| { interop.setIntAttribute(self.ref, "BUTTONRESPONSE", .{}, @enumToInt(value)); } else { interop.clearAttribute(self.ref, "BUTTONRESPONSE", .{}); } return self.*; } pub fn setMdiMenu(self: *Initializer, arg: *iup.Menu) Initializer { if (self.last_error) |_| return self.*; interop.setHandleAttribute(self.ref, "MDIMENU", .{}, arg); return self.*; } pub fn setMdiMenuHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "MDIMENU", .{}, arg); return self.*; } pub fn setStartFocus(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "STARTFOCUS", .{}, arg); return self.*; } pub fn setFontSize(self: *Initializer, arg: i32) Initializer { if (self.last_error) |_| return self.*; interop.setIntAttribute(self.ref, "FONTSIZE", .{}, arg); return self.*; } pub fn setDropTypes(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "DROPTYPES", .{}, arg); return self.*; } pub fn setTrayTipMarkup(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TRAYTIPMARKUP", .{}, arg); return self.*; } pub fn setUserSize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "USERSIZE", .{}, value); return self.*; } pub fn setTipDelay(self: *Initializer, arg: i32) Initializer { if (self.last_error) |_| return self.*; interop.setIntAttribute(self.ref, "TIPDELAY", .{}, arg); return self.*; } pub fn setCustomFrame(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "CUSTOMFRAME", .{}, arg); return self.*; } /// /// TITLE: Dialog title. pub fn setTitle(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TITLE", .{}, arg); return self.*; } pub fn setDefaultEsc(self: *Initializer, arg: *iup.Button) Initializer { if (self.last_error) |_| return self.*; interop.setHandleAttribute(self.ref, "DEFAULTESC", .{}, arg); return self.*; } pub fn setDefaultEscHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "DEFAULTESC", .{}, arg); return self.*; } pub fn setPlacement(self: *Initializer, arg: ?Placement) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| switch (value) { .Maximized => interop.setStrAttribute(self.ref, "PLACEMENT", .{}, "MAXIMIZED"), .Minimized => interop.setStrAttribute(self.ref, "PLACEMENT", .{}, "MINIMIZED"), .Full => interop.setStrAttribute(self.ref, "PLACEMENT", .{}, "FULL"), } else { interop.clearAttribute(self.ref, "PLACEMENT", .{}); } return self.*; } pub fn setPropagateFocus(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "PROPAGATEFOCUS", .{}, arg); return self.*; } pub fn setBgColor(self: *Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self.*; interop.setRgb(self.ref, "BGCOLOR", .{}, rgb); return self.*; } pub fn setDropTarget(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "DROPTARGET", .{}, arg); return self.*; } pub fn setDragSource(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "DRAGSOURCE", .{}, arg); return self.*; } /// /// BUTTONDEFAULT: Number of the default button. /// Can be "1", "2" or "3". /// "2" is valid only for "RETRYCANCEL", "OKCANCEL" and "YESNO" button configurations. /// "3" is valid only for "YESNOCANCEL". /// Default: "1". pub fn setButtonDefault(self: *Initializer, arg: ?ButtonDefault) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| { interop.setIntAttribute(self.ref, "BUTTONDEFAULT", .{}, @enumToInt(value)); } else { interop.clearAttribute(self.ref, "BUTTONDEFAULT", .{}); } return self.*; } pub fn setResize(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "RESIZE", .{}, arg); return self.*; } pub fn setFloating(self: *Initializer, arg: ?Floating) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self.ref, "FLOATING", .{}, "YES"), .Ignore => interop.setStrAttribute(self.ref, "FLOATING", .{}, "IGNORE"), .No => interop.setStrAttribute(self.ref, "FLOATING", .{}, "NO"), } else { interop.clearAttribute(self.ref, "FLOATING", .{}); } return self.*; } pub fn setNormalizerGroup(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "NORMALIZERGROUP", .{}, arg); return self.*; } pub fn setRasterSize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "RASTERSIZE", .{}, value); return self.*; } pub fn setShapeImage(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "SHAPEIMAGE", .{}, arg); return self.*; } pub fn setTipFgColor(self: *Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self.*; interop.setRgb(self.ref, "TIPFGCOLOR", .{}, rgb); return self.*; } pub fn setFontFace(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "FONTFACE", .{}, arg); return self.*; } pub fn topMost(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "TOPMOST", .{}, arg); return self.*; } pub fn setName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "NAME", .{}, arg); return self.*; } pub fn setMinBox(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "MINBOX", .{}, arg); return self.*; } pub fn setDefaultEnter(self: *Initializer, arg: *iup.Button) Initializer { if (self.last_error) |_| return self.*; interop.setHandleAttribute(self.ref, "DEFAULTENTER", .{}, arg); return self.*; } pub fn setDefaultEnterHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "DEFAULTENTER", .{}, arg); return self.*; } /// /// PARENTDIALOG (creation only): Name of a dialog to be used as parent. /// This dialog will be always in front of the parent dialog. /// If not defined in Motif the dialog could not be modal. /// In Windows, if PARENTDIALOG is specified then it will be modal relative /// only to its parent. pub fn setParentDialog(self: *Initializer, arg: anytype) Initializer { if (self.last_error) |_| return self.*; if (interop.validateHandle(.Dialog, arg)) { interop.setHandleAttribute(self.ref, "PARENTDIALOG", .{}, arg); } else |err| { self.last_error = err; } return self.*; } pub fn setParentDialogHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "PARENTDIALOG", .{}, arg); return self.*; } pub fn setBackground(self: *Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self.*; interop.setRgb(self.ref, "BACKGROUND", .{}, rgb); return self.*; } pub fn setHideTaskbar(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "HIDETASKBAR", .{}, arg); return self.*; } /// /// VALUE: Message text. pub fn setValue(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "VALUE", .{}, arg); return self.*; } pub fn setBringFront(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "BRINGFRONT", .{}, arg); return self.*; } pub fn setTrayImage(self: *Initializer, arg: anytype) Initializer { if (self.last_error) |_| return self.*; if (interop.validateHandle(.Image, arg)) { interop.setHandleAttribute(self.ref, "TRAYIMAGE", .{}, arg); } else |err| { self.last_error = err; } return self.*; } pub fn setTrayImageHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TRAYIMAGE", .{}, arg); return self.*; } pub fn setActive(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "ACTIVE", .{}, arg); return self.*; } pub fn setTipVisible(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "TIPVISIBLE", .{}, arg); return self.*; } pub fn setExpandWeight(self: *Initializer, arg: f64) Initializer { if (self.last_error) |_| return self.*; interop.setDoubleAttribute(self.ref, "EXPANDWEIGHT", .{}, arg); return self.*; } pub fn setMinSize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "MINSIZE", .{}, value); return self.*; } pub fn setNTheme(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "NTHEME", .{}, arg); return self.*; } pub fn setBorder(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "BORDER", .{}, arg); return self.*; } pub fn setCustomFramesImulate(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "CUSTOMFRAMESIMULATE", .{}, arg); return self.*; } pub fn setShrink(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "SHRINK", .{}, arg); return self.*; } pub fn setClientSize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "CLIENTSIZE", .{}, value); return self.*; } pub fn setTrayTip(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TRAYTIP", .{}, arg); return self.*; } pub fn setDragTypes(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "DRAGTYPES", .{}, arg); return self.*; } pub fn setToolBox(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "TOOLBOX", .{}, arg); return self.*; } pub fn setMdiFrame(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "MDIFRAME", .{}, arg); return self.*; } pub fn setFontStyle(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "FONTSTYLE", .{}, arg); return self.*; } pub fn setMdiChild(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "MDICHILD", .{}, arg); return self.*; } pub fn fullScreen(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "FULLSCREEN", .{}, arg); return self.*; } pub fn setNativeParent(self: *Initializer, arg: anytype) !Initializer { if (self.last_error) |_| return self.*; interop.setHandleAttribute(self.ref, "NATIVEPARENT", .{}, arg); return self.*; } pub fn setNativeParentHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "NATIVEPARENT", .{}, arg); return self.*; } pub fn setFont(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "FONT", .{}, arg); return self.*; } pub fn simulateModal(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "SIMULATEMODAL", .{}, arg); return self.*; } /// /// TABIMAGEn (non inheritable): image name to be used in the respective tab. /// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name. /// n starts at 0. /// See also IupImage. /// In Motif, the image is shown only if TABTITLEn is NULL. /// In Windows and Motif set the BGCOLOR attribute before setting the image. /// When set after map will update the TABIMAGE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabImage(self: *Initializer, index: i32, arg: anytype) Initializer { if (self.last_error) |_| return self.*; if (interop.validateHandle(.Image, arg)) { interop.setHandleAttribute(self.ref, "TABIMAGE", .{index}, arg); } else |err| { self.last_error = err; } return self.*; } pub fn setTabImageHandleName(self: *Initializer, index: i32, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TABIMAGE", .{index}, arg); return self.*; } /// /// TABTITLEn (non inheritable): Contains the text to be shown in the /// respective tab title. /// n starts at 0. /// If this value is NULL, it will remain empty. /// The "&" character can be used to define a mnemonic, the next character will /// be used as key. /// Use "&&" to show the "&" character instead on defining a mnemonic. /// The button can be activated from any control in the dialog using the /// "Alt+key" combination. /// (mnemonic support since 3.3). /// When set after map will update the TABTITLE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabTitle(self: *Initializer, index: i32, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TABTITLE", .{index}, arg); return self.*; } pub fn setFocusCallback(self: *Initializer, callback: ?OnFocusFn) Initializer { const Handler = CallbackHandler(Self, OnFocusFn, "FOCUS_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// K_ANY K_ANY Action generated when a keyboard event occurs. /// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) -> /// (ret: number) [in Lua] ih: identifier of the element that activated the event. /// c: identifier of typed key. /// Please refer to the Keyboard Codes table for a list of possible values. /// Returns: If IUP_IGNORE is returned the key is ignored and not processed by /// the control and not propagated. /// If returns IUP_CONTINUE, the key will be processed and the event will be /// propagated to the parent of the element receiving it, this is the default behavior. /// If returns IUP_DEFAULT the key is processed but it is not propagated. /// IUP_CLOSE will be processed. /// Notes Keyboard callbacks depend on the keyboard usage of the control with /// the focus. /// So if you return IUP_IGNORE the control will usually not process the key. /// But be aware that sometimes the control process the key in another event so /// even returning IUP_IGNORE the key can get processed. /// Although it will not be propagated. /// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on /// the IUP_CONTINUE return value to work while the control is in focus. /// If the callback does not exists it is automatically propagated to the /// parent of the element. /// K_* callbacks All defined keys are also callbacks of any element, called /// when the respective key is activated. /// For example: "K_cC" is also a callback activated when the user press /// Ctrl+C, when the focus is at the element or at a children with focus. /// This is the way an application can create shortcut keys, also called hot keys. /// These callbacks are not available in IupLua. /// Affects All elements with keyboard interaction. pub fn setKAnyCallback(self: *Initializer, callback: ?OnKAnyFn) Initializer { const Handler = CallbackHandler(Self, OnKAnyFn, "K_ANY"); Handler.setCallback(self.ref, callback); return self.*; } /// /// HELP_CB HELP_CB Action generated when the user press F1 at a control. /// In Motif is also activated by the Help button in some workstations keyboard. /// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Returns: IUP_CLOSE will be processed. /// Affects All elements with user interaction. pub fn setHelpCallback(self: *Initializer, callback: ?OnHelpFn) Initializer { const Handler = CallbackHandler(Self, OnHelpFn, "HELP_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// CLOSE_CB CLOSE_CB Called just before a dialog is closed when the user /// clicks the close button of the title bar or an equivalent action. /// Callback int function(Ihandle *ih); [in C] ih:close_cb() -> (ret: number) /// [in Lua] ih: identifies the element that activated the event. /// Returns: if IUP_IGNORE, it prevents the dialog from being closed. /// If you destroy the dialog in this callback, you must return IUP_IGNORE. /// IUP_CLOSE will be processed. /// Affects IupDialog pub fn setCloseCallback(self: *Initializer, callback: ?OnCloseFn) Initializer { const Handler = CallbackHandler(Self, OnCloseFn, "CLOSE_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setDropMotionCallback(self: *Initializer, callback: ?OnDropMotionFn) Initializer { const Handler = CallbackHandler(Self, OnDropMotionFn, "DROPMOTION_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setDragEndCallback(self: *Initializer, callback: ?OnDragEndFn) Initializer { const Handler = CallbackHandler(Self, OnDragEndFn, "DRAGEND_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setDragBeginCallback(self: *Initializer, callback: ?OnDragBeginFn) Initializer { const Handler = CallbackHandler(Self, OnDragBeginFn, "DRAGBEGIN_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// MAP_CB MAP_CB Called right after an element is mapped and its attributes /// updated in IupMap. /// When the element is a dialog, it is called after the layout is updated. /// For all other elements is called before the layout is updated, so the /// element current size will still be 0x0 during MAP_CB (since 3.14). /// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setMapCallback(self: *Initializer, callback: ?OnMapFn) Initializer { const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also LEAVEWINDOW_CB pub fn setEnterWindowCallback(self: *Initializer, callback: ?OnEnterWindowFn) Initializer { const Handler = CallbackHandler(Self, OnEnterWindowFn, "ENTERWINDOW_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// DESTROY_CB DESTROY_CB Called right before an element is destroyed. /// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Notes If the dialog is visible then it is hidden before it is destroyed. /// The callback will be called right after it is hidden. /// The callback will be called before all other destroy procedures. /// For instance, if the element has children then it is called before the /// children are destroyed. /// For language binding implementations use the callback name "LDESTROY_CB" to /// release memory allocated by the binding for the element. /// Also the callback will be called before the language callback. /// Affects All. pub fn setDestroyCallback(self: *Initializer, callback: ?OnDestroyFn) Initializer { const Handler = CallbackHandler(Self, OnDestroyFn, "DESTROY_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setDropDataCallback(self: *Initializer, callback: ?OnDropDataFn) Initializer { const Handler = CallbackHandler(Self, OnDropDataFn, "DROPDATA_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus. /// This callback is called before the GETFOCUS_CB of the element that gets the focus. /// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Affects All elements with user interaction, except menus. /// In Windows, there are restrictions when using this callback. /// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any /// function calls that display or activate a window. /// This causes the thread to yield control and can cause the application to /// stop responding to messages. /// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus pub fn setKillFocusCallback(self: *Initializer, callback: ?OnKillFocusFn) Initializer { const Handler = CallbackHandler(Self, OnKillFocusFn, "KILLFOCUS_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setDragDataCallback(self: *Initializer, callback: ?OnDragDataFn) Initializer { const Handler = CallbackHandler(Self, OnDragDataFn, "DRAGDATA_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setDragDataSizeCallback(self: *Initializer, callback: ?OnDragDataSizeFn) Initializer { const Handler = CallbackHandler(Self, OnDragDataSizeFn, "DRAGDATASIZE_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// SHOW_CB SHOW_CB Called right after the dialog is showed, hidden, maximized, /// minimized or restored from minimized/maximized. /// This callback is called when those actions were performed by the user or /// programmatically by the application. /// Callback int function(Ihandle *ih, int state); [in C] ih:show_cb(state: /// number) -> (ret: number) [in Lua] ih: identifier of the element that /// activated the event. /// state: indicates which of the following situations generated the event: /// IUP_HIDE (since 3.0) IUP_SHOW IUP_RESTORE (was minimized or maximized) /// IUP_MINIMIZE IUP_MAXIMIZE (since 3.0) (not received in Motif when activated /// from the maximize button) Returns: IUP_CLOSE will be processed. /// Affects IupDialog pub fn setShowCallback(self: *Initializer, callback: ?OnShowFn) Initializer { const Handler = CallbackHandler(Self, OnShowFn, "SHOW_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control. /// When several files are dropped at once, the callback is called several /// times, once for each file. /// If defined after the element is mapped then the attribute DROPFILESTARGET /// must be set to YES. /// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const /// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename: /// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the /// element that activated the event. /// filename: Name of the dropped file. /// num: Number index of the dropped file. /// If several files are dropped, num is the index of the dropped file starting /// from "total-1" to "0". /// x: X coordinate of the point where the user released the mouse button. /// y: Y coordinate of the point where the user released the mouse button. /// Returns: If IUP_IGNORE is returned the callback will NOT be called for the /// next dropped files, and the processing of dropped files will be interrupted. /// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList pub fn setDropFilesCallback(self: *Initializer, callback: ?OnDropFilesFn) Initializer { const Handler = CallbackHandler(Self, OnDropFilesFn, "DROPFILES_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// RESIZE_CB RESIZE_CB Action generated when the canvas or dialog size is changed. /// Callback int function(Ihandle *ih, int width, int height); [in C] /// ih:resize_cb(width, height: number) -> (ret: number) [in Lua] ih: /// identifier of the element that activated the event. /// width: the width of the internal element size in pixels not considering the /// decorations (client size) height: the height of the internal element size /// in pixels not considering the decorations (client size) Notes For the /// dialog, this action is also generated when the dialog is mapped, after the /// map and before the show. /// When XAUTOHIDE=Yes or YAUTOHIDE=Yes, if the canvas scrollbar is /// hidden/shown after changing the DX or DY attributes from inside the /// callback, the size of the drawing area will immediately change, so the /// parameters with and height will be invalid. /// To update the parameters consult the DRAWSIZE attribute. /// Also activate the drawing toolkit only after updating the DX or DY attributes. /// Affects IupCanvas, IupGLCanvas, IupDialog pub fn setResizeCallback(self: *Initializer, callback: ?OnResizeFn) Initializer { const Handler = CallbackHandler(Self, OnResizeFn, "RESIZE_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// UNMAP_CB UNMAP_CB Called right before an element is unmapped. /// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setUnmapCallback(self: *Initializer, callback: ?OnUnmapFn) Initializer { const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setTrayClickCallback(self: *Initializer, callback: ?OnTrayClickFn) Initializer { const Handler = CallbackHandler(Self, OnTrayClickFn, "TRAYCLICK_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus. /// This callback is called after the KILLFOCUS_CB of the element that loosed /// the focus. /// The IupGetFocus function during the callback returns the element that /// loosed the focus. /// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that received keyboard focus. /// Affects All elements with user interaction, except menus. /// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus pub fn setGetFocusCallback(self: *Initializer, callback: ?OnGetFocusFn) Initializer { const Handler = CallbackHandler(Self, OnGetFocusFn, "GETFOCUS_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setLDestroyCallback(self: *Initializer, callback: ?OnLDestroyFn) Initializer { const Handler = CallbackHandler(Self, OnLDestroyFn, "LDESTROY_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also ENTERWINDOW_CB pub fn setLeaveWindowCallback(self: *Initializer, callback: ?OnLeaveWindowFn) Initializer { const Handler = CallbackHandler(Self, OnLeaveWindowFn, "LEAVEWINDOW_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setPostMessageCallback(self: *Initializer, callback: ?OnPostMessageFn) Initializer { const Handler = CallbackHandler(Self, OnPostMessageFn, "POSTMESSAGE_CB"); Handler.setCallback(self.ref, callback); return self.*; } }; pub fn setStrAttribute(self: *Self, attribute: [:0]const u8, arg: [:0]const u8) void { interop.setStrAttribute(self, attribute, .{}, arg); } pub fn getStrAttribute(self: *Self, attribute: [:0]const u8) [:0]const u8 { return interop.getStrAttribute(self, attribute, .{}); } pub fn setIntAttribute(self: *Self, attribute: [:0]const u8, arg: i32) void { interop.setIntAttribute(self, attribute, .{}, arg); } pub fn getIntAttribute(self: *Self, attribute: [:0]const u8) i32 { return interop.getIntAttribute(self, attribute, .{}); } pub fn setBoolAttribute(self: *Self, attribute: [:0]const u8, arg: bool) void { interop.setBoolAttribute(self, attribute, .{}, arg); } pub fn getBoolAttribute(self: *Self, attribute: [:0]const u8) bool { return interop.getBoolAttribute(self, attribute, .{}); } pub fn getPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8) ?*T { return interop.getPtrAttribute(T, self, attribute, .{}); } pub fn setPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8, value: ?*T) void { interop.setPtrAttribute(T, self, attribute, .{}, value); } pub fn setHandle(self: *Self, arg: [:0]const u8) void { interop.setHandle(self, arg); } pub fn fromHandleName(handle_name: [:0]const u8) ?*Self { return interop.fromHandleName(Self, handle_name); } /// /// Creates an interface element given its class name and parameters. /// After creation the element still needs to be attached to a container and mapped to the native system so it can be visible. pub fn init() Initializer { var handle = interop.create(Self); if (handle) |valid| { return .{ .ref = @ptrCast(*Self, valid), }; } else { return .{ .ref = undefined, .last_error = Error.NotInitialized }; } } /// /// Displays a dialog in the current position, or changes a control VISIBLE attribute. /// For dialogs it is equivalent to call IupShowXY using IUP_CURRENT. See IupShowXY for more details. /// For other controls, to call IupShow is the same as setting VISIBLE=YES. pub fn show(self: *Self) !void { try interop.show(self); } /// /// Hides an interface element. This function has the same effect as attributing value "NO" to the interface element’s VISIBLE attribute. /// Once a dialog is hidden, either by means of IupHide or by changing the VISIBLE attribute or by means of a click in the window close button, the elements inside this dialog are not destroyed, so that you can show the dialog again. To destroy dialogs, the IupDestroy function must be called. pub fn hide(self: *Self) void { interop.hide(self); } /// /// Destroys an interface element and all its children. /// Only dialogs, timers, popup menus and images should be normally destroyed, but detached elements can also be destroyed. pub fn deinit(self: *Self) void { interop.destroy(self); } /// /// Creates (maps) the native interface objects corresponding to the given IUP interface elements. /// It will also called recursively to create the native element of all the children in the element's tree. /// The element must be already attached to a mapped container, except the dialog. A child can only be mapped if its parent is already mapped. /// This function is automatically called before the dialog is shown in IupShow, IupShowXY or IupPopup. /// If the element is a dialog then the abstract layout will be updated even if the dialog is already mapped. If the dialog is visible the elements will be immediately repositioned. Calling IupMap for an already mapped dialog is the same as only calling IupRefresh for the dialog. /// Calling IupMap for an already mapped element that is not a dialog does nothing. /// If you add new elements to an already mapped dialog you must call IupMap for that elements. And then call IupRefresh to update the dialog layout. /// If the WID attribute of an element is NULL, it means the element was not already mapped. Some containers do not have a native element associated, like VBOX and HBOX. In this case their WID is a fake value (void*)(-1). /// It is useful for the application to call IupMap when the value of the WID attribute must be known, i.e. the native element must exist, before a dialog is made visible. /// The MAP_CB callback is called at the end of the IupMap function, after all processing, so it can also be used to create other things that depend on the WID attribute. But notice that for non dialog elements it will be called before the dialog layout has been updated, so the element current size will still be 0x0 (since 3.14). pub fn map(self: *Self) !void { try interop.map(self); } pub fn popup(self: *Self, x: iup.DialogPosX, y: iup.DialogPosY) !void { try interop.popup(self, x, y); } pub fn showXY(self: *Self, x: iup.DialogPosX, y: iup.DialogPosY) !void { try interop.showXY(self, x, y); } pub fn alert(parent: *iup.Dialog, title: ?[:0]const u8, message: [:0]const u8) !void { try Impl(Self).messageDialogAlert(parent, title, message); } pub fn confirm(parent: *iup.Dialog, title: ?[:0]const u8, message: [:0]const u8) !bool { return try Impl(Self).messageDialogAlertConfirm(parent, title, message); } /// /// Returns the the child element that has the NAME attribute equals to the given value on the same dialog hierarchy. /// Works also for children of a menu that is associated with a dialog. pub fn getDialogChild(self: *Self, byName: [:0]const u8) ?Element { return interop.getDialogChild(self, byName); } /// /// Updates the size and layout of all controls in the same dialog. /// To be used after changing size attributes, or attributes that affect the size of the control. Can be used for any element inside a dialog, but the layout of the dialog and all controls will be updated. It can change the layout of all the controls inside the dialog because of the dynamic layout positioning. pub fn refresh(self: *Self) void { Impl(Self).refresh(self); } pub fn getHandleName(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "HANDLENAME", .{}); } pub fn setHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "HANDLENAME", .{}, arg); } pub fn getTipBgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "TIPBGCOLOR", .{}); } pub fn setTipBgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "TIPBGCOLOR", .{}, rgb); } pub fn getMdiClient(self: *Self) bool { return interop.getBoolAttribute(self, "MDICLIENT", .{}); } pub fn setMdiClient(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "MDICLIENT", .{}, arg); } pub fn getControl(self: *Self) bool { return interop.getBoolAttribute(self, "CONTROL", .{}); } pub fn setControl(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "CONTROL", .{}, arg); } pub fn getTipIcon(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TIPICON", .{}); } pub fn setTipIcon(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TIPICON", .{}, arg); } pub fn getMenu(self: *Self) ?*iup.Menu { if (interop.getHandleAttribute(self, "MENU", .{})) |handle| { return @ptrCast(*iup.Menu, handle); } else { return null; } } pub fn setMenu(self: *Self, arg: *iup.Menu) void { interop.setHandleAttribute(self, "MENU", .{}, arg); } pub fn setMenuHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "MENU", .{}, arg); } pub fn getNoFlush(self: *Self) bool { return interop.getBoolAttribute(self, "NOFLUSH", .{}); } pub fn setNoFlush(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "NOFLUSH", .{}, arg); } pub fn getMaxSize(self: *Self) Size { var str = interop.getStrAttribute(self, "MAXSIZE", .{}); return Size.parse(str); } pub fn setMaxSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "MAXSIZE", .{}, value); } pub fn getOpacityImage(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "OPACITYIMAGE", .{}); } pub fn setOpacityImage(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "OPACITYIMAGE", .{}, arg); } pub fn getHelpButton(self: *Self) bool { return interop.getBoolAttribute(self, "HELPBUTTON", .{}); } pub fn setHelpButton(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "HELPBUTTON", .{}, arg); } pub fn getShowNoFocus(self: *Self) bool { return interop.getBoolAttribute(self, "SHOWNOFOCUS", .{}); } pub fn setShowNoFocus(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "SHOWNOFOCUS", .{}, arg); } pub fn getScreenPosition(self: *Self) iup.XYPos { var str = interop.getStrAttribute(self, "SCREENPOSITION", .{}); return iup.XYPos.parse(str, ','); } pub fn getOpacity(self: *Self) i32 { return interop.getIntAttribute(self, "OPACITY", .{}); } pub fn setOpacity(self: *Self, arg: i32) void { interop.setIntAttribute(self, "OPACITY", .{}, arg); } pub fn getPosition(self: *Self) iup.XYPos { var str = interop.getStrAttribute(self, "POSITION", .{}); return iup.XYPos.parse(str, ','); } pub fn setPosition(self: *Self, x: i32, y: i32) void { var buffer: [128]u8 = undefined; var value = iup.XYPos.intIntToString(&buffer, x, y, ','); interop.setStrAttribute(self, "POSITION", .{}, value); } pub fn getComposited(self: *Self) bool { return interop.getBoolAttribute(self, "COMPOSITED", .{}); } pub fn setComposited(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "COMPOSITED", .{}, arg); } pub fn getDropFilesTarget(self: *Self) bool { return interop.getBoolAttribute(self, "DROPFILESTARGET", .{}); } pub fn setDropFilesTarget(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DROPFILESTARGET", .{}, arg); } pub fn getBorderSize(self: *Self) i32 { return interop.getIntAttribute(self, "BORDERSIZE", .{}); } pub fn getTip(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TIP", .{}); } pub fn setTip(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TIP", .{}, arg); } pub fn getCanFocus(self: *Self) bool { return interop.getBoolAttribute(self, "CANFOCUS", .{}); } pub fn setCanFocus(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "CANFOCUS", .{}, arg); } pub fn getDragSourceMove(self: *Self) bool { return interop.getBoolAttribute(self, "DRAGSOURCEMOVE", .{}); } pub fn setDragSourceMove(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DRAGSOURCEMOVE", .{}, arg); } pub fn getIcon(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "ICON", .{}); } pub fn setIcon(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "ICON", .{}, arg); } pub fn getVisible(self: *Self) bool { return interop.getBoolAttribute(self, "VISIBLE", .{}); } pub fn setVisible(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "VISIBLE", .{}, arg); } pub fn getCursor(self: *Self) ?iup.Element { if (interop.getHandleAttribute(self, "CURSOR", .{})) |handle| { return iup.Element.fromHandle(handle); } else { return null; } } pub fn setCursor(self: *Self, arg: anytype) !void { try interop.validateHandle(.Image, arg); interop.setHandleAttribute(self, "CURSOR", .{}, arg); } pub fn setCursorHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "CURSOR", .{}, arg); } pub fn getMenuBox(self: *Self) bool { return interop.getBoolAttribute(self, "MENUBOX", .{}); } pub fn setMenuBox(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "MENUBOX", .{}, arg); } /// /// DIALOGTYPE: Type of dialog defines which icon will be displayed besides the /// message text. /// Can have values: "MESSAGE" (No Icon), "ERROR" (Stop-sign), "WARNING" /// (Exclamation-point), "QUESTION" (Question-mark) or "INFORMATION" (Letter "i"). /// Default: "MESSAGE". pub fn getDialogType(self: *Self) ?DialogType { var ret = interop.getStrAttribute(self, "DIALOGTYPE", .{}); if (std.ascii.eqlIgnoreCase("ERROR", ret)) return .Error; if (std.ascii.eqlIgnoreCase("WARNING", ret)) return .Warning; if (std.ascii.eqlIgnoreCase("INFORMATION", ret)) return .Information; if (std.ascii.eqlIgnoreCase("QUESTION", ret)) return .Question; return null; } /// /// DIALOGTYPE: Type of dialog defines which icon will be displayed besides the /// message text. /// Can have values: "MESSAGE" (No Icon), "ERROR" (Stop-sign), "WARNING" /// (Exclamation-point), "QUESTION" (Question-mark) or "INFORMATION" (Letter "i"). /// Default: "MESSAGE". pub fn setDialogType(self: *Self, arg: ?DialogType) void { if (arg) |value| switch (value) { .Error => interop.setStrAttribute(self, "DIALOGTYPE", .{}, "ERROR"), .Warning => interop.setStrAttribute(self, "DIALOGTYPE", .{}, "WARNING"), .Information => interop.setStrAttribute(self, "DIALOGTYPE", .{}, "INFORMATION"), .Question => interop.setStrAttribute(self, "DIALOGTYPE", .{}, "QUESTION"), } else { interop.clearAttribute(self, "DIALOGTYPE", .{}); } } pub fn zOrder(self: *Self, arg: ?ZOrder) void { if (arg) |value| switch (value) { .Top => interop.setStrAttribute(self, "ZORDER", .{}, "TOP"), .Bottom => interop.setStrAttribute(self, "ZORDER", .{}, "BOTTOM"), } else { interop.clearAttribute(self, "ZORDER", .{}); } } pub fn getX(self: *Self) i32 { return interop.getIntAttribute(self, "X", .{}); } pub fn getY(self: *Self) i32 { return interop.getIntAttribute(self, "Y", .{}); } pub fn getHideTitleBar(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "HIDETITLEBAR", .{}); } pub fn setHideTitleBar(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "HIDETITLEBAR", .{}, arg); } pub fn getMaxBox(self: *Self) bool { return interop.getBoolAttribute(self, "MAXBOX", .{}); } pub fn setMaxBox(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "MAXBOX", .{}, arg); } pub fn getDragDrop(self: *Self) bool { return interop.getBoolAttribute(self, "DRAGDROP", .{}); } pub fn setDragDrop(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DRAGDROP", .{}, arg); } pub fn getDialogHint(self: *Self) bool { return interop.getBoolAttribute(self, "DIALOGHINT", .{}); } pub fn setDialogHint(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DIALOGHINT", .{}, arg); } pub fn getDialogFrame(self: *Self) bool { return interop.getBoolAttribute(self, "DIALOGFRAME", .{}); } pub fn setDialogFrame(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DIALOGFRAME", .{}, arg); } pub fn getNActive(self: *Self) bool { return interop.getBoolAttribute(self, "NACTIVE", .{}); } pub fn setNActive(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "NACTIVE", .{}, arg); } pub fn getTheme(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "THEME", .{}); } pub fn setTheme(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "THEME", .{}, arg); } pub fn getSaveUnder(self: *Self) bool { return interop.getBoolAttribute(self, "SAVEUNDER", .{}); } pub fn setSaveUnder(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "SAVEUNDER", .{}, arg); } pub fn getTray(self: *Self) bool { return interop.getBoolAttribute(self, "TRAY", .{}); } pub fn setTray(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "TRAY", .{}, arg); } /// /// BUTTONS: Buttons configuration. /// Can have values: "OK", "OKCANCEL", "RETRYCANCEL", "YESNO", or "YESNOCANCEL". /// Default: "OK". /// Additionally the "Help" button is displayed if the HELP_CB callback is defined. /// (RETRYCANCEL and YESNOCANCEL since 3.16) pub fn getButtons(self: *Self) ?Buttons { var ret = interop.getStrAttribute(self, "BUTTONS", .{}); if (std.ascii.eqlIgnoreCase("OKCANCEL", ret)) return .OkCanCel; if (std.ascii.eqlIgnoreCase("RETRYCANCEL", ret)) return .RetrYCanCel; if (std.ascii.eqlIgnoreCase("YESNO", ret)) return .YesNo; if (std.ascii.eqlIgnoreCase("YESNOCANCEL", ret)) return .YesNoCanCel; if (std.ascii.eqlIgnoreCase("OK", ret)) return .Ok; return null; } /// /// BUTTONS: Buttons configuration. /// Can have values: "OK", "OKCANCEL", "RETRYCANCEL", "YESNO", or "YESNOCANCEL". /// Default: "OK". /// Additionally the "Help" button is displayed if the HELP_CB callback is defined. /// (RETRYCANCEL and YESNOCANCEL since 3.16) pub fn setButtons(self: *Self, arg: ?Buttons) void { if (arg) |value| switch (value) { .OkCanCel => interop.setStrAttribute(self, "BUTTONS", .{}, "OKCANCEL"), .RetrYCanCel => interop.setStrAttribute(self, "BUTTONS", .{}, "RETRYCANCEL"), .YesNo => interop.setStrAttribute(self, "BUTTONS", .{}, "YESNO"), .YesNoCanCel => interop.setStrAttribute(self, "BUTTONS", .{}, "YESNOCANCEL"), .Ok => interop.setStrAttribute(self, "BUTTONS", .{}, "OK"), } else { interop.clearAttribute(self, "BUTTONS", .{}); } } pub fn getChildOffset(self: *Self) Size { var str = interop.getStrAttribute(self, "CHILDOFFSET", .{}); return Size.parse(str); } pub fn setChildOffset(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "CHILDOFFSET", .{}, value); } pub fn getExpand(self: *Self) ?Expand { var ret = interop.getStrAttribute(self, "EXPAND", .{}); if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes; if (std.ascii.eqlIgnoreCase("HORIZONTAL", ret)) return .Horizontal; if (std.ascii.eqlIgnoreCase("VERTICAL", ret)) return .Vertical; if (std.ascii.eqlIgnoreCase("HORIZONTALFREE", ret)) return .HorizontalFree; if (std.ascii.eqlIgnoreCase("VERTICALFREE", ret)) return .VerticalFree; if (std.ascii.eqlIgnoreCase("NO", ret)) return .No; return null; } pub fn setExpand(self: *Self, arg: ?Expand) void { if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self, "EXPAND", .{}, "YES"), .Horizontal => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTAL"), .Vertical => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICAL"), .HorizontalFree => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTALFREE"), .VerticalFree => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICALFREE"), .No => interop.setStrAttribute(self, "EXPAND", .{}, "NO"), } else { interop.clearAttribute(self, "EXPAND", .{}); } } pub fn getSize(self: *Self) iup.DialogSize { var str = interop.getStrAttribute(self, "SIZE", .{}); return iup.DialogSize.parse(str); } pub fn setSize(self: *Self, width: ?iup.ScreenSize, height: ?iup.ScreenSize) void { var buffer: [128]u8 = undefined; var str = iup.DialogSize.screenSizeToString(&buffer, width, height); interop.setStrAttribute(self, "SIZE", .{}, str); } pub fn getWId(self: *Self) i32 { return interop.getIntAttribute(self, "WID", .{}); } pub fn getTipMarkup(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TIPMARKUP", .{}); } pub fn setTipMarkup(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TIPMARKUP", .{}, arg); } /// /// BUTTONRESPONSE: Number of the pressed button. /// Can be "1", "2" or "3". /// Default: "1". pub fn getButtonResponse(self: *Self) ButtonResponse { var ret = interop.getIntAttribute(self, "BUTTONRESPONSE", .{}); return @intToEnum(ButtonResponse, ret); } /// /// BUTTONRESPONSE: Number of the pressed button. /// Can be "1", "2" or "3". /// Default: "1". pub fn setButtonResponse(self: *Self, arg: ?ButtonResponse) void { if (arg) |value| { interop.setIntAttribute(self, "BUTTONRESPONSE", .{}, @enumToInt(value)); } else { interop.clearAttribute(self, "BUTTONRESPONSE", .{}); } } pub fn getMdiMenu(self: *Self) ?*iup.Menu { if (interop.getHandleAttribute(self, "MDIMENU", .{})) |handle| { return @ptrCast(*iup.Menu, handle); } else { return null; } } pub fn setMdiMenu(self: *Self, arg: *iup.Menu) void { interop.setHandleAttribute(self, "MDIMENU", .{}, arg); } pub fn setMdiMenuHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "MDIMENU", .{}, arg); } pub fn getStartFocus(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "STARTFOCUS", .{}); } pub fn setStartFocus(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "STARTFOCUS", .{}, arg); } pub fn getFontSize(self: *Self) i32 { return interop.getIntAttribute(self, "FONTSIZE", .{}); } pub fn setFontSize(self: *Self, arg: i32) void { interop.setIntAttribute(self, "FONTSIZE", .{}, arg); } pub fn getNaturalSize(self: *Self) Size { var str = interop.getStrAttribute(self, "NATURALSIZE", .{}); return Size.parse(str); } pub fn getDropTypes(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "DROPTYPES", .{}); } pub fn setDropTypes(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "DROPTYPES", .{}, arg); } pub fn getTrayTipMarkup(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TRAYTIPMARKUP", .{}); } pub fn setTrayTipMarkup(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TRAYTIPMARKUP", .{}, arg); } pub fn getUserSize(self: *Self) Size { var str = interop.getStrAttribute(self, "USERSIZE", .{}); return Size.parse(str); } pub fn setUserSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "USERSIZE", .{}, value); } pub fn getTipDelay(self: *Self) i32 { return interop.getIntAttribute(self, "TIPDELAY", .{}); } pub fn setTipDelay(self: *Self, arg: i32) void { interop.setIntAttribute(self, "TIPDELAY", .{}, arg); } pub fn getCustomFrame(self: *Self) bool { return interop.getBoolAttribute(self, "CUSTOMFRAME", .{}); } pub fn setCustomFrame(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "CUSTOMFRAME", .{}, arg); } /// /// TITLE: Dialog title. pub fn getTitle(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TITLE", .{}); } /// /// TITLE: Dialog title. pub fn setTitle(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TITLE", .{}, arg); } pub fn getDefaultEsc(self: *Self) ?*iup.Button { if (interop.getHandleAttribute(self, "DEFAULTESC", .{})) |handle| { return @ptrCast(*iup.Button, handle); } else { return null; } } pub fn setDefaultEsc(self: *Self, arg: *iup.Button) void { interop.setHandleAttribute(self, "DEFAULTESC", .{}, arg); } pub fn setDefaultEscHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "DEFAULTESC", .{}, arg); } pub fn getPlacement(self: *Self) ?Placement { var ret = interop.getStrAttribute(self, "PLACEMENT", .{}); if (std.ascii.eqlIgnoreCase("MAXIMIZED", ret)) return .Maximized; if (std.ascii.eqlIgnoreCase("MINIMIZED", ret)) return .Minimized; if (std.ascii.eqlIgnoreCase("FULL", ret)) return .Full; return null; } pub fn setPlacement(self: *Self, arg: ?Placement) void { if (arg) |value| switch (value) { .Maximized => interop.setStrAttribute(self, "PLACEMENT", .{}, "MAXIMIZED"), .Minimized => interop.setStrAttribute(self, "PLACEMENT", .{}, "MINIMIZED"), .Full => interop.setStrAttribute(self, "PLACEMENT", .{}, "FULL"), } else { interop.clearAttribute(self, "PLACEMENT", .{}); } } pub fn getPropagateFocus(self: *Self) bool { return interop.getBoolAttribute(self, "PROPAGATEFOCUS", .{}); } pub fn setPropagateFocus(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "PROPAGATEFOCUS", .{}, arg); } pub fn getBgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "BGCOLOR", .{}); } pub fn setBgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "BGCOLOR", .{}, rgb); } pub fn getDropTarget(self: *Self) bool { return interop.getBoolAttribute(self, "DROPTARGET", .{}); } pub fn setDropTarget(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DROPTARGET", .{}, arg); } pub fn getDragSource(self: *Self) bool { return interop.getBoolAttribute(self, "DRAGSOURCE", .{}); } pub fn setDragSource(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DRAGSOURCE", .{}, arg); } /// /// BUTTONDEFAULT: Number of the default button. /// Can be "1", "2" or "3". /// "2" is valid only for "RETRYCANCEL", "OKCANCEL" and "YESNO" button configurations. /// "3" is valid only for "YESNOCANCEL". /// Default: "1". pub fn getButtonDefault(self: *Self) ButtonDefault { var ret = interop.getIntAttribute(self, "BUTTONDEFAULT", .{}); return @intToEnum(ButtonDefault, ret); } /// /// BUTTONDEFAULT: Number of the default button. /// Can be "1", "2" or "3". /// "2" is valid only for "RETRYCANCEL", "OKCANCEL" and "YESNO" button configurations. /// "3" is valid only for "YESNOCANCEL". /// Default: "1". pub fn setButtonDefault(self: *Self, arg: ?ButtonDefault) void { if (arg) |value| { interop.setIntAttribute(self, "BUTTONDEFAULT", .{}, @enumToInt(value)); } else { interop.clearAttribute(self, "BUTTONDEFAULT", .{}); } } pub fn getResize(self: *Self) bool { return interop.getBoolAttribute(self, "RESIZE", .{}); } pub fn setResize(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "RESIZE", .{}, arg); } pub fn getMaximized(self: *Self) bool { return interop.getBoolAttribute(self, "MAXIMIZED", .{}); } pub fn getFloating(self: *Self) ?Floating { var ret = interop.getStrAttribute(self, "FLOATING", .{}); if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes; if (std.ascii.eqlIgnoreCase("IGNORE", ret)) return .Ignore; if (std.ascii.eqlIgnoreCase("NO", ret)) return .No; return null; } pub fn setFloating(self: *Self, arg: ?Floating) void { if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self, "FLOATING", .{}, "YES"), .Ignore => interop.setStrAttribute(self, "FLOATING", .{}, "IGNORE"), .No => interop.setStrAttribute(self, "FLOATING", .{}, "NO"), } else { interop.clearAttribute(self, "FLOATING", .{}); } } pub fn getNormalizerGroup(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "NORMALIZERGROUP", .{}); } pub fn setNormalizerGroup(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "NORMALIZERGROUP", .{}, arg); } pub fn getRasterSize(self: *Self) Size { var str = interop.getStrAttribute(self, "RASTERSIZE", .{}); return Size.parse(str); } pub fn setRasterSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "RASTERSIZE", .{}, value); } pub fn getShapeImage(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "SHAPEIMAGE", .{}); } pub fn setShapeImage(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "SHAPEIMAGE", .{}, arg); } pub fn getTipFgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "TIPFGCOLOR", .{}); } pub fn setTipFgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "TIPFGCOLOR", .{}, rgb); } pub fn getFontFace(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "FONTFACE", .{}); } pub fn setFontFace(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "FONTFACE", .{}, arg); } pub fn topMost(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "TOPMOST", .{}, arg); } pub fn getName(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "NAME", .{}); } pub fn setName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "NAME", .{}, arg); } pub fn getMinBox(self: *Self) bool { return interop.getBoolAttribute(self, "MINBOX", .{}); } pub fn setMinBox(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "MINBOX", .{}, arg); } pub fn getDefaultEnter(self: *Self) ?*iup.Button { if (interop.getHandleAttribute(self, "DEFAULTENTER", .{})) |handle| { return @ptrCast(*iup.Button, handle); } else { return null; } } pub fn setDefaultEnter(self: *Self, arg: *iup.Button) void { interop.setHandleAttribute(self, "DEFAULTENTER", .{}, arg); } pub fn setDefaultEnterHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "DEFAULTENTER", .{}, arg); } pub fn getModal(self: *Self) bool { return interop.getBoolAttribute(self, "MODAL", .{}); } /// /// PARENTDIALOG (creation only): Name of a dialog to be used as parent. /// This dialog will be always in front of the parent dialog. /// If not defined in Motif the dialog could not be modal. /// In Windows, if PARENTDIALOG is specified then it will be modal relative /// only to its parent. pub fn getParentDialog(self: *Self) ?iup.Element { if (interop.getHandleAttribute(self, "PARENTDIALOG", .{})) |handle| { return iup.Element.fromHandle(handle); } else { return null; } } /// /// PARENTDIALOG (creation only): Name of a dialog to be used as parent. /// This dialog will be always in front of the parent dialog. /// If not defined in Motif the dialog could not be modal. /// In Windows, if PARENTDIALOG is specified then it will be modal relative /// only to its parent. pub fn setParentDialog(self: *Self, arg: anytype) !void { try interop.validateHandle(.Dialog, arg); interop.setHandleAttribute(self, "PARENTDIALOG", .{}, arg); } pub fn setParentDialogHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "PARENTDIALOG", .{}, arg); } pub fn getBackground(self: *Self) ?iup.Rgb { return interop.getRgb(self, "BACKGROUND", .{}); } pub fn setBackground(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "BACKGROUND", .{}, rgb); } pub fn getHideTaskbar(self: *Self) bool { return interop.getBoolAttribute(self, "HIDETASKBAR", .{}); } pub fn setHideTaskbar(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "HIDETASKBAR", .{}, arg); } /// /// VALUE: Message text. pub fn getValue(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "VALUE", .{}); } /// /// VALUE: Message text. pub fn setValue(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "VALUE", .{}, arg); } pub fn getBringFront(self: *Self) bool { return interop.getBoolAttribute(self, "BRINGFRONT", .{}); } pub fn setBringFront(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "BRINGFRONT", .{}, arg); } pub fn getTrayImage(self: *Self) ?iup.Element { if (interop.getHandleAttribute(self, "TRAYIMAGE", .{})) |handle| { return iup.Element.fromHandle(handle); } else { return null; } } pub fn setTrayImage(self: *Self, arg: anytype) !void { try interop.validateHandle(.Image, arg); interop.setHandleAttribute(self, "TRAYIMAGE", .{}, arg); } pub fn setTrayImageHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TRAYIMAGE", .{}, arg); } pub fn getActive(self: *Self) bool { return interop.getBoolAttribute(self, "ACTIVE", .{}); } pub fn setActive(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "ACTIVE", .{}, arg); } pub fn getTipVisible(self: *Self) bool { return interop.getBoolAttribute(self, "TIPVISIBLE", .{}); } pub fn setTipVisible(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "TIPVISIBLE", .{}, arg); } pub fn getExpandWeight(self: *Self) f64 { return interop.getDoubleAttribute(self, "EXPANDWEIGHT", .{}); } pub fn setExpandWeight(self: *Self, arg: f64) void { interop.setDoubleAttribute(self, "EXPANDWEIGHT", .{}, arg); } pub fn getMinSize(self: *Self) Size { var str = interop.getStrAttribute(self, "MINSIZE", .{}); return Size.parse(str); } pub fn setMinSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "MINSIZE", .{}, value); } pub fn getActiveWindow(self: *Self) bool { return interop.getBoolAttribute(self, "ACTIVEWINDOW", .{}); } pub fn getNTheme(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "NTHEME", .{}); } pub fn setNTheme(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "NTHEME", .{}, arg); } pub fn getBorder(self: *Self) bool { return interop.getBoolAttribute(self, "BORDER", .{}); } pub fn setBorder(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "BORDER", .{}, arg); } pub fn getCustomFramesImulate(self: *Self) bool { return interop.getBoolAttribute(self, "CUSTOMFRAMESIMULATE", .{}); } pub fn setCustomFramesImulate(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "CUSTOMFRAMESIMULATE", .{}, arg); } pub fn getShrink(self: *Self) bool { return interop.getBoolAttribute(self, "SHRINK", .{}); } pub fn setShrink(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "SHRINK", .{}, arg); } pub fn getCharSize(self: *Self) Size { var str = interop.getStrAttribute(self, "CHARSIZE", .{}); return Size.parse(str); } pub fn getClientSize(self: *Self) Size { var str = interop.getStrAttribute(self, "CLIENTSIZE", .{}); return Size.parse(str); } pub fn setClientSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "CLIENTSIZE", .{}, value); } pub fn getClientOffset(self: *Self) Size { var str = interop.getStrAttribute(self, "CLIENTOFFSET", .{}); return Size.parse(str); } pub fn getTrayTip(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TRAYTIP", .{}); } pub fn setTrayTip(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TRAYTIP", .{}, arg); } pub fn getDragTypes(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "DRAGTYPES", .{}); } pub fn setDragTypes(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "DRAGTYPES", .{}, arg); } pub fn getToolBox(self: *Self) bool { return interop.getBoolAttribute(self, "TOOLBOX", .{}); } pub fn setToolBox(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "TOOLBOX", .{}, arg); } pub fn getMdiFrame(self: *Self) bool { return interop.getBoolAttribute(self, "MDIFRAME", .{}); } pub fn setMdiFrame(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "MDIFRAME", .{}, arg); } pub fn getFontStyle(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "FONTSTYLE", .{}); } pub fn setFontStyle(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "FONTSTYLE", .{}, arg); } pub fn getMdiChild(self: *Self) bool { return interop.getBoolAttribute(self, "MDICHILD", .{}); } pub fn setMdiChild(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "MDICHILD", .{}, arg); } pub fn fullScreen(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "FULLSCREEN", .{}, arg); } pub fn getNativeParent(self: *Self) ?iup.Element { if (interop.getHandleAttribute(self, "NATIVEPARENT", .{})) |handle| { return iup.Element.fromHandle(handle); } else { return null; } } pub fn setNativeParent(self: *Self, arg: anytype) !void { interop.setHandleAttribute(self, "NATIVEPARENT", .{}, arg); } pub fn setNativeParentHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "NATIVEPARENT", .{}, arg); } pub fn getFont(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "FONT", .{}); } pub fn setFont(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "FONT", .{}, arg); } pub fn simulateModal(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "SIMULATEMODAL", .{}, arg); } /// /// TABIMAGEn (non inheritable): image name to be used in the respective tab. /// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name. /// n starts at 0. /// See also IupImage. /// In Motif, the image is shown only if TABTITLEn is NULL. /// In Windows and Motif set the BGCOLOR attribute before setting the image. /// When set after map will update the TABIMAGE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn getTabImage(self: *Self, index: i32) ?iup.Element { if (interop.getHandleAttribute(self, "TABIMAGE", .{index})) |handle| { return iup.Element.fromHandle(handle); } else { return null; } } /// /// TABIMAGEn (non inheritable): image name to be used in the respective tab. /// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name. /// n starts at 0. /// See also IupImage. /// In Motif, the image is shown only if TABTITLEn is NULL. /// In Windows and Motif set the BGCOLOR attribute before setting the image. /// When set after map will update the TABIMAGE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabImage(self: *Self, index: i32, arg: anytype) !void { try interop.validateHandle(.Image, arg); interop.setHandleAttribute(self, "TABIMAGE", .{index}, arg); } pub fn setTabImageHandleName(self: *Self, index: i32, arg: [:0]const u8) void { interop.setStrAttribute(self, "TABIMAGE", .{index}, arg); } /// /// TABTITLEn (non inheritable): Contains the text to be shown in the /// respective tab title. /// n starts at 0. /// If this value is NULL, it will remain empty. /// The "&" character can be used to define a mnemonic, the next character will /// be used as key. /// Use "&&" to show the "&" character instead on defining a mnemonic. /// The button can be activated from any control in the dialog using the /// "Alt+key" combination. /// (mnemonic support since 3.3). /// When set after map will update the TABTITLE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn getTabTitle(self: *Self, index: i32) [:0]const u8 { return interop.getStrAttribute(self, "TABTITLE", .{index}); } /// /// TABTITLEn (non inheritable): Contains the text to be shown in the /// respective tab title. /// n starts at 0. /// If this value is NULL, it will remain empty. /// The "&" character can be used to define a mnemonic, the next character will /// be used as key. /// Use "&&" to show the "&" character instead on defining a mnemonic. /// The button can be activated from any control in the dialog using the /// "Alt+key" combination. /// (mnemonic support since 3.3). /// When set after map will update the TABTITLE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabTitle(self: *Self, index: i32, arg: [:0]const u8) void { interop.setStrAttribute(self, "TABTITLE", .{index}, arg); } pub fn setFocusCallback(self: *Self, callback: ?OnFocusFn) void { const Handler = CallbackHandler(Self, OnFocusFn, "FOCUS_CB"); Handler.setCallback(self, callback); } /// /// K_ANY K_ANY Action generated when a keyboard event occurs. /// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) -> /// (ret: number) [in Lua] ih: identifier of the element that activated the event. /// c: identifier of typed key. /// Please refer to the Keyboard Codes table for a list of possible values. /// Returns: If IUP_IGNORE is returned the key is ignored and not processed by /// the control and not propagated. /// If returns IUP_CONTINUE, the key will be processed and the event will be /// propagated to the parent of the element receiving it, this is the default behavior. /// If returns IUP_DEFAULT the key is processed but it is not propagated. /// IUP_CLOSE will be processed. /// Notes Keyboard callbacks depend on the keyboard usage of the control with /// the focus. /// So if you return IUP_IGNORE the control will usually not process the key. /// But be aware that sometimes the control process the key in another event so /// even returning IUP_IGNORE the key can get processed. /// Although it will not be propagated. /// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on /// the IUP_CONTINUE return value to work while the control is in focus. /// If the callback does not exists it is automatically propagated to the /// parent of the element. /// K_* callbacks All defined keys are also callbacks of any element, called /// when the respective key is activated. /// For example: "K_cC" is also a callback activated when the user press /// Ctrl+C, when the focus is at the element or at a children with focus. /// This is the way an application can create shortcut keys, also called hot keys. /// These callbacks are not available in IupLua. /// Affects All elements with keyboard interaction. pub fn setKAnyCallback(self: *Self, callback: ?OnKAnyFn) void { const Handler = CallbackHandler(Self, OnKAnyFn, "K_ANY"); Handler.setCallback(self, callback); } /// /// HELP_CB HELP_CB Action generated when the user press F1 at a control. /// In Motif is also activated by the Help button in some workstations keyboard. /// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Returns: IUP_CLOSE will be processed. /// Affects All elements with user interaction. pub fn setHelpCallback(self: *Self, callback: ?OnHelpFn) void { const Handler = CallbackHandler(Self, OnHelpFn, "HELP_CB"); Handler.setCallback(self, callback); } /// /// CLOSE_CB CLOSE_CB Called just before a dialog is closed when the user /// clicks the close button of the title bar or an equivalent action. /// Callback int function(Ihandle *ih); [in C] ih:close_cb() -> (ret: number) /// [in Lua] ih: identifies the element that activated the event. /// Returns: if IUP_IGNORE, it prevents the dialog from being closed. /// If you destroy the dialog in this callback, you must return IUP_IGNORE. /// IUP_CLOSE will be processed. /// Affects IupDialog pub fn setCloseCallback(self: *Self, callback: ?OnCloseFn) void { const Handler = CallbackHandler(Self, OnCloseFn, "CLOSE_CB"); Handler.setCallback(self, callback); } pub fn setDropMotionCallback(self: *Self, callback: ?OnDropMotionFn) void { const Handler = CallbackHandler(Self, OnDropMotionFn, "DROPMOTION_CB"); Handler.setCallback(self, callback); } pub fn setDragEndCallback(self: *Self, callback: ?OnDragEndFn) void { const Handler = CallbackHandler(Self, OnDragEndFn, "DRAGEND_CB"); Handler.setCallback(self, callback); } pub fn setDragBeginCallback(self: *Self, callback: ?OnDragBeginFn) void { const Handler = CallbackHandler(Self, OnDragBeginFn, "DRAGBEGIN_CB"); Handler.setCallback(self, callback); } /// /// MAP_CB MAP_CB Called right after an element is mapped and its attributes /// updated in IupMap. /// When the element is a dialog, it is called after the layout is updated. /// For all other elements is called before the layout is updated, so the /// element current size will still be 0x0 during MAP_CB (since 3.14). /// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setMapCallback(self: *Self, callback: ?OnMapFn) void { const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB"); Handler.setCallback(self, callback); } /// /// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also LEAVEWINDOW_CB pub fn setEnterWindowCallback(self: *Self, callback: ?OnEnterWindowFn) void { const Handler = CallbackHandler(Self, OnEnterWindowFn, "ENTERWINDOW_CB"); Handler.setCallback(self, callback); } /// /// DESTROY_CB DESTROY_CB Called right before an element is destroyed. /// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Notes If the dialog is visible then it is hidden before it is destroyed. /// The callback will be called right after it is hidden. /// The callback will be called before all other destroy procedures. /// For instance, if the element has children then it is called before the /// children are destroyed. /// For language binding implementations use the callback name "LDESTROY_CB" to /// release memory allocated by the binding for the element. /// Also the callback will be called before the language callback. /// Affects All. pub fn setDestroyCallback(self: *Self, callback: ?OnDestroyFn) void { const Handler = CallbackHandler(Self, OnDestroyFn, "DESTROY_CB"); Handler.setCallback(self, callback); } pub fn setDropDataCallback(self: *Self, callback: ?OnDropDataFn) void { const Handler = CallbackHandler(Self, OnDropDataFn, "DROPDATA_CB"); Handler.setCallback(self, callback); } /// /// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus. /// This callback is called before the GETFOCUS_CB of the element that gets the focus. /// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Affects All elements with user interaction, except menus. /// In Windows, there are restrictions when using this callback. /// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any /// function calls that display or activate a window. /// This causes the thread to yield control and can cause the application to /// stop responding to messages. /// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus pub fn setKillFocusCallback(self: *Self, callback: ?OnKillFocusFn) void { const Handler = CallbackHandler(Self, OnKillFocusFn, "KILLFOCUS_CB"); Handler.setCallback(self, callback); } pub fn setDragDataCallback(self: *Self, callback: ?OnDragDataFn) void { const Handler = CallbackHandler(Self, OnDragDataFn, "DRAGDATA_CB"); Handler.setCallback(self, callback); } pub fn setDragDataSizeCallback(self: *Self, callback: ?OnDragDataSizeFn) void { const Handler = CallbackHandler(Self, OnDragDataSizeFn, "DRAGDATASIZE_CB"); Handler.setCallback(self, callback); } /// /// SHOW_CB SHOW_CB Called right after the dialog is showed, hidden, maximized, /// minimized or restored from minimized/maximized. /// This callback is called when those actions were performed by the user or /// programmatically by the application. /// Callback int function(Ihandle *ih, int state); [in C] ih:show_cb(state: /// number) -> (ret: number) [in Lua] ih: identifier of the element that /// activated the event. /// state: indicates which of the following situations generated the event: /// IUP_HIDE (since 3.0) IUP_SHOW IUP_RESTORE (was minimized or maximized) /// IUP_MINIMIZE IUP_MAXIMIZE (since 3.0) (not received in Motif when activated /// from the maximize button) Returns: IUP_CLOSE will be processed. /// Affects IupDialog pub fn setShowCallback(self: *Self, callback: ?OnShowFn) void { const Handler = CallbackHandler(Self, OnShowFn, "SHOW_CB"); Handler.setCallback(self, callback); } /// /// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control. /// When several files are dropped at once, the callback is called several /// times, once for each file. /// If defined after the element is mapped then the attribute DROPFILESTARGET /// must be set to YES. /// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const /// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename: /// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the /// element that activated the event. /// filename: Name of the dropped file. /// num: Number index of the dropped file. /// If several files are dropped, num is the index of the dropped file starting /// from "total-1" to "0". /// x: X coordinate of the point where the user released the mouse button. /// y: Y coordinate of the point where the user released the mouse button. /// Returns: If IUP_IGNORE is returned the callback will NOT be called for the /// next dropped files, and the processing of dropped files will be interrupted. /// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList pub fn setDropFilesCallback(self: *Self, callback: ?OnDropFilesFn) void { const Handler = CallbackHandler(Self, OnDropFilesFn, "DROPFILES_CB"); Handler.setCallback(self, callback); } /// /// RESIZE_CB RESIZE_CB Action generated when the canvas or dialog size is changed. /// Callback int function(Ihandle *ih, int width, int height); [in C] /// ih:resize_cb(width, height: number) -> (ret: number) [in Lua] ih: /// identifier of the element that activated the event. /// width: the width of the internal element size in pixels not considering the /// decorations (client size) height: the height of the internal element size /// in pixels not considering the decorations (client size) Notes For the /// dialog, this action is also generated when the dialog is mapped, after the /// map and before the show. /// When XAUTOHIDE=Yes or YAUTOHIDE=Yes, if the canvas scrollbar is /// hidden/shown after changing the DX or DY attributes from inside the /// callback, the size of the drawing area will immediately change, so the /// parameters with and height will be invalid. /// To update the parameters consult the DRAWSIZE attribute. /// Also activate the drawing toolkit only after updating the DX or DY attributes. /// Affects IupCanvas, IupGLCanvas, IupDialog pub fn setResizeCallback(self: *Self, callback: ?OnResizeFn) void { const Handler = CallbackHandler(Self, OnResizeFn, "RESIZE_CB"); Handler.setCallback(self, callback); } /// /// UNMAP_CB UNMAP_CB Called right before an element is unmapped. /// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setUnmapCallback(self: *Self, callback: ?OnUnmapFn) void { const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB"); Handler.setCallback(self, callback); } pub fn setTrayClickCallback(self: *Self, callback: ?OnTrayClickFn) void { const Handler = CallbackHandler(Self, OnTrayClickFn, "TRAYCLICK_CB"); Handler.setCallback(self, callback); } /// /// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus. /// This callback is called after the KILLFOCUS_CB of the element that loosed /// the focus. /// The IupGetFocus function during the callback returns the element that /// loosed the focus. /// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that received keyboard focus. /// Affects All elements with user interaction, except menus. /// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus pub fn setGetFocusCallback(self: *Self, callback: ?OnGetFocusFn) void { const Handler = CallbackHandler(Self, OnGetFocusFn, "GETFOCUS_CB"); Handler.setCallback(self, callback); } pub fn setLDestroyCallback(self: *Self, callback: ?OnLDestroyFn) void { const Handler = CallbackHandler(Self, OnLDestroyFn, "LDESTROY_CB"); Handler.setCallback(self, callback); } /// /// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also ENTERWINDOW_CB pub fn setLeaveWindowCallback(self: *Self, callback: ?OnLeaveWindowFn) void { const Handler = CallbackHandler(Self, OnLeaveWindowFn, "LEAVEWINDOW_CB"); Handler.setCallback(self, callback); } pub fn setPostMessageCallback(self: *Self, callback: ?OnPostMessageFn) void { const Handler = CallbackHandler(Self, OnPostMessageFn, "POSTMESSAGE_CB"); Handler.setCallback(self, callback); } }; test "MessageDlg HandleName" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setHandleName("Hello").unwrap()); defer item.deinit(); var ret = item.getHandleName(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg TipBgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setTipBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getTipBgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "MessageDlg MdiClient" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setMdiClient(true).unwrap()); defer item.deinit(); var ret = item.getMdiClient(); try std.testing.expect(ret == true); } test "MessageDlg Control" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setControl(true).unwrap()); defer item.deinit(); var ret = item.getControl(); try std.testing.expect(ret == true); } test "MessageDlg TipIcon" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setTipIcon("Hello").unwrap()); defer item.deinit(); var ret = item.getTipIcon(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg NoFlush" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setNoFlush(true).unwrap()); defer item.deinit(); var ret = item.getNoFlush(); try std.testing.expect(ret == true); } test "MessageDlg MaxSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setMaxSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getMaxSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "MessageDlg OpacityImage" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setOpacityImage("Hello").unwrap()); defer item.deinit(); var ret = item.getOpacityImage(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg HelpButton" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setHelpButton(true).unwrap()); defer item.deinit(); var ret = item.getHelpButton(); try std.testing.expect(ret == true); } test "MessageDlg ShowNoFocus" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setShowNoFocus(true).unwrap()); defer item.deinit(); var ret = item.getShowNoFocus(); try std.testing.expect(ret == true); } test "MessageDlg Opacity" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setOpacity(42).unwrap()); defer item.deinit(); var ret = item.getOpacity(); try std.testing.expect(ret == 42); } test "MessageDlg Position" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setPosition(9, 10).unwrap()); defer item.deinit(); var ret = item.getPosition(); try std.testing.expect(ret.x == 9 and ret.y == 10); } test "MessageDlg Composited" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setComposited(true).unwrap()); defer item.deinit(); var ret = item.getComposited(); try std.testing.expect(ret == true); } test "MessageDlg DropFilesTarget" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setDropFilesTarget(true).unwrap()); defer item.deinit(); var ret = item.getDropFilesTarget(); try std.testing.expect(ret == true); } test "MessageDlg Tip" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setTip("Hello").unwrap()); defer item.deinit(); var ret = item.getTip(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg CanFocus" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setCanFocus(true).unwrap()); defer item.deinit(); var ret = item.getCanFocus(); try std.testing.expect(ret == true); } test "MessageDlg DragSourceMove" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setDragSourceMove(true).unwrap()); defer item.deinit(); var ret = item.getDragSourceMove(); try std.testing.expect(ret == true); } test "MessageDlg Icon" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setIcon("Hello").unwrap()); defer item.deinit(); var ret = item.getIcon(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg Visible" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setVisible(true).unwrap()); defer item.deinit(); var ret = item.getVisible(); try std.testing.expect(ret == true); } test "MessageDlg MenuBox" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setMenuBox(true).unwrap()); defer item.deinit(); var ret = item.getMenuBox(); try std.testing.expect(ret == true); } test "MessageDlg DialogType" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setDialogType(.Error).unwrap()); defer item.deinit(); var ret = item.getDialogType(); try std.testing.expect(ret != null and ret.? == .Error); } test "MessageDlg HideTitleBar" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setHideTitleBar("Hello").unwrap()); defer item.deinit(); var ret = item.getHideTitleBar(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg MaxBox" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setMaxBox(true).unwrap()); defer item.deinit(); var ret = item.getMaxBox(); try std.testing.expect(ret == true); } test "MessageDlg DragDrop" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setDragDrop(true).unwrap()); defer item.deinit(); var ret = item.getDragDrop(); try std.testing.expect(ret == true); } test "MessageDlg DialogHint" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setDialogHint(true).unwrap()); defer item.deinit(); var ret = item.getDialogHint(); try std.testing.expect(ret == true); } test "MessageDlg DialogFrame" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setDialogFrame(true).unwrap()); defer item.deinit(); var ret = item.getDialogFrame(); try std.testing.expect(ret == true); } test "MessageDlg NActive" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setNActive(true).unwrap()); defer item.deinit(); var ret = item.getNActive(); try std.testing.expect(ret == true); } test "MessageDlg Theme" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setTheme("Hello").unwrap()); defer item.deinit(); var ret = item.getTheme(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg SaveUnder" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setSaveUnder(true).unwrap()); defer item.deinit(); var ret = item.getSaveUnder(); try std.testing.expect(ret == true); } test "MessageDlg Tray" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setTray(true).unwrap()); defer item.deinit(); var ret = item.getTray(); try std.testing.expect(ret == true); } test "MessageDlg Buttons" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setButtons(.OkCanCel).unwrap()); defer item.deinit(); var ret = item.getButtons(); try std.testing.expect(ret != null and ret.? == .OkCanCel); } test "MessageDlg ChildOffset" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setChildOffset(9, 10).unwrap()); defer item.deinit(); var ret = item.getChildOffset(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "MessageDlg Expand" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setExpand(.Yes).unwrap()); defer item.deinit(); var ret = item.getExpand(); try std.testing.expect(ret != null and ret.? == .Yes); } test "MessageDlg TipMarkup" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setTipMarkup("Hello").unwrap()); defer item.deinit(); var ret = item.getTipMarkup(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg ButtonResponse" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setButtonResponse(.Button1).unwrap()); defer item.deinit(); var ret = item.getButtonResponse(); try std.testing.expect(ret == .Button1); } test "MessageDlg StartFocus" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setStartFocus("Hello").unwrap()); defer item.deinit(); var ret = item.getStartFocus(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg FontSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setFontSize(42).unwrap()); defer item.deinit(); var ret = item.getFontSize(); try std.testing.expect(ret == 42); } test "MessageDlg DropTypes" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setDropTypes("Hello").unwrap()); defer item.deinit(); var ret = item.getDropTypes(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg TrayTipMarkup" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setTrayTipMarkup("Hello").unwrap()); defer item.deinit(); var ret = item.getTrayTipMarkup(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg UserSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setUserSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getUserSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "MessageDlg TipDelay" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setTipDelay(42).unwrap()); defer item.deinit(); var ret = item.getTipDelay(); try std.testing.expect(ret == 42); } test "MessageDlg CustomFrame" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setCustomFrame(true).unwrap()); defer item.deinit(); var ret = item.getCustomFrame(); try std.testing.expect(ret == true); } test "MessageDlg Title" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setTitle("Hello").unwrap()); defer item.deinit(); var ret = item.getTitle(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg Placement" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setPlacement(.Maximized).unwrap()); defer item.deinit(); var ret = item.getPlacement(); try std.testing.expect(ret != null and ret.? == .Maximized); } test "MessageDlg PropagateFocus" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setPropagateFocus(true).unwrap()); defer item.deinit(); var ret = item.getPropagateFocus(); try std.testing.expect(ret == true); } test "MessageDlg BgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getBgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "MessageDlg DropTarget" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setDropTarget(true).unwrap()); defer item.deinit(); var ret = item.getDropTarget(); try std.testing.expect(ret == true); } test "MessageDlg DragSource" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setDragSource(true).unwrap()); defer item.deinit(); var ret = item.getDragSource(); try std.testing.expect(ret == true); } test "MessageDlg ButtonDefault" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setButtonDefault(.Button1).unwrap()); defer item.deinit(); var ret = item.getButtonDefault(); try std.testing.expect(ret == .Button1); } test "MessageDlg Resize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setResize(true).unwrap()); defer item.deinit(); var ret = item.getResize(); try std.testing.expect(ret == true); } test "MessageDlg Floating" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setFloating(.Yes).unwrap()); defer item.deinit(); var ret = item.getFloating(); try std.testing.expect(ret != null and ret.? == .Yes); } test "MessageDlg NormalizerGroup" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setNormalizerGroup("Hello").unwrap()); defer item.deinit(); var ret = item.getNormalizerGroup(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg RasterSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setRasterSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getRasterSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "MessageDlg ShapeImage" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setShapeImage("Hello").unwrap()); defer item.deinit(); var ret = item.getShapeImage(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg TipFgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setTipFgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getTipFgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "MessageDlg FontFace" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setFontFace("Hello").unwrap()); defer item.deinit(); var ret = item.getFontFace(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg Name" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setName("Hello").unwrap()); defer item.deinit(); var ret = item.getName(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg MinBox" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setMinBox(true).unwrap()); defer item.deinit(); var ret = item.getMinBox(); try std.testing.expect(ret == true); } test "MessageDlg Background" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setBackground(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getBackground(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "MessageDlg HideTaskbar" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setHideTaskbar(true).unwrap()); defer item.deinit(); var ret = item.getHideTaskbar(); try std.testing.expect(ret == true); } test "MessageDlg Value" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setValue("Hello").unwrap()); defer item.deinit(); var ret = item.getValue(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg BringFront" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setBringFront(true).unwrap()); defer item.deinit(); var ret = item.getBringFront(); try std.testing.expect(ret == true); } test "MessageDlg Active" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setActive(true).unwrap()); defer item.deinit(); var ret = item.getActive(); try std.testing.expect(ret == true); } test "MessageDlg TipVisible" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setTipVisible(true).unwrap()); defer item.deinit(); var ret = item.getTipVisible(); try std.testing.expect(ret == true); } test "MessageDlg ExpandWeight" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setExpandWeight(3.14).unwrap()); defer item.deinit(); var ret = item.getExpandWeight(); try std.testing.expect(ret == @as(f64, 3.14)); } test "MessageDlg MinSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setMinSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getMinSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "MessageDlg NTheme" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setNTheme("Hello").unwrap()); defer item.deinit(); var ret = item.getNTheme(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg Border" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setBorder(true).unwrap()); defer item.deinit(); var ret = item.getBorder(); try std.testing.expect(ret == true); } test "MessageDlg CustomFramesImulate" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setCustomFramesImulate(true).unwrap()); defer item.deinit(); var ret = item.getCustomFramesImulate(); try std.testing.expect(ret == true); } test "MessageDlg Shrink" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setShrink(true).unwrap()); defer item.deinit(); var ret = item.getShrink(); try std.testing.expect(ret == true); } test "MessageDlg ClientSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setClientSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getClientSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "MessageDlg TrayTip" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setTrayTip("Hello").unwrap()); defer item.deinit(); var ret = item.getTrayTip(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg DragTypes" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setDragTypes("Hello").unwrap()); defer item.deinit(); var ret = item.getDragTypes(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg ToolBox" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setToolBox(true).unwrap()); defer item.deinit(); var ret = item.getToolBox(); try std.testing.expect(ret == true); } test "MessageDlg MdiFrame" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setMdiFrame(true).unwrap()); defer item.deinit(); var ret = item.getMdiFrame(); try std.testing.expect(ret == true); } test "MessageDlg FontStyle" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setFontStyle("Hello").unwrap()); defer item.deinit(); var ret = item.getFontStyle(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "MessageDlg MdiChild" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setMdiChild(true).unwrap()); defer item.deinit(); var ret = item.getMdiChild(); try std.testing.expect(ret == true); } test "MessageDlg Font" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.MessageDlg.init().setFont("Hello").unwrap()); defer item.deinit(); var ret = item.getFont(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); }
src/elements/message_dlg.zig
pub const WCM_API_VERSION_1_0 = @as(u32, 1); pub const WCM_UNKNOWN_DATAPLAN_STATUS = @as(u32, 4294967295); pub const WCM_MAX_PROFILE_NAME = @as(u32, 256); pub const NET_INTERFACE_FLAG_NONE = @as(u32, 0); pub const NET_INTERFACE_FLAG_CONNECT_IF_NEEDED = @as(u32, 1); //-------------------------------------------------------------------------------- // Section: Types (15) //-------------------------------------------------------------------------------- pub const WCM_PROPERTY = enum(i32) { global_property_domain_policy = 0, global_property_minimize_policy = 1, global_property_roaming_policy = 2, global_property_powermanagement_policy = 3, intf_property_connection_cost = 4, intf_property_dataplan_status = 5, intf_property_hotspot_profile = 6, }; pub const wcm_global_property_domain_policy = WCM_PROPERTY.global_property_domain_policy; pub const wcm_global_property_minimize_policy = WCM_PROPERTY.global_property_minimize_policy; pub const wcm_global_property_roaming_policy = WCM_PROPERTY.global_property_roaming_policy; pub const wcm_global_property_powermanagement_policy = WCM_PROPERTY.global_property_powermanagement_policy; pub const wcm_intf_property_connection_cost = WCM_PROPERTY.intf_property_connection_cost; pub const wcm_intf_property_dataplan_status = WCM_PROPERTY.intf_property_dataplan_status; pub const wcm_intf_property_hotspot_profile = WCM_PROPERTY.intf_property_hotspot_profile; pub const WCM_MEDIA_TYPE = enum(i32) { unknown = 0, ethernet = 1, wlan = 2, mbn = 3, invalid = 4, max = 5, }; pub const wcm_media_unknown = WCM_MEDIA_TYPE.unknown; pub const wcm_media_ethernet = WCM_MEDIA_TYPE.ethernet; pub const wcm_media_wlan = WCM_MEDIA_TYPE.wlan; pub const wcm_media_mbn = WCM_MEDIA_TYPE.mbn; pub const wcm_media_invalid = WCM_MEDIA_TYPE.invalid; pub const wcm_media_max = WCM_MEDIA_TYPE.max; pub const WCM_POLICY_VALUE = extern struct { fValue: BOOL, fIsGroupPolicy: BOOL, }; pub const WCM_PROFILE_INFO = extern struct { strProfileName: [256]u16, AdapterGUID: Guid, Media: WCM_MEDIA_TYPE, }; pub const WCM_PROFILE_INFO_LIST = extern struct { dwNumberOfItems: u32, ProfileInfo: [1]WCM_PROFILE_INFO, }; pub const WCM_CONNECTION_COST = enum(i32) { UNKNOWN = 0, UNRESTRICTED = 1, FIXED = 2, VARIABLE = 4, OVERDATALIMIT = 65536, CONGESTED = 131072, ROAMING = 262144, APPROACHINGDATALIMIT = 524288, }; pub const WCM_CONNECTION_COST_UNKNOWN = WCM_CONNECTION_COST.UNKNOWN; pub const WCM_CONNECTION_COST_UNRESTRICTED = WCM_CONNECTION_COST.UNRESTRICTED; pub const WCM_CONNECTION_COST_FIXED = WCM_CONNECTION_COST.FIXED; pub const WCM_CONNECTION_COST_VARIABLE = WCM_CONNECTION_COST.VARIABLE; pub const WCM_CONNECTION_COST_OVERDATALIMIT = WCM_CONNECTION_COST.OVERDATALIMIT; pub const WCM_CONNECTION_COST_CONGESTED = WCM_CONNECTION_COST.CONGESTED; pub const WCM_CONNECTION_COST_ROAMING = WCM_CONNECTION_COST.ROAMING; pub const WCM_CONNECTION_COST_APPROACHINGDATALIMIT = WCM_CONNECTION_COST.APPROACHINGDATALIMIT; pub const WCM_CONNECTION_COST_SOURCE = enum(i32) { DEFAULT = 0, GP = 1, USER = 2, OPERATOR = 3, }; pub const WCM_CONNECTION_COST_SOURCE_DEFAULT = WCM_CONNECTION_COST_SOURCE.DEFAULT; pub const WCM_CONNECTION_COST_SOURCE_GP = WCM_CONNECTION_COST_SOURCE.GP; pub const WCM_CONNECTION_COST_SOURCE_USER = WCM_CONNECTION_COST_SOURCE.USER; pub const WCM_CONNECTION_COST_SOURCE_OPERATOR = WCM_CONNECTION_COST_SOURCE.OPERATOR; pub const WCM_CONNECTION_COST_DATA = extern struct { ConnectionCost: u32, CostSource: WCM_CONNECTION_COST_SOURCE, }; pub const WCM_TIME_INTERVAL = extern struct { wYear: u16, wMonth: u16, wDay: u16, wHour: u16, wMinute: u16, wSecond: u16, wMilliseconds: u16, }; pub const WCM_USAGE_DATA = extern struct { UsageInMegabytes: u32, LastSyncTime: FILETIME, }; pub const WCM_BILLING_CYCLE_INFO = extern struct { StartDate: FILETIME, Duration: WCM_TIME_INTERVAL, Reset: BOOL, }; pub const WCM_DATAPLAN_STATUS = extern struct { UsageData: WCM_USAGE_DATA, DataLimitInMegabytes: u32, InboundBandwidthInKbps: u32, OutboundBandwidthInKbps: u32, BillingCycle: WCM_BILLING_CYCLE_INFO, MaxTransferSizeInMegabytes: u32, Reserved: u32, }; pub const ONDEMAND_NOTIFICATION_CALLBACK = fn( param0: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) void; pub const NET_INTERFACE_CONTEXT = extern struct { InterfaceIndex: u32, ConfigurationName: ?PWSTR, }; pub const NET_INTERFACE_CONTEXT_TABLE = extern struct { InterfaceContextHandle: ?HANDLE, NumberOfEntries: u32, InterfaceContextArray: ?*NET_INTERFACE_CONTEXT, }; //-------------------------------------------------------------------------------- // Section: Functions (10) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows8.0' pub extern "wcmapi" fn WcmQueryProperty( pInterface: ?*const Guid, strProfileName: ?[*:0]const u16, Property: WCM_PROPERTY, pReserved: ?*c_void, pdwDataSize: ?*u32, ppData: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "wcmapi" fn WcmSetProperty( pInterface: ?*const Guid, strProfileName: ?[*:0]const u16, Property: WCM_PROPERTY, pReserved: ?*c_void, dwDataSize: u32, pbData: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "wcmapi" fn WcmGetProfileList( pReserved: ?*c_void, ppProfileList: ?*?*WCM_PROFILE_INFO_LIST, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "wcmapi" fn WcmSetProfileList( pProfileList: ?*WCM_PROFILE_INFO_LIST, dwPosition: u32, fIgnoreUnknownProfiles: BOOL, pReserved: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "wcmapi" fn WcmFreeMemory( pMemory: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows8.1' pub extern "OnDemandConnRouteHelper" fn OnDemandGetRoutingHint( destinationHostName: ?[*:0]const u16, interfaceIndex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows8.1' pub extern "OnDemandConnRouteHelper" fn OnDemandRegisterNotification( callback: ?ONDEMAND_NOTIFICATION_CALLBACK, callbackContext: ?*c_void, registrationHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows8.1' pub extern "OnDemandConnRouteHelper" fn OnDemandUnRegisterNotification( registrationHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.10240' pub extern "OnDemandConnRouteHelper" fn GetInterfaceContextTableForHostName( HostName: ?[*:0]const u16, ProxyName: ?[*:0]const u16, Flags: u32, // TODO: what to do with BytesParamIndex 4? ConnectionProfileFilterRawData: ?*u8, ConnectionProfileFilterRawDataSize: u32, InterfaceContextTable: ?*?*NET_INTERFACE_CONTEXT_TABLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.10240' pub extern "OnDemandConnRouteHelper" fn FreeInterfaceContextTable( InterfaceContextTable: ?*NET_INTERFACE_CONTEXT_TABLE, ) callconv(@import("std").os.windows.WINAPI) void; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (6) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const FILETIME = @import("../foundation.zig").FILETIME; const HANDLE = @import("../foundation.zig").HANDLE; const HRESULT = @import("../foundation.zig").HRESULT; const PWSTR = @import("../foundation.zig").PWSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "ONDEMAND_NOTIFICATION_CALLBACK")) { _ = ONDEMAND_NOTIFICATION_CALLBACK; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
deps/zigwin32/win32/network_management/windows_connection_manager.zig
const std = @import("std"); const Client = @import("client.zig").Client; const MAX_SHM_POOLS = 512; var SHM_POOLS: [MAX_SHM_POOLS]ShmPool = undefined; pub const ShmPool = struct { index: usize, in_use: bool = false, fd: i32, data: []align(4096) u8, wl_shm_pool_id: u32, ref_count: usize, client: *Client, to_be_destroyed: bool = false, const Self = @This(); pub fn deinit(self: *Self) void { std.os.munmap(self.data); // std.debug.warn("shm_pool closing file descriptor: {}\n", .{self.fd}); std.os.close(self.fd); self.in_use = false; self.fd = -1; } pub fn resize(self: *Self, size: i32) !void { std.os.munmap(self.data); self.data = try std.os.mmap(null, @intCast(usize, size), std.os.linux.PROT_READ | std.os.linux.PROT_WRITE, std.os.linux.MAP_SHARED, self.fd, 0); } pub fn incrementRefCount(self: *Self) void { self.ref_count += 1; } pub fn decrementRefCount(self: *Self) void { if (self.ref_count > 0) { self.ref_count -= 1; if (self.ref_count == 0 and self.to_be_destroyed) { self.deinit(); } } } }; pub fn newShmPool(client: *Client, fd: i32, wl_shm_pool_id: u32, size: i32) !*ShmPool { var i: usize = 0; while (i < MAX_SHM_POOLS) { var shm_pool: *ShmPool = &SHM_POOLS[i]; if (shm_pool.in_use == false) { shm_pool.index = i; shm_pool.in_use = true; shm_pool.to_be_destroyed = false; shm_pool.client = client; shm_pool.fd = fd; shm_pool.ref_count = 0; shm_pool.wl_shm_pool_id = wl_shm_pool_id; shm_pool.data = try std.os.mmap(null, @intCast(usize, size), std.os.linux.PROT_READ | std.os.linux.PROT_WRITE, std.os.linux.MAP_SHARED, fd, 0); // std.debug.warn("data length: {}\n", .{shm_pool.data.len}); return shm_pool; } else { i = i + 1; continue; } } return ShmPoolsError.ShmPoolsExhausted; } pub fn releaseShmPools(client: *Client) void { var i: usize = 0; while (i < MAX_SHM_POOLS) { var shm_pool: *ShmPool = &SHM_POOLS[i]; if (shm_pool.in_use and shm_pool.client == client) { shm_pool.deinit(); } i = i + 1; } } const ShmPoolsError = error{ ShmPoolsExhausted, };
src/shm_pool.zig
const std = @import("std"); const getty = @import("../../../lib.zig"); pub fn Visitor(comptime Struct: type) type { return struct { const Self = @This(); pub usingnamespace getty.de.Visitor( Self, Value, undefined, undefined, undefined, undefined, visitMap, undefined, undefined, undefined, undefined, undefined, ); const Value = Struct; fn visitMap(_: Self, allocator: ?std.mem.Allocator, comptime Deserializer: type, map: anytype) Deserializer.Error!Value { const fields = std.meta.fields(Value); var structure: Value = undefined; var seen = [_]bool{false} ** fields.len; errdefer { if (allocator) |alloc| { inline for (fields) |field, i| { if (!field.is_comptime and seen[i]) { getty.de.free(alloc, @field(structure, field.name)); } } } } while (try map.nextKey(allocator, []const u8)) |key| { var found = false; inline for (fields) |field, i| { if (std.mem.eql(u8, field.name, key)) { if (seen[i]) { return error.DuplicateField; } switch (field.is_comptime) { true => @compileError("TODO"), false => @field(structure, field.name) = try map.nextValue(allocator, field.field_type), } seen[i] = true; found = true; break; } } if (!found) { return error.UnknownField; } } inline for (fields) |field, i| { if (!seen[i]) { if (field.default_value) |default| { if (!field.is_comptime) { @field(structure, field.name) = default; } } else { return error.MissingField; } } } return structure; } }; }
src/de/impl/visitor/struct.zig
/// The function fiatP448AddcarryxU28 is an addition with carry. /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^28 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^28⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xfffffff] /// arg3: [0x0 ~> 0xfffffff] /// Output Bounds: /// out1: [0x0 ~> 0xfffffff] /// out2: [0x0 ~> 0x1] fn fiatP448AddcarryxU28(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { const x1: u32 = ((@intCast(u32, arg1) + arg2) + arg3); const x2: u32 = (x1 & 0xfffffff); const x3: u1 = @intCast(u1, (x1 >> 28)); out1.* = x2; out2.* = x3; } /// The function fiatP448SubborrowxU28 is a subtraction with borrow. /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^28 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^28⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xfffffff] /// arg3: [0x0 ~> 0xfffffff] /// Output Bounds: /// out1: [0x0 ~> 0xfffffff] /// out2: [0x0 ~> 0x1] fn fiatP448SubborrowxU28(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { const x1: i32 = @intCast(i32, (@intCast(i64, @intCast(i32, (@intCast(i64, arg2) - @intCast(i64, arg1)))) - @intCast(i64, arg3))); const x2: i1 = @intCast(i1, (x1 >> 28)); const x3: u32 = @intCast(u32, (@intCast(i64, x1) & @intCast(i64, 0xfffffff))); out1.* = x3; out2.* = @intCast(u1, (@intCast(i2, 0x0) - @intCast(i2, x2))); } /// The function fiatP448CmovznzU32 is a single-word conditional move. /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffff] /// arg3: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] fn fiatP448CmovznzU32(out1: *u32, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { const x1: u1 = (~(~arg1)); const x2: u32 = @intCast(u32, (@intCast(i64, @intCast(i1, (@intCast(i2, 0x0) - @intCast(i2, x1)))) & @intCast(i64, 0xffffffff))); const x3: u32 = ((x2 & arg3) | ((~x2) & arg2)); out1.* = x3; } /// The function fiatP448CarryMul multiplies two field elements and reduces the result. /// Postconditions: /// eval out1 mod m = (eval arg1 * eval arg2) mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000]] /// arg2: [[0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000]] pub fn fiatP448CarryMul(out1: *[16]u32, arg1: [16]u32, arg2: [16]u32) void { const x1: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[15]))); const x2: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[14]))); const x3: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[13]))); const x4: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[12]))); const x5: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[11]))); const x6: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[10]))); const x7: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[9]))); const x8: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[15]))); const x9: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[14]))); const x10: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[13]))); const x11: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[12]))); const x12: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[11]))); const x13: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[10]))); const x14: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[15]))); const x15: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[14]))); const x16: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[13]))); const x17: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[12]))); const x18: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[11]))); const x19: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[15]))); const x20: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[14]))); const x21: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[13]))); const x22: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[12]))); const x23: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[15]))); const x24: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[14]))); const x25: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[13]))); const x26: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[15]))); const x27: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[14]))); const x28: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[15]))); const x29: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[15]))); const x30: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[14]))); const x31: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[13]))); const x32: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[12]))); const x33: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[11]))); const x34: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[10]))); const x35: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[9]))); const x36: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[15]))); const x37: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[14]))); const x38: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[13]))); const x39: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[12]))); const x40: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[11]))); const x41: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[10]))); const x42: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[15]))); const x43: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[14]))); const x44: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[13]))); const x45: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[12]))); const x46: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[11]))); const x47: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[15]))); const x48: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[14]))); const x49: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[13]))); const x50: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[12]))); const x51: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[15]))); const x52: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[14]))); const x53: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[13]))); const x54: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[15]))); const x55: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[14]))); const x56: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[15]))); const x57: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[15]))); const x58: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[14]))); const x59: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[13]))); const x60: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[12]))); const x61: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[11]))); const x62: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[10]))); const x63: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[9]))); const x64: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[8]))); const x65: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[7]))); const x66: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[6]))); const x67: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[5]))); const x68: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[4]))); const x69: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[3]))); const x70: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[2]))); const x71: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[1]))); const x72: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[15]))); const x73: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[14]))); const x74: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[13]))); const x75: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[12]))); const x76: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[11]))); const x77: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[10]))); const x78: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[9]))); const x79: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[8]))); const x80: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[7]))); const x81: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[6]))); const x82: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[5]))); const x83: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[4]))); const x84: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[3]))); const x85: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[2]))); const x86: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[15]))); const x87: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[14]))); const x88: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[13]))); const x89: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[12]))); const x90: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[11]))); const x91: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[10]))); const x92: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[9]))); const x93: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[8]))); const x94: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[7]))); const x95: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[6]))); const x96: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[5]))); const x97: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[4]))); const x98: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[3]))); const x99: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[15]))); const x100: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[14]))); const x101: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[13]))); const x102: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[12]))); const x103: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[11]))); const x104: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[10]))); const x105: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[9]))); const x106: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[8]))); const x107: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[7]))); const x108: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[6]))); const x109: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[5]))); const x110: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[4]))); const x111: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[15]))); const x112: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[14]))); const x113: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[13]))); const x114: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[12]))); const x115: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[11]))); const x116: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[10]))); const x117: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[9]))); const x118: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[8]))); const x119: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[7]))); const x120: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[6]))); const x121: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[5]))); const x122: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[15]))); const x123: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[14]))); const x124: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[13]))); const x125: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[12]))); const x126: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[11]))); const x127: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[10]))); const x128: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[9]))); const x129: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[8]))); const x130: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[7]))); const x131: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[6]))); const x132: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[15]))); const x133: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[14]))); const x134: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[13]))); const x135: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[12]))); const x136: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[11]))); const x137: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[10]))); const x138: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[9]))); const x139: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[8]))); const x140: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[7]))); const x141: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[15]))); const x142: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[14]))); const x143: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[13]))); const x144: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[12]))); const x145: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[11]))); const x146: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[10]))); const x147: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[9]))); const x148: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[8]))); const x149: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[15]))); const x150: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[14]))); const x151: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[13]))); const x152: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[12]))); const x153: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[11]))); const x154: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[10]))); const x155: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[9]))); const x156: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[15]))); const x157: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[14]))); const x158: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[13]))); const x159: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[12]))); const x160: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[11]))); const x161: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[10]))); const x162: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[15]))); const x163: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[14]))); const x164: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[13]))); const x165: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[12]))); const x166: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[11]))); const x167: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[15]))); const x168: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[14]))); const x169: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[13]))); const x170: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[12]))); const x171: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[15]))); const x172: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[14]))); const x173: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[13]))); const x174: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[15]))); const x175: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[14]))); const x176: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[15]))); const x177: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[8]))); const x178: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[7]))); const x179: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[6]))); const x180: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[5]))); const x181: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[4]))); const x182: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[3]))); const x183: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[2]))); const x184: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[1]))); const x185: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[9]))); const x186: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[8]))); const x187: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[7]))); const x188: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[6]))); const x189: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[5]))); const x190: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[4]))); const x191: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[3]))); const x192: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[2]))); const x193: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[10]))); const x194: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[9]))); const x195: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[8]))); const x196: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[7]))); const x197: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[6]))); const x198: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[5]))); const x199: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[4]))); const x200: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[3]))); const x201: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[11]))); const x202: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[10]))); const x203: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[9]))); const x204: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[8]))); const x205: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[7]))); const x206: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[6]))); const x207: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[5]))); const x208: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[4]))); const x209: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[12]))); const x210: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[11]))); const x211: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[10]))); const x212: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[9]))); const x213: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[8]))); const x214: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[7]))); const x215: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[6]))); const x216: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[5]))); const x217: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[13]))); const x218: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[12]))); const x219: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[11]))); const x220: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[10]))); const x221: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[9]))); const x222: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[8]))); const x223: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[7]))); const x224: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[6]))); const x225: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[14]))); const x226: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[13]))); const x227: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[12]))); const x228: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[11]))); const x229: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[10]))); const x230: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[9]))); const x231: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[8]))); const x232: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[7]))); const x233: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[15]))); const x234: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[14]))); const x235: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[13]))); const x236: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[12]))); const x237: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[11]))); const x238: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[10]))); const x239: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[9]))); const x240: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[8]))); const x241: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[15]))); const x242: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[14]))); const x243: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[13]))); const x244: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[12]))); const x245: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[11]))); const x246: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[10]))); const x247: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[9]))); const x248: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[15]))); const x249: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[14]))); const x250: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[13]))); const x251: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[12]))); const x252: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[11]))); const x253: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[10]))); const x254: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[15]))); const x255: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[14]))); const x256: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[13]))); const x257: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[12]))); const x258: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[11]))); const x259: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[15]))); const x260: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[14]))); const x261: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[13]))); const x262: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[12]))); const x263: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[15]))); const x264: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[14]))); const x265: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[13]))); const x266: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[15]))); const x267: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[14]))); const x268: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[15]))); const x269: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, (arg2[0]))); const x270: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[1]))); const x271: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, (arg2[0]))); const x272: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[2]))); const x273: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[1]))); const x274: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, (arg2[0]))); const x275: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[3]))); const x276: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[2]))); const x277: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[1]))); const x278: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, (arg2[0]))); const x279: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[4]))); const x280: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[3]))); const x281: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[2]))); const x282: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[1]))); const x283: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, (arg2[0]))); const x284: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[5]))); const x285: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[4]))); const x286: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[3]))); const x287: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[2]))); const x288: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[1]))); const x289: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, (arg2[0]))); const x290: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[6]))); const x291: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[5]))); const x292: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[4]))); const x293: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[3]))); const x294: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[2]))); const x295: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[1]))); const x296: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, (arg2[0]))); const x297: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[7]))); const x298: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[6]))); const x299: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[5]))); const x300: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[4]))); const x301: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[3]))); const x302: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[2]))); const x303: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[1]))); const x304: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, (arg2[0]))); const x305: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[8]))); const x306: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[7]))); const x307: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[6]))); const x308: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[5]))); const x309: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[4]))); const x310: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[3]))); const x311: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[2]))); const x312: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[1]))); const x313: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg2[0]))); const x314: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[9]))); const x315: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[8]))); const x316: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[7]))); const x317: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[6]))); const x318: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[5]))); const x319: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[4]))); const x320: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[3]))); const x321: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[2]))); const x322: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[1]))); const x323: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg2[0]))); const x324: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[10]))); const x325: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[9]))); const x326: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[8]))); const x327: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[7]))); const x328: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[6]))); const x329: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[5]))); const x330: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[4]))); const x331: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[3]))); const x332: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[2]))); const x333: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[1]))); const x334: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg2[0]))); const x335: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[11]))); const x336: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[10]))); const x337: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[9]))); const x338: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[8]))); const x339: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[7]))); const x340: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[6]))); const x341: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[5]))); const x342: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[4]))); const x343: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[3]))); const x344: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[2]))); const x345: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[1]))); const x346: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg2[0]))); const x347: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[12]))); const x348: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[11]))); const x349: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[10]))); const x350: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[9]))); const x351: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[8]))); const x352: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[7]))); const x353: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[6]))); const x354: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[5]))); const x355: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[4]))); const x356: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[3]))); const x357: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[2]))); const x358: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[1]))); const x359: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg2[0]))); const x360: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[13]))); const x361: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[12]))); const x362: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[11]))); const x363: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[10]))); const x364: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[9]))); const x365: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[8]))); const x366: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[7]))); const x367: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[6]))); const x368: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[5]))); const x369: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[4]))); const x370: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[3]))); const x371: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[2]))); const x372: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[1]))); const x373: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg2[0]))); const x374: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[14]))); const x375: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[13]))); const x376: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[12]))); const x377: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[11]))); const x378: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[10]))); const x379: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[9]))); const x380: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[8]))); const x381: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[7]))); const x382: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[6]))); const x383: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[5]))); const x384: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[4]))); const x385: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[3]))); const x386: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[2]))); const x387: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[1]))); const x388: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg2[0]))); const x389: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[15]))); const x390: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[14]))); const x391: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[13]))); const x392: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[12]))); const x393: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[11]))); const x394: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[10]))); const x395: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[9]))); const x396: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[8]))); const x397: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[7]))); const x398: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[6]))); const x399: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[5]))); const x400: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[4]))); const x401: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[3]))); const x402: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[2]))); const x403: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[1]))); const x404: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg2[0]))); const x405: u64 = (x397 + (x382 + (x368 + (x355 + (x343 + (x332 + (x322 + (x313 + (x141 + (x133 + (x124 + (x114 + (x103 + (x91 + (x78 + x64))))))))))))))); const x406: u64 = (x405 >> 28); const x407: u32 = @intCast(u32, (x405 & @intCast(u64, 0xfffffff))); const x408: u64 = (x389 + (x374 + (x360 + (x347 + (x335 + (x324 + (x314 + (x305 + (x297 + (x290 + (x284 + (x279 + (x275 + (x272 + (x270 + (x269 + (x233 + (x225 + (x217 + (x209 + (x201 + (x193 + (x185 + x177))))))))))))))))))))))); const x409: u64 = (x390 + (x375 + (x361 + (x348 + (x336 + (x325 + (x315 + (x306 + (x298 + (x291 + (x285 + (x280 + (x276 + (x273 + (x271 + (x241 + (x234 + (x226 + (x218 + (x210 + (x202 + (x194 + (x186 + (x178 + (x57 + x29))))))))))))))))))))))))); const x410: u64 = (x391 + (x376 + (x362 + (x349 + (x337 + (x326 + (x316 + (x307 + (x299 + (x292 + (x286 + (x281 + (x277 + (x274 + (x248 + (x242 + (x235 + (x227 + (x219 + (x211 + (x203 + (x195 + (x187 + (x179 + (x72 + (x58 + (x36 + x30))))))))))))))))))))))))))); const x411: u128 = (@intCast(u128, x392) + (@intCast(u128, x377) + @intCast(u128, (x363 + (x350 + (x338 + (x327 + (x317 + (x308 + (x300 + (x293 + (x287 + (x282 + (x278 + (x254 + (x249 + (x243 + (x236 + (x228 + (x220 + (x212 + (x204 + (x196 + (x188 + (x180 + (x86 + (x73 + (x59 + (x42 + (x37 + x31)))))))))))))))))))))))))))))); const x412: u128 = (@intCast(u128, x393) + (@intCast(u128, x378) + (@intCast(u128, x364) + (@intCast(u128, x351) + @intCast(u128, (x339 + (x328 + (x318 + (x309 + (x301 + (x294 + (x288 + (x283 + (x259 + (x255 + (x250 + (x244 + (x237 + (x229 + (x221 + (x213 + (x205 + (x197 + (x189 + (x181 + (x99 + (x87 + (x74 + (x60 + (x47 + (x43 + (x38 + x32)))))))))))))))))))))))))))))))); const x413: u128 = (@intCast(u128, x394) + (@intCast(u128, x379) + (@intCast(u128, x365) + (@intCast(u128, x352) + (@intCast(u128, x340) + (@intCast(u128, x329) + @intCast(u128, (x319 + (x310 + (x302 + (x295 + (x289 + (x263 + (x260 + (x256 + (x251 + (x245 + (x238 + (x230 + (x222 + (x214 + (x206 + (x198 + (x190 + (x182 + (x111 + (x100 + (x88 + (x75 + (x61 + (x51 + (x48 + (x44 + (x39 + x33)))))))))))))))))))))))))))))))))); const x414: u128 = (@intCast(u128, x395) + (@intCast(u128, x380) + (@intCast(u128, x366) + (@intCast(u128, x353) + (@intCast(u128, x341) + (@intCast(u128, x330) + (@intCast(u128, x320) + (@intCast(u128, x311) + @intCast(u128, (x303 + (x296 + (x266 + (x264 + (x261 + (x257 + (x252 + (x246 + (x239 + (x231 + (x223 + (x215 + (x207 + (x199 + (x191 + (x183 + (x122 + (x112 + (x101 + (x89 + (x76 + (x62 + (x54 + (x52 + (x49 + (x45 + (x40 + x34)))))))))))))))))))))))))))))))))))); const x415: u128 = (@intCast(u128, x396) + (@intCast(u128, x381) + (@intCast(u128, x367) + (@intCast(u128, x354) + (@intCast(u128, x342) + (@intCast(u128, x331) + (@intCast(u128, x321) + (@intCast(u128, x312) + (@intCast(u128, x304) + (@intCast(u128, x268) + @intCast(u128, (x267 + (x265 + (x262 + (x258 + (x253 + (x247 + (x240 + (x232 + (x224 + (x216 + (x208 + (x200 + (x192 + (x184 + (x132 + (x123 + (x113 + (x102 + (x90 + (x77 + (x63 + (x56 + (x55 + (x53 + (x50 + (x46 + (x41 + x35)))))))))))))))))))))))))))))))))))))); const x416: u64 = (x398 + (x383 + (x369 + (x356 + (x344 + (x333 + (x323 + (x149 + (x142 + (x134 + (x125 + (x115 + (x104 + (x92 + (x79 + (x65 + x1)))))))))))))))); const x417: u64 = (x399 + (x384 + (x370 + (x357 + (x345 + (x334 + (x156 + (x150 + (x143 + (x135 + (x126 + (x116 + (x105 + (x93 + (x80 + (x66 + (x8 + x2))))))))))))))))); const x418: u64 = (x400 + (x385 + (x371 + (x358 + (x346 + (x162 + (x157 + (x151 + (x144 + (x136 + (x127 + (x117 + (x106 + (x94 + (x81 + (x67 + (x14 + (x9 + x3)))))))))))))))))); const x419: u64 = (x401 + (x386 + (x372 + (x359 + (x167 + (x163 + (x158 + (x152 + (x145 + (x137 + (x128 + (x118 + (x107 + (x95 + (x82 + (x68 + (x19 + (x15 + (x10 + x4))))))))))))))))))); const x420: u64 = (x402 + (x387 + (x373 + (x171 + (x168 + (x164 + (x159 + (x153 + (x146 + (x138 + (x129 + (x119 + (x108 + (x96 + (x83 + (x69 + (x23 + (x20 + (x16 + (x11 + x5)))))))))))))))))))); const x421: u64 = (x403 + (x388 + (x174 + (x172 + (x169 + (x165 + (x160 + (x154 + (x147 + (x139 + (x130 + (x120 + (x109 + (x97 + (x84 + (x70 + (x26 + (x24 + (x21 + (x17 + (x12 + x6))))))))))))))))))))); const x422: u64 = (x404 + (x176 + (x175 + (x173 + (x170 + (x166 + (x161 + (x155 + (x148 + (x140 + (x131 + (x121 + (x110 + (x98 + (x85 + (x71 + (x28 + (x27 + (x25 + (x22 + (x18 + (x13 + x7)))))))))))))))))))))); const x423: u128 = (@intCast(u128, x406) + x415); const x424: u64 = (x408 >> 28); const x425: u32 = @intCast(u32, (x408 & @intCast(u64, 0xfffffff))); const x426: u128 = (x423 + @intCast(u128, x424)); const x427: u64 = @intCast(u64, (x426 >> 28)); const x428: u32 = @intCast(u32, (x426 & @intCast(u128, 0xfffffff))); const x429: u64 = (x422 + x424); const x430: u128 = (@intCast(u128, x427) + x414); const x431: u64 = (x429 >> 28); const x432: u32 = @intCast(u32, (x429 & @intCast(u64, 0xfffffff))); const x433: u64 = (x431 + x421); const x434: u64 = @intCast(u64, (x430 >> 28)); const x435: u32 = @intCast(u32, (x430 & @intCast(u128, 0xfffffff))); const x436: u128 = (@intCast(u128, x434) + x413); const x437: u64 = (x433 >> 28); const x438: u32 = @intCast(u32, (x433 & @intCast(u64, 0xfffffff))); const x439: u64 = (x437 + x420); const x440: u64 = @intCast(u64, (x436 >> 28)); const x441: u32 = @intCast(u32, (x436 & @intCast(u128, 0xfffffff))); const x442: u128 = (@intCast(u128, x440) + x412); const x443: u64 = (x439 >> 28); const x444: u32 = @intCast(u32, (x439 & @intCast(u64, 0xfffffff))); const x445: u64 = (x443 + x419); const x446: u64 = @intCast(u64, (x442 >> 28)); const x447: u32 = @intCast(u32, (x442 & @intCast(u128, 0xfffffff))); const x448: u128 = (@intCast(u128, x446) + x411); const x449: u64 = (x445 >> 28); const x450: u32 = @intCast(u32, (x445 & @intCast(u64, 0xfffffff))); const x451: u64 = (x449 + x418); const x452: u64 = @intCast(u64, (x448 >> 28)); const x453: u32 = @intCast(u32, (x448 & @intCast(u128, 0xfffffff))); const x454: u64 = (x452 + x410); const x455: u64 = (x451 >> 28); const x456: u32 = @intCast(u32, (x451 & @intCast(u64, 0xfffffff))); const x457: u64 = (x455 + x417); const x458: u64 = (x454 >> 28); const x459: u32 = @intCast(u32, (x454 & @intCast(u64, 0xfffffff))); const x460: u64 = (x458 + x409); const x461: u64 = (x457 >> 28); const x462: u32 = @intCast(u32, (x457 & @intCast(u64, 0xfffffff))); const x463: u64 = (x461 + x416); const x464: u64 = (x460 >> 28); const x465: u32 = @intCast(u32, (x460 & @intCast(u64, 0xfffffff))); const x466: u64 = (x464 + @intCast(u64, x425)); const x467: u64 = (x463 >> 28); const x468: u32 = @intCast(u32, (x463 & @intCast(u64, 0xfffffff))); const x469: u64 = (x467 + @intCast(u64, x407)); const x470: u32 = @intCast(u32, (x466 >> 28)); const x471: u32 = @intCast(u32, (x466 & @intCast(u64, 0xfffffff))); const x472: u32 = @intCast(u32, (x469 >> 28)); const x473: u32 = @intCast(u32, (x469 & @intCast(u64, 0xfffffff))); const x474: u32 = (x428 + x470); const x475: u32 = (x432 + x470); const x476: u32 = (x472 + x474); const x477: u1 = @intCast(u1, (x476 >> 28)); const x478: u32 = (x476 & 0xfffffff); const x479: u32 = (@intCast(u32, x477) + x435); const x480: u1 = @intCast(u1, (x475 >> 28)); const x481: u32 = (x475 & 0xfffffff); const x482: u32 = (@intCast(u32, x480) + x438); out1[0] = x481; out1[1] = x482; out1[2] = x444; out1[3] = x450; out1[4] = x456; out1[5] = x462; out1[6] = x468; out1[7] = x473; out1[8] = x478; out1[9] = x479; out1[10] = x441; out1[11] = x447; out1[12] = x453; out1[13] = x459; out1[14] = x465; out1[15] = x471; } /// The function fiatP448CarrySquare squares a field element and reduces the result. /// Postconditions: /// eval out1 mod m = (eval arg1 * eval arg1) mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000]] pub fn fiatP448CarrySquare(out1: *[16]u32, arg1: [16]u32) void { const x1: u32 = (arg1[15]); const x2: u32 = (arg1[15]); const x3: u32 = (x1 * 0x2); const x4: u32 = (x2 * 0x2); const x5: u32 = ((arg1[15]) * 0x2); const x6: u32 = (arg1[14]); const x7: u32 = (arg1[14]); const x8: u32 = (x6 * 0x2); const x9: u32 = (x7 * 0x2); const x10: u32 = ((arg1[14]) * 0x2); const x11: u32 = (arg1[13]); const x12: u32 = (arg1[13]); const x13: u32 = (x11 * 0x2); const x14: u32 = (x12 * 0x2); const x15: u32 = ((arg1[13]) * 0x2); const x16: u32 = (arg1[12]); const x17: u32 = (arg1[12]); const x18: u32 = (x16 * 0x2); const x19: u32 = (x17 * 0x2); const x20: u32 = ((arg1[12]) * 0x2); const x21: u32 = (arg1[11]); const x22: u32 = (arg1[11]); const x23: u32 = (x21 * 0x2); const x24: u32 = (x22 * 0x2); const x25: u32 = ((arg1[11]) * 0x2); const x26: u32 = (arg1[10]); const x27: u32 = (arg1[10]); const x28: u32 = (x26 * 0x2); const x29: u32 = (x27 * 0x2); const x30: u32 = ((arg1[10]) * 0x2); const x31: u32 = (arg1[9]); const x32: u32 = (arg1[9]); const x33: u32 = (x31 * 0x2); const x34: u32 = (x32 * 0x2); const x35: u32 = ((arg1[9]) * 0x2); const x36: u32 = (arg1[8]); const x37: u32 = (arg1[8]); const x38: u32 = ((arg1[8]) * 0x2); const x39: u32 = ((arg1[7]) * 0x2); const x40: u32 = ((arg1[6]) * 0x2); const x41: u32 = ((arg1[5]) * 0x2); const x42: u32 = ((arg1[4]) * 0x2); const x43: u32 = ((arg1[3]) * 0x2); const x44: u32 = ((arg1[2]) * 0x2); const x45: u32 = ((arg1[1]) * 0x2); const x46: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, x1)); const x47: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, x3)); const x48: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, x6)); const x49: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, x3)); const x50: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, x8)); const x51: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, x11)); const x52: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, x3)); const x53: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, x8)); const x54: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, x13)); const x55: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, x16)); const x56: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, x3)); const x57: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, x8)); const x58: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, x13)); const x59: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, x3)); const x60: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, x8)); const x61: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, x3)); const x62: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, x1)); const x63: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, x3)); const x64: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, x6)); const x65: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, x3)); const x66: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, x8)); const x67: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, x11)); const x68: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, x3)); const x69: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, x8)); const x70: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, x13)); const x71: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, x16)); const x72: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, x3)); const x73: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, x8)); const x74: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, x13)); const x75: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, x3)); const x76: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, x8)); const x77: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, x3)); const x78: u64 = (@intCast(u64, (arg1[15])) * @intCast(u64, x2)); const x79: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, x4)); const x80: u64 = (@intCast(u64, (arg1[14])) * @intCast(u64, x7)); const x81: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, x4)); const x82: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, x9)); const x83: u64 = (@intCast(u64, (arg1[13])) * @intCast(u64, x12)); const x84: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, x4)); const x85: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, x9)); const x86: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, x14)); const x87: u64 = (@intCast(u64, (arg1[12])) * @intCast(u64, x17)); const x88: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, x4)); const x89: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, x9)); const x90: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, x14)); const x91: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, x19)); const x92: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, x18)); const x93: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, x22)); const x94: u64 = (@intCast(u64, (arg1[11])) * @intCast(u64, x21)); const x95: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, x4)); const x96: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, x9)); const x97: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, x14)); const x98: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, x13)); const x99: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, x19)); const x100: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, x18)); const x101: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, x24)); const x102: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, x23)); const x103: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, x27)); const x104: u64 = (@intCast(u64, (arg1[10])) * @intCast(u64, x26)); const x105: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, x4)); const x106: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, x9)); const x107: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, x8)); const x108: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, x14)); const x109: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, x13)); const x110: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, x19)); const x111: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, x18)); const x112: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, x24)); const x113: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, x23)); const x114: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, x29)); const x115: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, x28)); const x116: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, x32)); const x117: u64 = (@intCast(u64, (arg1[9])) * @intCast(u64, x31)); const x118: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x4)); const x119: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x3)); const x120: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x9)); const x121: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x8)); const x122: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x14)); const x123: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x13)); const x124: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x19)); const x125: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x18)); const x126: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x24)); const x127: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x23)); const x128: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x29)); const x129: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x28)); const x130: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x34)); const x131: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x33)); const x132: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x37)); const x133: u64 = (@intCast(u64, (arg1[8])) * @intCast(u64, x36)); const x134: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, x4)); const x135: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, x3)); const x136: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, x9)); const x137: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, x8)); const x138: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, x14)); const x139: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, x13)); const x140: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, x19)); const x141: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, x18)); const x142: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, x24)); const x143: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, x23)); const x144: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, x29)); const x145: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, x28)); const x146: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, x34)); const x147: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, x33)); const x148: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, x38)); const x149: u64 = (@intCast(u64, (arg1[7])) * @intCast(u64, (arg1[7]))); const x150: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, x4)); const x151: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, x3)); const x152: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, x9)); const x153: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, x8)); const x154: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, x14)); const x155: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, x13)); const x156: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, x19)); const x157: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, x18)); const x158: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, x24)); const x159: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, x23)); const x160: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, x29)); const x161: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, x28)); const x162: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, x35)); const x163: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, x38)); const x164: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, x39)); const x165: u64 = (@intCast(u64, (arg1[6])) * @intCast(u64, (arg1[6]))); const x166: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, x4)); const x167: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, x3)); const x168: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, x9)); const x169: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, x8)); const x170: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, x14)); const x171: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, x13)); const x172: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, x19)); const x173: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, x18)); const x174: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, x24)); const x175: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, x23)); const x176: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, x30)); const x177: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, x35)); const x178: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, x38)); const x179: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, x39)); const x180: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, x40)); const x181: u64 = (@intCast(u64, (arg1[5])) * @intCast(u64, (arg1[5]))); const x182: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x4)); const x183: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x3)); const x184: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x9)); const x185: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x8)); const x186: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x14)); const x187: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x13)); const x188: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x19)); const x189: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x18)); const x190: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x25)); const x191: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x30)); const x192: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x35)); const x193: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x38)); const x194: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x39)); const x195: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x40)); const x196: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, x41)); const x197: u64 = (@intCast(u64, (arg1[4])) * @intCast(u64, (arg1[4]))); const x198: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x4)); const x199: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x3)); const x200: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x9)); const x201: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x8)); const x202: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x14)); const x203: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x13)); const x204: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x20)); const x205: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x25)); const x206: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x30)); const x207: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x35)); const x208: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x38)); const x209: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x39)); const x210: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x40)); const x211: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x41)); const x212: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, x42)); const x213: u64 = (@intCast(u64, (arg1[3])) * @intCast(u64, (arg1[3]))); const x214: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x4)); const x215: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x3)); const x216: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x9)); const x217: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x8)); const x218: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x15)); const x219: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x20)); const x220: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x25)); const x221: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x30)); const x222: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x35)); const x223: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x38)); const x224: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x39)); const x225: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x40)); const x226: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x41)); const x227: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x42)); const x228: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, x43)); const x229: u64 = (@intCast(u64, (arg1[2])) * @intCast(u64, (arg1[2]))); const x230: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x4)); const x231: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x3)); const x232: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x10)); const x233: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x15)); const x234: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x20)); const x235: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x25)); const x236: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x30)); const x237: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x35)); const x238: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x38)); const x239: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x39)); const x240: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x40)); const x241: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x41)); const x242: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x42)); const x243: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x43)); const x244: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, x44)); const x245: u64 = (@intCast(u64, (arg1[1])) * @intCast(u64, (arg1[1]))); const x246: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x5)); const x247: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x10)); const x248: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x15)); const x249: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x20)); const x250: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x25)); const x251: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x30)); const x252: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x35)); const x253: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x38)); const x254: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x39)); const x255: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x40)); const x256: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x41)); const x257: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x42)); const x258: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x43)); const x259: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x44)); const x260: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, x45)); const x261: u64 = (@intCast(u64, (arg1[0])) * @intCast(u64, (arg1[0]))); const x262: u64 = (x254 + (x240 + (x226 + (x212 + (x118 + (x106 + (x97 + x91))))))); const x263: u64 = (x262 >> 28); const x264: u32 = @intCast(u32, (x262 & @intCast(u64, 0xfffffff))); const x265: u64 = (x246 + (x232 + (x218 + (x204 + (x190 + (x176 + (x162 + (x148 + (x119 + (x107 + (x98 + x92))))))))))); const x266: u64 = (x247 + (x233 + (x219 + (x205 + (x191 + (x177 + (x163 + (x149 + (x135 + (x121 + (x109 + (x100 + (x94 + (x78 + x62)))))))))))))); const x267: u64 = (x248 + (x234 + (x220 + (x206 + (x192 + (x178 + (x164 + (x151 + (x137 + (x123 + (x111 + (x102 + (x79 + x63))))))))))))); const x268: u128 = (@intCast(u128, x249) + @intCast(u128, (x235 + (x221 + (x207 + (x193 + (x179 + (x167 + (x165 + (x153 + (x139 + (x125 + (x113 + (x104 + (x81 + (x80 + (x65 + x64))))))))))))))))); const x269: u128 = (@intCast(u128, x250) + (@intCast(u128, x236) + @intCast(u128, (x222 + (x208 + (x194 + (x183 + (x180 + (x169 + (x155 + (x141 + (x127 + (x115 + (x84 + (x82 + (x68 + x66)))))))))))))))); const x270: u128 = (@intCast(u128, x251) + (@intCast(u128, x237) + (@intCast(u128, x223) + @intCast(u128, (x209 + (x199 + (x195 + (x185 + (x181 + (x171 + (x157 + (x143 + (x129 + (x117 + (x88 + (x85 + (x83 + (x72 + (x69 + x67))))))))))))))))))); const x271: u128 = (@intCast(u128, x252) + (@intCast(u128, x238) + (@intCast(u128, x224) + (@intCast(u128, x215) + @intCast(u128, (x210 + (x201 + (x196 + (x187 + (x173 + (x159 + (x145 + (x131 + (x95 + (x89 + (x86 + (x75 + (x73 + x70)))))))))))))))))); const x272: u128 = (@intCast(u128, x253) + (@intCast(u128, x239) + (@intCast(u128, x231) + (@intCast(u128, x225) + (@intCast(u128, x217) + @intCast(u128, (x211 + (x203 + (x197 + (x189 + (x175 + (x161 + (x147 + (x133 + (x105 + (x96 + (x90 + (x87 + (x77 + (x76 + (x74 + x71))))))))))))))))))))); const x273: u64 = (x255 + (x241 + (x227 + (x213 + (x134 + (x120 + (x108 + (x99 + (x93 + x46))))))))); const x274: u64 = (x256 + (x242 + (x228 + (x150 + (x136 + (x122 + (x110 + (x101 + x47)))))))); const x275: u64 = (x257 + (x243 + (x229 + (x166 + (x152 + (x138 + (x124 + (x112 + (x103 + (x49 + x48)))))))))); const x276: u64 = (x258 + (x244 + (x182 + (x168 + (x154 + (x140 + (x126 + (x114 + (x52 + x50))))))))); const x277: u64 = (x259 + (x245 + (x198 + (x184 + (x170 + (x156 + (x142 + (x128 + (x116 + (x56 + (x53 + x51))))))))))); const x278: u64 = (x260 + (x214 + (x200 + (x186 + (x172 + (x158 + (x144 + (x130 + (x59 + (x57 + x54)))))))))); const x279: u64 = (x261 + (x230 + (x216 + (x202 + (x188 + (x174 + (x160 + (x146 + (x132 + (x61 + (x60 + (x58 + x55)))))))))))); const x280: u128 = (@intCast(u128, x263) + x272); const x281: u64 = (x265 >> 28); const x282: u32 = @intCast(u32, (x265 & @intCast(u64, 0xfffffff))); const x283: u128 = (x280 + @intCast(u128, x281)); const x284: u64 = @intCast(u64, (x283 >> 28)); const x285: u32 = @intCast(u32, (x283 & @intCast(u128, 0xfffffff))); const x286: u64 = (x279 + x281); const x287: u128 = (@intCast(u128, x284) + x271); const x288: u64 = (x286 >> 28); const x289: u32 = @intCast(u32, (x286 & @intCast(u64, 0xfffffff))); const x290: u64 = (x288 + x278); const x291: u64 = @intCast(u64, (x287 >> 28)); const x292: u32 = @intCast(u32, (x287 & @intCast(u128, 0xfffffff))); const x293: u128 = (@intCast(u128, x291) + x270); const x294: u64 = (x290 >> 28); const x295: u32 = @intCast(u32, (x290 & @intCast(u64, 0xfffffff))); const x296: u64 = (x294 + x277); const x297: u64 = @intCast(u64, (x293 >> 28)); const x298: u32 = @intCast(u32, (x293 & @intCast(u128, 0xfffffff))); const x299: u128 = (@intCast(u128, x297) + x269); const x300: u64 = (x296 >> 28); const x301: u32 = @intCast(u32, (x296 & @intCast(u64, 0xfffffff))); const x302: u64 = (x300 + x276); const x303: u64 = @intCast(u64, (x299 >> 28)); const x304: u32 = @intCast(u32, (x299 & @intCast(u128, 0xfffffff))); const x305: u128 = (@intCast(u128, x303) + x268); const x306: u64 = (x302 >> 28); const x307: u32 = @intCast(u32, (x302 & @intCast(u64, 0xfffffff))); const x308: u64 = (x306 + x275); const x309: u64 = @intCast(u64, (x305 >> 28)); const x310: u32 = @intCast(u32, (x305 & @intCast(u128, 0xfffffff))); const x311: u64 = (x309 + x267); const x312: u64 = (x308 >> 28); const x313: u32 = @intCast(u32, (x308 & @intCast(u64, 0xfffffff))); const x314: u64 = (x312 + x274); const x315: u64 = (x311 >> 28); const x316: u32 = @intCast(u32, (x311 & @intCast(u64, 0xfffffff))); const x317: u64 = (x315 + x266); const x318: u64 = (x314 >> 28); const x319: u32 = @intCast(u32, (x314 & @intCast(u64, 0xfffffff))); const x320: u64 = (x318 + x273); const x321: u64 = (x317 >> 28); const x322: u32 = @intCast(u32, (x317 & @intCast(u64, 0xfffffff))); const x323: u64 = (x321 + @intCast(u64, x282)); const x324: u64 = (x320 >> 28); const x325: u32 = @intCast(u32, (x320 & @intCast(u64, 0xfffffff))); const x326: u64 = (x324 + @intCast(u64, x264)); const x327: u32 = @intCast(u32, (x323 >> 28)); const x328: u32 = @intCast(u32, (x323 & @intCast(u64, 0xfffffff))); const x329: u32 = @intCast(u32, (x326 >> 28)); const x330: u32 = @intCast(u32, (x326 & @intCast(u64, 0xfffffff))); const x331: u32 = (x285 + x327); const x332: u32 = (x289 + x327); const x333: u32 = (x329 + x331); const x334: u1 = @intCast(u1, (x333 >> 28)); const x335: u32 = (x333 & 0xfffffff); const x336: u32 = (@intCast(u32, x334) + x292); const x337: u1 = @intCast(u1, (x332 >> 28)); const x338: u32 = (x332 & 0xfffffff); const x339: u32 = (@intCast(u32, x337) + x295); out1[0] = x338; out1[1] = x339; out1[2] = x301; out1[3] = x307; out1[4] = x313; out1[5] = x319; out1[6] = x325; out1[7] = x330; out1[8] = x335; out1[9] = x336; out1[10] = x298; out1[11] = x304; out1[12] = x310; out1[13] = x316; out1[14] = x322; out1[15] = x328; } /// The function fiatP448Carry reduces a field element. /// Postconditions: /// eval out1 mod m = eval arg1 mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000]] pub fn fiatP448Carry(out1: *[16]u32, arg1: [16]u32) void { const x1: u32 = (arg1[7]); const x2: u32 = (arg1[15]); const x3: u32 = (x2 >> 28); const x4: u32 = (((x1 >> 28) + (arg1[8])) + x3); const x5: u32 = ((arg1[0]) + x3); const x6: u32 = ((x4 >> 28) + (arg1[9])); const x7: u32 = ((x5 >> 28) + (arg1[1])); const x8: u32 = ((x6 >> 28) + (arg1[10])); const x9: u32 = ((x7 >> 28) + (arg1[2])); const x10: u32 = ((x8 >> 28) + (arg1[11])); const x11: u32 = ((x9 >> 28) + (arg1[3])); const x12: u32 = ((x10 >> 28) + (arg1[12])); const x13: u32 = ((x11 >> 28) + (arg1[4])); const x14: u32 = ((x12 >> 28) + (arg1[13])); const x15: u32 = ((x13 >> 28) + (arg1[5])); const x16: u32 = ((x14 >> 28) + (arg1[14])); const x17: u32 = ((x15 >> 28) + (arg1[6])); const x18: u32 = ((x16 >> 28) + (x2 & 0xfffffff)); const x19: u32 = ((x17 >> 28) + (x1 & 0xfffffff)); const x20: u1 = @intCast(u1, (x18 >> 28)); const x21: u32 = ((x5 & 0xfffffff) + @intCast(u32, x20)); const x22: u32 = (@intCast(u32, @intCast(u1, (x19 >> 28))) + ((x4 & 0xfffffff) + @intCast(u32, x20))); const x23: u32 = (x21 & 0xfffffff); const x24: u32 = (@intCast(u32, @intCast(u1, (x21 >> 28))) + (x7 & 0xfffffff)); const x25: u32 = (x9 & 0xfffffff); const x26: u32 = (x11 & 0xfffffff); const x27: u32 = (x13 & 0xfffffff); const x28: u32 = (x15 & 0xfffffff); const x29: u32 = (x17 & 0xfffffff); const x30: u32 = (x19 & 0xfffffff); const x31: u32 = (x22 & 0xfffffff); const x32: u32 = (@intCast(u32, @intCast(u1, (x22 >> 28))) + (x6 & 0xfffffff)); const x33: u32 = (x8 & 0xfffffff); const x34: u32 = (x10 & 0xfffffff); const x35: u32 = (x12 & 0xfffffff); const x36: u32 = (x14 & 0xfffffff); const x37: u32 = (x16 & 0xfffffff); const x38: u32 = (x18 & 0xfffffff); out1[0] = x23; out1[1] = x24; out1[2] = x25; out1[3] = x26; out1[4] = x27; out1[5] = x28; out1[6] = x29; out1[7] = x30; out1[8] = x31; out1[9] = x32; out1[10] = x33; out1[11] = x34; out1[12] = x35; out1[13] = x36; out1[14] = x37; out1[15] = x38; } /// The function fiatP448Add adds two field elements. /// Postconditions: /// eval out1 mod m = (eval arg1 + eval arg2) mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000]] /// arg2: [[0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000]] pub fn fiatP448Add(out1: *[16]u32, arg1: [16]u32, arg2: [16]u32) void { const x1: u32 = ((arg1[0]) + (arg2[0])); const x2: u32 = ((arg1[1]) + (arg2[1])); const x3: u32 = ((arg1[2]) + (arg2[2])); const x4: u32 = ((arg1[3]) + (arg2[3])); const x5: u32 = ((arg1[4]) + (arg2[4])); const x6: u32 = ((arg1[5]) + (arg2[5])); const x7: u32 = ((arg1[6]) + (arg2[6])); const x8: u32 = ((arg1[7]) + (arg2[7])); const x9: u32 = ((arg1[8]) + (arg2[8])); const x10: u32 = ((arg1[9]) + (arg2[9])); const x11: u32 = ((arg1[10]) + (arg2[10])); const x12: u32 = ((arg1[11]) + (arg2[11])); const x13: u32 = ((arg1[12]) + (arg2[12])); const x14: u32 = ((arg1[13]) + (arg2[13])); const x15: u32 = ((arg1[14]) + (arg2[14])); const x16: u32 = ((arg1[15]) + (arg2[15])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; out1[5] = x6; out1[6] = x7; out1[7] = x8; out1[8] = x9; out1[9] = x10; out1[10] = x11; out1[11] = x12; out1[12] = x13; out1[13] = x14; out1[14] = x15; out1[15] = x16; } /// The function fiatP448Sub subtracts two field elements. /// Postconditions: /// eval out1 mod m = (eval arg1 - eval arg2) mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000]] /// arg2: [[0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000]] pub fn fiatP448Sub(out1: *[16]u32, arg1: [16]u32, arg2: [16]u32) void { const x1: u32 = ((0x1ffffffe + (arg1[0])) - (arg2[0])); const x2: u32 = ((0x1ffffffe + (arg1[1])) - (arg2[1])); const x3: u32 = ((0x1ffffffe + (arg1[2])) - (arg2[2])); const x4: u32 = ((0x1ffffffe + (arg1[3])) - (arg2[3])); const x5: u32 = ((0x1ffffffe + (arg1[4])) - (arg2[4])); const x6: u32 = ((0x1ffffffe + (arg1[5])) - (arg2[5])); const x7: u32 = ((0x1ffffffe + (arg1[6])) - (arg2[6])); const x8: u32 = ((0x1ffffffe + (arg1[7])) - (arg2[7])); const x9: u32 = ((0x1ffffffc + (arg1[8])) - (arg2[8])); const x10: u32 = ((0x1ffffffe + (arg1[9])) - (arg2[9])); const x11: u32 = ((0x1ffffffe + (arg1[10])) - (arg2[10])); const x12: u32 = ((0x1ffffffe + (arg1[11])) - (arg2[11])); const x13: u32 = ((0x1ffffffe + (arg1[12])) - (arg2[12])); const x14: u32 = ((0x1ffffffe + (arg1[13])) - (arg2[13])); const x15: u32 = ((0x1ffffffe + (arg1[14])) - (arg2[14])); const x16: u32 = ((0x1ffffffe + (arg1[15])) - (arg2[15])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; out1[5] = x6; out1[6] = x7; out1[7] = x8; out1[8] = x9; out1[9] = x10; out1[10] = x11; out1[11] = x12; out1[12] = x13; out1[13] = x14; out1[14] = x15; out1[15] = x16; } /// The function fiatP448Opp negates a field element. /// Postconditions: /// eval out1 mod m = -eval arg1 mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000]] /// Output Bounds: /// out1: [[0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000], [0x0 ~> 0x30000000]] pub fn fiatP448Opp(out1: *[16]u32, arg1: [16]u32) void { const x1: u32 = (0x1ffffffe - (arg1[0])); const x2: u32 = (0x1ffffffe - (arg1[1])); const x3: u32 = (0x1ffffffe - (arg1[2])); const x4: u32 = (0x1ffffffe - (arg1[3])); const x5: u32 = (0x1ffffffe - (arg1[4])); const x6: u32 = (0x1ffffffe - (arg1[5])); const x7: u32 = (0x1ffffffe - (arg1[6])); const x8: u32 = (0x1ffffffe - (arg1[7])); const x9: u32 = (0x1ffffffc - (arg1[8])); const x10: u32 = (0x1ffffffe - (arg1[9])); const x11: u32 = (0x1ffffffe - (arg1[10])); const x12: u32 = (0x1ffffffe - (arg1[11])); const x13: u32 = (0x1ffffffe - (arg1[12])); const x14: u32 = (0x1ffffffe - (arg1[13])); const x15: u32 = (0x1ffffffe - (arg1[14])); const x16: u32 = (0x1ffffffe - (arg1[15])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; out1[5] = x6; out1[6] = x7; out1[7] = x8; out1[8] = x9; out1[9] = x10; out1[10] = x11; out1[11] = x12; out1[12] = x13; out1[13] = x14; out1[14] = x15; out1[15] = x16; } /// The function fiatP448Selectznz 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 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatP448Selectznz(out1: *[16]u32, arg1: u1, arg2: [16]u32, arg3: [16]u32) void { var x1: u32 = undefined; fiatP448CmovznzU32(&x1, arg1, (arg2[0]), (arg3[0])); var x2: u32 = undefined; fiatP448CmovznzU32(&x2, arg1, (arg2[1]), (arg3[1])); var x3: u32 = undefined; fiatP448CmovznzU32(&x3, arg1, (arg2[2]), (arg3[2])); var x4: u32 = undefined; fiatP448CmovznzU32(&x4, arg1, (arg2[3]), (arg3[3])); var x5: u32 = undefined; fiatP448CmovznzU32(&x5, arg1, (arg2[4]), (arg3[4])); var x6: u32 = undefined; fiatP448CmovznzU32(&x6, arg1, (arg2[5]), (arg3[5])); var x7: u32 = undefined; fiatP448CmovznzU32(&x7, arg1, (arg2[6]), (arg3[6])); var x8: u32 = undefined; fiatP448CmovznzU32(&x8, arg1, (arg2[7]), (arg3[7])); var x9: u32 = undefined; fiatP448CmovznzU32(&x9, arg1, (arg2[8]), (arg3[8])); var x10: u32 = undefined; fiatP448CmovznzU32(&x10, arg1, (arg2[9]), (arg3[9])); var x11: u32 = undefined; fiatP448CmovznzU32(&x11, arg1, (arg2[10]), (arg3[10])); var x12: u32 = undefined; fiatP448CmovznzU32(&x12, arg1, (arg2[11]), (arg3[11])); var x13: u32 = undefined; fiatP448CmovznzU32(&x13, arg1, (arg2[12]), (arg3[12])); var x14: u32 = undefined; fiatP448CmovznzU32(&x14, arg1, (arg2[13]), (arg3[13])); var x15: u32 = undefined; fiatP448CmovznzU32(&x15, arg1, (arg2[14]), (arg3[14])); var x16: u32 = undefined; fiatP448CmovznzU32(&x16, arg1, (arg2[15]), (arg3[15])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; out1[5] = x6; out1[6] = x7; out1[7] = x8; out1[8] = x9; out1[9] = x10; out1[10] = x11; out1[11] = x12; out1[12] = x13; out1[13] = x14; out1[14] = x15; out1[15] = x16; } /// The function fiatP448ToBytes serializes a field element to bytes in little-endian order. /// Postconditions: /// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..55] /// /// Input Bounds: /// arg1: [[0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000]] /// 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], [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 fiatP448ToBytes(out1: *[56]u8, arg1: [16]u32) void { var x1: u32 = undefined; var x2: u1 = undefined; fiatP448SubborrowxU28(&x1, &x2, 0x0, (arg1[0]), 0xfffffff); var x3: u32 = undefined; var x4: u1 = undefined; fiatP448SubborrowxU28(&x3, &x4, x2, (arg1[1]), 0xfffffff); var x5: u32 = undefined; var x6: u1 = undefined; fiatP448SubborrowxU28(&x5, &x6, x4, (arg1[2]), 0xfffffff); var x7: u32 = undefined; var x8: u1 = undefined; fiatP448SubborrowxU28(&x7, &x8, x6, (arg1[3]), 0xfffffff); var x9: u32 = undefined; var x10: u1 = undefined; fiatP448SubborrowxU28(&x9, &x10, x8, (arg1[4]), 0xfffffff); var x11: u32 = undefined; var x12: u1 = undefined; fiatP448SubborrowxU28(&x11, &x12, x10, (arg1[5]), 0xfffffff); var x13: u32 = undefined; var x14: u1 = undefined; fiatP448SubborrowxU28(&x13, &x14, x12, (arg1[6]), 0xfffffff); var x15: u32 = undefined; var x16: u1 = undefined; fiatP448SubborrowxU28(&x15, &x16, x14, (arg1[7]), 0xfffffff); var x17: u32 = undefined; var x18: u1 = undefined; fiatP448SubborrowxU28(&x17, &x18, x16, (arg1[8]), 0xffffffe); var x19: u32 = undefined; var x20: u1 = undefined; fiatP448SubborrowxU28(&x19, &x20, x18, (arg1[9]), 0xfffffff); var x21: u32 = undefined; var x22: u1 = undefined; fiatP448SubborrowxU28(&x21, &x22, x20, (arg1[10]), 0xfffffff); var x23: u32 = undefined; var x24: u1 = undefined; fiatP448SubborrowxU28(&x23, &x24, x22, (arg1[11]), 0xfffffff); var x25: u32 = undefined; var x26: u1 = undefined; fiatP448SubborrowxU28(&x25, &x26, x24, (arg1[12]), 0xfffffff); var x27: u32 = undefined; var x28: u1 = undefined; fiatP448SubborrowxU28(&x27, &x28, x26, (arg1[13]), 0xfffffff); var x29: u32 = undefined; var x30: u1 = undefined; fiatP448SubborrowxU28(&x29, &x30, x28, (arg1[14]), 0xfffffff); var x31: u32 = undefined; var x32: u1 = undefined; fiatP448SubborrowxU28(&x31, &x32, x30, (arg1[15]), 0xfffffff); var x33: u32 = undefined; fiatP448CmovznzU32(&x33, x32, @intCast(u32, 0x0), 0xffffffff); var x34: u32 = undefined; var x35: u1 = undefined; fiatP448AddcarryxU28(&x34, &x35, 0x0, x1, (x33 & 0xfffffff)); var x36: u32 = undefined; var x37: u1 = undefined; fiatP448AddcarryxU28(&x36, &x37, x35, x3, (x33 & 0xfffffff)); var x38: u32 = undefined; var x39: u1 = undefined; fiatP448AddcarryxU28(&x38, &x39, x37, x5, (x33 & 0xfffffff)); var x40: u32 = undefined; var x41: u1 = undefined; fiatP448AddcarryxU28(&x40, &x41, x39, x7, (x33 & 0xfffffff)); var x42: u32 = undefined; var x43: u1 = undefined; fiatP448AddcarryxU28(&x42, &x43, x41, x9, (x33 & 0xfffffff)); var x44: u32 = undefined; var x45: u1 = undefined; fiatP448AddcarryxU28(&x44, &x45, x43, x11, (x33 & 0xfffffff)); var x46: u32 = undefined; var x47: u1 = undefined; fiatP448AddcarryxU28(&x46, &x47, x45, x13, (x33 & 0xfffffff)); var x48: u32 = undefined; var x49: u1 = undefined; fiatP448AddcarryxU28(&x48, &x49, x47, x15, (x33 & 0xfffffff)); var x50: u32 = undefined; var x51: u1 = undefined; fiatP448AddcarryxU28(&x50, &x51, x49, x17, (x33 & 0xffffffe)); var x52: u32 = undefined; var x53: u1 = undefined; fiatP448AddcarryxU28(&x52, &x53, x51, x19, (x33 & 0xfffffff)); var x54: u32 = undefined; var x55: u1 = undefined; fiatP448AddcarryxU28(&x54, &x55, x53, x21, (x33 & 0xfffffff)); var x56: u32 = undefined; var x57: u1 = undefined; fiatP448AddcarryxU28(&x56, &x57, x55, x23, (x33 & 0xfffffff)); var x58: u32 = undefined; var x59: u1 = undefined; fiatP448AddcarryxU28(&x58, &x59, x57, x25, (x33 & 0xfffffff)); var x60: u32 = undefined; var x61: u1 = undefined; fiatP448AddcarryxU28(&x60, &x61, x59, x27, (x33 & 0xfffffff)); var x62: u32 = undefined; var x63: u1 = undefined; fiatP448AddcarryxU28(&x62, &x63, x61, x29, (x33 & 0xfffffff)); var x64: u32 = undefined; var x65: u1 = undefined; fiatP448AddcarryxU28(&x64, &x65, x63, x31, (x33 & 0xfffffff)); const x66: u32 = (x64 << 4); const x67: u32 = (x60 << 4); const x68: u32 = (x56 << 4); const x69: u32 = (x52 << 4); const x70: u32 = (x48 << 4); const x71: u32 = (x44 << 4); const x72: u32 = (x40 << 4); const x73: u32 = (x36 << 4); const x74: u8 = @intCast(u8, (x34 & @intCast(u32, 0xff))); const x75: u32 = (x34 >> 8); const x76: u8 = @intCast(u8, (x75 & @intCast(u32, 0xff))); const x77: u32 = (x75 >> 8); const x78: u8 = @intCast(u8, (x77 & @intCast(u32, 0xff))); const x79: u8 = @intCast(u8, (x77 >> 8)); const x80: u32 = (x73 + @intCast(u32, x79)); const x81: u8 = @intCast(u8, (x80 & @intCast(u32, 0xff))); const x82: u32 = (x80 >> 8); const x83: u8 = @intCast(u8, (x82 & @intCast(u32, 0xff))); const x84: u32 = (x82 >> 8); const x85: u8 = @intCast(u8, (x84 & @intCast(u32, 0xff))); const x86: u8 = @intCast(u8, (x84 >> 8)); const x87: u8 = @intCast(u8, (x38 & @intCast(u32, 0xff))); const x88: u32 = (x38 >> 8); const x89: u8 = @intCast(u8, (x88 & @intCast(u32, 0xff))); const x90: u32 = (x88 >> 8); const x91: u8 = @intCast(u8, (x90 & @intCast(u32, 0xff))); const x92: u8 = @intCast(u8, (x90 >> 8)); const x93: u32 = (x72 + @intCast(u32, x92)); const x94: u8 = @intCast(u8, (x93 & @intCast(u32, 0xff))); const x95: u32 = (x93 >> 8); const x96: u8 = @intCast(u8, (x95 & @intCast(u32, 0xff))); const x97: u32 = (x95 >> 8); const x98: u8 = @intCast(u8, (x97 & @intCast(u32, 0xff))); const x99: u8 = @intCast(u8, (x97 >> 8)); const x100: u8 = @intCast(u8, (x42 & @intCast(u32, 0xff))); const x101: u32 = (x42 >> 8); const x102: u8 = @intCast(u8, (x101 & @intCast(u32, 0xff))); const x103: u32 = (x101 >> 8); const x104: u8 = @intCast(u8, (x103 & @intCast(u32, 0xff))); const x105: u8 = @intCast(u8, (x103 >> 8)); const x106: u32 = (x71 + @intCast(u32, x105)); const x107: u8 = @intCast(u8, (x106 & @intCast(u32, 0xff))); const x108: u32 = (x106 >> 8); const x109: u8 = @intCast(u8, (x108 & @intCast(u32, 0xff))); const x110: u32 = (x108 >> 8); const x111: u8 = @intCast(u8, (x110 & @intCast(u32, 0xff))); const x112: u8 = @intCast(u8, (x110 >> 8)); const x113: u8 = @intCast(u8, (x46 & @intCast(u32, 0xff))); const x114: u32 = (x46 >> 8); const x115: u8 = @intCast(u8, (x114 & @intCast(u32, 0xff))); const x116: u32 = (x114 >> 8); const x117: u8 = @intCast(u8, (x116 & @intCast(u32, 0xff))); const x118: u8 = @intCast(u8, (x116 >> 8)); const x119: u32 = (x70 + @intCast(u32, x118)); const x120: u8 = @intCast(u8, (x119 & @intCast(u32, 0xff))); const x121: u32 = (x119 >> 8); const x122: u8 = @intCast(u8, (x121 & @intCast(u32, 0xff))); const x123: u32 = (x121 >> 8); const x124: u8 = @intCast(u8, (x123 & @intCast(u32, 0xff))); const x125: u8 = @intCast(u8, (x123 >> 8)); const x126: u8 = @intCast(u8, (x50 & @intCast(u32, 0xff))); const x127: u32 = (x50 >> 8); const x128: u8 = @intCast(u8, (x127 & @intCast(u32, 0xff))); const x129: u32 = (x127 >> 8); const x130: u8 = @intCast(u8, (x129 & @intCast(u32, 0xff))); const x131: u8 = @intCast(u8, (x129 >> 8)); const x132: u32 = (x69 + @intCast(u32, x131)); const x133: u8 = @intCast(u8, (x132 & @intCast(u32, 0xff))); const x134: u32 = (x132 >> 8); const x135: u8 = @intCast(u8, (x134 & @intCast(u32, 0xff))); const x136: u32 = (x134 >> 8); const x137: u8 = @intCast(u8, (x136 & @intCast(u32, 0xff))); const x138: u8 = @intCast(u8, (x136 >> 8)); const x139: u8 = @intCast(u8, (x54 & @intCast(u32, 0xff))); const x140: u32 = (x54 >> 8); const x141: u8 = @intCast(u8, (x140 & @intCast(u32, 0xff))); const x142: u32 = (x140 >> 8); const x143: u8 = @intCast(u8, (x142 & @intCast(u32, 0xff))); const x144: u8 = @intCast(u8, (x142 >> 8)); const x145: u32 = (x68 + @intCast(u32, x144)); const x146: u8 = @intCast(u8, (x145 & @intCast(u32, 0xff))); const x147: u32 = (x145 >> 8); const x148: u8 = @intCast(u8, (x147 & @intCast(u32, 0xff))); const x149: u32 = (x147 >> 8); const x150: u8 = @intCast(u8, (x149 & @intCast(u32, 0xff))); const x151: u8 = @intCast(u8, (x149 >> 8)); const x152: u8 = @intCast(u8, (x58 & @intCast(u32, 0xff))); const x153: u32 = (x58 >> 8); const x154: u8 = @intCast(u8, (x153 & @intCast(u32, 0xff))); const x155: u32 = (x153 >> 8); const x156: u8 = @intCast(u8, (x155 & @intCast(u32, 0xff))); const x157: u8 = @intCast(u8, (x155 >> 8)); const x158: u32 = (x67 + @intCast(u32, x157)); const x159: u8 = @intCast(u8, (x158 & @intCast(u32, 0xff))); const x160: u32 = (x158 >> 8); const x161: u8 = @intCast(u8, (x160 & @intCast(u32, 0xff))); const x162: u32 = (x160 >> 8); const x163: u8 = @intCast(u8, (x162 & @intCast(u32, 0xff))); const x164: u8 = @intCast(u8, (x162 >> 8)); const x165: u8 = @intCast(u8, (x62 & @intCast(u32, 0xff))); const x166: u32 = (x62 >> 8); const x167: u8 = @intCast(u8, (x166 & @intCast(u32, 0xff))); const x168: u32 = (x166 >> 8); const x169: u8 = @intCast(u8, (x168 & @intCast(u32, 0xff))); const x170: u8 = @intCast(u8, (x168 >> 8)); const x171: u32 = (x66 + @intCast(u32, x170)); const x172: u8 = @intCast(u8, (x171 & @intCast(u32, 0xff))); const x173: u32 = (x171 >> 8); const x174: u8 = @intCast(u8, (x173 & @intCast(u32, 0xff))); const x175: u32 = (x173 >> 8); const x176: u8 = @intCast(u8, (x175 & @intCast(u32, 0xff))); const x177: u8 = @intCast(u8, (x175 >> 8)); out1[0] = x74; out1[1] = x76; out1[2] = x78; out1[3] = x81; out1[4] = x83; out1[5] = x85; out1[6] = x86; out1[7] = x87; out1[8] = x89; out1[9] = x91; out1[10] = x94; out1[11] = x96; out1[12] = x98; out1[13] = x99; out1[14] = x100; out1[15] = x102; out1[16] = x104; out1[17] = x107; out1[18] = x109; out1[19] = x111; out1[20] = x112; out1[21] = x113; out1[22] = x115; out1[23] = x117; out1[24] = x120; out1[25] = x122; out1[26] = x124; out1[27] = x125; out1[28] = x126; out1[29] = x128; out1[30] = x130; out1[31] = x133; out1[32] = x135; out1[33] = x137; out1[34] = x138; out1[35] = x139; out1[36] = x141; out1[37] = x143; out1[38] = x146; out1[39] = x148; out1[40] = x150; out1[41] = x151; out1[42] = x152; out1[43] = x154; out1[44] = x156; out1[45] = x159; out1[46] = x161; out1[47] = x163; out1[48] = x164; out1[49] = x165; out1[50] = x167; out1[51] = x169; out1[52] = x172; out1[53] = x174; out1[54] = x176; out1[55] = x177; } /// The function fiatP448FromBytes deserializes a field element from bytes in little-endian order. /// Postconditions: /// eval out1 mod m = bytes_eval arg1 mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 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], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] /// Output Bounds: /// out1: [[0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000], [0x0 ~> 0x10000000]] pub fn fiatP448FromBytes(out1: *[16]u32, arg1: [56]u8) void { const x1: u32 = (@intCast(u32, (arg1[55])) << 20); const x2: u32 = (@intCast(u32, (arg1[54])) << 12); const x3: u32 = (@intCast(u32, (arg1[53])) << 4); const x4: u32 = (@intCast(u32, (arg1[52])) << 24); const x5: u32 = (@intCast(u32, (arg1[51])) << 16); const x6: u32 = (@intCast(u32, (arg1[50])) << 8); const x7: u8 = (arg1[49]); const x8: u32 = (@intCast(u32, (arg1[48])) << 20); const x9: u32 = (@intCast(u32, (arg1[47])) << 12); const x10: u32 = (@intCast(u32, (arg1[46])) << 4); const x11: u32 = (@intCast(u32, (arg1[45])) << 24); const x12: u32 = (@intCast(u32, (arg1[44])) << 16); const x13: u32 = (@intCast(u32, (arg1[43])) << 8); const x14: u8 = (arg1[42]); const x15: u32 = (@intCast(u32, (arg1[41])) << 20); const x16: u32 = (@intCast(u32, (arg1[40])) << 12); const x17: u32 = (@intCast(u32, (arg1[39])) << 4); const x18: u32 = (@intCast(u32, (arg1[38])) << 24); const x19: u32 = (@intCast(u32, (arg1[37])) << 16); const x20: u32 = (@intCast(u32, (arg1[36])) << 8); const x21: u8 = (arg1[35]); const x22: u32 = (@intCast(u32, (arg1[34])) << 20); const x23: u32 = (@intCast(u32, (arg1[33])) << 12); const x24: u32 = (@intCast(u32, (arg1[32])) << 4); const x25: u32 = (@intCast(u32, (arg1[31])) << 24); const x26: u32 = (@intCast(u32, (arg1[30])) << 16); const x27: u32 = (@intCast(u32, (arg1[29])) << 8); const x28: u8 = (arg1[28]); const x29: u32 = (@intCast(u32, (arg1[27])) << 20); const x30: u32 = (@intCast(u32, (arg1[26])) << 12); const x31: u32 = (@intCast(u32, (arg1[25])) << 4); const x32: u32 = (@intCast(u32, (arg1[24])) << 24); const x33: u32 = (@intCast(u32, (arg1[23])) << 16); const x34: u32 = (@intCast(u32, (arg1[22])) << 8); const x35: u8 = (arg1[21]); const x36: u32 = (@intCast(u32, (arg1[20])) << 20); const x37: u32 = (@intCast(u32, (arg1[19])) << 12); const x38: u32 = (@intCast(u32, (arg1[18])) << 4); const x39: u32 = (@intCast(u32, (arg1[17])) << 24); const x40: u32 = (@intCast(u32, (arg1[16])) << 16); const x41: u32 = (@intCast(u32, (arg1[15])) << 8); const x42: u8 = (arg1[14]); const x43: u32 = (@intCast(u32, (arg1[13])) << 20); const x44: u32 = (@intCast(u32, (arg1[12])) << 12); const x45: u32 = (@intCast(u32, (arg1[11])) << 4); const x46: u32 = (@intCast(u32, (arg1[10])) << 24); const x47: u32 = (@intCast(u32, (arg1[9])) << 16); const x48: u32 = (@intCast(u32, (arg1[8])) << 8); const x49: u8 = (arg1[7]); const x50: u32 = (@intCast(u32, (arg1[6])) << 20); const x51: u32 = (@intCast(u32, (arg1[5])) << 12); const x52: u32 = (@intCast(u32, (arg1[4])) << 4); const x53: u32 = (@intCast(u32, (arg1[3])) << 24); const x54: u32 = (@intCast(u32, (arg1[2])) << 16); const x55: u32 = (@intCast(u32, (arg1[1])) << 8); const x56: u8 = (arg1[0]); const x57: u32 = (x55 + @intCast(u32, x56)); const x58: u32 = (x54 + x57); const x59: u32 = (x53 + x58); const x60: u32 = (x59 & 0xfffffff); const x61: u8 = @intCast(u8, (x59 >> 28)); const x62: u32 = (x52 + @intCast(u32, x61)); const x63: u32 = (x51 + x62); const x64: u32 = (x50 + x63); const x65: u32 = (x48 + @intCast(u32, x49)); const x66: u32 = (x47 + x65); const x67: u32 = (x46 + x66); const x68: u32 = (x67 & 0xfffffff); const x69: u8 = @intCast(u8, (x67 >> 28)); const x70: u32 = (x45 + @intCast(u32, x69)); const x71: u32 = (x44 + x70); const x72: u32 = (x43 + x71); const x73: u32 = (x41 + @intCast(u32, x42)); const x74: u32 = (x40 + x73); const x75: u32 = (x39 + x74); const x76: u32 = (x75 & 0xfffffff); const x77: u8 = @intCast(u8, (x75 >> 28)); const x78: u32 = (x38 + @intCast(u32, x77)); const x79: u32 = (x37 + x78); const x80: u32 = (x36 + x79); const x81: u32 = (x34 + @intCast(u32, x35)); const x82: u32 = (x33 + x81); const x83: u32 = (x32 + x82); const x84: u32 = (x83 & 0xfffffff); const x85: u8 = @intCast(u8, (x83 >> 28)); const x86: u32 = (x31 + @intCast(u32, x85)); const x87: u32 = (x30 + x86); const x88: u32 = (x29 + x87); const x89: u32 = (x27 + @intCast(u32, x28)); const x90: u32 = (x26 + x89); const x91: u32 = (x25 + x90); const x92: u32 = (x91 & 0xfffffff); const x93: u8 = @intCast(u8, (x91 >> 28)); const x94: u32 = (x24 + @intCast(u32, x93)); const x95: u32 = (x23 + x94); const x96: u32 = (x22 + x95); const x97: u32 = (x20 + @intCast(u32, x21)); const x98: u32 = (x19 + x97); const x99: u32 = (x18 + x98); const x100: u32 = (x99 & 0xfffffff); const x101: u8 = @intCast(u8, (x99 >> 28)); const x102: u32 = (x17 + @intCast(u32, x101)); const x103: u32 = (x16 + x102); const x104: u32 = (x15 + x103); const x105: u32 = (x13 + @intCast(u32, x14)); const x106: u32 = (x12 + x105); const x107: u32 = (x11 + x106); const x108: u32 = (x107 & 0xfffffff); const x109: u8 = @intCast(u8, (x107 >> 28)); const x110: u32 = (x10 + @intCast(u32, x109)); const x111: u32 = (x9 + x110); const x112: u32 = (x8 + x111); const x113: u32 = (x6 + @intCast(u32, x7)); const x114: u32 = (x5 + x113); const x115: u32 = (x4 + x114); const x116: u32 = (x115 & 0xfffffff); const x117: u8 = @intCast(u8, (x115 >> 28)); const x118: u32 = (x3 + @intCast(u32, x117)); const x119: u32 = (x2 + x118); const x120: u32 = (x1 + x119); out1[0] = x60; out1[1] = x64; out1[2] = x68; out1[3] = x72; out1[4] = x76; out1[5] = x80; out1[6] = x84; out1[7] = x88; out1[8] = x92; out1[9] = x96; out1[10] = x100; out1[11] = x104; out1[12] = x108; out1[13] = x112; out1[14] = x116; out1[15] = x120; }
fiat-zig/src/p448_solinas_32.zig
const std = @import("std"); const dbg = std.debug; pub fn main() void { var fuel_for_module_mass: i32 = 0; var fuel_for_total_mass: i32 = 0; for (input) |mass| { var module_mass_fuel = get_fuel(mass); var total_fuel = get_total_module_fuel(mass); fuel_for_module_mass += module_mass_fuel; fuel_for_total_mass += total_fuel; } dbg.warn("01-1 Total fuel for the modules: {}\n", fuel_for_module_mass); dbg.warn("01-2 Total fuel for the modules and fuel: {}\n", fuel_for_total_mass); } fn get_fuel(mass: i32) i32 { return @divFloor(mass, 3) - 2; } test "get fuel" { dbg.assert(get_fuel(12) == 2); dbg.assert(get_fuel(14) == 2); dbg.assert(get_fuel(1969) == 654); dbg.assert(get_fuel(100756) == 33583); } fn get_total_module_fuel(module_mass: i32) i32 { const module_fuel_mass = get_fuel(module_mass); var unfueled_fuel = module_fuel_mass; var fuel_fuel_mass: i32 = 0; while (unfueled_fuel > 0) { // "fuel" is a really strange word var fuel_for_fuel = get_fuel(unfueled_fuel); if (fuel_for_fuel <= 0) { break; } fuel_fuel_mass += fuel_for_fuel; unfueled_fuel = fuel_for_fuel; } return module_fuel_mass + fuel_fuel_mass; } test "get total module fuel" { dbg.assert(get_total_module_fuel(14) == 2); dbg.assert(get_total_module_fuel(1969) == 966); dbg.assert(get_total_module_fuel(100756) == 50346); } const input = [_]i32{ 91617, 134652, 101448, 83076, 53032, 80487, 106061, 103085, 71513, 143874, 102830, 121433, 139937, 104468, 53098, 75999, 113915, 73992, 90028, 64164, 101248, 111333, 89201, 89076, 129360, 81573, 54381, 64105, 104272, 144188, 81022, 125558, 87910, 135654, 110929, 131610, 147160, 139648, 118129, 93967, 123117, 77927, 112034, 84847, 145527, 72652, 123043, 136324, 71228, 118583, 56992, 141812, 60119, 105185, 97653, 134563, 54195, 64473, 75606, 148515, 88765, 112562, 52156, 119805, 117149, 149791, 128964, 108955, 55806, 86025, 148350, 74382, 73632, 141124, 101688, 106829, 132594, 113645, 90320, 104874, 95210, 118499, 56445, 86371, 113833, 122860, 112507, 55964, 105993, 92005, 83760, 90258, 56238, 127426, 147641, 129484, 107162, 99535, 107975, 136238, };
2019/day01.zig
const builtin = @import("builtin"); const TypeId = builtin.TypeId; const std = @import("std"); const math = std.math; const assert = std.debug.assert; const warn = std.debug.warn; const bufPrint = std.fmt.bufPrint; const matrix = @import("matrix.zig"); const Matrix = matrix.Matrix; const M44f32 = matrix.M44f32; const m44f32_unit = matrix.m44f32_unit; const ae = @import("../modules/zig-approxEql/approxeql.zig"); const tc = @import("typeconversions.zig"); const testExpected = @import("testexpected.zig").testExpected; const DBG = false; pub fn Vec(comptime T: type, comptime size: usize) type { if (@typeId(T) != TypeId.Float) @compileError("Vec only support TypeId.Floats at this time"); switch (size) { 2 => { return struct { const Self = @This(); pub m: Matrix(T, 1, size), pub fn init(xp: T, yp: T) Self { var mtrx: Self = undefined; mtrx.m.data[0][0] = xp; mtrx.m.data[0][1] = yp; return mtrx; } pub fn initVal(val: T) Self { return Vec(T, size).init(val, val); } pub fn x(pSelf: *const Self) T { return pSelf.m.data[0][0]; } pub fn y(pSelf: *const Self) T { return pSelf.m.data[0][1]; } pub fn setX(pSelf: *Self, v: T) void { pSelf.m.data[0][0] = v; } pub fn setY(pSelf: *Self, v: T) void { pSelf.m.data[0][1] = v; } pub fn eql(pSelf: *const Self, pOther: *const Self) bool { return pSelf.x() == pOther.x() and pSelf.y() == pOther.y(); } pub fn approxEql(pSelf: *const Self, pOther: *const Self, digits: usize) bool { return ae.approxEql(pSelf.x(), pOther.x(), digits) and ae.approxEql(pSelf.y(), pOther.y(), digits); } pub fn neg(pSelf: *const Self) Self { return Vec(T, size).init(-pSelf.x(), -pSelf.y()); } pub fn add(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init((pSelf.x() + pOther.x()), (pSelf.y() + pOther.y())); } pub fn sub(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.x() - pOther.x()), (pSelf.y() - pOther.y()), ); } pub fn mul(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.x() * pOther.x()), (pSelf.y() * pOther.y()), ); } pub fn div(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.x() / pOther.x()), (pSelf.y() / pOther.y()), ); } /// Custom format routine pub fn format( self: *const Self, comptime fmt: []const u8, context: var, comptime FmtError: type, output: fn (@typeOf(context), []const u8) FmtError!void, ) FmtError!void { try formatVec(T, size, self, fmt, context, FmtError, output); } }; }, 3 => { return struct { const Self = @This(); pub m: Matrix(T, 1, size), pub fn init(xp: T, yp: T, zp: T) Self { var mtrx: Self = undefined; mtrx.m.data[0][0] = xp; mtrx.m.data[0][1] = yp; mtrx.m.data[0][2] = zp; return mtrx; } pub fn initVal(val: T) Self { return Vec(T, size).init(val, val, val); } pub fn x(pSelf: *const Self) T { return pSelf.m.data[0][0]; } pub fn y(pSelf: *const Self) T { return pSelf.m.data[0][1]; } pub fn z(pSelf: *const Self) T { return pSelf.m.data[0][2]; } pub fn setX(pSelf: *Self, v: T) void { pSelf.m.data[0][0] = v; } pub fn setY(pSelf: *Self, v: T) void { pSelf.m.data[0][1] = v; } pub fn setZ(pSelf: *Self, v: T) void { pSelf.m.data[0][2] = v; } pub fn eql(pSelf: *const Self, pOther: *const Self) bool { return pSelf.x() == pOther.x() and pSelf.y() == pOther.y() and pSelf.z() == pOther.z(); } pub fn approxEql(pSelf: *const Self, pOther: *const Self, digits: usize) bool { return ae.approxEql(pSelf.x(), pOther.x(), digits) and ae.approxEql(pSelf.y(), pOther.y(), digits) and ae.approxEql(pSelf.z(), pOther.z(), digits); } pub fn neg(pSelf: *const Self) Self { return Vec(T, size).init(-pSelf.x(), -pSelf.y(), -pSelf.z()); } pub fn add(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.x() + pOther.x()), (pSelf.y() + pOther.y()), (pSelf.z() + pOther.z()), ); } pub fn sub(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.x() - pOther.x()), (pSelf.y() - pOther.y()), (pSelf.z() - pOther.z()), ); } pub fn mul(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.x() * pOther.x()), (pSelf.y() * pOther.y()), (pSelf.z() * pOther.z()), ); } pub fn div(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.x() / pOther.x()), (pSelf.y() / pOther.y()), (pSelf.z() / pOther.z()), ); } /// Custom format routine pub fn format( self: *const Self, comptime fmt: []const u8, context: var, comptime FmtError: type, output: fn (@typeOf(context), []const u8) FmtError!void, ) FmtError!void { try formatVec(T, size, self, fmt, context, FmtError, output); } /// Returns the length as a f64, f32 or f16 pub fn length(pSelf: *const Self) T { return math.sqrt(pSelf.normal()); } pub fn dot(pSelf: *const Self, pOther: *const Self) T { return (pSelf.x() * pOther.x()) + (pSelf.y() * pOther.y()) + (pSelf.z() * pOther.z()); } pub fn normal(pSelf: *const Self) T { return (pSelf.x() * pSelf.x()) + (pSelf.y() * pSelf.y()) + (pSelf.z() * pSelf.z()); } pub fn normalize(pSelf: *const Self) Self { var len = pSelf.length(); var v: Self = undefined; if (len > 0) { v.setX(pSelf.x() / len); v.setY(pSelf.y() / len); v.setZ(pSelf.z() / len); } else { v = pSelf.*; } return v; } pub fn cross(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.y() * pOther.z()) - (pSelf.z() * pOther.y()), (pSelf.z() * pOther.x()) - (pSelf.x() * pOther.z()), (pSelf.x() * pOther.y()) - (pSelf.y() * pOther.x()), ); } pub fn transform(pSelf: *const Self, m: *const Matrix(T, 4, 4)) Self { var vx = pSelf.x(); var vy = pSelf.y(); var vz = pSelf.z(); const rx = (vx * m.data[0][0]) + (vy * m.data[1][0]) + (vz * m.data[2][0]) + m.data[3][0]; const ry = (vx * m.data[0][1]) + (vy * m.data[1][1]) + (vz * m.data[2][1]) + m.data[3][1]; const rz = (vx * m.data[0][2]) + (vy * m.data[1][2]) + (vz * m.data[2][2]) + m.data[3][2]; var rw = (vx * m.data[0][3]) + (vy * m.data[1][3]) + (vz * m.data[2][3]) + m.data[3][3]; if (rw != 1) { rw = 1.0 / rw; } return Self.init(rx * rw, ry * rw, rz * rw); } }; }, else => @compileError("Only Vec size 2 and 3 supported"), } } pub const V3f32 = Vec(f32, 3); /// Custom format routine fn formatVec( comptime T: type, comptime size: usize, self: *const Vec(T, size), comptime fmt: []const u8, context: var, comptime FmtError: type, output: fn (@typeOf(context), []const u8) FmtError!void, ) FmtError!void { for (self.m.data) |row, i| { try std.fmt.format(context, FmtError, output, "[]{}.{{ ", @typeName(T)); for (row) |col, j| { try std.fmt.format(context, FmtError, output, "{.7}{}", col, if (j < (row.len - 1)) ", " else " "); } try std.fmt.format(context, FmtError, output, "}}"); } } test "vec3.init" { const vf64 = Vec(f64, 3).initVal(0); assert(vf64.x() == 0); assert(vf64.y() == 0); assert(vf64.z() == 0); const vf32 = Vec(f32, 3).initVal(1); assert(vf32.x() == 1); assert(vf32.y() == 1); assert(vf32.z() == 1); const v1 = Vec(f64, 3).init(1, 2, 3); assert(v1.x() == 1); assert(v1.y() == 2); assert(v1.z() == 3); } test "vec3.copy" { var v1 = Vec(f32, 3).init(1, 2, 3); assert(v1.x() == 1); assert(v1.y() == 2); assert(v1.z() == 3); // Copy a vector var v2 = v1; assert(v2.x() == 1); assert(v2.y() == 2); assert(v2.z() == 3); // Copy via a pointer var pV1 = &v1; var v3 = pV1.*; assert(v3.x() == 1); assert(v3.y() == 2); assert(v3.z() == 3); } test "vec3.eql" { const v1 = Vec(f32, 3).init(1.2345678, 2.3456789, 3.4567890); const v2 = Vec(f32, 3).init(1.2345678, 2.3456789, 3.4567890); assert(v1.eql(&v2)); } test "vec3.approxEql" { const v1 = Vec(f32, 3).init(1.2345678, 2.3456789, 3.4567890); const v2 = Vec(f32, 3).init(1.2345600, 2.3456700, 3.4567800); assert(v1.approxEql(&v2, 1)); assert(v1.approxEql(&v2, 2)); assert(v1.approxEql(&v2, 3)); assert(v1.approxEql(&v2, 4)); assert(v1.approxEql(&v2, 5)); assert(v1.approxEql(&v2, 6)); assert(!v1.approxEql(&v2, 7)); assert(!v1.approxEql(&v2, 8)); } test "vec2.neg" { const v1 = Vec(f32, 2).init(1, 2); const v2 = Vec(f32, 2).init(-1, -2); assert(v2.eql(&v1.neg())); } test "vec3.neg" { const v1 = Vec(f32, 3).init(1, 2, 3); const v2 = Vec(f32, 3).init(-1, -2, -3); assert(v2.eql(&v1.neg())); } test "vec3.add" { const v1 = Vec(f32, 3).init(3, 2, 1); const v2 = Vec(f32, 3).init(1, 2, 3); const v3 = v1.add(&v2); assert(v3.x() == 4); assert(v3.y() == 4); assert(v3.z() == 4); } test "vec3.sub" { const v1 = Vec(f32, 3).init(3, 2, 1); const v2 = Vec(f32, 3).init(1, 2, 3); const v3 = v1.sub(&v2); assert(v3.x() == 2); assert(v3.y() == 0); assert(v3.z() == -2); } test "vec3.mul" { const v1 = Vec(f32, 3).init(3, 2, 1); const v2 = Vec(f32, 3).init(1, 2, 3); const v3 = v1.mul(&v2); assert(v3.x() == 3); assert(v3.y() == 4); assert(v3.z() == 3); } test "vec3.div" { const v1 = Vec(f32, 3).init(3, 2, 1); const v2 = Vec(f32, 3).init(1, 2, 3); const v3 = v1.div(&v2); assert(v3.x() == 3); assert(v3.y() == 1); assert(v3.z() == f32(1.0 / 3.0)); } test "vec2.format" { var buf: [100]u8 = undefined; const v2 = Vec(f32, 2).init(2, 1); var result = try bufPrint(buf[0..], "v2={}", v2); if (DBG) warn("\nvec.format: {}\n", result); try testExpected("v2=[]f32.{ 2.0000000, 1.0000000 }", result); } test "vec3.format" { var buf: [100]u8 = undefined; const v3 = Vec(f32, 3).init(3, 2, 1); var result = try bufPrint(buf[0..], "v3={}", v3); if (DBG) warn("vec3.format: {}\n", result); try testExpected("v3=[]f32.{ 3.0000000, 2.0000000, 1.0000000 }", result); } test "vec3.length" { const v1 = Vec(f32, 3).init(2, 3, 4); assert(v1.length() == math.sqrt(29.0)); } test "vec3.dot" { const v1 = Vec(f32, 3).init(3, 2, 1); const v2 = Vec(f32, 3).init(1, 2, 3); assert(v1.dot(&v2) == (3 * 1) + (2 * 2) + (3 * 1)); // Sqrt of the dot product of itself is the length assert(math.sqrt(v2.dot(&v2)) == v2.length()); } test "vec3.normal" { var v0 = Vec(f32, 3).initVal(0); assert(v0.normal() == 0); v0 = Vec(f32, 3).init(4, 5, 6); assert(v0.normal() == 4 * 4 + 5 * 5 + 6 * 6); } test "vec3.normalize" { var v0 = Vec(f32, 3).initVal(0); var v1 = v0.normalize(); assert(v1.x() == 0); assert(v1.y() == 0); assert(v1.z() == 0); v0 = Vec(f32, 3).init(1, 1, 1); v1 = v0.normalize(); var len: f32 = math.sqrt(1.0 + 1.0 + 1.0); assert(v1.x() == 1.0 / len); assert(v1.y() == 1.0 / len); assert(v1.z() == 1.0 / len); } test "vec3.cross" { var v1 = Vec(f32, 3).init(1, 0, 0); // Unit Vector X var v2 = Vec(f32, 3).init(0, 1, 0); // Unit Vector Y // Cross product of two unit vectors on X,Y yields unit vector Z var v3 = v1.cross(&v2); assert(v3.x() == 0); assert(v3.y() == 0); assert(v3.z() == 1); v1 = Vec(f32, 3).init(3, 2, 1); v2 = Vec(f32, 3).init(1, 2, 3); v3 = v1.cross(&v2); assert(v3.x() == 4); assert(v3.y() == -8); assert(v3.z() == 4); // Changing the order yields neg. var v4 = v2.cross(&v1); assert(v3.x() == -v4.x()); assert(v3.y() == -v4.y()); assert(v3.z() == -v4.z()); assert(v4.eql(&v3.neg())); } test "vec3.transform" { if (DBG) warn("\n"); var v1 = V3f32.init(2, 3, 4); var v2 = v1.transform(&m44f32_unit); assert(v1.eql(&v2)); var m1 = M44f32.initVal(0.2); v1 = V3f32.init(0.5, 0.5, 0.5); v2 = v1.transform(&m1); if (DBG) warn("v1:\n{}\nm1:\n{}\nv2:\n{}\n", &v1, &m1, &v2); assert(v2.eql(&V3f32.init(1, 1, 1))); m1.data[3][3] = 1; v2 = v1.transform(&m1); if (DBG) warn("v1:\n{}\nm1:\n{}\nv2:\n{}\n", &v1, &m1, &v2); assert(v2.approxEql(&V3f32.init(0.3846154, 0.3846154, 0.3846154), 6)); } test "vec3.world_to_screen" { if (DBG) warn("\n"); const T = f32; const M44 = Matrix(T, 4, 4); const fov: T = 90; const widthf: T = 512; const heightf: T = 512; const width: u32 = @floatToInt(u32, 512); const height: u32 = @floatToInt(u32, 512); const aspect: T = widthf / heightf; const znear: T = 0.01; const zfar: T = 1.0; var camera_to_perspective_matrix = matrix.perspectiveM44(T, fov, aspect, znear, zfar); var world_to_camera_matrix = matrix.M44f32.initUnit(); world_to_camera_matrix.data[3][2] = -2; var world_vertexs = []V3f32{ V3f32.init(0, 1.0, 0), V3f32.init(0, -1.0, 0), V3f32.init(0, 1.0, 0.2), V3f32.init(0, -1.0, -0.2), }; var expected_camera_vertexs = []V3f32{ V3f32.init(0, 1.0, -2), V3f32.init(0, -1.0, -2), V3f32.init(0, 1.0, -1.8), V3f32.init(0, -1.0, -2.2), }; var expected_projected_vertexs = []V3f32{ V3f32.init(0, 0.5, 1.0050504), V3f32.init(0, -0.5, 1.0050504), V3f32.init(0, 0.5555555, 1.0044893), V3f32.init(0, -0.4545454, 1.0055095), }; var expected_screen_vertexs = [][2]u32{ []u32{ 256, 128 }, []u32{ 256, 384 }, []u32{ 256, 113 }, []u32{ 256, 372 }, }; for (world_vertexs) |world_vert, i| { if (DBG) warn("world_vert[{}] = {}\n", i, &world_vert); var camera_vert = world_vert.transform(&world_to_camera_matrix); if (DBG) warn("camera_vert = {}\n", camera_vert); assert(camera_vert.approxEql(&expected_camera_vertexs[i], 6)); var projected_vert = camera_vert.transform(&camera_to_perspective_matrix); if (DBG) warn("projected_vert = {}", projected_vert); assert(projected_vert.approxEql(&expected_projected_vertexs[i], 6)); var xf = projected_vert.x(); var yf = projected_vert.y(); if (DBG) warn(" {.3}:{.3}", xf, yf); if ((xf < -1) or (xf > 1) or (yf < -1) or (yf > 1)) { if (DBG) warn(" clipped\n"); } var x = @floatToInt(u32, math.min(widthf - 1, (xf + 1) * 0.5 * widthf)); var y = @floatToInt(u32, math.min(heightf - 1, (1 - (yf + 1) * 0.5) * heightf)); if (DBG) warn(" visible {}:{}\n", x, y); assert(x == expected_screen_vertexs[i][0]); assert(y == expected_screen_vertexs[i][1]); } }
src/vec.zig
const std = @import("std"); const TestData = struct { a: []const u8, b: []const u8, expected_result: bool }; const TestContext = struct { data: []const TestData, results: []bool }; const tests = [_]TestData{ createTestData("aab", "aa", false), createTestData("hello", "hello", true), createTestData("hello", "lohel", true), createTestData("hollo", "lohel", false), createTestData("glockenspiel", "spielglocken", true), createTestData("glockenspiel", "glockenspien", false), createTestData("keyboard", "eyboardk", true), createTestData("nicole", "icolen", true), createTestData("nicole", "lenico", true), createTestData("nicole", "coneli", false), createTestData("aabaaaaabaab", "aabaabaabaaa", true), createTestData("abc", "cba", false), createTestData("xxyyy", "xxxyy", false), createTestData("xyxxz", "xxyxz", false), createTestData("x", "x", true), createTestData("x", "xx", false), createTestData("x", "", false), createTestData("", "", true), createTestData("scott", "ttocs", false), }; const MAX_WORKING_MEM_LENGTH = 25; const AllocationError = error{OutOfMemory}; /// Helper function to populate the array as Zig doesn't seem to support assigning directly in array /// fn createTestData(a: []const u8, b: []const u8, expected_result: bool) TestData { return TestData{ .a = a, .b = b, .expected_result = expected_result }; } /// Reddit Daily Challenge #383 /// https://www.reddit.com/r/dailyprogrammer/comments/ffxabb/20200309_challenge_383_easy_necklace_matching/ /// pub fn main() !void { //Splitting the tests across threads just to test how threading works in Zig var test_results: [tests.len]bool = undefined; const batch_size = tests.len / 2; var ctx1 = TestContext{ .data = tests[0..batch_size], .results = test_results[0..batch_size] }; var ctx2 = TestContext{ .data = tests[batch_size..tests.len], .results = test_results[batch_size..tests.len] }; const thread1 = try std.Thread.spawn(@as(TestContext, ctx1), runTestBatch); const thread2 = try std.Thread.spawn(@as(TestContext, ctx2), runTestBatch); thread1.wait(); thread2.wait(); const stdout = std.io.getStdOut().outStream(); for (tests) |t, i| { if (test_results[i] != t.expected_result) try stdout.print("Failed '{}' => '{}'. Expected: {} Actual: {}\n", .{ t.a, t.b, t.expected_result, test_results[i] }); } try stdout.print("Completed {} Tests\n", .{tests.len}); } /// Runs a subset of the tests (used for multithreading) /// fn runTestBatch(ctx: TestContext) void { var working_memory: [MAX_WORKING_MEM_LENGTH]u8 = undefined; var working_slice = working_memory[0..working_memory.len]; for (ctx.data) |t, i| { const result = isRotation(t.a, t.b, working_slice) catch false; ctx.results[i] = result; } } /// Simple algorithm that duplicates 'A' and searches for 'B' as a substring. /// The substring algorithm is just a naive search and nothing fancier like KMP, etc /// /// Zig prefers stack allocation so we need to pass in enough memory to expand 'a' /// fn isRotation(a: []const u8, b: []const u8, working_memory: []u8) !bool { if (a.len * 2 >= working_memory.len) return AllocationError.OutOfMemory; if (a.len != b.len) return false; if (a.len == 0 and b.len == 0) return true; //Duplicate 'a' e.g "hello" => "hellohello" so that 'b' is now a potential substring of 'a' for (a) |char, i| { working_memory[i] = char; working_memory[i + a.len] = char; } const m = b.len; const n = a.len * 2; var i: usize = 0; return while (i < n) : (i += 1) { var j: usize = 0; while (j < m) : (j += 1) { if (working_memory[i + j] != b[j]) break; } if (j == m) break true; } else false; }
383_NecklaceMatching/main.zig
pub const InputKey = @import("protocols/simple_text_input_ex_protocol.zig").InputKey; pub const KeyData = @import("protocols/simple_text_input_ex_protocol.zig").KeyData; pub const KeyState = @import("protocols/simple_text_input_ex_protocol.zig").KeyState; pub const SimpleTextInputExProtocol = @import("protocols/simple_text_input_ex_protocol.zig").SimpleTextInputExProtocol; pub const SimpleTextOutputMode = @import("protocols/simple_text_output_protocol.zig").SimpleTextOutputMode; pub const SimpleTextOutputProtocol = @import("protocols/simple_text_output_protocol.zig").SimpleTextOutputProtocol; pub const SimplePointerMode = @import("protocols/simple_pointer_protocol.zig").SimplePointerMode; pub const SimplePointerProtocol = @import("protocols/simple_pointer_protocol.zig").SimplePointerProtocol; pub const SimplePointerState = @import("protocols/simple_pointer_protocol.zig").SimplePointerState; pub const AbsolutePointerMode = @import("protocols/absolute_pointer_protocol.zig").AbsolutePointerMode; pub const AbsolutePointerProtocol = @import("protocols/absolute_pointer_protocol.zig").AbsolutePointerProtocol; pub const AbsolutePointerState = @import("protocols/absolute_pointer_protocol.zig").AbsolutePointerState; pub const GraphicsOutputBltPixel = @import("protocols/graphics_output_protocol.zig").GraphicsOutputBltPixel; pub const GraphicsOutputBltOperation = @import("protocols/graphics_output_protocol.zig").GraphicsOutputBltOperation; pub const GraphicsOutputModeInformation = @import("protocols/graphics_output_protocol.zig").GraphicsOutputModeInformation; pub const GraphicsOutputProtocol = @import("protocols/graphics_output_protocol.zig").GraphicsOutputProtocol; pub const GraphicsOutputProtocolMode = @import("protocols/graphics_output_protocol.zig").GraphicsOutputProtocolMode; pub const GraphicsPixelFormat = @import("protocols/graphics_output_protocol.zig").GraphicsPixelFormat; pub const PixelBitmask = @import("protocols/graphics_output_protocol.zig").PixelBitmask; pub const EdidDiscoveredProtocol = @import("protocols/edid_discovered_protocol.zig").EdidDiscoveredProtocol; pub const EdidActiveProtocol = @import("protocols/edid_active_protocol.zig").EdidActiveProtocol; pub const EdidOverrideProtocol = @import("protocols/edid_override_protocol.zig").EdidOverrideProtocol; pub const EdidOverrideProtocolAttributes = @import("protocols/edid_override_protocol.zig").EdidOverrideProtocolAttributes; pub const hii = @import("protocols/hii.zig"); pub const HIIDatabaseProtocol = @import("protocols/hii_database_protocol.zig").HIIDatabaseProtocol; pub const HIIPopupProtocol = @import("protocols/hii_popup_protocol.zig").HIIPopupProtocol; pub const HIIPopupStyle = @import("protocols/hii_popup_protocol.zig").HIIPopupStyle; pub const HIIPopupType = @import("protocols/hii_popup_protocol.zig").HIIPopupType; pub const HIIPopupSelection = @import("protocols/hii_popup_protocol.zig").HIIPopupSelection; pub const RNGProtocol = @import("protocols/rng_protocol.zig").RNGProtocol;
lib/std/os/uefi/protocols.zig
const psp = @import("Zig-PSP/src/psp/utils/psp.zig"); const gfx = @import("gfx.zig"); usingnamespace @import("Zig-PSP/src/psp/include/psprtc.zig"); usingnamespace @import("Zig-PSP/src/psp/include/pspdisplay.zig"); usingnamespace @import("Zig-PSP/src/psp/include/psploadexec.zig"); var current_time : u64 = 0; var tickRate : u32 = 0; comptime { asm(psp.module_info("zTetris", 0, 1, 0)); } //Tetris board const tetris_columns : u32 = 10; const tetris_rows : u32 = 24; const bg_color : u32 = 0xffffeecc; const board_color : u32 = 0xff111111; const outline_color : u32 = 0xff333333; const block_side : u32 = 16; const pieceData : [7][4][16]u8 = [7][4][16]u8{ //Line [4][16]u8{ [_]u8{ 0,0,0,0, 1,1,1,1, 0,0,0,0, 0,0,0,0, }, [_]u8{ 0,0,1,0, 0,0,1,0, 0,0,1,0, 0,0,1,0, }, [_]u8{ 0,0,0,0, 0,0,0,0, 1,1,1,1, 0,0,0,0, }, [_]u8{ 0,1,0,0, 0,1,0,0, 0,1,0,0, 0,1,0,0, } }, //Square [4][16]u8{ [_]u8{ 1,1,0,0, 1,1,0,0, 0,0,0,0, 0,0,0,0, }, [_]u8{ 1,1,0,0, 1,1,0,0, 0,0,0,0, 0,0,0,0, }, [_]u8{ 1,1,0,0, 1,1,0,0, 0,0,0,0, 0,0,0,0, }, [_]u8{ 1,1,0,0, 1,1,0,0, 0,0,0,0, 0,0,0,0, } }, //T [4][16]u8{ [_]u8{ 0,1,0,0, 1,1,1,0, 0,0,0,0, 0,0,0,0, }, [_]u8{ 0,1,0,0, 0,1,1,0, 0,1,0,0, 0,0,0,0, }, [_]u8{ 0,0,0,0, 1,1,1,0, 0,1,0,0, 0,0,0,0, }, [_]u8{ 0,1,0,0, 1,1,0,0, 0,1,0,0, 0,0,0,0, }, }, //Z [4][16]u8{ [_]u8{ 1,1,0,0, 0,1,1,0, 0,0,0,0, 0,0,0,0, }, [_]u8{ 0,0,1,0, 0,1,1,0, 0,1,0,0, 0,0,0,0, }, [_]u8{ 0,0,0,0, 1,1,0,0, 0,1,1,0, 0,0,0,0, }, [_]u8{ 0,1,0,0, 1,1,0,0, 1,0,0,0, 0,0,0,0, } }, //Zr [4][16]u8{ [_]u8{ 0,1,1,0, 1,1,0,0, 0,0,0,0, 0,0,0,0, }, [_]u8{ 0,1,0,0, 0,1,1,0, 0,0,1,0, 0,0,0,0, }, [_]u8{ 0,0,0,0, 0,1,1,0, 1,1,0,0, 0,0,0,0, }, [_]u8{ 1,0,0,0, 1,1,0,0, 0,1,0,0, 0,0,0,0, } }, //L [4][16]u8 { [_]u8{ 1,0,0,0, 1,1,1,0, 0,0,0,0, 0,0,0,0, }, [_]u8{ 0,1,1,0, 0,1,0,0, 0,1,0,0, 0,0,0,0, }, [_]u8{ 0,0,0,0, 1,1,1,0, 0,0,1,0, 0,0,0,0, }, [_]u8{ 0,1,0,0, 0,1,0,0, 1,1,0,0, 0,0,0,0, } }, //Lr [4][16]u8{ [_]u8{ 0,0,1,0, 1,1,1,0, 0,0,0,0, 0,0,0,0, }, [_]u8{ 0,1,0,0, 0,1,0,0, 0,1,1,0, 0,0,0,0, }, [_]u8{ 0,0,0,0, 1,1,1,0, 1,0,0,0, 0,0,0,0, }, [_]u8{ 1,1,0,0, 0,1,0,0, 0,1,0,0, 0,0,0,0, } } }; const colorArray : [8]u32 = [_]u32{ 0xFFFFFFFF, 0xFF777777, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000, 0xFFFF00FF, }; pub const PieceType = enum(u8) { Line = 0, Square = 1, T = 2, Z = 3, Zr = 4, L = 5, Lr = 6, }; pub const Block = struct{ x: i32, y: i32, }; pub const Piece = struct{ x: i32, y: i32, orietation: usize, ptype: PieceType, block: [4]Block, count: usize, color: u32, }; pub var activePiece : Piece = undefined; var grid : [tetris_columns][tetris_rows]u32 = undefined; fn initBlocks() void{ var i : usize = 0; while(i < tetris_rows) : (i += 1){ var j : usize = 0; while(j < tetris_columns) : (j += 1){ grid[j][i] = 0xff111111; } } } fn drawLogo() void{ gfx.print(16, 8, "T", 0xFF0000FF); gfx.print(16, 8 + 32*1, "E", 0xFF00FFFF); gfx.print(16, 8 + 32*2, "T", 0xFF00FF00); gfx.print(16, 8 + 32*3, "R", 0xFFFFFF00); gfx.print(16, 8 + 32*4, "I", 0xFFFF0000); gfx.print(16, 8 + 32*5, "S", 0xFFFF00FF); } fn drawBlock(x : usize, y : usize) void{ gfx.drawRect(24 + x * block_side, 24 + y * block_side, block_side, block_side, 0xFF000000); gfx.drawRect(26 + x * block_side, 26 + y * block_side, block_side - 4, block_side - 4, grid[y][x]); } fn drawBlockCol(x : i32, y : i32, color : u32) void{ gfx.drawRect(@intCast(u32, 24 + x * @intCast(i32, block_side)), @intCast(u32, 24 + y * @intCast(i32, block_side)), block_side, block_side, 0xFF000000); gfx.drawRect(@intCast(u32, 26 + x * @intCast(i32, block_side)), @intCast(u32, 26 + y * @intCast(i32, block_side)), block_side - 4, block_side - 4, color); } fn drawBlocks() void { var i : usize = 0; while(i < tetris_rows) : (i += 1){ var j : usize = 0; while(j < tetris_columns) : (j += 1){ drawBlock(i, j); } } } fn drawPiece() void { var i : usize = 0; while(i < 4) : (i += 1){ drawBlockCol(activePiece.block[i].y + activePiece.y, activePiece.block[i].x + activePiece.x, activePiece.color); } } const std = @import("std"); var r = std.rand.DefaultPrng.init(0); fn newPiece() void { activePiece.ptype = @intToEnum(PieceType, r.random.uintLessThanBiased(u8, 7)); activePiece.x = 0; activePiece.y = 20; activePiece.count = 0; activePiece.orietation = 0; activePiece.color = colorArray[r.random.uintLessThanBiased(usize, 8)]; var i : i32 = 0; while(i < 16) : (i += 1){ if(pieceData[@enumToInt(activePiece.ptype)][activePiece.orietation][@intCast(usize, i)] != 0){ var x : i32 = @rem(i, 4); var y : i32 = @divTrunc(i, 4); activePiece.block[activePiece.count].x = x; activePiece.block[activePiece.count].y = y; activePiece.count += 1; } } } fn rightWallCollided() bool { var i : usize = 0; while(i < activePiece.count) : (i += 1){ if(activePiece.block[i].x + activePiece.x >= tetris_columns){ return true; } } return false; } fn leftWallCollided() bool { var i : usize = 0; while(i < activePiece.count) : (i += 1){ if(activePiece.block[i].x + activePiece.x < 0){ return true; } } return false; } fn getCell(x : usize, y : usize) bool { if(y < 0 or y >= tetris_rows or x < 0 or x >= tetris_columns){ return false; } return grid[x][y] != 0xff111111; } fn gridCollided() bool { var i : usize = 0; while(i < activePiece.count) : (i += 1){ if(getCell(@intCast(usize, activePiece.x + activePiece.block[i].x), @intCast(usize, activePiece.y + activePiece.block[i].y))){ return true; } } return false; } const control = @import("Zig-PSP/src/psp/include/pspctrl.zig"); var oldPadData : control.SceCtrlData = undefined; var newPadData : control.SceCtrlData = undefined; fn handleInput() void{ oldPadData = newPadData; _ = control.sceCtrlReadBufferPositive(&newPadData, 1); if(oldPadData.Buttons != newPadData.Buttons){ if(newPadData.Buttons & @bitCast(c_uint, @enumToInt(control.PspCtrlButtons.PSP_CTRL_UP)) != 0){ activePiece.x -= 1; if(leftWallCollided() or gridCollided()){ activePiece.x += 1; } } if(newPadData.Buttons & @bitCast(c_uint, @enumToInt(control.PspCtrlButtons.PSP_CTRL_DOWN)) != 0){ activePiece.x += 1; if(rightWallCollided() or gridCollided()){ activePiece.x -= 1; } //TODO: Grid Check } if(newPadData.Buttons & @bitCast(c_uint, @enumToInt(control.PspCtrlButtons.PSP_CTRL_LEFT)) != 0){ activePiece.y -= 1; } if(newPadData.Buttons & @bitCast(c_uint, @enumToInt(control.PspCtrlButtons.PSP_CTRL_RIGHT)) != 0){ rotate(); } } } fn rotate() void{ var blockBack: [4]Block = activePiece.block; activePiece.orietation += 1; activePiece.orietation %= 4; activePiece.count = 0; var i : i32 = 0; while(i < 16) : (i += 1){ if(pieceData[@enumToInt(activePiece.ptype)][activePiece.orietation][@intCast(usize, i)] != 0){ var x : i32 = @rem(i, 4); var y : i32 = @divTrunc(i, 4); activePiece.block[activePiece.count].x = x; activePiece.block[activePiece.count].y = y; activePiece.count += 1; } } if(leftWallCollided()){ activePiece.x += 1; while(leftWallCollided()){ activePiece.x += 1; } } if(rightWallCollided()){ activePiece.x -= 1; while(rightWallCollided()){ activePiece.x -= 1; } } //TODO: GRID CHECK } fn bottomCollided() bool{ var i : usize = 0; while(i < activePiece.count) : (i += 1){ if(activePiece.block[i].y + activePiece.y < 0 or gridCollided()){ return true; } } return false; } fn topCollided() bool{ var i : usize = 0; while(i < activePiece.count) : (i += 1){ if(activePiece.block[i].y + activePiece.y >= 20){ return true; } } return false; } fn addPieceToBoard() void { var i : usize = 0; while(i < activePiece.count) : (i += 1){ grid[@intCast(usize, activePiece.block[i].x + activePiece.x)][@intCast(usize, activePiece.block[i].y + activePiece.y)] = activePiece.color; } } fn checkRows() void { var y : usize = 0; while(y < tetris_rows) : (y += 1){ var cleared : bool = true; var x : usize = 0; while(x < tetris_columns) : (x += 1){ if(grid[x][y] == 0xff111111){ cleared = false; break; } } if(cleared){ //We clear this line and above var i : usize = y; //I is this line while(i < (tetris_rows-4)) : (i += 1){ var j : usize = 0; while(j < tetris_columns) : (j += 1){ grid[j][i] = grid[j][i + 1]; } } } } } pub fn main() !void { oldPadData.Buttons = 0; newPadData.Buttons = 0; psp.utils.enableHBCB(); gfx.init(); _ = control.sceCtrlSetSamplingCycle(0); _ = control.sceCtrlSetSamplingMode(@enumToInt(control.PspCtrlMode.PSP_CTRL_MODE_ANALOG)); initBlocks(); tickRate = sceRtcGetTickResolution(); _ = sceRtcGetCurrentTick(&current_time); r = std.rand.DefaultPrng.init(current_time); newPiece(); var timer : f64 = 0.0; while(true){ //Clear screen gfx.clear(bg_color); //Draw logo drawLogo(); //Draw outline gfx.drawRect(16, 16, (tetris_rows+1) * block_side, (tetris_columns+1) * block_side, outline_color); //Draw board drawBlocks(); drawPiece(); var oldTime = current_time; _ = sceRtcGetCurrentTick(&current_time); var delta = current_time - oldTime; var deltaF = @intToFloat(f64, delta) / @intToFloat(f64, tickRate); timer += deltaF; if(timer > 0.5){ timer = 0.0; //Tick activePiece.y -= 1; } handleInput(); if(bottomCollided()){ activePiece.y += 1; if(topCollided()){ sceKernelExitGame(); }else{ addPieceToBoard(); newPiece(); } } checkRows(); gfx.swapBuffers(); _ = sceDisplayWaitVblankStart(); } }
src/main.zig
const std = @import("std"); const util = @import("util.zig"); const data = @embedFile("../data/day06.txt"); const Input = struct { fish_ages: std.ArrayList(u8) = std.ArrayList(u8).init(std.testing.allocator), pub fn deinit(self: @This()) void { self.fish_ages.deinit(); } }; fn parseInput(input_text: []const u8) !Input { var input = Input{}; errdefer input.deinit(); var ages = std.mem.tokenize(u8, input_text, ",\r\n"); while (ages.next()) |age| { try input.fish_ages.append(try parseInt(u8, age, 10)); } return input; } fn simulateFish(input: Input, day_count: usize) i64 { var fish_at_age: [9]i64 = .{0} ** 9; for (input.fish_ages.items) |age| { fish_at_age[age] += 1; } var day: usize = 0; while (day < day_count) : (day += 1) { const parent_count = fish_at_age[0]; std.mem.rotate(i64, fish_at_age[0..], 1); fish_at_age[8] = parent_count; fish_at_age[6] += parent_count; } var sum: i64 = 0; for (fish_at_age) |fish_count| { sum += fish_count; } return sum; } fn part1(input: Input) i64 { return simulateFish(input, 80); } fn part2(input: Input) i64 { return simulateFish(input, 256); } const test_data = "3,4,3,1,2"; const part1_test_solution: ?i64 = 5934; const part1_solution: ?i64 = 388739; const part2_test_solution: ?i64 = 26984457539; const part2_solution: ?i64 = 1741362314973; fn testPart1() !void { var test_input = try parseInput(test_data); defer test_input.deinit(); if (part1_test_solution) |solution| { try std.testing.expectEqual(solution, part1(test_input)); } var input = try parseInput(data); defer input.deinit(); if (part1_solution) |solution| { try std.testing.expectEqual(solution, part1(input)); } } fn testPart2() !void { var test_input = try parseInput(test_data); defer test_input.deinit(); if (part2_test_solution) |solution| { try std.testing.expectEqual(solution, part2(test_input)); } var input = try parseInput(data); defer input.deinit(); if (part2_solution) |solution| { try std.testing.expectEqual(solution, part2(input)); } } pub fn main() !void { try testPart1(); try testPart2(); } test "part1" { try testPart1(); } test "part2" { try testPart2(); } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const parseInt = std.fmt.parseInt; const min = std.math.min; const max = std.math.max; const print = std.debug.print; const expect = std.testing.expect; const assert = std.debug.assert;
src/day06.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day01.txt"); fn parseInput(input_text: []const u8) std.ArrayList(u64) { var list = std.ArrayList(u64).init(std.testing.allocator); var lines = tokenize(u8, input_text, "\r\n"); while (lines.next()) |line| { const num = parseInt(u64, line, 10) catch unreachable; list.append(num) catch unreachable; } return list; } fn countIncreases(input: std.ArrayList(u64), window_size: u64) u64 { var count: u64 = 0; var i: usize = 0; var prev_sum: u64 = 0; while (i < window_size) : (i += 1) { prev_sum += input.items[i]; } i = window_size; while (i < input.items.len) : (i += 1) { const sum = prev_sum - input.items[i - window_size] + input.items[i]; if (sum > prev_sum) count += 1; prev_sum = sum; } return count; } pub fn main() !void {} const test_data = \\199 \\200 \\208 \\210 \\200 \\207 \\240 \\269 \\260 \\263 ; test "part1" { const test_input = parseInput(test_data); defer test_input.deinit(); try std.testing.expectEqual(@as(u64, 7), countIncreases(test_input, 1)); const input = parseInput(data); defer input.deinit(); try std.testing.expectEqual(@as(u64, 1451), countIncreases(input, 1)); } test "part2" { const test_input = parseInput(test_data); defer test_input.deinit(); try std.testing.expectEqual(@as(u64, 5), countIncreases(test_input, 3)); const input = parseInput(data); defer input.deinit(); try std.testing.expectEqual(@as(u64, 1395), countIncreases(input, 3)); } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc;
src/day01.zig
const std = @import("std"); const parser = @import("parser.zig"); const Allocator = std.mem.Allocator; pub const log_level = .info; /// Value for the call stack to be limited at in order to avoid an actual stack overflow from whom Lunez doesn't know how to recover. /// It is implemented by throwing a 'stack overflow' error. /// Set to 0 to disable. pub const MAX_CALL_STACK_SIZE = 1000; const LuaFunction = struct { stats: []const parser.Stat, argNames: []const []const u8 }; const LuaTable = std.HashMap(LuaValue, LuaValue, ValueContext, std.hash_map.default_max_load_percentage); const ValueContext = struct { pub fn hash(_: ValueContext, value: LuaValue) u64 { return switch (value) { .String => |str| std.hash.Wyhash.hash(0, str), else => std.hash.Wyhash.hash(0, std.mem.asBytes(&value)) }; } pub fn eql(_: ValueContext, a: LuaValue, b: LuaValue) bool { return a.equals(b); } }; // TODO: should be same type as LuaTable const LuaValues = std.StringHashMap(LuaValue); const LuaValue = union(enum) { Number: f64, String: []const u8, Boolean: bool, Nil: void, CFunction: fn(env: *LuaEnv, args: []const LuaValue) anyerror![]LuaValue, Function: LuaFunction, Table: LuaTable, pub fn getTypeName(self: LuaValue) []const u8 { return switch (self) { .Number => return "number", .Boolean => return "boolean", .String => return "string", .Nil => return "nil", .CFunction => return "function", .Function => return "function", .Table => return "table" }; } pub fn equals(self: LuaValue, other: LuaValue) bool { if (std.meta.activeTag(self) != std.meta.activeTag(other)) return false; return switch (self) { .Number => |num| num == other.Number, .String => |str| std.mem.eql(u8, str, other.String), .Boolean => |boolean| boolean == other.Boolean, .Nil => other == .Nil, .CFunction => other.CFunction == self.CFunction, .Function => other.Function.stats.ptr == self.Function.stats.ptr, .Table => other.Table.unmanaged.metadata == self.Table.unmanaged.metadata, }; } }; const nil = LuaValue { .Nil = .{} }; const VariableAvailability = enum { Local, Global, None }; const LuaEnv = struct { allocator: *Allocator, callStack: CallStack, // TODO: replace upvalues by local variables in the first call frame (which lives for the duration of the whole program) upvalues: LuaValues, pub fn init(allocator: *Allocator) LuaEnv { return LuaEnv { .callStack = CallStack.init(allocator), .upvalues = LuaValues.init(allocator), .allocator = allocator }; } pub fn getAvailability(self: *const LuaEnv, variable: parser.Var) VariableAvailability { var i: usize = self.callStack.items.len; while (i > 0) : (i -= 1) { const frame = self.callStack.items[i - 1]; if (frame.locals.contains(variable.Name)) { return .Local; } } return if (self.upvalues.contains(variable.Name)) .Global else .None; } pub fn getCurrentFrame(self: *const LuaEnv) *CallFrame { return &self.callStack.items[self.callStack.items.len - 1]; } /// Get the closest call scope's value with this name or if none, the global with this name, or if none, nil pub fn getVar(self: *LuaEnv, variable: parser.Var) LuaValue { std.log.scoped(.env).debug("Get var {}", .{variable}); var i: usize = self.callStack.items.len; while (i > 0) : (i -= 1) { const frame = self.callStack.items[i - 1]; if (frame.locals.get(variable.Name)) |value| { return value; } } if (self.upvalues.get(variable.Name)) |value| { return value; } return nil; } pub fn setUpvalue(self: *LuaEnv, variable: parser.Var, value: LuaValue) !void { std.log.scoped(.env).debug("Set upvalue {} to value {}", .{variable, value}); try self.upvalues.put(variable.Name, value); } pub fn setLocal(self: *LuaEnv, variable: parser.Var, value: LuaValue) !void { std.log.scoped(.env).debug("Set local {} to value {}", .{variable, value}); var i: usize = self.callStack.items.len; while (i > 0) : (i -= 1) { const frame = &self.callStack.items[i - 1]; if (frame.locals.contains(variable.Name)) { frame.locals.putAssumeCapacity(variable.Name, value); return; } } try self.getCurrentFrame().locals.put(variable.Name, value); } const ThrowError = error { LuaError }; /// This function calls the message handler and always returns error.LuaError /// in order to interrupt the current control flow. pub fn throwString(self: *LuaEnv, comptime msg: []const u8, fmt: anytype) ThrowError { var buf: [4096]u8 = undefined; return self.throwError(LuaValue { .String = std.fmt.bufPrint(&buf, msg, fmt) catch unreachable }); } /// This function calls the message handler and always returns error.LuaError /// in order to interrupt the current control flow. pub fn throwError(self: *LuaEnv, msg: LuaValue) ThrowError { while (true) { var callFrame = self.callStack.pop(); callFrame.deinit(); if (callFrame.messageHandler) |msgHandler| { msgHandler(self, msg); return ThrowError.LuaError; // convenience error to stop the current control flow } } } pub fn deinit(self: *LuaEnv) void { while (self.callStack.popOrNull()) |*callFrame| { callFrame.deinit(); } self.callStack.deinit(); self.upvalues.deinit(); } }; const CallFrame = struct { locals: LuaValues, statements: []const parser.Stat, statIdx: usize = 0, /// Called on error messageHandler: ?fn(env: *LuaEnv, msg: LuaValue) void = null, pub fn init(allocator: *Allocator, statements: []const parser.Stat) CallFrame { return CallFrame { .locals = LuaValues.init(allocator), .statements = statements }; } pub fn deinit(self: *CallFrame) void { self.locals.deinit(); } }; const CallStack = std.ArrayList(CallFrame); const ResolveExpressionError = LuaEnv.ThrowError || FunctionCallError; pub fn resolveExpr(env: *LuaEnv, expr: parser.Expr) ResolveExpressionError!LuaValue { switch (expr) { .LiteralString => |string| { return LuaValue { .String = string }; }, .Number => |number| { return LuaValue { .Number = number }; }, .Boolean => |boolean| { return LuaValue { .Boolean = boolean }; }, .Var => |str| { return env.getVar(str); }, .Nil => return nil, .FunctionCall => |call| { const values = try callFunction(env, call); return if (values.len > 0) values[0] else nil; // TODO: handle multiple returns! }, .FunctionDefinition => |def| { const func = LuaFunction { .stats = def.stats, .argNames = def.argNames }; return LuaValue { .Function = func }; }, .TableConstructor => |constructor| { var table = LuaTable.init(env.allocator); const entries = constructor.entries; for (entries) |entry| { const key = try resolveExpr(env, entry.key); const value = try resolveExpr(env, entry.value); table.put(key, value) catch |err| switch (err) { error.OutOfMemory => return env.throwString("out of memory", .{}) }; } return LuaValue { .Table = table }; }, .Index => |index| { const lhs = try resolveExpr(env, index.lhs.*); const rhs = try resolveExpr(env, index.rhs.*); if (lhs == .Table) { return lhs.Table.get(rhs) orelse nil; } else { return env.throwString("attempt to index a {s} value", .{ lhs.getTypeName() }); } }, .BinaryOperation => |op| { const lhs = try resolveExpr(env, op.lhs.*); const rhs = try resolveExpr(env, op.rhs.*); if (std.mem.eql(u8, op.op, "+") or std.mem.eql(u8, op.op, "-")) { if (lhs != .Number) { return env.throwString("attempt to perform arithmetic on a {s} value", .{ lhs.getTypeName() }); } else if (rhs != .Number) { return env.throwString("attempt to perform arithmetic on a {s} value", .{ rhs.getTypeName() }); } } if (std.mem.eql(u8, op.op, "+")) { return LuaValue { .Number = lhs.Number + rhs.Number }; } else if (std.mem.eql(u8, op.op, "-")) { return LuaValue { .Number = lhs.Number - rhs.Number }; } else if (std.mem.eql(u8, op.op, "*")) { return LuaValue { .Number = lhs.Number * rhs.Number }; } else if (std.mem.eql(u8, op.op, "/")) { return LuaValue { .Number = lhs.Number / rhs.Number }; } if (std.mem.eql(u8, op.op, "..")) { if (lhs != .String or rhs != .String) { return env.throwString("attempt to concatenate a {s} value", .{ rhs.getTypeName() }); } const str = std.mem.concat(env.allocator, u8, &[_][]const u8{ lhs.String, rhs.String }) catch unreachable; return LuaValue { .String = str }; } if (std.mem.eql(u8, op.op, "==")) { return LuaValue { .Boolean = lhs.equals(rhs) }; } else if (std.mem.eql(u8, op.op, "~=")) { return LuaValue { .Boolean = !lhs.equals(rhs) }; } return env.throwString("binary operation {s} has not yet been implemented", .{ op.op }); } } } /// If there is a lua error, returns null instead of error.LuaError /// This can be used to break out of execution loop as when error.LuaError is returned, /// the error has already been catched and handled by the message handler. pub fn resolveExprNullable(env: *LuaEnv, expr: parser.Expr) !?LuaValue { return resolveExpr(env, expr) catch |err| switch (err) { error.LuaError => return null, else => return err }; } pub fn resolveExprs(env: *LuaEnv, expressions: []const parser.Expr) ![]const LuaValue { var values = try env.allocator.alloc(LuaValue, expressions.len); for (expressions) |expr, i| { values[i] = try resolveExpr(env, expr); } return values; } fn toString(env: *LuaEnv, value: LuaValue) ![]const u8 { const str: []const u8 = switch (value) { .CFunction => |func| return try std.fmt.allocPrint(env.allocator, "function 0x{x}", .{@ptrToInt(func)}), .Function => |func| return try std.fmt.allocPrint(env.allocator, "function 0x{x}", .{@ptrToInt(func.stats.ptr)}), .String => |str| return str, .Number => |num| return try std.fmt.allocPrint(env.allocator, "{d}", .{num}), .Boolean => |boolean| return try std.fmt.allocPrint(env.allocator, "{}", .{boolean}), .Nil => return "nil", .Table => |table| return try std.fmt.allocPrint(env.allocator, "table 0x{x}", .{@ptrToInt(&table)}), }; return str; } fn luaCreateError(env: *LuaEnv, args: []const LuaValue) LuaEnv.ThrowError![]LuaValue { const errorObject: LuaValue = blk: { if (args.len > 0) { break :blk args[0]; } else { break :blk LuaValue { .String = "(error object is a nil value)" }; } }; return env.throwError(errorObject); } fn luaToString(env: *LuaEnv, args: []const LuaValue) ![]LuaValue { if (args.len != 1) { return env.throwString("bad argument #1 to 'tostring' (value expected)", .{}); } const str = try toString(env, args[0]); const values = try env.allocator.alloc(LuaValue, 1); values[0] = LuaValue { .String = str }; return values; } fn luaPrint(env: *LuaEnv, args: []const LuaValue) ![]LuaValue { _ = env; const stdout = std.io.getStdOut().writer(); for (args) |arg| { try stdout.print("{s}\t", .{ try toString(env, arg) }); } try stdout.print("\n", .{}); return &[0]LuaValue {}; } fn rootError(env: *LuaEnv, msg: LuaValue) void { const stderr = std.io.getStdErr().writer(); stderr.print("error: ", .{}) catch unreachable; _ = luaPrint(env, &.{ msg }) catch unreachable; env.callStack.clearAndFree(); } fn createTable(env: *LuaEnv, args: []const LuaValue) ![]LuaValue { _ = args; const values = try env.allocator.alloc(LuaValue, 1); values[0] = LuaValue { .Table = LuaTable.init(env.allocator) }; return values; } const FunctionCallError = anyerror; // TODO: narrow it down pub fn callFunction(env: *LuaEnv, call: parser.FunctionCall) FunctionCallError![]const LuaValue { const values = try resolveExprs(env, call.args); defer env.allocator.free(values); if (MAX_CALL_STACK_SIZE != 0 and env.callStack.items.len >= MAX_CALL_STACK_SIZE) { return env.throwString("stack overflow", .{}); } const value = env.getVar(call.callee); switch (value) { .CFunction => |func| { return try func(env, values); }, .Function => |func| { var newFrame = CallFrame.init(env.allocator, func.stats); try env.callStack.append(newFrame); for (func.argNames) |name, i| { if (i < values.len) { try env.getCurrentFrame().locals.put(name, values[i]); } } return try evalLoop(env); }, else => |v| { return env.throwString("attempt to call a {s} value (global '{}')", .{v.getTypeName(), call.callee}); } } return &[0]LuaValue {}; } pub fn evalLoop(env: *LuaEnv) anyerror![]const LuaValue { var targetSize: usize = env.callStack.items.len - 1; // only stop when current function is finished // const frame = env.getCurrentFrame(); // defer { // frame.deinit(); // _ = env.callStack.pop(); // pop it // } while (true) { // It can abrutly be under the target size if an error was thrown that went down through this call frame if (env.callStack.items.len <= targetSize) { // in that case, we propagate the LuaError return error.LuaError; } const frame = env.getCurrentFrame(); if (frame.statements.len == frame.statIdx) { frame.deinit(); _ = env.callStack.pop(); // pop it continue; } const stat = frame.statements[frame.statIdx]; frame.statIdx += 1; switch (stat) { .NoOp => {}, .Definition => |defs| { for (defs.vars) |variable, i| { const expr = if (i < defs.exprs.len) defs.exprs[i] else parser.Expr { .Nil = .{} }; const value = (try resolveExprNullable(env, expr)) orelse continue; if (env.callStack.items.len == 0) break; if (env.getAvailability(variable) == .Local) { env.setLocal(variable, value) catch unreachable; } else { try env.setUpvalue(variable, value); } } }, .LocalDefinition => |defs| { const currentFrame = &env.callStack.items[env.callStack.items.len - 1]; for (defs.names) |variable, i| { const expr = if (i < defs.exprs.len) defs.exprs[i] else parser.Expr { .Nil = .{} }; const value = (try resolveExprNullable(env, expr)) orelse continue; if (env.callStack.items.len == 0) break; try currentFrame.locals.put(variable, value); } }, .FunctionCall => |call| { _ = callFunction(env, call) catch |err| switch (err) { error.LuaError => continue, else => return err }; }, .If => |ifStat| { const condition = (try resolveExprNullable(env, ifStat.expr)) orelse continue; const executeBlock = switch (condition) { .Nil => false, .Boolean => |boolean| boolean, // execute block if 'true' and do not execute if 'false' else => true }; if (executeBlock) { var newFrame = CallFrame.init(env.allocator, ifStat.statements); try env.callStack.append(newFrame); } }, .Return => |retStat| { const values = try resolveExprs(env, retStat.expressions); while (env.callStack.items.len > targetSize) { const f = env.getCurrentFrame(); f.deinit(); _ = env.callStack.pop(); } return values; } } } return &[0]LuaValue {}; } pub fn run(allocator: *Allocator, text: []const u8) !void { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const parsed = parser.parse(&arena.allocator, text) catch |err| switch (err) { error.ParserFailed => { // it didn't provide any useful information is stack trace anyway std.log.crit("parser failed", .{}); return; }, else => return err }; //std.log.info("lua: {any}", .{parsed}); var env = LuaEnv.init(&arena.allocator); defer env.deinit(); // The top frame, the one corresponding to the executed chunk var defaultFrame = CallFrame.init(allocator, parsed); defaultFrame.messageHandler = rootError; try env.callStack.append(defaultFrame); // (very) basic standard library try env.setUpvalue(.{ .Name = "_VERSION" }, LuaValue { .String = "Lua 5.3" }); try env.setUpvalue(.{ .Name = "print" }, LuaValue { .CFunction = luaPrint }); try env.setUpvalue(.{ .Name = "tostring" }, LuaValue { .CFunction = luaToString }); try env.setUpvalue(.{ .Name = "error" }, LuaValue { .CFunction = luaCreateError }); try env.setUpvalue(.{ .Name = "newTable" }, LuaValue { .CFunction = createTable }); var package = LuaTable.init(env.allocator); try package.put(.{ .String = "path" }, .{ .String = "" }); // require(...) not even implemented try env.setUpvalue(.{ .Name = "package" }, LuaValue { .Table = package }); _ = evalLoop(&env) catch |err| switch (err) { error.LuaError => {}, else => return err }; } pub fn do_file(allocator: *Allocator, path: []const u8) !void { const file = std.fs.cwd().openFile(path, .{ .read = true }) catch |err| { std.log.err("could not open file: {s}", .{@errorName(err)}); return; }; const all = try file.readToEndAlloc(allocator, std.math.maxInt(usize)); defer allocator.free(all); try run(allocator, all); } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{ .enable_memory_limit = true }) {}; defer { //std.log.info("Used {} of memory.", .{std.fmt.fmtIntSizeDec(gpa.total_requested_bytes)}); _ = gpa.deinit(); } const allocator = &gpa.allocator; var args = try std.process.argsAlloc(allocator); defer allocator.free(args); //var logging = std.heap.loggingAllocator(allocator); if (args.len > 1) { const path = args[1]; try do_file(allocator, path); } else { std.debug.print("Nelua 5 Copyright (C) zenith391\n", .{}); const stdin = std.io.getStdIn().reader(); while (true) { std.debug.print("> ", .{}); const line = try stdin.readUntilDelimiterAlloc(allocator, '\n', std.math.maxInt(usize)); defer allocator.free(line); run(allocator, line) catch |err| { std.log.err("{s}", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } }; } } }
src/main.zig
const Interface = @This(); ptr: *anyopaque, vtable: *const VTable, pub const VTable = struct { /// Read from memory. read: fn(ptr: *anyopaque, addr: u16) u8, /// Write to memory. write: fn(ptr: *anyopaque, addr: u16, value: u8) void, /// Read data for a maskable interrupt (address low byte for mode 2, opcode byte(s) for mode 0) irq: fn(ptr: *anyopaque) u8, /// Read from I/O. in: fn(ptr: *anyopaque, port: u16) u8, /// Write to I/O. out: fn(ptr: *anyopaque, port: u16, value: u8) void, /// Called when an interrupt routine is completed. reti: fn(ptr: *anyopaque) void, }; fn writeDefault(ptr: *anyopaque, addr: u16, value: u8) void { _ = ptr; _ = addr; _ = value; } fn irqDefault(ptr: *anyopaque) u8 { _ = ptr; return 0; } fn inDefault(ptr: *anyopaque, port: u16) u8 { _ = ptr; _ = port; return 0; } fn outDefault(ptr: *anyopaque, port: u16, value: u8) void { _ = ptr; _ = port; _ = value; } fn retiDefault(ptr: *anyopaque) void { _ = ptr; } pub fn init( pointer: anytype, comptime vtable: struct { read: fn(self: @TypeOf(pointer), addr: u16) u8, write: ?fn(self: @TypeOf(pointer), addr: u16, value: u8) void = null, irq: ?fn(self: @TypeOf(pointer)) u8 = null, in: ?fn(self: @TypeOf(pointer), port: u16) u8 = null, out: ?fn(self: @TypeOf(pointer), port: u16, value: u8) void = null, reti: ?fn(self: @TypeOf(pointer)) void = null, }, ) Interface { const Ptr = @TypeOf(pointer); const alignment = @alignOf(@TypeOf(pointer.*)); const gen = struct { inline fn cast(ptr: *anyopaque) Ptr { return @ptrCast(Ptr, @alignCast(alignment, ptr)); } fn readImpl(ptr: *anyopaque, addr: u16) u8 { return vtable.read(cast(ptr), addr); } fn writeImpl(ptr: *anyopaque, addr: u16, value: u8) void { return vtable.write.?(cast(ptr), addr, value); } fn irqImpl(ptr: *anyopaque) u8 { return vtable.irq.?(cast(ptr)); } fn inImpl(ptr: *anyopaque, port: u16) u8 { return vtable.in.?(cast(ptr), port); } fn outImpl(ptr: *anyopaque, port: u16, value: u8) void { return vtable.out.?(cast(ptr), port, value); } fn retiImpl(ptr: *anyopaque) void { return vtable.reti.?(cast(ptr)); } const gen_vtable = VTable{ .read = readImpl, .write = if (vtable.write != null) writeImpl else writeDefault, .irq = if (vtable.irq != null) irqImpl else irqDefault, .in = if (vtable.in != null) inImpl else inDefault, .out = if (vtable.out != null) outImpl else outDefault, .reti = if (vtable.reti != null) retiImpl else retiDefault, }; }; return .{ .ptr = pointer, .vtable = &gen.gen_vtable, }; } pub inline fn read(self: Interface, addr: u16) u8 { return self.vtable.read(self.ptr, addr); } pub inline fn write(self: Interface, addr: u16, value: u8) void { return self.vtable.write(self.ptr, addr, value); } pub inline fn irq(self: Interface) u8 { return self.vtable.irq(self.ptr); } pub inline fn in(self: Interface, port: u16) u8 { return self.vtable.in(self.ptr, port); } pub inline fn out(self: Interface, port: u16, value: u8) void { return self.vtable.out(self.ptr, port, value); } pub inline fn reti(self: Interface) void { return self.vtable.reti(self.ptr); }
src/Interface.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const webgpu = @import("../../../webgpu.zig"); const vulkan = @import("../vulkan.zig"); const vk = @import("../vk.zig"); const QueueFamilies = @import("../QueueFamilies.zig"); const log = @import("../log.zig"); const Device = @This(); const DeviceDispatch = vk.DeviceWrapper(.{ .destroyDevice = true, .getDeviceQueue = true, .createBuffer = true, .destroyBuffer = true, }); pub const vtable = webgpu.Device.VTable{ .destroy_fn = destroy, .create_buffer_fn = createBuffer, .create_texture_fn = undefined, .create_sampler_fn = undefined, .create_bind_group_layout_fn = undefined, .create_pipeline_layout_fn = undefined, .create_bind_group_fn = undefined, .create_shader_module_fn = undefined, .create_compute_pipeline_fn = undefined, .create_render_pipeline_fn = undefined, .create_command_encoder_fn = undefined, .create_render_bundle_encoder_fn = undefined, }; super: webgpu.Device, allocator: Allocator, handle: vk.Device, queue_families: QueueFamilies, vkd: DeviceDispatch, queue: *vulkan.Queue, pub fn create(adapter: *vulkan.Adapter, descriptor: webgpu.DeviceDescriptor) !*Device { var instance = @fieldParentPtr(vulkan.Instance, "super", adapter.super.instance); _ = descriptor; var device = try instance.allocator.create(Device); errdefer instance.allocator.destroy(device); device.super = .{ .__vtable = &vtable, .instance = &instance.super, .adapter = &adapter.super, .queue = undefined, .features = .{}, .limits = .{}, }; device.allocator = instance.allocator; device.queue_families = adapter.queue_families; if (!(try device.checkDeviceLayersSupport())) { return error.MissingDeviceLayers; } if (!(try device.checkDeviceExtensionsSupport())) { return error.MissingDeviceExtensions; } const queue_priorities: f32 = 1; const queue_create_info = vk.DeviceQueueCreateInfo{ .flags = vk.DeviceQueueCreateFlags{}, .queue_family_index = device.queue_families.graphics.?, .queue_count = 1, .p_queue_priorities = @ptrCast([*]const f32, &queue_priorities), }; const features = vk.PhysicalDeviceFeatures{}; const create_info = vk.DeviceCreateInfo{ .flags = vk.DeviceCreateFlags{}, .queue_create_info_count = 1, .p_queue_create_infos = @ptrCast([*]const vk.DeviceQueueCreateInfo, &queue_create_info), .enabled_layer_count = vulkan.DEVICE_LAYERS.len, .pp_enabled_layer_names = @ptrCast([*]const [*:0]const u8, &vulkan.DEVICE_LAYERS), .enabled_extension_count = vulkan.DEVICE_EXTENSIONS.len, .pp_enabled_extension_names = @ptrCast([*]const [*:0]const u8, &vulkan.DEVICE_EXTENSIONS), .p_enabled_features = &features, }; device.handle = instance.vki.createDevice(adapter.handle, &create_info, null) catch return error.Failed; device.vkd = DeviceDispatch.load(device.handle, instance.vki.dispatch.vkGetDeviceProcAddr) catch return error.Failed; errdefer device.vkd.destroyDevice(device.handle, null); device.queue = vulkan.Queue.create(device, adapter.queue_families.graphics.?, 0) catch return error.Failed; errdefer device.queue.destroy(device); device.super.queue = &device.queue.super; return device; } fn destroy(super: *webgpu.Device) void { var device = @fieldParentPtr(Device, "super", super); device.queue.destroy(device); device.allocator.destroy(device); } fn createBuffer(super: *webgpu.Device, descriptor: webgpu.BufferDescriptor) webgpu.Device.CreateBufferError!*webgpu.Buffer { var device = @fieldParentPtr(Device, "super", super); var buffer = try vulkan.Buffer.create(device, descriptor); return &buffer.super; } fn checkDeviceLayersSupport(device: *Device) !bool { var instance = @fieldParentPtr(vulkan.Instance, "super", device.super.instance); var adapter = @fieldParentPtr(vulkan.Adapter, "super", device.super.adapter); var layers_len: u32 = undefined; if ((try instance.vki.enumerateDeviceLayerProperties(adapter.handle, &layers_len, null)) != .success) { return error.Failed; } var layers = try instance.allocator.alloc(vk.LayerProperties, layers_len); defer instance.allocator.free(layers); if ((try instance.vki.enumerateDeviceLayerProperties(adapter.handle, &layers_len, layers.ptr)) != .success) { return error.Failed; } for (vulkan.DEVICE_LAYERS) |validation_layer| { const validation_layer_name = std.mem.sliceTo(validation_layer, 0); var found = false; for (layers) |layer| { if (std.mem.eql(u8, validation_layer_name, std.mem.sliceTo(&layer.layer_name, 0))) { found = true; break; } } if (!found) { log.err("Missing required device layer: {s}", .{ validation_layer_name }); return false; } else { log.debug("Found required device layer: {s}", .{ validation_layer_name }); } } return true; } fn checkDeviceExtensionsSupport(device: *Device) !bool { var instance = @fieldParentPtr(vulkan.Instance, "super", device.super.instance); var adapter = @fieldParentPtr(vulkan.Adapter, "super", device.super.adapter); var extensions_len: u32 = undefined; if ((try instance.vki.enumerateDeviceExtensionProperties(adapter.handle, null, &extensions_len, null)) != .success) { return error.Failed; } var extensions = try instance.allocator.alloc(vk.ExtensionProperties, extensions_len); defer instance.allocator.free(extensions); if ((try instance.vki.enumerateDeviceExtensionProperties(adapter.handle, null, &extensions_len, extensions.ptr)) != .success) { return error.Failed; } for (vulkan.DEVICE_EXTENSIONS) |surface_extension| { const surface_extension_name = std.mem.sliceTo(surface_extension, 0); var found = false; for (extensions) |extension| { if (std.mem.eql(u8, surface_extension_name, std.mem.sliceTo(&extension.extension_name, 0))) { found = true; break; } } if (!found) { log.err("Missing required device extension: {s}", .{ surface_extension_name }); return false; } else { log.debug("Found required device extension: {s}", .{ surface_extension_name }); } } return true; }
src/backends/vulkan/device/Device.zig
const windows = @import("windows.zig"); const UINT = windows.UINT; const IUnknown = windows.IUnknown; const GUID = windows.GUID; const HRESULT = windows.HRESULT; const WINAPI = windows.WINAPI; const LPCWSTR = windows.LPCWSTR; const FLOAT = windows.FLOAT; pub const MEASURING_MODE = enum(UINT) { NATURAL = 0, GDI_CLASSIC = 1, GDI_NATURAL = 2, }; pub const FONT_WEIGHT = enum(UINT) { THIN = 100, EXTRA_LIGHT = 200, LIGHT = 300, SEMI_LIGHT = 350, NORMAL = 400, MEDIUM = 500, SEMI_BOLD = 600, BOLD = 700, EXTRA_BOLD = 800, HEAVY = 900, ULTRA_BLACK = 950, }; pub const FONT_STRETCH = enum(UINT) { UNDEFINED = 0, ULTRA_CONDENSED = 1, EXTRA_CONDENSED = 2, CONDENSED = 3, SEMI_CONDENSED = 4, NORMAL = 5, SEMI_EXPANDED = 6, EXPANDED = 7, EXTRA_EXPANDED = 8, ULTRA_EXPANDED = 9, }; pub const FONT_STYLE = enum(UINT) { NORMAL = 0, OBLIQUE = 1, ITALIC = 2, }; pub const FACTORY_TYPE = enum(UINT) { SHARED = 0, ISOLATED = 1, }; pub const TEXT_ALIGNMENT = enum(UINT) { LEADING = 0, TRAILING = 1, CENTER = 2, JUSTIFIED = 3, }; pub const PARAGRAPH_ALIGNMENT = enum(UINT) { NEAR = 0, FAR = 1, CENTER = 2, }; pub const IFontCollection = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), fontcollect: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { _ = T; return extern struct {}; } pub fn VTable(comptime T: type) type { _ = T; return extern struct { GetFontFamilyCount: *anyopaque, GetFontFamily: *anyopaque, FindFamilyName: *anyopaque, GetFontFromFontFace: *anyopaque, }; } }; pub const ITextFormat = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), textformat: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { return extern struct { pub inline fn SetTextAlignment(self: *T, alignment: TEXT_ALIGNMENT) HRESULT { return self.v.textformat.SetTextAlignment(self, alignment); } pub inline fn SetParagraphAlignment(self: *T, alignment: PARAGRAPH_ALIGNMENT) HRESULT { return self.v.textformat.SetParagraphAlignment(self, alignment); } }; } pub fn VTable(comptime T: type) type { return extern struct { SetTextAlignment: fn (*T, TEXT_ALIGNMENT) callconv(WINAPI) HRESULT, SetParagraphAlignment: fn (*T, PARAGRAPH_ALIGNMENT) callconv(WINAPI) HRESULT, SetWordWrapping: *anyopaque, SetReadingDirection: *anyopaque, SetFlowDirection: *anyopaque, SetIncrementalTabStop: *anyopaque, SetTrimming: *anyopaque, SetLineSpacing: *anyopaque, GetTextAlignment: *anyopaque, GetParagraphAlignment: *anyopaque, GetWordWrapping: *anyopaque, GetReadingDirection: *anyopaque, GetFlowDirection: *anyopaque, GetIncrementalTabStop: *anyopaque, GetTrimming: *anyopaque, GetLineSpacing: *anyopaque, GetFontCollection: *anyopaque, GetFontFamilyNameLength: *anyopaque, GetFontFamilyName: *anyopaque, GetFontWeight: *anyopaque, GetFontStyle: *anyopaque, GetFontStretch: *anyopaque, GetFontSize: *anyopaque, GetLocaleNameLength: *anyopaque, GetLocaleName: *anyopaque, }; } }; pub const IFactory = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), factory: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { return extern struct { pub inline fn CreateTextFormat( self: *T, font_family_name: LPCWSTR, font_collection: ?*IFontCollection, font_weight: FONT_WEIGHT, font_style: FONT_STYLE, font_stretch: FONT_STRETCH, font_size: FLOAT, locale_name: LPCWSTR, text_format: *?*ITextFormat, ) HRESULT { return self.v.factory.CreateTextFormat( self, font_family_name, font_collection, font_weight, font_style, font_stretch, font_size, locale_name, text_format, ); } }; } pub fn VTable(comptime T: type) type { return extern struct { GetSystemFontCollection: *anyopaque, CreateCustomFontCollection: *anyopaque, RegisterFontCollectionLoader: *anyopaque, UnregisterFontCollectionLoader: *anyopaque, CreateFontFileReference: *anyopaque, CreateCustomFontFileReference: *anyopaque, CreateFontFace: *anyopaque, CreateRenderingParams: *anyopaque, CreateMonitorRenderingParams: *anyopaque, CreateCustomRenderingParams: *anyopaque, RegisterFontFileLoader: *anyopaque, UnregisterFontFileLoader: *anyopaque, CreateTextFormat: fn ( *T, LPCWSTR, ?*IFontCollection, FONT_WEIGHT, FONT_STYLE, FONT_STRETCH, FLOAT, LPCWSTR, *?*ITextFormat, ) callconv(WINAPI) HRESULT, CreateTypography: *anyopaque, GetGdiInterop: *anyopaque, CreateTextLayout: *anyopaque, CreateGdiCompatibleTextLayout: *anyopaque, CreateEllipsisTrimmingSign: *anyopaque, CreateTextAnalyzer: *anyopaque, CreateNumberSubstitution: *anyopaque, CreateGlyphRunAnalysis: *anyopaque, }; } }; pub const IID_IFactory = GUID{ .Data1 = 0xb859ee5a, .Data2 = 0xd838, .Data3 = 0x4b5b, .Data4 = .{ 0xa2, 0xe8, 0x1a, 0xdc, 0x7d, 0x93, 0xdb, 0x48 }, }; pub extern "dwrite" fn DWriteCreateFactory( factory_type: FACTORY_TYPE, guid: *const GUID, factory: *?*anyopaque, ) callconv(WINAPI) HRESULT; pub const E_FILEFORMAT = @bitCast(HRESULT, @as(c_ulong, 0x88985000)); pub const Error = error{ E_FILEFORMAT, };
modules/platform/vendored/zwin32/src/dwrite.zig
const windows = @import("windows.zig"); const IUnknown = windows.IUnknown; const UINT = windows.UINT; const UINT32 = windows.UINT32; const HRESULT = windows.HRESULT; const ULONG = windows.ULONG; const DWORD = windows.DWORD; const WINAPI = windows.WINAPI; const GUID = windows.GUID; const LPCWSTR = windows.LPCWSTR; const BYTE = windows.BYTE; const LONGLONG = windows.LONGLONG; const PROPVARIANT = windows.PROPVARIANT; // 0x0002 for Windows 7+ pub const SDK_VERSION: UINT = 0x0002; pub const API_VERSION: UINT = 0x0070; pub const VERSION: UINT = (SDK_VERSION << 16 | API_VERSION); pub const SOURCE_READER_INVALID_STREAM_INDEX: DWORD = 0xffffffff; pub const SOURCE_READER_ALL_STREAMS: DWORD = 0xfffffffe; pub const SOURCE_READER_ANY_STREAM: DWORD = 0xfffffffe; pub const SOURCE_READER_FIRST_AUDIO_STREAM: DWORD = 0xfffffffd; pub const SOURCE_READER_FIRST_VIDEO_STREAM: DWORD = 0xfffffffc; pub const SOURCE_READER_MEDIASOURCE: DWORD = 0xffffffff; pub const SOURCE_READERF_ERROR: DWORD = 0x1; pub const SOURCE_READERF_ENDOFSTREAM: DWORD = 0x2; pub const SOURCE_READERF_NEWSTREAM: DWORD = 0x4; pub const SOURCE_READERF_NATIVEMEDIATYPECHANGED: DWORD = 0x10; pub const SOURCE_READERF_CURRENTMEDIATYPECHANGED: DWORD = 0x20; pub const SOURCE_READERF_STREAMTICK: DWORD = 0x100; pub const SOURCE_READERF_ALLEFFECTSREMOVED: DWORD = 0x200; pub extern "mfplat" fn MFStartup(version: ULONG, flags: DWORD) callconv(WINAPI) HRESULT; pub extern "mfplat" fn MFShutdown() callconv(WINAPI) HRESULT; pub extern "mfplat" fn MFCreateAttributes(attribs: **IAttributes, init_size: UINT32) callconv(WINAPI) HRESULT; pub extern "mfreadwrite" fn MFCreateSourceReaderFromURL( url: LPCWSTR, attribs: ?*IAttributes, reader: **ISourceReader, ) callconv(WINAPI) HRESULT; pub const IAttributes = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), attribs: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn GetUINT32(self: *T, guid: *const GUID, value: *UINT32) HRESULT { return self.v.attribs.GetUINT32(self, guid, value); } pub inline fn GetGUID(self: *T, key: *const GUID, value: *GUID) HRESULT { return self.v.attribs.GetGUID(self, key, value); } pub inline fn SetUINT32(self: *T, guid: *const GUID, value: UINT32) HRESULT { return self.v.attribs.SetUINT32(self, guid, value); } pub inline fn SetGUID(self: *T, key: *const GUID, value: *const GUID) HRESULT { return self.v.attribs.SetGUID(self, key, value); } pub inline fn SetUnknown(self: *T, guid: *const GUID, unknown: ?*IUnknown) HRESULT { return self.v.attribs.SetUnknown(self, guid, unknown); } }; } fn VTable(comptime T: type) type { return extern struct { GetItem: *anyopaque, GetItemType: *anyopaque, CompareItem: *anyopaque, Compare: *anyopaque, GetUINT32: fn (*T, *const GUID, *UINT32) callconv(WINAPI) HRESULT, GetUINT64: *anyopaque, GetDouble: *anyopaque, GetGUID: fn (*T, *const GUID, *GUID) callconv(WINAPI) HRESULT, GetStringLength: *anyopaque, GetString: *anyopaque, GetAllocatedString: *anyopaque, GetBlobSize: *anyopaque, GetBlob: *anyopaque, GetAllocatedBlob: *anyopaque, GetUnknown: *anyopaque, SetItem: *anyopaque, DeleteItem: *anyopaque, DeleteAllItems: *anyopaque, SetUINT32: fn (*T, *const GUID, UINT32) callconv(WINAPI) HRESULT, SetUINT64: *anyopaque, SetDouble: *anyopaque, SetGUID: fn (*T, *const GUID, *const GUID) callconv(WINAPI) HRESULT, SetString: *anyopaque, SetBlob: *anyopaque, SetUnknown: fn (*T, *const GUID, ?*IUnknown) callconv(WINAPI) HRESULT, LockStore: *anyopaque, UnlockStore: *anyopaque, GetCount: *anyopaque, GetItemByIndex: *anyopaque, CopyAllItems: *anyopaque, }; } }; pub const IMediaEvent = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), attribs: IAttributes.VTable(Self), event: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IAttributes.Methods(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn GetType(self: *T, met: *MediaEventType) HRESULT { return self.v.event.GetType(self, met); } pub inline fn GetExtendedType(self: *T, ex_met: *GUID) HRESULT { return self.v.event.GetExtendedType(self, ex_met); } pub inline fn GetStatus(self: *T, status: *HRESULT) HRESULT { return self.v.event.GetStatus(self, status); } pub inline fn GetValue(self: *T, value: *PROPVARIANT) HRESULT { return self.v.event.GetValue(self, value); } }; } fn VTable(comptime T: type) type { return extern struct { GetType: fn (*T, *MediaEventType) callconv(WINAPI) HRESULT, GetExtendedType: fn (*T, *GUID) callconv(WINAPI) HRESULT, GetStatus: fn (*T, *HRESULT) callconv(WINAPI) HRESULT, GetValue: fn (*T, *PROPVARIANT) callconv(WINAPI) HRESULT, }; } }; pub const ISourceReader = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), reader: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn GetNativeMediaType( self: *T, stream_index: DWORD, media_type_index: DWORD, media_type: **IMediaType, ) HRESULT { return self.v.reader.GetNativeMediaType(self, stream_index, media_type_index, media_type); } pub inline fn GetCurrentMediaType( self: *T, stream_index: DWORD, media_type: **IMediaType, ) HRESULT { return self.v.reader.GetCurrentMediaType(self, stream_index, media_type); } pub inline fn SetCurrentMediaType( self: *T, stream_index: DWORD, reserved: ?*DWORD, media_type: *IMediaType, ) HRESULT { return self.v.reader.SetCurrentMediaType(self, stream_index, reserved, media_type); } pub inline fn ReadSample( self: *T, stream_index: DWORD, control_flags: DWORD, actual_stream_index: ?*DWORD, stream_flags: ?*DWORD, timestamp: ?*LONGLONG, sample: ?*?*ISample, ) HRESULT { return self.v.reader.ReadSample( self, stream_index, control_flags, actual_stream_index, stream_flags, timestamp, sample, ); } pub inline fn SetCurrentPosition(self: *T, guid: *const GUID, prop: *const PROPVARIANT) HRESULT { return self.v.reader.SetCurrentPosition(self, guid, prop); } }; } fn VTable(comptime T: type) type { return extern struct { GetStreamSelection: *anyopaque, SetStreamSelection: *anyopaque, GetNativeMediaType: fn (*T, DWORD, DWORD, **IMediaType) callconv(WINAPI) HRESULT, GetCurrentMediaType: fn (*T, DWORD, **IMediaType) callconv(WINAPI) HRESULT, SetCurrentMediaType: fn (*T, DWORD, ?*DWORD, *IMediaType) callconv(WINAPI) HRESULT, SetCurrentPosition: fn (*T, *const GUID, *const PROPVARIANT) callconv(WINAPI) HRESULT, ReadSample: fn (*T, DWORD, DWORD, ?*DWORD, ?*DWORD, ?*LONGLONG, ?*?*ISample) callconv(WINAPI) HRESULT, Flush: *anyopaque, GetServiceForStream: *anyopaque, GetPresentationAttribute: *anyopaque, }; } }; pub const IMediaType = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), attribs: IAttributes.VTable(Self), mediatype: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IAttributes.Methods(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { _ = T; return extern struct {}; } fn VTable(comptime T: type) type { _ = T; return extern struct { GetMajorType: *anyopaque, IsCompressedFormat: *anyopaque, IsEqual: *anyopaque, GetRepresentation: *anyopaque, FreeRepresentation: *anyopaque, }; } }; pub const ISample = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), attribs: IAttributes.VTable(Self), sample: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IAttributes.Methods(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn ConvertToContiguousBuffer(self: *T, buffer: **IMediaBuffer) HRESULT { return self.v.sample.ConvertToContiguousBuffer(self, buffer); } pub inline fn GetBufferByIndex(self: *T, index: DWORD, buffer: **IMediaBuffer) HRESULT { return self.v.sample.GetBufferByIndex(self, index, buffer); } }; } fn VTable(comptime T: type) type { return extern struct { GetSampleFlags: *anyopaque, SetSampleFlags: *anyopaque, GetSampleTime: *anyopaque, SetSampleTime: *anyopaque, GetSampleDuration: *anyopaque, SetSampleDuration: *anyopaque, GetBufferCount: *anyopaque, GetBufferByIndex: fn (*T, DWORD, **IMediaBuffer) callconv(WINAPI) HRESULT, ConvertToContiguousBuffer: fn (*T, **IMediaBuffer) callconv(WINAPI) HRESULT, AddBuffer: *anyopaque, RemoveBufferByIndex: *anyopaque, RemoveAllBuffers: *anyopaque, GetTotalLength: *anyopaque, CopyToBuffer: *anyopaque, }; } }; pub const IMediaBuffer = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), buffer: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn Lock(self: *T, ptr: *[*]BYTE, max_len: ?*DWORD, current_len: ?*DWORD) HRESULT { return self.v.buffer.Lock(self, ptr, max_len, current_len); } pub inline fn Unlock(self: *T) HRESULT { return self.v.buffer.Unlock(self); } pub inline fn GetCurrentLength(self: *T, length: *DWORD) HRESULT { return self.v.buffer.GetCurrentLength(self, length); } }; } fn VTable(comptime T: type) type { return extern struct { Lock: fn (*T, *[*]BYTE, ?*DWORD, ?*DWORD) callconv(WINAPI) HRESULT, Unlock: fn (*T) callconv(WINAPI) HRESULT, GetCurrentLength: fn (*T, *DWORD) callconv(WINAPI) HRESULT, SetCurrentLength: *anyopaque, GetMaxLength: *anyopaque, }; } }; pub const MediaEventType = DWORD; pub fn ISourceReaderCallbackVTable(comptime T: type) type { return extern struct { unknown: IUnknown.VTable(T), cb: extern struct { OnReadSample: fn (*T, HRESULT, DWORD, DWORD, LONGLONG, ?*ISample) callconv(WINAPI) HRESULT, OnFlush: fn (*T, DWORD) callconv(WINAPI) HRESULT, OnEvent: fn (*T, DWORD, *IMediaEvent) callconv(WINAPI) HRESULT, }, }; } pub const IID_ISourceReaderCallback = GUID.parse("{deec8d99-fa1d-4d82-84c2-2c8969944867}"); pub const ISourceReaderCallback = extern struct { v: *const ISourceReaderCallbackVTable(Self), const Self = @This(); usingnamespace IUnknown.Methods(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn OnReadSample( self: *T, status: HRESULT, stream_index: DWORD, stream_flags: DWORD, timestamp: LONGLONG, sample: ?*ISample, ) HRESULT { return self.v.cb.OnReadSample(self, status, stream_index, stream_flags, timestamp, sample); } pub inline fn OnFlush(self: *T, stream_index: DWORD) HRESULT { return self.v.cb.OnFlush(self, stream_index); } pub inline fn OnEvent(self: *T, stream_index: DWORD, event: *IMediaEvent) HRESULT { return self.v.cb.OnEvent(self, stream_index, event); } }; } }; pub const LOW_LATENCY = GUID.parse("{9C27891A-ED7A-40e1-88E8-B22727A024EE}"); // {UINT32 (BOOL)} pub const SOURCE_READER_ASYNC_CALLBACK = GUID.parse("{1e3dbeac-bb43-4c35-b507-cd644464c965}"); // {*IUnknown} pub const MT_MAJOR_TYPE = GUID.parse("{48eba18e-f8c9-4687-bf11-0a74c9f96a8f}"); // {GUID} pub const MT_SUBTYPE = GUID.parse("{f7e34c9a-42e8-4714-b74b-cb29d72c35e5}"); // {GUID} pub const MT_AUDIO_BITS_PER_SAMPLE = GUID.parse("{f2deb57f-40fa-4764-aa33-ed4f2d1ff669}"); // {UINT32} pub const MT_AUDIO_SAMPLES_PER_SECOND = GUID.parse("{5faeeae7-0290-4c31-9e8a-c534f68d9dba}"); // {UINT32} pub const MT_AUDIO_NUM_CHANNELS = GUID.parse("{37e48bf5-645e-4c5b-89de-ada9e29b696a}"); // {UINT32} pub const MT_AUDIO_BLOCK_ALIGNMENT = GUID.parse("{322de230-9eeb-43bd-ab7a-ff412251541d}"); // {UINT32} pub const MT_AUDIO_AVG_BYTES_PER_SECOND = GUID.parse("{1aab75c8-cfef-451c-ab95-ac034b8e1731}"); // {UINT32} pub const MT_ALL_SAMPLES_INDEPENDENT = GUID.parse("{c9173739-5e56-461c-b713-46fb995cb95f}"); // {UINT32 (BOOL)} pub const AudioFormat_Base = GUID.parse("{00000000-0000-0010-8000-00aa00389b71}"); pub const AudioFormat_PCM = GUID.parse("{00000001-0000-0010-8000-00aa00389b71}"); pub const AudioFormat_Float = GUID.parse("{00000003-0000-0010-8000-00aa00389b71}"); pub const MediaType_Audio = GUID.parse("{73647561-0000-0010-8000-00aa00389b71}");
modules/platform/vendored/zwin32/src/mf.zig
const std = @import("std"); const zargo = @import("zargo"); const c = @cImport({ @cDefine("GLFW_INCLUDE_NONE", {}); @cInclude("GLFW/glfw3.h"); }); fn errorCallback(err: c_int, description: [*c]const u8) callconv(.C) void { std.debug.panic("Error: {s}\n", .{description}); } fn keyCallback(win: ?*c.GLFWwindow, key: c_int, scancode: c_int, action: c_int, mods: c_int) callconv(.C) void { if (action != c.GLFW_PRESS) return; switch (key) { c.GLFW_KEY_ESCAPE => c.glfwSetWindowShouldClose(win, 1), else => {}, } } pub fn main() !u8 { _ = c.glfwSetErrorCallback(errorCallback); if (c.glfwInit() == 0) { std.debug.warn("Failed to initialize GLFW\n", .{}); return 1; } c.glfwWindowHint(c.GLFW_SAMPLES, 4); c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, 3); c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, 2); c.glfwWindowHint(c.GLFW_OPENGL_FORWARD_COMPAT, 1); c.glfwWindowHint(c.GLFW_OPENGL_PROFILE, c.GLFW_OPENGL_CORE_PROFILE); if (std.builtin.os.tag == .windows) { c.glfwWindowHint(c.GLFW_OPENGL_DEBUG_CONTEXT, c.GL_TRUE); } var window = c.glfwCreateWindow(800, 600, "test", null, null) orelse { std.debug.panic("unable to create window\n", .{}); }; _ = c.glfwSetKeyCallback(window, keyCallback); c.glfwMakeContextCurrent(window); c.glfwSwapInterval(1); var w: c_int = undefined; var h: c_int = undefined; c.glfwGetFramebufferSize(window, &w, &h); var e: zargo.Engine = undefined; try e.init(std.heap.c_allocator, switch (std.builtin.os.tag) { .macos => .ogl_32, .windows => .ogl_43, else => .ogles_20, }, @intCast(u32, w), @intCast(u32, h), std.builtin.os.tag == .windows); var tex = e.loadImage("test.png"); std.debug.print("loaded texture: w = {}, h = {}, alpha= {}\n", .{tex.width, tex.height, tex.has_alpha}); var mask = e.loadImage("paper.png"); std.debug.print("loaded mask: w = {}, h = {}\n", .{tex.width, tex.height}); var angle: f32 = 0; var iangle: f32 = 0; var iw = @intCast(i32, w); var ih = @intCast(i32, h); var painted = zargo.Image.empty(); { var canvas = e.createCanvas(200, 200, false) catch unreachable; defer canvas.close(); var area = canvas.rectangle(); e.fillRect(area.position(100, 100, .left, .top), [_]u8{255,0,0,255}, true); e.fillRect(area.position(100, 100, .right, .top), [_]u8{255,255,0,255}, true); e.fillRect(area.position(100, 100, .left, .bottom), [_]u8{0,0,255,255}, true); e.fillRect(area.position(100, 100, .right, .bottom), [_]u8{0,255,0,255}, true); painted = canvas.finish() catch unreachable; } var r1 = zargo.Rectangle{.x = @divTrunc(iw, 4) - 50, .y = @divTrunc(ih, 4) - 50, .width = 100, .height = 100}; var r2 = zargo.Rectangle{.x = @divTrunc(iw * 3, 4) - 50, .y = @divTrunc(ih * 3, 4) - 50, .width = 100, .height = 100}; while (c.glfwWindowShouldClose(window) == 0) { e.clear([_]u8{0,0,0,255}); e.fillRect(r1, [_]u8{255,0,0,255}, true); e.fillUnit(r2.transformation().rotate(angle), [_]u8{0,255,0,255}, true); e.drawImage(tex, tex.area().move(400, 550).transformation(), tex.area().transformation(), 255); if (!painted.isEmpty()) painted.drawAll(&e, painted.area(), 255); const mRect = zargo.Rectangle{.x = 400, .y = 0, .width = @intCast(u31, 2*mask.width), .height = @intCast(u31, mask.height)}; e.blendUnit(mask, mRect.transformation(), mRect.scale(0.5, 0.5).transformation().rotate(iangle), [_]u8{128,128,0,255}, [_]u8{20,20,0,255}); angle = @rem((angle + 0.01), 2*3.14159); iangle = @rem((iangle + 0.001), 2*3.14159); c.glfwSwapBuffers(window); c.glfwPollEvents(); } return 0; }
tests/test.zig
const std = @import("std"); const liu = @import("liu"); const wasm = liu.wasm; const gon = liu.gon; const util = @import("./util.zig"); const erlang = @import("./erlang.zig"); const ext = erlang.ext; const BBox = erlang.BBox; const EntityId = liu.ecs.EntityId; const Vec2 = liu.Vec2; const FrameInput = liu.gamescreen.FrameInput; pub fn unitSquareBBoxForPos(pos: Vec2) BBox { return BBox{ .pos = @floor(pos), .width = 1, .height = 1, }; } pub fn boxWillCollide(bbox: BBox) bool { var view = erlang.registry.view(struct { pos_c: erlang.PositionC, force_c: ?*const erlang.ForceC, }); while (view.next()) |elem| { if (elem.force_c == null) continue; const overlap = elem.pos_c.bbox.overlap(bbox); if (overlap.result) return true; } return false; } pub const Tool = struct { const Self = @This(); const VTable = struct { frame: fn (self: *anyopaque, input: FrameInput) void, reset: fn (self: *anyopaque) void, }; name: []const u8, ptr: *anyopaque, vtable: *const VTable, pub fn create(alloc: std.mem.Allocator, obj: anytype) !Self { const val = try alloc.create(@TypeOf(obj)); val.* = obj; return init(val); } pub fn init(obj: anytype) Self { const PtrT = @TypeOf(obj); const T = std.meta.Child(PtrT); return initWithVtable(T, obj, T); } pub fn initWithVtable(comptime T: type, obj: *T, comptime VtableType: type) Self { const info = std.meta.fieldInfo; const vtable = comptime VTable{ .frame = @ptrCast(info(VTable, .frame).field_type, VtableType.frame), .reset = @ptrCast(info(VTable, .reset).field_type, VtableType.reset), }; return Self{ .name = if (@hasDecl(T, "tool_name")) T.tool_name else @typeName(T), .ptr = @ptrCast(*anyopaque, obj), .vtable = &vtable, }; } pub fn reset(self: *Self) void { return self.vtable.reset(self.ptr); } pub fn frame(self: *Self, input: FrameInput) void { return self.vtable.frame(self.ptr, input); } }; fn makeBox(pos: Vec2) !EntityId { const id = try erlang.registry.create("box"); errdefer erlang.registry.delete(id); try erlang.registry.addComponent(id, erlang.PositionC{ .bbox = .{ .pos = pos, .width = 1, .height = 1, } }); try erlang.registry.addComponent(id, erlang.RenderC{ .color = erlang.Vec4{ 0.2, 0.5, 0.3, 1 }, }); return id; } pub const ClickTool = struct { dummy: bool = false, pub fn reset(self: *@This()) void { _ = self; } pub fn frame(self: *@This(), input: FrameInput) void { if (!input.mouse.left_clicked and !input.mouse.right_clicked) return; _ = self; const bbox = unitSquareBBoxForPos(input.mouse.pos); if (input.mouse.left_clicked) { if (boxWillCollide(bbox)) return; _ = makeBox(bbox.pos) catch return; return; } if (input.mouse.right_clicked) { var view = erlang.registry.view(struct { pos_c: erlang.PositionC, force_c: ?*const erlang.ForceC, }); while (view.next()) |elem| { if (elem.force_c != null) continue; const overlap = elem.pos_c.bbox.overlap(bbox); if (overlap.result) { _ = erlang.registry.delete(elem.id); } } } } }; pub const LineTool = struct { data: ?Data = null, const Data = struct { entity: EntityId, pos: Vec2, }; pub fn reset(self: *@This()) void { const data = self.data orelse return; self.data = null; _ = erlang.registry.delete(data.entity); } pub fn frame(self: *@This(), input: FrameInput) void { const pos = @floor(input.mouse.pos); if (input.mouse.right_clicked) { if (self.data) |data| { _ = erlang.registry.delete(data.entity); } self.data = null; return; } if (input.mouse.left_clicked) { if (self.data != null) { self.data = null; } else { const entity = makeBox(pos) catch return; self.data = .{ .entity = entity, .pos = pos }; } return; } const data = self.data orelse return; const bbox = bbox: { // Project the floored mouse position onto the X and Y axes, so that // the line will always be straight horizontal or straight vertical const xProj = Vec2{ pos[0], data.pos[1] }; const yProj = Vec2{ data.pos[0], pos[1] }; // Get squared distance between each projection and line origin const xDiff = pos - xProj; const yDiff = pos - yProj; const xSqr = @reduce(.Add, xDiff * xDiff); const ySqr = @reduce(.Add, yDiff * yDiff); // Pick the projection with least distance const proj = if (xSqr < ySqr) xProj else yProj; // Translate position and projection into top-left pos0 and bottom-right // pos1 const mask = proj < data.pos; const pos0 = @select(f32, mask, proj, data.pos); const pos1 = @select(f32, mask, data.pos, proj) + Vec2{ 1, 1 }; break :bbox erlang.BBox{ .pos = pos0, .width = pos1[0] - pos0[0], .height = pos1[1] - pos0[1], }; }; if (boxWillCollide(bbox)) return; var view = erlang.registry.view(struct { pos_c: *erlang.PositionC, render: *erlang.RenderC, }); const val = view.get(data.entity) orelse { self.data = null; return; }; val.pos_c.bbox = bbox; } }; pub const DrawTool = struct { drawing: bool = false, pub fn reset(self: *@This()) void { self.drawing = false; } pub fn frame(self: *@This(), input: FrameInput) void { if (input.mouse.left_clicked) { self.drawing = !self.drawing; } if (!self.drawing) return; const bbox = unitSquareBBoxForPos(input.mouse.pos); if (boxWillCollide(bbox)) return; const new_solid = makeBox(bbox.pos) catch return; _ = new_solid; } }; const AssetEntity = struct { move: ?erlang.MoveC, render: ?erlang.RenderC, pos: ?erlang.PositionC, force: ?erlang.ForceC, decide: ?erlang.DecisionC, }; // Use stable declaration on type pub fn serializeLevel() ![]const u8 { var entities = std.ArrayList(AssetEntity).init(liu.Temp); var view = erlang.registry.view(AssetEntity); while (view.next()) |elem| { try entities.append(.{ .move = elem.move, .pos = elem.pos, .render = elem.render, .decide = elem.decide, .force = elem.force, }); } const gon_data = try gon.Value.init(.{ .entities = entities.items, }); var output = std.ArrayList(u8).init(liu.Temp); try gon_data.write(output.writer(), true); return output.items; } pub fn readFromAsset(bytes: []const u8) !void { const registry = &erlang.registry; var view = registry.view(struct {}); while (view.next()) |elem| { _ = registry.delete(elem.id); } const gon_data = try gon.parseGon(bytes); const asset_data = try gon_data.expect(struct { entities: []const AssetEntity, }); for (asset_data.entities) |entity| { const id = try registry.create(""); errdefer _ = registry.delete(id); if (entity.move) |move| { try registry.addComponent(id, move); } if (entity.pos) |pos| { try registry.addComponent(id, pos); } if (entity.render) |render| { try registry.addComponent(id, render); } if (entity.decide) |decide| { try registry.addComponent(id, decide); } if (entity.force) |force| { try registry.addComponent(id, force); } } }
src/routes/erlang/editor.zig
const std = @import("std"); const c = @import("../c.zig"); const zupnp = @import("../lib.zig"); const ClientResponse = @This(); const logger = std.log.scoped(.@"zupnp.web.ClientResponse"); /// HTTP status code. http_status: c_int, /// Content type. content_type: ?[:0]const u8, /// Content length. content_length: ?u32, timeout: c_int, // keepalive: bool, handle: ?*anyopaque, connection_closed: bool = false, /// Read full contents of HTTP request into a memory allocated string. /// Caller owns the returned string. pub fn readAll(self: *ClientResponse, allocator: std.mem.Allocator) ![:0]u8 { var buf = std.ArrayList(u8).init(allocator); defer buf.deinit(); var chunk: [1024]u8 = undefined; while (try self.readChunk(&chunk)) |chunk_read| { try buf.appendSlice(chunk_read); } return try buf.toOwnedSliceSentinel(0); } /// Read contents of HTTP request into buffer and returns a slice if anything was read. /// If there's nothing to read, the request is cancelled and null is returned. pub fn readChunk(self: *ClientResponse, buf: []u8) !?[]const u8 { if (self.connection_closed) { logger.err("Connection closed", .{}); return zupnp.Error; } errdefer self.cancel(); var size = buf.len; if (c.is_error(c.UpnpReadHttpResponse(self.handle, buf.ptr, &size, self.timeout))) |err| { logger.err("Failed reading HTTP response: {s}", .{err}); return zupnp.Error; } if (size == 0) { self.cancel(); return null; } return buf[0..size]; } /// Cancel the current request and, if keepalive was unset, also closes the connection to the server. pub fn cancel(self: *ClientResponse) void { if (!self.connection_closed) { logger.debug("Cancel err {d}", .{c.UpnpCancelHttpGet(self.handle)}); // if (!self.keepalive) { logger.debug("Close err {d}", .{c.UpnpCloseHttpConnection(self.handle)}); self.connection_closed = true; // Due to the nature of pupnp, once the handle is closed, content type get clobbered self.content_type = null; // } } }
src/web/client_response.zig
const std = @import("std"); const aoc = @import("aoc-lib.zig"); test "examples" { const test1 = aoc.readChunks(aoc.talloc, aoc.test1file); defer aoc.talloc.free(test1); try aoc.assertEq(@as(usize, 11), part1(aoc.talloc, test1)); try aoc.assertEq(@as(usize, 6), part2(aoc.talloc, test1)); const inp = aoc.readChunks(aoc.talloc, aoc.inputfile); defer aoc.talloc.free(inp); try aoc.assertEq(@as(usize, 6506), part1(aoc.talloc, inp)); try aoc.assertEq(@as(usize, 3243), part2(aoc.talloc, inp)); } fn part1(alloc: std.mem.Allocator, inp: anytype) usize { var c: usize = 0; for (inp) |ent| { var m = std.AutoHashMap(u8, usize).init(alloc); defer m.deinit(); var pit = std.mem.split(u8, ent, "\n"); while (pit.next()) |ans| { for (ans) |ch| { aoc.minc(&m, ch); } } var gc: usize = 0; var mit = m.iterator(); while (mit.next()) |_| { gc += 1; } c += gc; } return c; } fn part2(alloc: std.mem.Allocator, inp: anytype) usize { var c: usize = 0; for (inp) |ent| { var m = std.AutoHashMap(u8, usize).init(alloc); defer m.deinit(); var people: usize = 0; var pit = std.mem.split(u8, ent, "\n"); while (pit.next()) |ans| { people += 1; for (ans) |ch| { aoc.minc(&m, ch); } } var gc: usize = 0; var mit = m.iterator(); while (mit.next()) |ch| { if (ch.value_ptr.* == people) { gc += 1; } } c += gc; } return c; } fn day06(inp: []const u8, bench: bool) anyerror!void { var dec = aoc.readChunks(aoc.halloc, inp); defer aoc.halloc.free(dec); var p1 = part1(aoc.halloc, dec); var p2 = part2(aoc.halloc, dec); if (!bench) { try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 }); } } pub fn main() anyerror!void { try aoc.benchme(aoc.input(), day06); }
2020/06/aoc.zig
const std = @import("std"); const sql = @import("sqlite"); const Allocator = std.mem.Allocator; const log = std.log; const testing = std.testing; const print = std.debug.print; const expect = testing.expect; const shame = @import("shame.zig"); const Table = @import("queries.zig").Table; pub const Db = struct { const Self = @This(); sql_db: sql.Db, allocator: Allocator, // abs_path == null will create in memory database pub fn init(allocator: Allocator, abs_path: ?[:0]const u8) !Db { const mode: sql.Db.Mode = blk: { if (abs_path) |path| { std.debug.assert(std.fs.path.isAbsoluteZ(path)); break :blk .{ .File = path }; } break :blk .{ .Memory = .{} }; }; var sql_db = try sql.Db.init(.{ .mode = mode, .open_flags = .{ .write = true, .create = true }, // .threading_mode = .SingleThread, }); var db = Db{ .sql_db = sql_db, .allocator = allocator }; try setup(&db); return db; } pub fn exec(self: *Self, comptime query: []const u8, args: anytype) !void { self.sql_db.exec(query, .{}, args) catch |err| { log.err("SQL_ERROR: {s}\n Failed query:\n{s}", .{ self.sql_db.getDetailedError().message, query }); return err; }; } // Non-alloc select query that returns one or no rows pub fn one(self: *Self, comptime T: type, comptime query: []const u8, args: anytype) !?T { return self.sql_db.one(T, query, .{}, args) catch |err| { log.err("SQL_ERROR: {s}\n Failed query:\n{s}", .{ self.sql_db.getDetailedError().message, query }); return err; }; } pub fn oneAlloc(self: *Self, comptime T: type, comptime query: []const u8, opts: anytype) !?T { return self.sql_db.oneAlloc(T, self.allocator, query, .{}, opts) catch |err| { log.err("SQL_ERROR: {s}\n Failed query:\n{s}", .{ self.sql_db.getDetailedError().message, query }); return err; }; } pub fn selectAll( self: *Self, comptime T: type, comptime query: []const u8, opts: anytype, ) ![]T { var stmt = self.sql_db.prepare(query) catch |err| { log.err("SQL_ERROR: {s}\n Failed query:\n{s}", .{ self.sql_db.getDetailedError().message, query }); return err; }; defer stmt.deinit(); return stmt.all(T, self.allocator, .{}, opts) catch |err| { log.err("SQL_ERROR: {s}\n Failed query:\n{s}", .{ self.sql_db.getDetailedError().message, query }); return err; }; } }; pub fn setup(db: *Db) !void { const user_version = try db.sql_db.pragma(usize, .{}, "user_version", null); if (user_version == null or user_version.? == 0) { log.info("Creating new database", .{}); _ = try db.sql_db.pragma(usize, .{}, "user_version", "1"); _ = try db.sql_db.pragma(usize, .{}, "foreign_keys", "1"); _ = try db.sql_db.pragma(usize, .{}, "journal_mode", "WAL"); _ = try db.sql_db.pragma(usize, .{}, "synchronous", "normal"); _ = try db.sql_db.pragma(usize, .{}, "temp_store", "2"); _ = try db.sql_db.pragma(usize, .{}, "cache_size", "-32000"); inline for (comptime std.meta.declarations(Table)) |decl| { const table_field = @field(Table, decl.name); if (@hasDecl(table_field, "create")) { const sql_create = @field(table_field, "create"); db.sql_db.exec(sql_create, .{}, .{}) catch |err| { log.err("SQL_ERROR: {s}\n Failed query:\n{s}\n", .{ db.sql_db.getDetailedError().message, sql_create }); return err; }; } } } } pub fn verifyTables(db: *sql.Db) bool { const select_table = "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?;"; inline for (@typeInfo(Table).Struct.decls) |decl| { if (@hasField(decl.data.Type, "create")) { const row = db.one(usize, db, select_table, .{decl.name}); if (row == null) return false; break; } } return true; } test "create and veriftyTables" { const base_allocator = std.testing.allocator; var arena = std.heap.ArenaAllocator.init(base_allocator); defer arena.deinit(); const allocator = arena.allocator(); var db = try Db.init(allocator, null); try expect(verifyTables(&db.sql_db)); }
src/db.zig
const std = @import("std"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; pub const tolerance = 1.0e-8; pub const Variable = struct { name: []const u8 = "", value: f32 = 0.0, context: ?usize = null, // ----------------------------------------------------------------------- // Multiply, divide, and invert create terms // ----------------------------------------------------------------------- pub inline fn mul(self: *Variable, coefficient: f32) Term { return Term{.variable=self, .coefficient=coefficient}; } pub inline fn div(self: *Variable, denominator: f32) Term { return self.mul(1.0/denominator); } // Unary invert pub inline fn invert(self: *Variable) Term { return self.mul(-1.0); } // ----------------------------------------------------------------------- // Add and subtract create expressions // ----------------------------------------------------------------------- pub inline fn add(self: *Variable, allocator: *Allocator, other: var) !Expression { var term = Term{.variable=self}; return term.add(allocator, other); } pub inline fn sub(self: *Variable, allocator: *Allocator, other: var) !Expression { var term = Term{.variable=self}; return term.sub(allocator, other); } // ----------------------------------------------------------------------- // Constraint API // ----------------------------------------------------------------------- // pub fn buildConstraint(self: Variable, allocator: *Allocator, // op: Constraint.Op, value: var, // strength: f32) !Constraint { // return Constraint{ // .expression=try Expression.init(allocator, &[_]Term{ // Term.init(self), Term.init(value)}), // .op = op, // .strength = strength, // }; // } // // pub fn eql(self: Variable, allocator: *Allocator, // value: var, strength: f32) !Constraint { // return self.buildConstraint(allocator, .eq, value, strength); // } // // pub fn lte(self: Variable, allocator: *Allocator, // value: var, strength: f32) !Constraint { // return self.buildConstraint(allocator, .lte, value, strength); // } // // pub fn gte(self: Variable, allocator: *Allocator, // value: var, strength: f32) !Constraint { // return self.buildConstraint(allocator, .gte, value, strength); // } }; pub const Term = struct { coefficient: f32 = 1.0, variable: *Variable, pub inline fn value(self: *const Term) f32 { return self.coefficient * self.variable.value; } // ----------------------------------------------------------------------- // Multiply, divide, and invert create terms // ----------------------------------------------------------------------- pub inline fn mul(self: *Term, coefficient: f32) Term { return Term{ .variable=self.variable, .coefficient=self.coefficient * coefficient }; } pub inline fn div(self: *Term, denominator: f32) Term { return self.mul(1.0/denominator); } // Unary invert pub inline fn invert(self: *Term) Term { return self.mul(-1.0); } // ----------------------------------------------------------------------- // Add and subtract create expressions // ----------------------------------------------------------------------- pub inline fn add(self: *Term, allocator: *Allocator, other: var) !Expression { // No need to allocate here since expr.add makes a copy var terms = Expression.Terms.fromOwnedSlice(allocator, &[_]Term{self.*}); var expr = Expression{.terms=terms}; return expr.add(allocator, other); } pub inline fn sub(self: *Term, allocator: *Allocator, other: var) !Expression { // No need to allocate here since expr.sub makes a copy var terms = Expression.Terms.fromOwnedSlice(allocator, &[_]Term{self.*}); var expr = Expression{.terms=terms}; return expr.sub(allocator, other); } // ----------------------------------------------------------------------- // Constraint API // ----------------------------------------------------------------------- // pub fn buildConstraint(self: Term, allocator: *Allocator, op: Constraint.Op, // value: var, strength: f32) !Constraint { // return Constraint{ // .expression=try Expression.init(allocator, // &[_]Term{self, Term.init(value)}), // .op = op, // .strength = strength, // }; // } // // pub inline fn eql(self: Term, allocator: *Allocator, // value: var, strength: f32) !Constraint { // return self.buildConstraint(allocator, .eq, value, strength); // } // // pub inline fn lte(self: Term, allocator: *Allocator, // value: var, strength: f32) !Constraint { // return self.buildConstraint(allocator, .lte, value, strength); // } // // pub inline fn gte(self: Term, allocator: *Allocator, // value: var, strength: f32) !Constraint { // return self.buildConstraint(allocator, .gte, value, strength); // } }; pub const Expression = struct { pub const Vars = std.AutoHashMap(*Variable, f32); pub const Terms = std.ArrayList(Term); terms: Terms, constant: f32 = 0.0, // Create a reduced expression from a slice of terms pub fn init(allocator: *Allocator, args: []Term) !Expression { return initConstant(allocator, args, 0.0); } // Create a reduced expression from a slice of terms with a constant pub fn initConstant(allocator: *Allocator, args: []Term, constant: f32) !Expression { var vars = Vars.init(allocator); defer vars.deinit(); for (args) |term| { var entry = try vars.getOrPutValue(term.variable, 0.0); entry.value += term.coefficient; } var terms = try Terms.initCapacity(allocator, vars.size); var it = vars.iterator(); while (it.next()) |entry| { terms.appendAssumeCapacity(Term{ .variable=entry.key, .coefficient=entry.value }); } return Expression{ .terms = terms, .constant = constant, }; } // Create a reduced expression by from the terms of an existing expression // For example 3x + 2x + y will be reduced to two terms 5x + y pub fn reduce(expr: *Expression, allocator: *Allocator) !Expression { var vars = Vars.init(allocator); defer vars.deinit(); for (expr.terms.items) |term| { var entry = try vars.getOrPutValue(term.variable, 0.0); entry.value += term.coefficient; } var terms = try Terms.initCapacity(allocator, vars.size); var it = vars.iterator(); while (it.next()) |entry| { terms.appendAssumeCapacity(Term{ .variable=entry.key, .coefficient=entry.value }); } return Expression{ .terms = terms, .constant = expr.constant, }; } pub inline fn deinit(self: *Expression) void { self.terms.deinit(); } // Evaluate the expression using the variable's values pub fn value(self: *const Expression) f32 { var result = self.constant; for (self.terms.items) |term| { result += term.value(); } return result; } // ----------------------------------------------------------------------- // Multiply, divide, and invert // ----------------------------------------------------------------------- pub fn mul(self: *Expression, allocator: *Allocator, coefficient: f32) !Expression { var terms = try Terms.initCapacity(allocator, self.terms.items.len); for (self.terms.items) |*term| { terms.appendAssumeCapacity(term.mul(coefficient)); } return Expression{ .terms=terms, .constant=self.constant * coefficient, }; } pub inline fn div(self: *Expression, allocator: *Allocator, denominator: f32) !Expression { return self.mul(allocator, 1.0/denominator); } // Unary invert pub inline fn invert(self: *Expression, allocator: *Allocator) !Expression { return self.mul(allocator, -1.0); } // ----------------------------------------------------------------------- // Add and subtract // ----------------------------------------------------------------------- pub fn addAndMul(self: *Expression, allocator: *Allocator, other: var, coefficient: f32) !Expression { comptime const T = @TypeOf(other); const size = self.terms.items.len + switch(T) { Expression => other.terms.items.len, *Term, *Variable => 1, Term, Variable => @compileError("Pass the Term/Variable as a reference"), else => 0, }; // TODO: Optimize this by avoiding creating two sets of terms var terms = try Terms.initCapacity(allocator, size); defer terms.deinit(); for (self.terms.items) |term| { terms.appendAssumeCapacity(term); } var constant: f32 = self.constant; switch (T) { Expression => { for (other.terms.items) |*term| { terms.appendAssumeCapacity(term.mul(coefficient)); } constant += other.constant * coefficient; }, *Term, *Variable => { terms.appendAssumeCapacity(other.mul(coefficient)); }, else => { constant += @as(f32, other) * coefficient; } } return Expression.initConstant(allocator, terms.items, constant); } pub fn add(self: *Expression, allocator: *Allocator, other: var) !Expression { return self.addAndMul(allocator, other, 1); } pub fn sub(self: *Expression, allocator: *Allocator, other: var) !Expression { return self.addAndMul(allocator, other, -1); } }; pub const Strength = struct { pub inline fn create(a: f32, b: f32, c: f32) f32 { return createWeighted(a, b, c, 1.0); } pub inline fn createWeighted(a: f32, b: f32, c: f32, w: f32) f32 { comptime const low = @as(f32, 0.0); comptime const high = @as(f32, 1000.0); var r: f32 = 0.0; r += std.math.clamp(a * w, low, high) * 1000000.0; r += std.math.clamp(b * w, low, high) * 1000.0; r += std.math.clamp(c * w, low, high); return r; } pub const required = create(1000.0, 1000.0, 1000.0); pub const strong = create(1.0, 0.0, 0.0); pub const medium = create(0.0, 1.0, 0.0); pub const weak = create(0.0, 0.0, 1.0); pub inline fn clamp(value: f32) f32 { return std.math.clamp(value, 0.0, required); } }; pub inline fn isNearZero(value: f32) bool { return std.math.approxEq(f32, value, 0.0, tolerance); } pub const Constraint = struct { pub const Op = enum { eq, gte, lte, pub fn str(op: Op) []const u8 { return switch (op) { .eq => "==", .gte => ">=", .lte => "<=", }; } }; op: Op, strength: f32 = 0.0, expression: Expression, pub inline fn deinit(self: *Constraint) void { self.expression.deinit(); } pub fn dumps(self: *Constraint) void { const expr = &self.expression; const last = expr.terms.items.len - 1; for (expr.terms.items) |term, i| { if (isNearZero(term.coefficient - 1.0)) { std.debug.warn("{}", .{term.variable.name}); } else { std.debug.warn("{d} * {}", .{term.coefficient, term.variable.name}); } if (i != last) { std.debug.warn(" + ", .{}); } } if (!isNearZero(expr.constant)) { std.debug.warn(" + {d}", .{expr.constant}); } std.debug.warn(" {} 0 | strength = {d}", .{self.op.str(), self.strength}); std.debug.warn("\n", .{}); } }; const Symbol = struct { pub const Type = enum { Invalid, External, Slack, Error, Dummy, pub fn str(self: Type) []const u8 { return switch(self) { .Invalid => "i", .External => "v", .Slack => "s", .Error => "e", .Dummy => "d", }; } }; id: u32 = 0, tp: Type = .Invalid, pub inline fn hash(self: Symbol) u32 { return self.id; } pub inline fn lte(self: Symbol, other: Symbol) bool { return self.id < other.id; } pub inline fn eql(self: Symbol, other: Symbol) bool { return self.id == other.id; } pub const Invalid = Symbol{.id=0, .tp=.Invalid}; pub fn dumps(self: Symbol) void { std.debug.warn("{}{}", .{self.tp.str(), self.id}); } }; const Row = struct { pub const CellMap = std.HashMap(Symbol, f32, Symbol.hash, Symbol.eql); cells: CellMap, constant: f32 = 0.0, pub fn init(allocator: *Allocator) Row { return Row{ .cells = CellMap.init(allocator), }; } pub fn deinit(self: *Row) void { self.cells.deinit(); } // Create a clone of the row using the original allocator pub fn clone(self: Row) !Row { return Row{ .cells = try self.cells.clone(), .constant = self.constant, }; } // Add a constant value to the row constant. // The new value of the constant is returned. pub inline fn add(self: *Row, value: f32) f32 { self.constant += value; return self.constant; } // Insert a symbol into the row with a given coefficient. // // If the symbol already exists in the row, the coefficient will be // added to the existing coefficient. If the resulting coefficient // is zero, the symbol will be removed from the row. pub inline fn insertSymbol(self: *Row, symbol: Symbol, coefficient: f32) !void { const entry = try self.cells.getOrPutValue(symbol, 0.0); entry.value += coefficient; if (isNearZero(entry.value)) { self.removeSymbol(symbol); } } // Remove the given symbol from the row. pub inline fn removeSymbol(self: *Row, symbol: Symbol) void { _ = self.cells.remove(symbol); } // Insert a row into this row with a given coefficient. // // The constant and the cells of the other row will be multiplied by // the coefficient and added to this row. Any cell with a resulting // coefficient of zero will be removed from the row. pub fn insertRow(self: *Row, row: *const Row, coefficient: f32) !void { self.constant += row.constant * coefficient; var it = row.cells.iterator(); while (it.next()) |item| { try self.insertSymbol(item.key, item.value * coefficient); } } // Reverse the sign of the constant and all cells in the row. pub fn reverseSign(self: *Row) void { self.constant = -self.constant; var it = self.cells.iterator(); while (it.next()) |entry| { entry.value = -entry.value; } } // Solve the row for the given symbol. // This method assumes the row is of the form a * x + b * y + c = 0 // and (assuming solve for x) will modify the row to represent the // right hand side of x = -b/a * y - c / a. The target symbol will // be removed from the row, and the constant and other cells will // be multiplied by the negative inverse of the target coefficient. // // The given symbol *must* exist in the row. pub fn solveForSymbol(self: *Row, symbol: Symbol) !void { if (self.cells.get(symbol)) |cell| { self.removeSymbol(symbol); const coeff = -1.0 / cell.value; self.constant *= coeff; var it = self.cells.iterator(); while (it.next()) |entry| { entry.value *= coeff; } } else { return error.CannotSolveForUnknownSymbol; } } // Solve the row for the given symbols. // // This method assumes the row is of the form x = b * y + c and will // solve the row such that y = x / b - c / b. The rhs symbol will be // removed from the row, the lhs added, and the result divided by the // negative inverse of the rhs coefficient. // // The lhs symbol *must not* exist in the row, and the rhs symbol // *must* exist in the row. pub fn solveFor(self: *Row, lhs: Symbol, rhs: Symbol) !void { assert(!self.cells.contains(lhs)); try self.insertSymbol(lhs, -1.0); return self.solveForSymbol(rhs); } // Get the coefficient for the given symbol. // If the symbol does not exist in the row, zero will be returned. pub inline fn coefficientFor(self: Row, symbol: Symbol) f32 { return if (self.cells.getValue(symbol)) |c| c else 0.0; } // Substitute a symbol with the data from another row. // // Given a row of the form a * x + b and a substitution of the // form x = 3 * y + c the row will be updated to reflect the // expression 3 * a * y + a * c + b. // // If the symbol does not exist in the row, this is a no-op. pub fn substitute(self: *Row, symbol: Symbol, row: *const Row) !void { if (self.cells.get(symbol)) |cell| { self.removeSymbol(symbol); try self.insertRow(row, cell.value); } } // Test whether a row is composed of all dummy variables. pub fn isAllDummies(self: Row) bool { var it = self.cells.iterator(); while (it.next()) |entry| { if (entry.key.tp != .Dummy) return false; } return true; } pub fn dumps(self: Row) void { var it = self.cells.iterator(); std.debug.warn("{d}", .{self.constant}); while (it.next()) |entry| { if (isNearZero(entry.value - 1.0)) { std.debug.warn(" + ", .{}); } else { std.debug.warn(" + {d} * ", .{entry.value}); } entry.key.dumps(); } std.debug.warn("\n", .{}); } }; pub const Solver = struct { pub const Tag = struct { marker: Symbol = Symbol.Invalid, other: Symbol = Symbol.Invalid, }; pub const EditInfo = struct { tag: *Tag, constraint: *Constraint, constant: f32 = 0.0, }; pub const VarMap = std.AutoHashMap(*Variable, Symbol); pub const RowMap = std.HashMap(Symbol, Row, Symbol.hash, Symbol.eql); pub const SymbolList = std.ArrayList(Symbol); pub const ConstraintMap = std.AutoHashMap(*Constraint, Tag); pub const EditMap = std.AutoHashMap(*Variable, EditInfo); // Fields allocator: *Allocator, cns: ConstraintMap, rows: RowMap, vars: VarMap, edits: EditMap, infeasible_rows: SymbolList, objective: Row, artificial: ?*Row = null, _next_id: u32 = 1, pub fn init(allocator: *Allocator) Solver { return Solver{ .allocator = allocator, .cns = ConstraintMap.init(allocator), .rows = RowMap.init(allocator), .vars = VarMap.init(allocator), .edits = EditMap.init(allocator), .infeasible_rows = SymbolList.init(allocator), .objective = Row.init(allocator), }; } pub fn deinit(self: *Solver) void { self.clearRows(); } // ----------------------------------------------------------------------- // Builder API // ----------------------------------------------------------------------- pub fn buildConstraint(self: *Solver, lhs: var, op: Constraint.Op, rhs: var, strength: f32) !Constraint { var expr = switch (@TypeOf(lhs)) { *Expression, *Variable, *Term => try lhs.sub(self.allocator, rhs), Expression, Variable, Term => @compileError("Pass a reference"), else => @compileError("Invalid lhs expression"), }; return Constraint{ .expression = expr, .op = op, .strength = strength, }; } // ----------------------------------------------------------------------- // Solver API // ----------------------------------------------------------------------- // Add a constraint to the solver. // Throws // ------ // DuplicateConstraint // The given constraint has already been added to the solver. // // UnsatisfiableConstraint // The given constraint is required and cannot be satisfied. pub fn addConstraint(self: *Solver, constraint: *Constraint) !void { if (self.cns.contains(constraint)) { return error.DuplicateConstraint; } // Creating a row causes symbols to be reserved for the variables // in the constraint. If this method exits with an exception, // then its possible those variables will linger in the var map. // Since its likely that those variables will be used in other // constraints and since exceptional conditions are uncommon, // i'm not too worried about aggressive cleanup of the var map. var tag = Tag{}; var row = try self.createRow(constraint, &tag); var subject = self.chooseSubject(row, &tag); // If chooseSubject could not find a valid entering symbol, one // last option is available if the entire row is composed of // dummy variables. If the constant of the row is zero, then // this represents redundant constraints and the new dummy // marker can enter the basis. If the constant is non-zero, // then it represents an unsatisfiable constraint. if (subject.tp == .Invalid and row.isAllDummies()) { if (!isNearZero(row.constant)) { return error.UnsatisfiableConstraint; } subject = tag.marker; } // If an entering symbol still isn't found, then the row must // be added using an artificial variable. If that fails, then // the row represents an unsatisfiable constraint. if (subject.tp == .Invalid) { if (!try self.addWithArtificialVariable(row)) { return error.UnsatisfiableConstraint; } } else { try row.solveForSymbol(subject); try self.substitute(subject, &row); _ = try self.rows.put(subject, row); } _ = try self.cns.put(constraint, tag); // Optimizing after each constraint is added performs less // aggregate work due to a smaller average system size. It // also ensures the solver remains in a consistent state. try self.optimize(&self.objective); } // Remove a constraint from the solver. pub fn removeConstraint(self: *Solver, constraint: *Constraint) !void { if (self.cns.remove(constraint)) |e| { const tag = e.value; // Remove the error effects from the objective function // *before* pivoting, or substitutions into the objective // will lead to incorrect solver results. try self.removeConstraintEffects(constraint, tag); // If the marker is basic, simply drop the row. Otherwise, // pivot the marker into the basis and then drop the row. if (self.rows.remove(tag.marker)) |_| { // Already removed } else if (self.getMarkerLeavingRow(tag.marker)) |entry| { _ = self.rows.remove(entry.key); const row = &entry.value; try row.solveFor(entry.key, tag.marker); try self.substitute(tag.marker, row); } else { return error.InternalSolverError; // Unable to find leaving row } // Optimizing after each constraint is removed ensures that the // solver remains consistent. It makes the solver api easier to // use at a small tradeoff for speed. try self.optimize(&self.objective); } else { return error.UnknownConstraint; } } // Test whether a constraint has been added to the solver. pub fn hasConstraint(self: *Solver, constraint: *Constraint) bool { return self.cns.contains(constraint); } // Add an edit variable to the solver. // // This method should be called before the `suggestValue` method is // used to supply a suggested value for the given edit variable. // // Throws // ------ // - DuplicateVariable // The given edit variable has already been added to the solver. // // - BadRequiredStrength // The given strength is >= required. pub fn addVariable(self: *Solver, variable: *Variable, strength: f32) !void { if (self.edits.contains(variable)) { return error.DuplicateVariable; } const s = Strength.clamp(strength); if (s >= Strength.required) { return error.BadRequiredStrength; } const constraint = try self.allocator.create(Constraint); errdefer self.allocator.destroy(constraint); var terms = try Expression.Terms.initCapacity(self.allocator, 1); terms.appendAssumeCapacity(Term{.variable=variable}); errdefer terms.deinit(); constraint.* = Constraint{ .expression = Expression{.terms=terms}, .op = .eq, .strength = strength, }; try self.addConstraint(constraint); var info = EditInfo{ .tag = &self.cns.get(constraint).?.value, .constraint = constraint, }; _ = try self.edits.put(variable, info); } // Remove an edit variable from the solver. // Throws // ------ // - UnknownVariable // The given edit variable has not been added to the solver. pub fn removeVariable(self: *Solver, variable: *Variable) !void { if (self.edits.remove(variable)) |entry| { const constraint = entry.value.constraint; try self.removeConstraint(constraint); constraint.deinit(); self.allocator.destroy(constraint); } else { return error.UnknownVariable; } } // Test whether an edit variable has been added to the solver. pub fn hasVariable(self: *Solver, variable: *Variable) bool { return self.edits.contains(variable); } // Suggest a value for the given edit variable. // // This method should be used after an edit variable as been added to // the solver in order to suggest the value for that variable. After // all suggestions have been made, the `solve` method can be used to // update the values of all variables. // // Throws // ------ // UnknownVariable // The given edit variable has not been added to the solver. // pub fn suggestValue(self: *Solver, variable: *Variable, value: f32) !void { if (self.edits.getValue(variable)) |*info| { const delta = value - info.constant; info.constant = value; // TODO: Ensure that dualOptimize is always called try self.updateSuggestion(info, delta); try self.dualOptimize(); } else { return error.UnknownVariable; } } // Helper function for suggested value fn updateSuggestion(self: *Solver, info: *const EditInfo, delta: f32) !void { // Check first if the positive error variable is basic. if (self.rows.get(info.tag.marker)) |entry| { if (entry.value.add(-delta) < 0.0) { try self.infeasible_rows.append(entry.key); } return; } // Check next if the negative error variable is basic. if (self.rows.get(info.tag.other)) |entry| { if (entry.value.add(delta) < 0.0) { try self.infeasible_rows.append(entry.key); } return; } // Otherwise update each row where the error variables exist. var it = self.rows.iterator(); while (it.next()) |entry| { const coeff = entry.value.coefficientFor(info.tag.marker); if (coeff != 0.0 and entry.value.add(delta * coeff) < 0.0 and entry.key.tp != .External) { try self.infeasible_rows.append(entry.key); } } } // Update the values of the external solver variables. pub fn updateVariables(self: *Solver) void { var it = self.vars.iterator(); while (it.next()) |entry| { const v = entry.key; const sym = entry.value; v.value = if (self.rows.getValue(sym)) |row| row.constant else 0.0; } } // Reset the solver to the empty starting condition. // This method resets the internal solver state to the empty starting // condition, as if no constraints or edit variables have been added. // This can be faster than deleting the solver and creating a new one // when the entire system must change, since it can avoid unecessary // heap (de)allocations. pub fn reset(self: *Solver) void { self.clearRows(); self.cns.clear(); self.vars.clear(); self.edits.clear(); self.infeasible_rows.deinit(); self.objective.deinit(); self.objective = Row.init(self.allocator); self.artificial = null; self._next_id = 1; } // ----------------------------------------------------------------------- // Internal API // ----------------------------------------------------------------------- fn clearRows(self: *Solver) void { var it = self.rows.iterator(); while (it.next()) |entry| { entry.value.deinit(); } self.rows.clear(); } // Get the symbol for the given variable. // If a symbol does not exist for the variable, one will be created. fn getVarSymbol(self: *Solver, variable: *Variable) !Symbol { if (self.vars.getValue(variable)) |symbol| { return symbol; } const symbol = self.createSymbol(.External); _ = try self.vars.put(variable, symbol); return symbol; } // Create a new symbol using a generated id inline fn createSymbol(self: *Solver, tp: Symbol.Type) Symbol { const id = self._next_id; self._next_id += 1; return Symbol{.id = id, .tp = tp}; } // Create a new Row object for the given constraint. // // The terms in the constraint will be converted to cells in the row. // Any term in the constraint with a coefficient of zero is ignored. // This method uses the `getVarSymbol` method to get the symbol for // the variables added to the row. If the symbol for a given cell // variable is basic, the cell variable will be substituted with the // basic row. // // The necessary slack and error variables will be added to the row. // If the constant for the row is negative, the sign for the row // will be inverted so the constant becomes positive. // // The tag will be updated with the marker and error symbols to use // for tracking the movement of the constraint in the tableau. fn createRow(self: *Solver, constraint: *Constraint, tag: *Tag) !Row { const expr = &constraint.expression; const objective = &self.objective; var row = Row.init(self.allocator); row.constant = expr.constant; // Substitute the current basic variables into the row. for (expr.terms.items) |term| { if (isNearZero(term.coefficient)) continue; const symbol = try self.getVarSymbol(term.variable); if (self.rows.getValue(symbol)) |*r| { try row.insertRow(r, term.coefficient); } else { try row.insertSymbol(symbol, term.coefficient); } } // Add the necessary slack, error, and dummy variables. switch (constraint.op) { .lte, .gte => { const coeff: f32 = if (constraint.op == .lte) 1.0 else -1.0; const slack = self.createSymbol(.Slack); tag.marker = slack; try row.insertSymbol(slack, coeff); if (constraint.strength < Strength.required) { const err = self.createSymbol(.Error); tag.other = err; try row.insertSymbol(err, -coeff); try objective.insertSymbol(err, constraint.strength); } }, .eq => { if (constraint.strength < Strength.required) { const errplus = self.createSymbol(.Error); const errminus = self.createSymbol(.Error); tag.marker = errplus; tag.other = errminus; try row.insertSymbol(errplus, -1.0); // v = eplus - eminus try row.insertSymbol(errminus, 1.0); // v - eplus + eminus = 0 try objective.insertSymbol(errplus, constraint.strength); try objective.insertSymbol(errminus, constraint.strength); } else { const dummy = self.createSymbol(.Dummy); tag.marker = dummy; try row.insertSymbol(dummy, 1.0); } } } // Ensure the row as a positive constant. if (row.constant < 0.0) { row.reverseSign(); } return row; } // Choose the subject for solving for the row. // // This method will choose the best subject for using as the solve // target for the row. An invalid symbol will be returned if there // is no valid target. // // The symbols are chosen according to the following precedence: // // 1) The first symbol representing an external variable. // 2) A negative slack or error tag variable. // // If a subject cannot be found, no symbol is returned. fn chooseSubject(self: *Solver, row: Row, tag: *const Tag) Symbol { var it = row.cells.iterator(); while (it.next()) |entry| { if (entry.key.tp == .External) { return entry.key; } } if ((tag.marker.tp == .Slack or tag.marker.tp == .Error) and row.coefficientFor(tag.marker) < 0.0) { return tag.marker; } if ((tag.other.tp == .Slack or tag.other.tp == .Error) and row.coefficientFor(tag.other) < 0.0) { return tag.other; } return Symbol{}; } // Add the row to the tableau using an artificial variable. // This will return false if the constraint cannot be satisfied. fn addWithArtificialVariable(self: *Solver, row: Row) !bool { // Create and add the artificial variable to the tableau const art = self.createSymbol(.Slack); var artificial = try row.clone(); _ = try self.rows.put(art, artificial); self.artificial = &artificial; // Optimize the artificial objective. This is successful // only if the artificial objective is optimized to zero. try self.optimize(&artificial); const success = isNearZero(artificial.constant); self.artificial = null; // If the artificial variable is not basic, pivot the row so that // it becomes basic. If the row is constant, exit early. if (self.rows.get(art)) |entry| { const r = &entry.value; _ = self.rows.remove(art); if (r.cells.size == 0) return success; if (self.getAnyPivotableSymbol(r)) |entering| { try r.solveFor(art, entering); try self.substitute(entering, r); _ = try self.rows.put(entering, entry.value); } else { return false; // unsatisfiable (will this ever happen?) } } // Remove the artificial variable from the tableau. var it = self.rows.iterator(); while (it.next()) |entry| { entry.value.removeSymbol(art); } self.objective.removeSymbol(art); return success; } // Substitute the parametric symbol with the given row. // // This method will substitute all instances of the parametric symbol // in the tableau and the objective function with the given row. fn substitute(self: *Solver, symbol: Symbol, row: *const Row) !void { var it = self.rows.iterator(); while (it.next()) |entry| { try entry.value.substitute(symbol, row); if (entry.key.tp != .External and entry.value.constant < 0.0) { try self.infeasible_rows.append(entry.key); } } try self.objective.substitute(symbol, row); if (self.artificial) |r| { try r.substitute(symbol, row); } } // Optimize the system for the given objective function. // // This method performs iterations of Phase 2 of the simplex method // until the objective function reaches a minimum. // // Throws // ------ // InternalSolverError // The value of the objective function is unbounded. fn optimize(self: *Solver, objective: *Row) !void { while (self.getEnteringSymbol(objective)) |entering| { if (self.getLeavingRow(entering)) |entry| { // pivot the entering symbol into the basis const leaving = entry.key; const row = &entry.value; assert(self.rows.remove(leaving) != null); try row.solveFor(leaving, entering); try self.substitute(entering, row); _ = try self.rows.put(entering, entry.value); } else { return error.InternalSolverError; // The objective is unbounded } } } // Optimize the system using the dual of the simplex method. // // The current state of the system should be such that the objective // function is optimal, but not feasible. This method will perform // an iteration of the dual simplex method to make the solution both // optimal and feasible. // // Throws // ------ // InternalSolverError // The system cannot be dual optimized. fn dualOptimize(self: *Solver) !void { while (self.infeasible_rows.popOrNull()) |leaving| { if (self.rows.get(leaving)) |entry| { const row = &entry.value; if (!isNearZero(row.constant) and row.constant < 0.0) { if (self.getDualEnteringSymbol(row)) |entering| { _ = self.rows.remove(leaving); try row.solveFor(leaving, entering); try self.substitute(entering, row); _ = try self.rows.put(entering, entry.value); } else { return error.InternalSolverError; // Dual optimize fail } } } } } // Compute the entering variable for a pivot operation. // // This method will return first symbol in the objective function which // is non-dummy and has a coefficient less than zero. If no symbol meets // the criteria, it means the objective function is at a minimum and no // symbol is returned. fn getEnteringSymbol(self: Solver, row: *const Row) ?Symbol { var it = row.cells.iterator(); while (it.next()) |entry| { if (entry.key.tp != .Dummy and entry.value < 0.0) { return entry.key; } } return null; } // Compute the entering symbol for the dual optimize operation. // // This method will return the symbol in the row which has a positive // coefficient and yields the minimum ratio for its respective symbol // in the objective function. The provided row *must* be infeasible. // If no symbol is found which meats the criteria, no symbol is returned. fn getDualEnteringSymbol(self: Solver, row: *const Row) ?Symbol { var ratio: f32 = std.math.f32_max; var symbol: ?Symbol = null; var it = row.cells.iterator(); while (it.next()) |entry| { if (entry.value > 0.0 and entry.key.tp != .Dummy) { const coeff = self.objective.coefficientFor(entry.key); const r = coeff/entry.value; if (r < ratio) { ratio = r; symbol = entry.key; } } } return symbol; } // Get the first Slack or Error symbol in the row. // If no such symbol is present, no nsymbol is returned. fn getAnyPivotableSymbol(self: Solver, row: *const Row) ?Symbol { var it = row.cells.iterator(); while (it.next()) |entry| { if (entry.key.tp == .Slack or entry.key.tp == .Error) { return entry.key; } } return null; } // Compute the row which holds the exit symbol for a pivot. // // This method will return an iterator to the row in the row map // which holds the exit symbol. If no appropriate exit symbol is // found, null is returned. This indicates that // the objective function is unbounded. fn getLeavingRow(self: Solver, entering: Symbol) ?*RowMap.KV { var ratio: f32 = std.math.f32_max; var result: ?*RowMap.KV = null; var it = self.rows.iterator(); while (it.next()) |entry| { if (entry.key.tp != .External) { const row = entry.value; const coeff = row.coefficientFor(entering); if (coeff < 0.0) { const r = -row.constant / coeff; if (r < ratio) { ratio = r; result = entry; } } } } return result; } // Compute the leaving row for a marker variable. // // This method will return an iterator to the row in the row map // which holds the given marker variable. The row will be chosen // according to the following precedence: // // 1) The row with a restricted basic varible and a negative coefficient // for the marker with the smallest ratio of -constant / coefficient. // // 2) The row with a restricted basic variable and the smallest ratio // of constant / coefficient. // // 3) The last unrestricted row which contains the marker. // // If the marker does not exist in any row, null will be returned. // This indicates an internal solver error since // the marker *should* exist somewhere in the tableau. fn getMarkerLeavingRow(self: Solver, marker: Symbol) ?*RowMap.KV { var r1: f32 = std.math.f32_max; var r2: f32 = std.math.f32_max; var first: ?*RowMap.KV = null; var second: ?*RowMap.KV = null; var third: ?*RowMap.KV = null; var it = self.rows.iterator(); while (it.next()) |entry| { const row = entry.value; const c = row.coefficientFor(marker); if (c == 0) continue; if (entry.key.tp == .External) { third = entry; } else if (c < 0.0) { const r = -row.constant / c; if (r < r1) { r1 = r; first = entry; } } else { const r = row.constant / c; if (r < r2) { r2 = r; second = entry; } } } if (first) |result| return result; if (second) |result| return result; return third; } // Remove the effects of a constraint on the objective function. fn removeConstraintEffects(self: *Solver, cn: *const Constraint, tag: Tag) !void { if (tag.marker.tp == .Error) { try self.removeMarkerEffects(tag.marker, cn.strength); } if (tag.other.tp == .Error) { try self.removeMarkerEffects(tag.other, cn.strength); } } // Remove the effects of an error marker on the objective function. fn removeMarkerEffects(self: *Solver, marker: Symbol, strength: f32) !void { if (self.rows.getValue(marker)) |*row| { try self.objective.insertRow(row, -strength); } else { try self.objective.insertSymbol(marker, -strength); } } pub fn dumps(self: Solver) void { std.debug.warn("\nObjective\n---------\n", .{}); self.objective.dumps(); std.debug.warn("\nTableau\n--------\n", .{}); var rows = self.rows.iterator(); while (rows.next()) |entry| { entry.key.dumps(); std.debug.warn(" | ", .{}); entry.value.dumps(); } std.debug.warn("\nInfeasible\n----------\n", .{}); for (self.infeasible_rows.items) |sym| { sym.dumps(); std.debug.warn("\n", .{}); } std.debug.warn("\nVariables\n---------\n", .{}); var vars = self.vars.iterator(); while (vars.next()) |entry| { std.debug.warn("{} = ", .{entry.key.name}); entry.value.dumps(); std.debug.warn("\n", .{}); } std.debug.warn("\nEdit Variables\n--------------\n", .{}); var edits = self.edits.iterator(); while (edits.next()) |entry| { std.debug.warn("{} = {}\n", .{entry.key, entry.value}); } std.debug.warn("\nConstraints\n-----------\n", .{}); var cns = self.cns.iterator(); while (cns.next()) |entry| { entry.key.dumps(); } std.debug.warn("\n", .{}); } }; test "strength" { const testing = std.testing; const mmedium = Strength.createWeighted(0, 1, 0, 1.25); testing.expectEqual(mmedium, 1250.0); const smedium = Strength.create(0, 100, 0); testing.expectEqual(smedium, 100000.0); } test "variables" { const testing = std.testing; const allocator = std.heap.page_allocator; var v1 = Variable{.name="v1", .value=1.0}; var v2 = Variable{.name="v2", .value=2.0}; var t = v1.invert(); testing.expectEqual(t.coefficient, -1); t = v1.mul(3); testing.expectEqual(t.coefficient, 3); t = v1.div(2); testing.expectEqual(t.coefficient, 0.5); testing.expectEqual(t.variable, &v1); // Adding variables returns an expression var expr = try v1.add(allocator, &v2); testing.expectEqual(expr.terms.items.len, 2); testing.expectEqual(expr.value(), 3.0); expr.deinit(); expr = try v1.sub(allocator, &v2); testing.expectEqual(expr.terms.items.len, 2); testing.expectEqual(expr.value(), -1.0); expr.deinit(); } test "terms" { const testing = std.testing; const allocator = std.heap.page_allocator; var x = Variable{.name="x", .value=2.0}; var t1 = Term{.variable=&x}; var t2 = t1.mul(3); testing.expectEqual(t2.coefficient, 3.0); testing.expectEqual(t2.variable, t1.variable); testing.expectEqual(t2.value(), 6.0); t2 = t1.div(2); testing.expectEqual(t2.coefficient, 0.5); testing.expectEqual(t2.value(), 1.0); t2 = t1.invert(); testing.expectEqual(t2.coefficient, -1); testing.expectEqual(t2.value(), -2.0); // Adding variables returns an expression var expr = try t1.add(allocator, 3); testing.expectEqual(expr.terms.items.len, 1); testing.expectEqual(expr.value(), 5.0); expr.deinit(); expr = try t1.add(allocator, &t2); testing.expectEqual(expr.value(), 0.0); expr.deinit(); } test "expressions" { const allocator = std.heap.page_allocator; const testing = std.testing; var x = Variable{.name="x", .value=1.0}; var y = Variable{.name="y", .value=3.0}; var z = Variable{.name="z", .value=2.0}; var expr = try Expression.init(allocator, &[_]Term{ Term{.variable=&x}, Term{.variable=&y}, }); testing.expectEqual(expr.terms.items.len, 2); testing.expectEqual(expr.value(), 4.0); expr.deinit(); expr = try Expression.init(allocator, &[_]Term{ x.mul(2), x.mul(4), }); defer expr.deinit(); testing.expectEqual(expr.terms.items.len, 1); testing.expectEqual(expr.value(), 6.0); // 6x * 3 var expr2 = try expr.mul(allocator, 3); testing.expectEqual(expr2.value(), 18.0); expr2.deinit(); // 6x / 2 expr2 = try expr.div(allocator, 2); testing.expectEqual(expr2.value(), 3.0); expr2.deinit(); // -6x expr2 = try expr.invert(allocator); testing.expectEqual(expr2.value(), -6.0); expr2.deinit(); // 6x - 6 expr2 = try expr.add(allocator, -6); testing.expectEqual(expr2.value(), 0.0); expr2.deinit(); // 6x + y expr2 = try expr.add(allocator, &y); testing.expectEqual(expr2.value(), 9.0); expr2.deinit(); // 6x + 3y expr2 = try expr.add(allocator, &y.mul(3)); testing.expectEqual(expr2.value(), 15.0); expr2.deinit(); // 6x - y expr2 = try expr.sub(allocator, &y); testing.expectEqual(expr2.value(), 3.0); //expr2.deinit(); // 6x + 6x - y var expr3 = try expr.add(allocator, expr2); testing.expectEqual(expr3.terms.items.len, 2); testing.expectEqual(expr3.value(), 9.0); //expr3.deinit(); var expr4 = try expr3.add(allocator, &z); testing.expectEqual(expr4.terms.items.len, 3); testing.expectEqual(expr4.value(), 11.0); } test "constraints" { // TODO: } test "row" { const testing = std.testing; const allocator = std.heap.page_allocator; var row = Row.init(allocator); testing.expectEqual(row.add(2.0), 2.0); row.reverseSign(); testing.expectEqual(row.constant, -2.0); testing.expectEqual(row.add(2.0), 0.0); var e1 = Symbol{.id=1, .tp=.Error}; var e2 = Symbol{.id=2, .tp=.Error}; var e3 = Symbol{.id=3, .tp=.Error}; // Add symbols try row.insertSymbol(e1, 2.0); try row.insertSymbol(e2, 1.0); testing.expectEqual(row.coefficientFor(e1), 2.0); testing.expectEqual(row.coefficientFor(e2), 1.0); // Re-add with reversed coeff, it should cancel try row.insertSymbol(e1, -2.0); testing.expectEqual(row.cells.get(e1), null); try row.insertSymbol(e1, 2.0); testing.expectEqual(row.coefficientFor(e1), 2.0); testing.expectEqual(row.coefficientFor(e2), 1.0); testing.expectError(error.CannotSolveForUnknownSymbol, row.solveForSymbol(e3)); // 2 + 2e1 + 1e2 = e3 --> e1 = e3 / 2 - e2 / 2 - 1 _ = row.add(2); try row.solveFor(e3, e1); testing.expectEqual(row.cells.get(e1), null); // Removes e1 testing.expectEqual(row.coefficientFor(e1), 0.0); testing.expectEqual(row.coefficientFor(e2), -0.5); testing.expectEqual(row.coefficientFor(e3), 0.5); testing.expectEqual(row.constant, -1.0); row.reverseSign(); testing.expectEqual(row.coefficientFor(e2), 0.5); testing.expectEqual(row.coefficientFor(e3), -0.5); testing.expectEqual(row.constant, 1.0); } test "solver-variable-managment" { const testing = std.testing; const allocator = std.heap.page_allocator; var solver = Solver.init(allocator); defer solver.deinit(); var v1 = Variable{.name="v1"}; var v2 = Variable{.name="v2"}; testing.expect(!solver.hasVariable(&v1)); try solver.addVariable(&v1, Strength.medium); testing.expectEqual(solver.cns.size, 1); testing.expectEqual(solver.edits.size, 1); testing.expectEqual(solver.rows.size, 1); testing.expect(solver.edits.contains(&v1)); testing.expect(solver.hasVariable(&v1)); // Already theres testing.expectError(error.DuplicateVariable, solver.addVariable(&v1, Strength.medium)); // Editable variables cannot have strength == required testing.expectError(error.BadRequiredStrength, solver.addVariable(&v2, Strength.required)); testing.expectEqual(solver.cns.size, 1); // Should still be 1 // Not yet added testing.expect(!solver.hasVariable(&v2)); // Cant suggest a value that wasn't added testing.expectError(error.UnknownVariable, solver.suggestValue(&v2, 5.0)); testing.expectError(error.UnknownVariable, solver.removeVariable(&v2)); try solver.addVariable(&v2, Strength.medium); testing.expect(solver.hasVariable(&v2)); testing.expectEqual(solver.cns.size, 2); try solver.removeVariable(&v1); testing.expect(!solver.hasVariable(&v1)); solver.reset(); testing.expect(!solver.hasVariable(&v2)); } test "suggestions-medium-suggestion-overrides-weak-constraint" { const testing = std.testing; const allocator = std.heap.page_allocator; var solver = Solver.init(allocator); defer solver.deinit(); var v1 = Variable{.name="v1"}; // This builds a constraint try solver.addVariable(&v1, Strength.medium); var c = try solver.buildConstraint(&v1, .eq, 1, Strength.weak); defer c.deinit(); try solver.addConstraint(&c); testing.expectEqual(solver.cns.size, 2); testing.expect(solver.hasConstraint(&c)); testing.expectError(error.DuplicateConstraint, solver.addConstraint(&c)); try solver.suggestValue(&v1, 2); //testing.expectEqual(@as(f32, 2.0), solver.edits.getValue(&v1).?.constant); solver.updateVariables(); //solver.dumps(); // Since v1 is medium it overwrites the weak constraint v1 == 1 testing.expectEqual(@as(f32, 2.0), v1.value); } test "suggestions-weak-suggestion-is-overriden-by-medium-constraint" { //if (!@hasDecl(std, "crap")) return error.SkipZigTest; const testing = std.testing; const allocator = std.heap.page_allocator; var solver = Solver.init(allocator); var v1 = Variable{.name="v1"}; try solver.addVariable(&v1, Strength.weak); var c = try solver.buildConstraint(&v1, .eq, 4, Strength.medium); defer c.deinit(); try solver.addConstraint(&c); try solver.suggestValue(&v1, 2); solver.updateVariables(); //solver.dumps(); // Since v1 is weak is is now overridden by the medium constraint v1 == 1 testing.expectEqual(@as(f32, 4.0), v1.value); } test "suggestions-readme-example" { //if (!@hasDecl(std, "crap")) return error.SkipZigTest; const testing = std.testing; const allocator = std.heap.page_allocator; var solver = Solver.init(allocator); defer solver.deinit(); var width = Variable{.name="width"}; var height = Variable{.name="height"}; try solver.addVariable(&width, Strength.medium); try solver.addVariable(&height, Strength.medium); // 16 * width = 9 * height var aspect = try solver.buildConstraint( &width.mul(3), .eq, &height.mul(4), Strength.strong); defer aspect.deinit(); try solver.addConstraint(&aspect); var min_width = try solver.buildConstraint( &width, .gte, 320, Strength.strong); defer min_width.deinit(); try solver.addConstraint(&min_width); try solver.suggestValue(&height, 1); solver.dumps(); solver.updateVariables(); // Updates the interal value of every variable testing.expectEqual(width.value, 320); testing.expectEqual(height.value, 240); } test "suggestions-3" { //if (!@hasDecl(std, "crap")) return error.SkipZigTest; const testing = std.testing; const allocator = std.heap.page_allocator; var solver = Solver.init(allocator); var v1 = Variable{.name="v1"}; var v2 = Variable{.name="v2"}; try solver.addVariable(&v1, Strength.medium); try solver.addVariable(&v2, Strength.medium); var c = try solver.buildConstraint(&v1, .gte, 1, Strength.weak); defer c.deinit(); try solver.addConstraint(&c); var expr = try v1.add(allocator, 10); defer expr.deinit(); // v2 >= v1 + 10 var c2 = try solver.buildConstraint(&v2, .gte, expr, Strength.strong); defer c2.deinit(); try solver.addConstraint(&c2); try solver.suggestValue(&v1, 2); solver.updateVariables(); solver.dumps(); std.debug.warn("v1 = {}\n", .{v1.value}); std.debug.warn("v2 = {}\n", .{v2.value}); testing.expect(v1.value >= 1); testing.expect(v2.value >= v1.value + 10); } // test "benchmark" { // TODO: // const testing = std.testing; // var buf: [10000]u8 = undefined; // const allocator = &std.heap.FixedBufferAllocator.init(&buf).allocator; // var solver = Solver.init(allocator); // // Create custom strength // const mmedium = Strength.createWeighted(0, 1, 0, 1.25); // testing.expectEqual(mmedium, 1250.0); // const smedium = Strength.create(0, 100, 0); // testing.expectEqual(smedium, 100000.0); // // Create some variables // var left = Variable{.name="left"}; // var height = Variable{.name="height"}; // var top = Variable{.name="top"}; // var width = Variable{.name="width"}; // var contents_top = Variable{.name="contents_top"}; // var contents_bottom = Variable{.name="contents_bottom"}; // var contents_left = Variable{.name="contents_left"}; // var contents_right = Variable{.name="contents_right"}; // var midline = Variable{.name="midline"}; // var ctleft = Variable{.name="ctleft"}; // var ctheight = Variable{.name="ctheight"}; // var cttop = Variable{.name="cttop"}; // var ctwidth = Variable{.name="ctwidth"}; // var lb1left = Variable{.name="lb1left"}; // var lb1height = Variable{.name="lb1height"}; // var lb1top = Variable{.name="lb1top"}; // var lb1width = Variable{.name="lb1width"}; // var lb2left = Variable{.name="lb2left"}; // var lb2height = Variable{.name="lb2height"}; // var lb2top = Variable{.name="lb2top"}; // var lb2width = Variable{.name="lb2width"}; // var lb3left = Variable{.name="lb3left"}; // var lb3height = Variable{.name="lb3height"}; // var lb3top = Variable{.name="lb3top"}; // var lb3width = Variable{.name="lb3width"}; // var fl1left = Variable{.name="fl1left"}; // var fl1height = Variable{.name="fl1height"}; // var fl1top = Variable{.name="fl1top"}; // var fl1width = Variable{.name="fl1width"}; // var fl2left = Variable{.name="fl2left"}; // var fl2height = Variable{.name="fl2height"}; // var fl2top = Variable{.name="fl2top"}; // var fl2width = Variable{.name="fl2width"}; // var fl3left = Variable{.name="fl3left"}; // var fl3height = Variable{.name="fl3height"}; // var fl3top = Variable{.name="fl3top"}; // var fl3width = Variable{.name="fl3width"}; // // Add the edit variables // try solver.addVariable(&width, Strength.strong); // try solver.addVariable(&height, Strength.strong); // // }
kiwi.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 logging = false; const data = @embedFile("../data/day18.txt"); const Item = struct { depth: u8, number: u8, }; pub fn main() !void { var timer = try std.time.Timer.start(); var snail_bois = blk: { var snailies = std.ArrayList([]const Item).init(gpa); errdefer snailies.deinit(); var parsed = std.ArrayList(Item).init(gpa); defer parsed.deinit(); var lines = tokenize(u8, data, "\r\n"); while (lines.next()) |line| { if (line.len == 0) { continue; } parsed.clearRetainingCapacity(); try parsed.ensureTotalCapacity(line.len); var depth: u8 = 0; for (line) |char| { switch (char) { '[' => depth += 1, ']' => depth -= 1, ',' => {}, '0'...'9' => try parsed.append(.{ .depth = depth, .number = char - '0' }), else => unreachable, } } try snailies.append(try gpa.dupe(Item, parsed.items)); } break :blk snailies.toOwnedSlice(); }; defer gpa.free(snail_bois); defer for (snail_bois) |it| { gpa.free(it); }; const parse_time = timer.lap(); var total = try addNumbers(snail_bois[0], snail_bois[1]); for (snail_bois[2..]) |it| { const next = try addNumbers(total, it); gpa.free(total); total = next; } const part1 = magnitude(total); gpa.free(total); const part1_time = timer.lap(); var part2: u64 = 0; for (snail_bois) |a| { for (snail_bois) |b| { const p0 = try addNumbers(a, b); const mag = magnitude(p0); gpa.free(p0); if (mag > part2) part2 = mag; } } const part2_time = timer.read(); print("part1={}, part2={}\n", .{part1, part2}); print("times: parse={}, part1={}, part2={} total={}\n", .{parse_time, part1_time, part2_time, parse_time + part1_time + part2_time}); } fn magnitude(value: []const Item) u64 { const State = struct { val: []const Item, pos: usize = 0, fn calc(self: *@This(), depth: u8) u64 { const it = self.val[self.pos]; assert(it.depth >= depth); if (depth == it.depth) { self.pos += 1; return it.number; } else { const a = self.calc(depth + 1); const b = self.calc(depth + 1); return a * 3 + b * 2; } } }; var state = State{ .val = value }; const result = state.calc(0); assert(state.pos == value.len); return result; } fn printItems(value: []const Item) void { const State = struct { val: []const Item, pos: usize = 0, fn printRec(self: *@This(), depth: u8) void { const it = self.val[self.pos]; assert(it.depth >= depth); if (depth == it.depth) { self.pos += 1; print("{}", .{it.number}); } else { print("[", .{}); self.printRec(depth + 1); print(",", .{}); self.printRec(depth + 1); print("]", .{}); } } }; var state = State{ .val = value }; const result = state.printRec(0); print("\n", .{}); assert(state.pos == value.len); return result; } fn addNumbers(a: []const Item, b: []const Item) ![]const Item { if (logging) printItems(a); if (logging) printItems(b); var output = std.ArrayList(Item).init(gpa); errdefer output.deinit(); try output.ensureTotalCapacity(a.len + b.len); try output.appendSlice(a); try output.appendSlice(b); for (output.items) |*it| { it.depth += 1; } { var i: usize = 0; while (i < output.items.len) : (i += 1) { const it = output.items[i]; if (it.depth >= 5) { assert(it.depth == 5); assert(output.items[i+1].depth == 5); if (i > 0) { output.items[i-1].number += it.number; } if (i + 2 < output.items.len) { output.items[i+2].number += output.items[i+1].number; } _ = output.orderedRemove(i+1); output.items[i] = .{ .number = 0, .depth = 4 }; } } } { var i: usize = 0; while (i < output.items.len) { const it = output.items[i]; if (it.number >= 10) { const left = it.number / 2; const right = (it.number + 1) / 2; if (it.depth == 4) { if (i+1 < output.items.len) { output.items[i+1].number += right; } output.items[i].number = 0; if (i > 0) { output.items[i-1].number += left; i -= 1; } } else { output.items[i] = .{ .depth = it.depth + 1, .number = left }; try output.insert(i+1, .{ .depth = it.depth + 1, .number = right }); } } else { i += 1; } } } if (logging) printItems(output.items); if (logging) print("\n", .{}); return output.toOwnedSlice(); } // 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/day18.zig
const std = @import("std"); const log = std.log; const os = std.os; const process = std.process; const l2 = @import("./missing_syscalls.zig"); const kill = @import("./killer.zig"); const Killer = kill.Killer; const MemoryStats = kill.MemoryStats; const proc = @import("./proc.zig"); fn usage(exit_code: u8) void { log.info("usage: boris [ -h ] [ -g ] [ -r Terminal RAM ] [ -s Terminal Swap ] [ -p Terminal PSI ] [ -u glob1|glob2 ]", .{}); log.info("-r and -s accept percentages. -u is a pipe-separated list of glob patterns that will be avoided by the killer.", .{}); os.exit(exit_code); } pub fn main() anyerror!void { // lock mempages if (l2.mlockall(l2.MCL.CURRENT | l2.MCL.FUTURE | l2.MCL.ONFAULT) catch null) |_| { log.info("Pages locked.", .{}); } else { log.warn("Pages unlocked. Process might be susceptible to being sent to swap.", .{}); } var terminal_ram: f64 = 15; var terminal_swap: f64 = 30; var terminal_psi: f32 = 10; var do_not_kill: []const u8 = ""; var arg_it = process.ArgIterator.init(); var dryrun = false; var pgroup = false; // skip program name. More args = options if (arg_it.skip()) { option_loop: while (arg_it.nextPosix()) |arg| { if (arg.len < 2 or arg[0] != '-') break; var opt_cluster = arg[1..]; // options without optarg first while (opt_cluster.len > 0) { const opt = opt_cluster[0]; switch (opt) { '-' => { if (std.mem.eql(u8, "-help", opt_cluster)) usage(0); if (opt_cluster.len > 1) { log.err("Long options are not supported.", .{}); usage(100); } break :option_loop; }, 'h' => { usage(0); }, 'n' => { dryrun = true; }, 'g' => { pgroup = true; }, // options with arguments, next block 'u', 'r', 'p', 's' => { const optarg = if (opt_cluster.len > 1) opt_cluster[1..] else arg_it.nextPosix() orelse { log.err("No argument provided for option -{c}.", .{opt}); usage(100); return; }; switch (opt) { 'u' => { do_not_kill = optarg[0..]; }, 'p' => { terminal_psi = try std.fmt.parseFloat(f32, optarg); }, 'r' => { terminal_ram = try std.fmt.parseFloat(f64, optarg); }, 's' => { terminal_swap = try std.fmt.parseFloat(f64, optarg); }, else => unreachable, } break; }, else => { log.err("Unrecognized option -{c}.", .{opt}); usage(100); }, } opt_cluster = opt_cluster[1..]; } } } log.info("Avoiding killing {s}", .{do_not_kill}); var k = Killer{ // Killer Initals .timer = try std.time.Timer.start(), .terminal_ram_percent = terminal_ram, .terminal_swap_percent = terminal_swap, .terminal_psi = terminal_psi, .do_not_kill = do_not_kill, .kill_pgroup = pgroup, }; if (dryrun) { try k.dryRun(); } else { while (true) { const mem = MemoryStats.fromSysInfo(try l2.sysinfo()); if (k.poll(mem)) { try k.trigger(); } const slp = k.calculateSleepTime(mem); std.debug.print("Adaptive sleep: {}ms\n", .{slp}); std.os.nanosleep(0, slp * 1000000 - 1); } } }
src/main.zig
pub const THIRTEEN = 13; pub const THIRTEEN_FUZZ = 0.5; pub const THIRTEEN_STRINGS = [][]u8{ "xiii", // Roman numeral 13 "1.3", // Basically 13, see proof in #420 "1️⃣3️⃣", // emoji sequence of 1 and 3 "https://en.wikipedia.org/wiki/This_Is_Thirteen", // Because it is thirteen "https://scontent.cdninstagram.com/hphotos-xtf1/t51.2885-15/s320x320/e35/12237511_444845689040315_1101385461_n.jpg", // Just because we can "https://www.youtube.com/watch?v=pte3Jg-2Ax4", // Thirteen by Big Star "https://www.youtube.com/watch?v=33Kv5D2zwyc", // The best Johny Cash's song "<NAME>", // And because she's "Thirteen" "olivia wilde", // AND because SHE's "Thirteen" "baker's dozen", // Bakers gonna bake "dr. <NAME>", // Why not 13's real name?! "<NAME>", // 蔡依珊 is a public figure in Taiwan. Her Chinese name sounds like "13". "https://s3.amazonaws.com/rapgenius/calle13.jpg", // Calle 13, famous Puerto Rican band "j<NAME>", // XIII of The XX "http://www.imdb.com/title/tt0798817/", // 13 (2010) "https://www.imdb.com/title/tt2991516/", // 13/13/13 (2013) "https://en.wikipedia.org/wiki/XIII_(video_game)", // Because video games are also culture "dilma", //Dilma, former president of Brazil. Her number is 13: https://www.google.com/search?q=dilma+13 "PT", // PT is Brazilian political party represented by the number 13 "<NAME>", // Brazil's thirteenth president "<NAME>", // Thirteenth President of the United States "Louis XIII", // Thirteenth king of France "https://s3.amazonaws.com/rapgenius/calle13.jpg", // Calle 13, famous latin american band // ALL HAIL ZALGO "1̵̧̨̡̢̡̧̨̪͍̮̗̯̮̲͖̥̳̲̯͔͉̬̘͍͔͙̳͚̠͓̳̪̯̣͚͍͎͇̦̗͙͕̬̭̝͕̱̺̮̼̞̤̙̹̙̘̗̘͔͎̼͙̤̝̖̝̫̝̲̼̫̙͚̗͖̳̱̳͕͙̜̖̘͎̖̭̝̖͔̠̦̜̎̀͌̈́̇͜͜͠ͅͅ3̷̧̢̡̛͖̘͎͎̥̼͙̱̜͖̩̪̼̫̭̙̓̽͆̌̀̈́͗̈͗̿̀̔̏͂́̏̅͛͒̓̐́͗̋̎̓̄͛̇͋̊̇́̅̔̇̉͌̈́̊̍͗̑̌̈͆̉͐̂́̉̓̇͛̃͑̾̌̄͐̀̔́̈̐͛̈́͛̇́̍́͊͛̐́̇͆͆́͒͑̃̾̿̏̀́͆̾̀̀̆̚̕͘͘̚͜͝͝͝͝͝͝͝͝", "<NAME>", // Agent 13 "end of slavery", // Thirteenth Amendment // Television characters "<NAME>", // the 13th Doctor in the BBC series, "Doctor Who" "weedle", //#13 Pokémon // Imaginary 13's "13+0i", "13 + 13i", "13i", // B just looks like 13 written closer "B", //For cultural inclusiveness also include German variants "ß", "ẞ", //Also greek "β", "Β", //actually upper case Beta, not B //And Chinese "阝", //(Kangxi radical) //Adding "l" 3, "i"3, |3 and !3 because they basically look like thirteen "i3", "l3", "|3", "!3", //Looks like 13 (flipped horizontally) - E equal to 3 "ei", "e1", "el", "e|", // Flipped characters "ƖƐ", "ƐƖ", // Password variations "th<PASSWORD>", "th1rte3n", "th1rteen", "thirt3en", "thirt33n", "thirte3n", // code variations // binary "00001101", "0b1101", // Octal "0o15", // Hexadecimal "0xd", // Morse ".---- ...--", "- .... .. .-. - . . -.", "- .... .. .-. - . . -.", // Caesar shift "wkluwhhq", "Wkluwhhq", "WKLUWHHQ", // hex "74 68 69 72 74 65 65 6e", "54 48 49 52 54 45 45 4e", "31 33", "74 68 69 72 74 65 65 6e 0d 0a", "54 68 69 72 74 65 65 6e 0d 0a", "54 48 49 52 54 45 45 4e 0d 0a 0d 0a", // base64 "dGhpcnRlZW4=", "VGhpcnRlZW4=", "VEhJUlRFRU4=", "MTM=", // Languages "thirteen", // English "ثلاثة عشر", // Arabic (masculine) "ثلاث عشرة", // Arabic (feminine) "تلطاشر", // Arabic Slang "تلتاشر", // Arabic Slang "طلتاشر", // Arabic Slang "طلطاشر", // Arabic Slang "يج", //Arabic (gematria) "سیزده", // Persian "۱۳", // Persian number "dertien", // Afrikaans / Dutch "dertiendertien", // Double Dutch "seri-un-teng", // Belter creole "seriunteng", "serí-un-teng", "seríunteng", "тринадесет", // Bulgarian "тринайсет", // Also Bulgarian "tretze", // Catalan "napulo ug tulo", // Cebuano "十三", // Chinese / Japanese "拾參", // Chinese (traditional, upper case) "拾叁", // Chinese (simplified, upper case) "拾叄", // Chinese (variant) "拾参", // Chinese (variant) "サーティーン", // Japanese "13", // Japanese full-width "trinaest", // Croatian / Serbian (latin) "tretten", // Danish / Norwegian "senthi", //Dothraki "þrettán", // Icelandic, following are different inflections "þrettándi", // e. thirteenth "þrettánda", "þrettándinn", // e. the thirteenth "þrettándann", "þrettándanum", "þrettándans", "þrettándar", // e. multiple thirteenths "þrettándu", "þrettándum", "þrettándarnir", // e. the multiple thirteenths "þrettándana", "þrettándunum", "þrettándanna", "threttan", // strings without special icelandic characters "threttandi", "threttanda", "threttandinn", "threttandann", "threttandanum", "threttandans", "threttandar", "threttandu", "threttandum", "threttandarnir", "threttandana", "threttandunum", "threttandanna", // end of Icelandic "threttandum", // end of Icelandic "třináct", // Czech "kolmteist", // Estonian "labintatlo", // Filipino "kolmetoista", // Finnish "treize", // French "treizième", //French (ordinal form) "dreizehn", // German "ცამეტი", // Georgian "δεκατρία", // Greek "drizäh", // Swiss German "wa’maH wej", // Klingon "‘umikūmākolu", // Hawaiian "שלוש עשרה", // Hebrew "שלושעשרה", // Hebrew (without space) "ֹשְלֹש- עֶשְֹרֵה", // Hebrew (with punctuation) "שלושה עשר", // Hebrew (male form) "שלושהעשר", // Hebrew (male form, without space) "ֹשְלֹשָה- עָשָֹר", // Hebrew (male form, with punctuation) "יג", // Hebrew (gematria) "י״ג", // Hebrew (gematria - apostrophes) "quainel", // Quenya "mînuiug", // Sindarin "dektri", // Esperanto "tizenhárom", // Hungarian "trí déag", // Irish "tredici", // Italian "ಹದಿಮೂರು", //Kannada (for thirteen) "೧೩", //Kannada (for 13) "sêzdeh", // Kurdish "tredecim", // Latin "trīspadsmit", // Latvian "trylika", // Lithuanian "dräizéng", // Luxembourgish "тринаесет", // Macedonian "tiga belas", // Malay "പതിമൂന്ന്", //Malayalam "൰൩", // Malayalam "तेरा", // Marathi (१३) "арван", // Mongolian ".---- ...--", // Morse code "matlactlihuan yei", // Classical Nahuatl (Aztec) "mahtlactli omei", // Nahuatl variant "mahtlactli ihuan yei", // Nahuatl variant "irteenthay", // Pig Latin // Beginning of some Korean variants 🇰🇷 "열셋", // Korean "십삼", // Korean "써틴", // Korean "썰틴", // Korean "떠틴", // Korean "떨틴", // Korean "씹쌈", // Korean "십쌈", // Korean "씹삼", // Korean "10삼", // Korean "십3", // Korean "시입삼", // Korean "시이입삼", // Korean (TODO: Anything that matches "^(십|(시이*입))(삼|(사아*암))$" is 13) "여얼세엣", // Korean "열세엣", // Korean (TODO: Also, Anything that matches "^(열|(여어*얼))(셋|(세에*엣))$" is 13) // End of some Korean variants 🇰🇷 // Beginning of all Polish variants 🇵🇱 "trzynaście", // Polish "trzynasty", // Polish "trzynasta", // Polish "trzynaste", // Polish "trzynaści", // Polish "trzynastego", // Polish "trzynastej", // Polish "trzynastych", // Polish "trzynastemu", // Polish "trzynastym", // Polish "trzynastą", // Polish "trzynastymi", // Polish "trzynastu", // Polish "trzynastek", // Polish "trzynastoma", // Polish "trzynaścioro", // Polish "trzynastka", // Polish "trzynastki", // Polish "trzynastką", // Polish "trzynastce", // Polish "trzynastko", // Polish "trzynaściorgiem", // Polish "trzynaściorgu", // Polish "trzynaściorga", // Polish "trzynastokrotny", // Polish "trzynastokrotnie", // Polish "trzynastokrotną", // Polish "trzynastokrotnemu", // Polish "trzynastokrotnej", // Polish "trzynastokrotnych", // Polish "trzynastokrotność", // Polish "trzynastokrotności", // Polish "trzynastokrotnością", // Polish // End of all Polish variants 🇵🇱 // Bangla/Bengali variants "১৩", // Bengali numeral "তেরো", "তের", "ত্রয়োদশ", // end of Bangla/Bengali variants "treze", // Portuguese "ਤੇਰਾਂ", // Punjabi - thirteen "੧੩", // Punjabi Numeral - 13 "treisprezece", // Romanian "treispe", // Romanian "тринадцать", // Russian (cyrillic) "ⱅⱃⰺⱀⰰⰴⱌⰰⱅⱐ", // Russian (glagolitic) "тринаест", // Serbian (cyrillic) "trinásť", // Slovak "trinajst", // Slovenian "trece", // Spanish "diez-y-tres", // Spanglish "trese", // Tagalog "on üç", // Turkish "dektri", //Speranto "tlettax", // Maltese "tretton", // Swedish "பதின்மூன்று", // Tamil "௧௩", // Tamil "௰௩", // Tamil "สิบสาม", // Thai "๑๓", // Thai Numeral "SipSam", // Thai Transcription "Sip Sam", // Thai Transcription with space "тринадцять", // Ukrainian "تیرہ", // Urdu "tayra", // Roman Urdu "mười ba", // Vietnamese "tri ar ddeg", // Welsh "דרייַצן", // Yiddish, "דרייצן", // Yiddish (without diacritics), "kumi na tatu", // Swahili "तेह्र", //Nepali "१३", //Devanagari "तेरह", //Hindi "7h1r733n", // Crypto // Thirteen pronunciation "θərˈtiːn", "పదమూడు", //Telugu "౧౩", // Telugu "shí sān", // Pinyin (formal) "shi san", // Pinyin (without tones) "shísān", // Pinyin (without spaces) "shisan", // Pinyin (without spaces and tones) "он үш", // Kazakh "он уш", // Kazakh "onúsh", // Kazakh latin, "онүш", // Kazakh "онуш", // Kazakh "onúsh", // Kazakh latin "paci", // lojban "ishumi nantathu", // isiZulu "lishumi elinesithathu", // isiXhosa };
src/consts.zig
// Two types of social contradictions - those between ourselves and the enemy // and those among the people themselves confront us. The two are totally // different in their nature. const std = @import("std"); const I_Instruction = @import("instruction.zig").I_Instruction; const C_Instruction = @import("instruction.zig").C_Instruction; const R_Instruction = @import("instruction.zig").R_Instruction; const Register = @import("register.zig").Register; const vm = @import("vm.zig"); /// Convert string to an enum variant. pub fn string_to_enum(comptime T: type, str: []const u8) ?T { // This is some advanced zig magic that I don't truly understand. // Thanks to people on the zig discord // inline for unrolls the loop inline for (@typeInfo(T).Enum.fields) |enumField| { // for each enum field it equates its name to the string // if they are equal, return the enum field if (std.mem.eql(u8, str, enumField.name)) { return @field(T, enumField.name); } } return null; } /// Covert from string with the register name to a u5 id of the register pub fn register_to_address(ident: []const u8) ?u5 { // for string methods they need a preallocated buffer to save to var buffer: [100]u8 = undefined; const lower_reg = std.ascii.lowerString(buffer[0..], ident); if (string_to_enum(Register, lower_reg)) |enum_variant| { return @enumToInt(enum_variant); } else { std.log.err("Unrecognized register {s}", .{ident}); return null; } } pub fn build_R_Instruction(opcode: R_Instruction, rd: u5, rs1: u5, rs2: u5) u32 { const r_ins = (@intCast(u32, @enumToInt(opcode)) << 2) | (@intCast(u32, rd) << 17) | (@intCast(u32, rs1) << 22) | (@intCast(u32, rs2) << 27); return r_ins; } pub fn build_I_Instruction(opcode: I_Instruction, rd: u5, rs1: u5, imm12: u12) u32 { const i_ins = 1 | (@intCast(u32, @enumToInt(opcode)) << 1) | (@intCast(u32, rd) << 10) | (@intCast(u32, rs1) << 15) | (@intCast(u32, imm12) << 20); return i_ins; } pub fn build_C_Instruction(opcode: C_Instruction, rd: u5, imm20: u20) u32 { const c_ins = 2 | (@intCast(u32, @enumToInt(opcode)) << 2) | (@intCast(u32, rd) << 7) | (@intCast(u32, imm20) << 12); return c_ins; } /// Build instruction of any type. Depending on the type fill unused operands with `null` pub fn build_instruction(comptime instruction: anytype, op1: ?[]const u8, op2: ?[]const u8, op3: ?[]const u8, imm: ?u32) u32 { switch (@TypeOf(instruction)) { C_Instruction => { const imm64 = imm.?; const ins = build_C_Instruction(instruction, register_to_address(op1.?).?, @truncate(u20, imm64)); return ins; }, I_Instruction => { const imm64 = imm.?; return build_I_Instruction(instruction, register_to_address(op1.?).?, register_to_address(op2.?).?, @truncate(u12, imm64)); }, R_Instruction => { return build_R_Instruction(instruction, register_to_address(op1.?).?, register_to_address(op2.?).?, register_to_address(op3.?).?); }, else => { @compileError("Cannot call build_instruction with non-instruction enum!"); }, } }
src/util.zig
pub const SpvId = c_uint; pub const SpvMagicNumber: c_uint = @bitCast(c_uint, @as(c_int, 119734787)); pub const SpvVersion: c_uint = @bitCast(c_uint, @as(c_int, 66816)); pub const SpvRevision: c_uint = @bitCast(c_uint, @as(c_int, 3)); pub const SpvOpCodeMask: c_uint = @bitCast(c_uint, @as(c_int, 65535)); pub const SpvWordCountShift: c_uint = @bitCast(c_uint, @as(c_int, 16)); pub const SpvSourceLanguageUnknown = @enumToInt(enum_SpvSourceLanguage_.SpvSourceLanguageUnknown); pub const SpvSourceLanguageESSL = @enumToInt(enum_SpvSourceLanguage_.SpvSourceLanguageESSL); pub const SpvSourceLanguageGLSL = @enumToInt(enum_SpvSourceLanguage_.SpvSourceLanguageGLSL); pub const SpvSourceLanguageOpenCL_C = @enumToInt(enum_SpvSourceLanguage_.SpvSourceLanguageOpenCL_C); pub const SpvSourceLanguageOpenCL_CPP = @enumToInt(enum_SpvSourceLanguage_.SpvSourceLanguageOpenCL_CPP); pub const SpvSourceLanguageHLSL = @enumToInt(enum_SpvSourceLanguage_.SpvSourceLanguageHLSL); pub const SpvSourceLanguageMax = @enumToInt(enum_SpvSourceLanguage_.SpvSourceLanguageMax); pub const enum_SpvSourceLanguage_ = extern enum(c_int) { SpvSourceLanguageUnknown = 0, SpvSourceLanguageESSL = 1, SpvSourceLanguageGLSL = 2, SpvSourceLanguageOpenCL_C = 3, SpvSourceLanguageOpenCL_CPP = 4, SpvSourceLanguageHLSL = 5, SpvSourceLanguageMax = 2147483647, _, }; pub const SpvSourceLanguage = enum_SpvSourceLanguage_; pub const SpvExecutionModelVertex = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelVertex); pub const SpvExecutionModelTessellationControl = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelTessellationControl); pub const SpvExecutionModelTessellationEvaluation = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelTessellationEvaluation); pub const SpvExecutionModelGeometry = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelGeometry); pub const SpvExecutionModelFragment = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelFragment); pub const SpvExecutionModelGLCompute = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelGLCompute); pub const SpvExecutionModelKernel = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelKernel); pub const SpvExecutionModelTaskNV = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelTaskNV); pub const SpvExecutionModelMeshNV = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelMeshNV); pub const SpvExecutionModelRayGenerationKHR = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelRayGenerationKHR); pub const SpvExecutionModelRayGenerationNV = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelRayGenerationNV); pub const SpvExecutionModelIntersectionKHR = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelIntersectionKHR); pub const SpvExecutionModelIntersectionNV = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelIntersectionNV); pub const SpvExecutionModelAnyHitKHR = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelAnyHitKHR); pub const SpvExecutionModelAnyHitNV = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelAnyHitNV); pub const SpvExecutionModelClosestHitKHR = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelClosestHitKHR); pub const SpvExecutionModelClosestHitNV = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelClosestHitNV); pub const SpvExecutionModelMissKHR = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelMissKHR); pub const SpvExecutionModelMissNV = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelMissNV); pub const SpvExecutionModelCallableKHR = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelCallableKHR); pub const SpvExecutionModelCallableNV = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelCallableNV); pub const SpvExecutionModelMax = @enumToInt(enum_SpvExecutionModel_.SpvExecutionModelMax); pub const enum_SpvExecutionModel_ = extern enum(c_int) { SpvExecutionModelVertex = 0, SpvExecutionModelTessellationControl = 1, SpvExecutionModelTessellationEvaluation = 2, SpvExecutionModelGeometry = 3, SpvExecutionModelFragment = 4, SpvExecutionModelGLCompute = 5, SpvExecutionModelKernel = 6, SpvExecutionModelTaskNV = 5267, SpvExecutionModelMeshNV = 5268, SpvExecutionModelRayGenerationKHR = 5313, SpvExecutionModelRayGenerationNV = 5313, SpvExecutionModelIntersectionKHR = 5314, SpvExecutionModelIntersectionNV = 5314, SpvExecutionModelAnyHitKHR = 5315, SpvExecutionModelAnyHitNV = 5315, SpvExecutionModelClosestHitKHR = 5316, SpvExecutionModelClosestHitNV = 5316, SpvExecutionModelMissKHR = 5317, SpvExecutionModelMissNV = 5317, SpvExecutionModelCallableKHR = 5318, SpvExecutionModelCallableNV = 5318, SpvExecutionModelMax = 2147483647, _, }; pub const SpvExecutionModel = enum_SpvExecutionModel_; pub const SpvAddressingModelLogical = @enumToInt(enum_SpvAddressingModel_.SpvAddressingModelLogical); pub const SpvAddressingModelPhysical32 = @enumToInt(enum_SpvAddressingModel_.SpvAddressingModelPhysical32); pub const SpvAddressingModelPhysical64 = @enumToInt(enum_SpvAddressingModel_.SpvAddressingModelPhysical64); pub const SpvAddressingModelPhysicalStorageBuffer64 = @enumToInt(enum_SpvAddressingModel_.SpvAddressingModelPhysicalStorageBuffer64); pub const SpvAddressingModelPhysicalStorageBuffer64EXT = @enumToInt(enum_SpvAddressingModel_.SpvAddressingModelPhysicalStorageBuffer64EXT); pub const SpvAddressingModelMax = @enumToInt(enum_SpvAddressingModel_.SpvAddressingModelMax); pub const enum_SpvAddressingModel_ = extern enum(c_int) { SpvAddressingModelLogical = 0, SpvAddressingModelPhysical32 = 1, SpvAddressingModelPhysical64 = 2, SpvAddressingModelPhysicalStorageBuffer64 = 5348, SpvAddressingModelPhysicalStorageBuffer64EXT = 5348, SpvAddressingModelMax = 2147483647, _, }; pub const SpvAddressingModel = enum_SpvAddressingModel_; pub const SpvMemoryModelSimple = @enumToInt(enum_SpvMemoryModel_.SpvMemoryModelSimple); pub const SpvMemoryModelGLSL450 = @enumToInt(enum_SpvMemoryModel_.SpvMemoryModelGLSL450); pub const SpvMemoryModelOpenCL = @enumToInt(enum_SpvMemoryModel_.SpvMemoryModelOpenCL); pub const SpvMemoryModelVulkan = @enumToInt(enum_SpvMemoryModel_.SpvMemoryModelVulkan); pub const SpvMemoryModelVulkanKHR = @enumToInt(enum_SpvMemoryModel_.SpvMemoryModelVulkanKHR); pub const SpvMemoryModelMax = @enumToInt(enum_SpvMemoryModel_.SpvMemoryModelMax); pub const enum_SpvMemoryModel_ = extern enum(c_int) { SpvMemoryModelSimple = 0, SpvMemoryModelGLSL450 = 1, SpvMemoryModelOpenCL = 2, SpvMemoryModelVulkan = 3, SpvMemoryModelVulkanKHR = 3, SpvMemoryModelMax = 2147483647, _, }; pub const SpvMemoryModel = enum_SpvMemoryModel_; pub const SpvExecutionModeInvocations = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeInvocations); pub const SpvExecutionModeSpacingEqual = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeSpacingEqual); pub const SpvExecutionModeSpacingFractionalEven = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeSpacingFractionalEven); pub const SpvExecutionModeSpacingFractionalOdd = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeSpacingFractionalOdd); pub const SpvExecutionModeVertexOrderCw = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeVertexOrderCw); pub const SpvExecutionModeVertexOrderCcw = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeVertexOrderCcw); pub const SpvExecutionModePixelCenterInteger = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModePixelCenterInteger); pub const SpvExecutionModeOriginUpperLeft = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeOriginUpperLeft); pub const SpvExecutionModeOriginLowerLeft = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeOriginLowerLeft); pub const SpvExecutionModeEarlyFragmentTests = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeEarlyFragmentTests); pub const SpvExecutionModePointMode = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModePointMode); pub const SpvExecutionModeXfb = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeXfb); pub const SpvExecutionModeDepthReplacing = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeDepthReplacing); pub const SpvExecutionModeDepthGreater = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeDepthGreater); pub const SpvExecutionModeDepthLess = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeDepthLess); pub const SpvExecutionModeDepthUnchanged = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeDepthUnchanged); pub const SpvExecutionModeLocalSize = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeLocalSize); pub const SpvExecutionModeLocalSizeHint = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeLocalSizeHint); pub const SpvExecutionModeInputPoints = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeInputPoints); pub const SpvExecutionModeInputLines = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeInputLines); pub const SpvExecutionModeInputLinesAdjacency = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeInputLinesAdjacency); pub const SpvExecutionModeTriangles = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeTriangles); pub const SpvExecutionModeInputTrianglesAdjacency = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeInputTrianglesAdjacency); pub const SpvExecutionModeQuads = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeQuads); pub const SpvExecutionModeIsolines = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeIsolines); pub const SpvExecutionModeOutputVertices = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeOutputVertices); pub const SpvExecutionModeOutputPoints = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeOutputPoints); pub const SpvExecutionModeOutputLineStrip = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeOutputLineStrip); pub const SpvExecutionModeOutputTriangleStrip = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeOutputTriangleStrip); pub const SpvExecutionModeVecTypeHint = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeVecTypeHint); pub const SpvExecutionModeContractionOff = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeContractionOff); pub const SpvExecutionModeInitializer = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeInitializer); pub const SpvExecutionModeFinalizer = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeFinalizer); pub const SpvExecutionModeSubgroupSize = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeSubgroupSize); pub const SpvExecutionModeSubgroupsPerWorkgroup = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeSubgroupsPerWorkgroup); pub const SpvExecutionModeSubgroupsPerWorkgroupId = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeSubgroupsPerWorkgroupId); pub const SpvExecutionModeLocalSizeId = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeLocalSizeId); pub const SpvExecutionModeLocalSizeHintId = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeLocalSizeHintId); pub const SpvExecutionModePostDepthCoverage = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModePostDepthCoverage); pub const SpvExecutionModeDenormPreserve = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeDenormPreserve); pub const SpvExecutionModeDenormFlushToZero = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeDenormFlushToZero); pub const SpvExecutionModeSignedZeroInfNanPreserve = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeSignedZeroInfNanPreserve); pub const SpvExecutionModeRoundingModeRTE = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeRoundingModeRTE); pub const SpvExecutionModeRoundingModeRTZ = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeRoundingModeRTZ); pub const SpvExecutionModeStencilRefReplacingEXT = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeStencilRefReplacingEXT); pub const SpvExecutionModeOutputLinesNV = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeOutputLinesNV); pub const SpvExecutionModeOutputPrimitivesNV = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeOutputPrimitivesNV); pub const SpvExecutionModeDerivativeGroupQuadsNV = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeDerivativeGroupQuadsNV); pub const SpvExecutionModeDerivativeGroupLinearNV = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeDerivativeGroupLinearNV); pub const SpvExecutionModeOutputTrianglesNV = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeOutputTrianglesNV); pub const SpvExecutionModePixelInterlockOrderedEXT = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModePixelInterlockOrderedEXT); pub const SpvExecutionModePixelInterlockUnorderedEXT = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModePixelInterlockUnorderedEXT); pub const SpvExecutionModeSampleInterlockOrderedEXT = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeSampleInterlockOrderedEXT); pub const SpvExecutionModeSampleInterlockUnorderedEXT = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeSampleInterlockUnorderedEXT); pub const SpvExecutionModeShadingRateInterlockOrderedEXT = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeShadingRateInterlockOrderedEXT); pub const SpvExecutionModeShadingRateInterlockUnorderedEXT = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeShadingRateInterlockUnorderedEXT); pub const SpvExecutionModeMaxWorkgroupSizeINTEL = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeMaxWorkgroupSizeINTEL); pub const SpvExecutionModeMaxWorkDimINTEL = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeMaxWorkDimINTEL); pub const SpvExecutionModeNoGlobalOffsetINTEL = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeNoGlobalOffsetINTEL); pub const SpvExecutionModeNumSIMDWorkitemsINTEL = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeNumSIMDWorkitemsINTEL); pub const SpvExecutionModeMax = @enumToInt(enum_SpvExecutionMode_.SpvExecutionModeMax); pub const enum_SpvExecutionMode_ = extern enum(c_int) { SpvExecutionModeInvocations = 0, SpvExecutionModeSpacingEqual = 1, SpvExecutionModeSpacingFractionalEven = 2, SpvExecutionModeSpacingFractionalOdd = 3, SpvExecutionModeVertexOrderCw = 4, SpvExecutionModeVertexOrderCcw = 5, SpvExecutionModePixelCenterInteger = 6, SpvExecutionModeOriginUpperLeft = 7, SpvExecutionModeOriginLowerLeft = 8, SpvExecutionModeEarlyFragmentTests = 9, SpvExecutionModePointMode = 10, SpvExecutionModeXfb = 11, SpvExecutionModeDepthReplacing = 12, SpvExecutionModeDepthGreater = 14, SpvExecutionModeDepthLess = 15, SpvExecutionModeDepthUnchanged = 16, SpvExecutionModeLocalSize = 17, SpvExecutionModeLocalSizeHint = 18, SpvExecutionModeInputPoints = 19, SpvExecutionModeInputLines = 20, SpvExecutionModeInputLinesAdjacency = 21, SpvExecutionModeTriangles = 22, SpvExecutionModeInputTrianglesAdjacency = 23, SpvExecutionModeQuads = 24, SpvExecutionModeIsolines = 25, SpvExecutionModeOutputVertices = 26, SpvExecutionModeOutputPoints = 27, SpvExecutionModeOutputLineStrip = 28, SpvExecutionModeOutputTriangleStrip = 29, SpvExecutionModeVecTypeHint = 30, SpvExecutionModeContractionOff = 31, SpvExecutionModeInitializer = 33, SpvExecutionModeFinalizer = 34, SpvExecutionModeSubgroupSize = 35, SpvExecutionModeSubgroupsPerWorkgroup = 36, SpvExecutionModeSubgroupsPerWorkgroupId = 37, SpvExecutionModeLocalSizeId = 38, SpvExecutionModeLocalSizeHintId = 39, SpvExecutionModePostDepthCoverage = 4446, SpvExecutionModeDenormPreserve = 4459, SpvExecutionModeDenormFlushToZero = 4460, SpvExecutionModeSignedZeroInfNanPreserve = 4461, SpvExecutionModeRoundingModeRTE = 4462, SpvExecutionModeRoundingModeRTZ = 4463, SpvExecutionModeStencilRefReplacingEXT = 5027, SpvExecutionModeOutputLinesNV = 5269, SpvExecutionModeOutputPrimitivesNV = 5270, SpvExecutionModeDerivativeGroupQuadsNV = 5289, SpvExecutionModeDerivativeGroupLinearNV = 5290, SpvExecutionModeOutputTrianglesNV = 5298, SpvExecutionModePixelInterlockOrderedEXT = 5366, SpvExecutionModePixelInterlockUnorderedEXT = 5367, SpvExecutionModeSampleInterlockOrderedEXT = 5368, SpvExecutionModeSampleInterlockUnorderedEXT = 5369, SpvExecutionModeShadingRateInterlockOrderedEXT = 5370, SpvExecutionModeShadingRateInterlockUnorderedEXT = 5371, SpvExecutionModeMaxWorkgroupSizeINTEL = 5893, SpvExecutionModeMaxWorkDimINTEL = 5894, SpvExecutionModeNoGlobalOffsetINTEL = 5895, SpvExecutionModeNumSIMDWorkitemsINTEL = 5896, SpvExecutionModeMax = 2147483647, _, }; pub const SpvExecutionMode = enum_SpvExecutionMode_; pub const SpvStorageClassUniformConstant = @enumToInt(enum_SpvStorageClass_.SpvStorageClassUniformConstant); pub const SpvStorageClassInput = @enumToInt(enum_SpvStorageClass_.SpvStorageClassInput); pub const SpvStorageClassUniform = @enumToInt(enum_SpvStorageClass_.SpvStorageClassUniform); pub const SpvStorageClassOutput = @enumToInt(enum_SpvStorageClass_.SpvStorageClassOutput); pub const SpvStorageClassWorkgroup = @enumToInt(enum_SpvStorageClass_.SpvStorageClassWorkgroup); pub const SpvStorageClassCrossWorkgroup = @enumToInt(enum_SpvStorageClass_.SpvStorageClassCrossWorkgroup); pub const SpvStorageClassPrivate = @enumToInt(enum_SpvStorageClass_.SpvStorageClassPrivate); pub const SpvStorageClassFunction = @enumToInt(enum_SpvStorageClass_.SpvStorageClassFunction); pub const SpvStorageClassGeneric = @enumToInt(enum_SpvStorageClass_.SpvStorageClassGeneric); pub const SpvStorageClassPushConstant = @enumToInt(enum_SpvStorageClass_.SpvStorageClassPushConstant); pub const SpvStorageClassAtomicCounter = @enumToInt(enum_SpvStorageClass_.SpvStorageClassAtomicCounter); pub const SpvStorageClassImage = @enumToInt(enum_SpvStorageClass_.SpvStorageClassImage); pub const SpvStorageClassStorageBuffer = @enumToInt(enum_SpvStorageClass_.SpvStorageClassStorageBuffer); pub const SpvStorageClassCallableDataKHR = @enumToInt(enum_SpvStorageClass_.SpvStorageClassCallableDataKHR); pub const SpvStorageClassCallableDataNV = @enumToInt(enum_SpvStorageClass_.SpvStorageClassCallableDataNV); pub const SpvStorageClassIncomingCallableDataKHR = @enumToInt(enum_SpvStorageClass_.SpvStorageClassIncomingCallableDataKHR); pub const SpvStorageClassIncomingCallableDataNV = @enumToInt(enum_SpvStorageClass_.SpvStorageClassIncomingCallableDataNV); pub const SpvStorageClassRayPayloadKHR = @enumToInt(enum_SpvStorageClass_.SpvStorageClassRayPayloadKHR); pub const SpvStorageClassRayPayloadNV = @enumToInt(enum_SpvStorageClass_.SpvStorageClassRayPayloadNV); pub const SpvStorageClassHitAttributeKHR = @enumToInt(enum_SpvStorageClass_.SpvStorageClassHitAttributeKHR); pub const SpvStorageClassHitAttributeNV = @enumToInt(enum_SpvStorageClass_.SpvStorageClassHitAttributeNV); pub const SpvStorageClassIncomingRayPayloadKHR = @enumToInt(enum_SpvStorageClass_.SpvStorageClassIncomingRayPayloadKHR); pub const SpvStorageClassIncomingRayPayloadNV = @enumToInt(enum_SpvStorageClass_.SpvStorageClassIncomingRayPayloadNV); pub const SpvStorageClassShaderRecordBufferKHR = @enumToInt(enum_SpvStorageClass_.SpvStorageClassShaderRecordBufferKHR); pub const SpvStorageClassShaderRecordBufferNV = @enumToInt(enum_SpvStorageClass_.SpvStorageClassShaderRecordBufferNV); pub const SpvStorageClassPhysicalStorageBuffer = @enumToInt(enum_SpvStorageClass_.SpvStorageClassPhysicalStorageBuffer); pub const SpvStorageClassPhysicalStorageBufferEXT = @enumToInt(enum_SpvStorageClass_.SpvStorageClassPhysicalStorageBufferEXT); pub const SpvStorageClassCodeSectionINTEL = @enumToInt(enum_SpvStorageClass_.SpvStorageClassCodeSectionINTEL); pub const SpvStorageClassMax = @enumToInt(enum_SpvStorageClass_.SpvStorageClassMax); pub const enum_SpvStorageClass_ = extern enum(c_int) { SpvStorageClassUniformConstant = 0, SpvStorageClassInput = 1, SpvStorageClassUniform = 2, SpvStorageClassOutput = 3, SpvStorageClassWorkgroup = 4, SpvStorageClassCrossWorkgroup = 5, SpvStorageClassPrivate = 6, SpvStorageClassFunction = 7, SpvStorageClassGeneric = 8, SpvStorageClassPushConstant = 9, SpvStorageClassAtomicCounter = 10, SpvStorageClassImage = 11, SpvStorageClassStorageBuffer = 12, SpvStorageClassCallableDataKHR = 5328, SpvStorageClassCallableDataNV = 5328, SpvStorageClassIncomingCallableDataKHR = 5329, SpvStorageClassIncomingCallableDataNV = 5329, SpvStorageClassRayPayloadKHR = 5338, SpvStorageClassRayPayloadNV = 5338, SpvStorageClassHitAttributeKHR = 5339, SpvStorageClassHitAttributeNV = 5339, SpvStorageClassIncomingRayPayloadKHR = 5342, SpvStorageClassIncomingRayPayloadNV = 5342, SpvStorageClassShaderRecordBufferKHR = 5343, SpvStorageClassShaderRecordBufferNV = 5343, SpvStorageClassPhysicalStorageBuffer = 5349, SpvStorageClassPhysicalStorageBufferEXT = 5349, SpvStorageClassCodeSectionINTEL = 5605, SpvStorageClassMax = 2147483647, _, }; pub const SpvStorageClass = enum_SpvStorageClass_; pub const SpvDim1D = @enumToInt(enum_SpvDim_.SpvDim1D); pub const SpvDim2D = @enumToInt(enum_SpvDim_.SpvDim2D); pub const SpvDim3D = @enumToInt(enum_SpvDim_.SpvDim3D); pub const SpvDimCube = @enumToInt(enum_SpvDim_.SpvDimCube); pub const SpvDimRect = @enumToInt(enum_SpvDim_.SpvDimRect); pub const SpvDimBuffer = @enumToInt(enum_SpvDim_.SpvDimBuffer); pub const SpvDimSubpassData = @enumToInt(enum_SpvDim_.SpvDimSubpassData); pub const SpvDimMax = @enumToInt(enum_SpvDim_.SpvDimMax); pub const enum_SpvDim_ = extern enum(c_int) { SpvDim1D = 0, SpvDim2D = 1, SpvDim3D = 2, SpvDimCube = 3, SpvDimRect = 4, SpvDimBuffer = 5, SpvDimSubpassData = 6, SpvDimMax = 2147483647, _, }; pub const SpvDim = enum_SpvDim_; pub const SpvSamplerAddressingModeNone = @enumToInt(enum_SpvSamplerAddressingMode_.SpvSamplerAddressingModeNone); pub const SpvSamplerAddressingModeClampToEdge = @enumToInt(enum_SpvSamplerAddressingMode_.SpvSamplerAddressingModeClampToEdge); pub const SpvSamplerAddressingModeClamp = @enumToInt(enum_SpvSamplerAddressingMode_.SpvSamplerAddressingModeClamp); pub const SpvSamplerAddressingModeRepeat = @enumToInt(enum_SpvSamplerAddressingMode_.SpvSamplerAddressingModeRepeat); pub const SpvSamplerAddressingModeRepeatMirrored = @enumToInt(enum_SpvSamplerAddressingMode_.SpvSamplerAddressingModeRepeatMirrored); pub const SpvSamplerAddressingModeMax = @enumToInt(enum_SpvSamplerAddressingMode_.SpvSamplerAddressingModeMax); pub const enum_SpvSamplerAddressingMode_ = extern enum(c_int) { SpvSamplerAddressingModeNone = 0, SpvSamplerAddressingModeClampToEdge = 1, SpvSamplerAddressingModeClamp = 2, SpvSamplerAddressingModeRepeat = 3, SpvSamplerAddressingModeRepeatMirrored = 4, SpvSamplerAddressingModeMax = 2147483647, _, }; pub const SpvSamplerAddressingMode = enum_SpvSamplerAddressingMode_; pub const SpvSamplerFilterModeNearest = @enumToInt(enum_SpvSamplerFilterMode_.SpvSamplerFilterModeNearest); pub const SpvSamplerFilterModeLinear = @enumToInt(enum_SpvSamplerFilterMode_.SpvSamplerFilterModeLinear); pub const SpvSamplerFilterModeMax = @enumToInt(enum_SpvSamplerFilterMode_.SpvSamplerFilterModeMax); pub const enum_SpvSamplerFilterMode_ = extern enum(c_int) { SpvSamplerFilterModeNearest = 0, SpvSamplerFilterModeLinear = 1, SpvSamplerFilterModeMax = 2147483647, _, }; pub const SpvSamplerFilterMode = enum_SpvSamplerFilterMode_; pub const SpvImageFormatUnknown = @enumToInt(enum_SpvImageFormat_.SpvImageFormatUnknown); pub const SpvImageFormatRgba32f = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRgba32f); pub const SpvImageFormatRgba16f = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRgba16f); pub const SpvImageFormatR32f = @enumToInt(enum_SpvImageFormat_.SpvImageFormatR32f); pub const SpvImageFormatRgba8 = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRgba8); pub const SpvImageFormatRgba8Snorm = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRgba8Snorm); pub const SpvImageFormatRg32f = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRg32f); pub const SpvImageFormatRg16f = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRg16f); pub const SpvImageFormatR11fG11fB10f = @enumToInt(enum_SpvImageFormat_.SpvImageFormatR11fG11fB10f); pub const SpvImageFormatR16f = @enumToInt(enum_SpvImageFormat_.SpvImageFormatR16f); pub const SpvImageFormatRgba16 = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRgba16); pub const SpvImageFormatRgb10A2 = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRgb10A2); pub const SpvImageFormatRg16 = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRg16); pub const SpvImageFormatRg8 = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRg8); pub const SpvImageFormatR16 = @enumToInt(enum_SpvImageFormat_.SpvImageFormatR16); pub const SpvImageFormatR8 = @enumToInt(enum_SpvImageFormat_.SpvImageFormatR8); pub const SpvImageFormatRgba16Snorm = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRgba16Snorm); pub const SpvImageFormatRg16Snorm = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRg16Snorm); pub const SpvImageFormatRg8Snorm = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRg8Snorm); pub const SpvImageFormatR16Snorm = @enumToInt(enum_SpvImageFormat_.SpvImageFormatR16Snorm); pub const SpvImageFormatR8Snorm = @enumToInt(enum_SpvImageFormat_.SpvImageFormatR8Snorm); pub const SpvImageFormatRgba32i = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRgba32i); pub const SpvImageFormatRgba16i = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRgba16i); pub const SpvImageFormatRgba8i = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRgba8i); pub const SpvImageFormatR32i = @enumToInt(enum_SpvImageFormat_.SpvImageFormatR32i); pub const SpvImageFormatRg32i = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRg32i); pub const SpvImageFormatRg16i = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRg16i); pub const SpvImageFormatRg8i = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRg8i); pub const SpvImageFormatR16i = @enumToInt(enum_SpvImageFormat_.SpvImageFormatR16i); pub const SpvImageFormatR8i = @enumToInt(enum_SpvImageFormat_.SpvImageFormatR8i); pub const SpvImageFormatRgba32ui = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRgba32ui); pub const SpvImageFormatRgba16ui = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRgba16ui); pub const SpvImageFormatRgba8ui = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRgba8ui); pub const SpvImageFormatR32ui = @enumToInt(enum_SpvImageFormat_.SpvImageFormatR32ui); pub const SpvImageFormatRgb10a2ui = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRgb10a2ui); pub const SpvImageFormatRg32ui = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRg32ui); pub const SpvImageFormatRg16ui = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRg16ui); pub const SpvImageFormatRg8ui = @enumToInt(enum_SpvImageFormat_.SpvImageFormatRg8ui); pub const SpvImageFormatR16ui = @enumToInt(enum_SpvImageFormat_.SpvImageFormatR16ui); pub const SpvImageFormatR8ui = @enumToInt(enum_SpvImageFormat_.SpvImageFormatR8ui); pub const SpvImageFormatMax = @enumToInt(enum_SpvImageFormat_.SpvImageFormatMax); pub const enum_SpvImageFormat_ = extern enum(c_int) { SpvImageFormatUnknown = 0, SpvImageFormatRgba32f = 1, SpvImageFormatRgba16f = 2, SpvImageFormatR32f = 3, SpvImageFormatRgba8 = 4, SpvImageFormatRgba8Snorm = 5, SpvImageFormatRg32f = 6, SpvImageFormatRg16f = 7, SpvImageFormatR11fG11fB10f = 8, SpvImageFormatR16f = 9, SpvImageFormatRgba16 = 10, SpvImageFormatRgb10A2 = 11, SpvImageFormatRg16 = 12, SpvImageFormatRg8 = 13, SpvImageFormatR16 = 14, SpvImageFormatR8 = 15, SpvImageFormatRgba16Snorm = 16, SpvImageFormatRg16Snorm = 17, SpvImageFormatRg8Snorm = 18, SpvImageFormatR16Snorm = 19, SpvImageFormatR8Snorm = 20, SpvImageFormatRgba32i = 21, SpvImageFormatRgba16i = 22, SpvImageFormatRgba8i = 23, SpvImageFormatR32i = 24, SpvImageFormatRg32i = 25, SpvImageFormatRg16i = 26, SpvImageFormatRg8i = 27, SpvImageFormatR16i = 28, SpvImageFormatR8i = 29, SpvImageFormatRgba32ui = 30, SpvImageFormatRgba16ui = 31, SpvImageFormatRgba8ui = 32, SpvImageFormatR32ui = 33, SpvImageFormatRgb10a2ui = 34, SpvImageFormatRg32ui = 35, SpvImageFormatRg16ui = 36, SpvImageFormatRg8ui = 37, SpvImageFormatR16ui = 38, SpvImageFormatR8ui = 39, SpvImageFormatMax = 2147483647, _, }; pub const SpvImageFormat = enum_SpvImageFormat_; pub const SpvImageChannelOrderR = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderR); pub const SpvImageChannelOrderA = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderA); pub const SpvImageChannelOrderRG = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderRG); pub const SpvImageChannelOrderRA = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderRA); pub const SpvImageChannelOrderRGB = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderRGB); pub const SpvImageChannelOrderRGBA = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderRGBA); pub const SpvImageChannelOrderBGRA = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderBGRA); pub const SpvImageChannelOrderARGB = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderARGB); pub const SpvImageChannelOrderIntensity = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderIntensity); pub const SpvImageChannelOrderLuminance = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderLuminance); pub const SpvImageChannelOrderRx = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderRx); pub const SpvImageChannelOrderRGx = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderRGx); pub const SpvImageChannelOrderRGBx = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderRGBx); pub const SpvImageChannelOrderDepth = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderDepth); pub const SpvImageChannelOrderDepthStencil = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderDepthStencil); pub const SpvImageChannelOrdersRGB = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrdersRGB); pub const SpvImageChannelOrdersRGBx = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrdersRGBx); pub const SpvImageChannelOrdersRGBA = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrdersRGBA); pub const SpvImageChannelOrdersBGRA = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrdersBGRA); pub const SpvImageChannelOrderABGR = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderABGR); pub const SpvImageChannelOrderMax = @enumToInt(enum_SpvImageChannelOrder_.SpvImageChannelOrderMax); pub const enum_SpvImageChannelOrder_ = extern enum(c_int) { SpvImageChannelOrderR = 0, SpvImageChannelOrderA = 1, SpvImageChannelOrderRG = 2, SpvImageChannelOrderRA = 3, SpvImageChannelOrderRGB = 4, SpvImageChannelOrderRGBA = 5, SpvImageChannelOrderBGRA = 6, SpvImageChannelOrderARGB = 7, SpvImageChannelOrderIntensity = 8, SpvImageChannelOrderLuminance = 9, SpvImageChannelOrderRx = 10, SpvImageChannelOrderRGx = 11, SpvImageChannelOrderRGBx = 12, SpvImageChannelOrderDepth = 13, SpvImageChannelOrderDepthStencil = 14, SpvImageChannelOrdersRGB = 15, SpvImageChannelOrdersRGBx = 16, SpvImageChannelOrdersRGBA = 17, SpvImageChannelOrdersBGRA = 18, SpvImageChannelOrderABGR = 19, SpvImageChannelOrderMax = 2147483647, _, }; pub const SpvImageChannelOrder = enum_SpvImageChannelOrder_; pub const SpvImageChannelDataTypeSnormInt8 = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeSnormInt8); pub const SpvImageChannelDataTypeSnormInt16 = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeSnormInt16); pub const SpvImageChannelDataTypeUnormInt8 = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeUnormInt8); pub const SpvImageChannelDataTypeUnormInt16 = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeUnormInt16); pub const SpvImageChannelDataTypeUnormShort565 = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeUnormShort565); pub const SpvImageChannelDataTypeUnormShort555 = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeUnormShort555); pub const SpvImageChannelDataTypeUnormInt101010 = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeUnormInt101010); pub const SpvImageChannelDataTypeSignedInt8 = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeSignedInt8); pub const SpvImageChannelDataTypeSignedInt16 = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeSignedInt16); pub const SpvImageChannelDataTypeSignedInt32 = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeSignedInt32); pub const SpvImageChannelDataTypeUnsignedInt8 = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeUnsignedInt8); pub const SpvImageChannelDataTypeUnsignedInt16 = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeUnsignedInt16); pub const SpvImageChannelDataTypeUnsignedInt32 = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeUnsignedInt32); pub const SpvImageChannelDataTypeHalfFloat = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeHalfFloat); pub const SpvImageChannelDataTypeFloat = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeFloat); pub const SpvImageChannelDataTypeUnormInt24 = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeUnormInt24); pub const SpvImageChannelDataTypeUnormInt101010_2 = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeUnormInt101010_2); pub const SpvImageChannelDataTypeMax = @enumToInt(enum_SpvImageChannelDataType_.SpvImageChannelDataTypeMax); pub const enum_SpvImageChannelDataType_ = extern enum(c_int) { SpvImageChannelDataTypeSnormInt8 = 0, SpvImageChannelDataTypeSnormInt16 = 1, SpvImageChannelDataTypeUnormInt8 = 2, SpvImageChannelDataTypeUnormInt16 = 3, SpvImageChannelDataTypeUnormShort565 = 4, SpvImageChannelDataTypeUnormShort555 = 5, SpvImageChannelDataTypeUnormInt101010 = 6, SpvImageChannelDataTypeSignedInt8 = 7, SpvImageChannelDataTypeSignedInt16 = 8, SpvImageChannelDataTypeSignedInt32 = 9, SpvImageChannelDataTypeUnsignedInt8 = 10, SpvImageChannelDataTypeUnsignedInt16 = 11, SpvImageChannelDataTypeUnsignedInt32 = 12, SpvImageChannelDataTypeHalfFloat = 13, SpvImageChannelDataTypeFloat = 14, SpvImageChannelDataTypeUnormInt24 = 15, SpvImageChannelDataTypeUnormInt101010_2 = 16, SpvImageChannelDataTypeMax = 2147483647, _, }; pub const SpvImageChannelDataType = enum_SpvImageChannelDataType_; pub const SpvImageOperandsBiasShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsBiasShift); pub const SpvImageOperandsLodShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsLodShift); pub const SpvImageOperandsGradShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsGradShift); pub const SpvImageOperandsConstOffsetShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsConstOffsetShift); pub const SpvImageOperandsOffsetShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsOffsetShift); pub const SpvImageOperandsConstOffsetsShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsConstOffsetsShift); pub const SpvImageOperandsSampleShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsSampleShift); pub const SpvImageOperandsMinLodShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsMinLodShift); pub const SpvImageOperandsMakeTexelAvailableShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsMakeTexelAvailableShift); pub const SpvImageOperandsMakeTexelAvailableKHRShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsMakeTexelAvailableKHRShift); pub const SpvImageOperandsMakeTexelVisibleShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsMakeTexelVisibleShift); pub const SpvImageOperandsMakeTexelVisibleKHRShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsMakeTexelVisibleKHRShift); pub const SpvImageOperandsNonPrivateTexelShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsNonPrivateTexelShift); pub const SpvImageOperandsNonPrivateTexelKHRShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsNonPrivateTexelKHRShift); pub const SpvImageOperandsVolatileTexelShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsVolatileTexelShift); pub const SpvImageOperandsVolatileTexelKHRShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsVolatileTexelKHRShift); pub const SpvImageOperandsSignExtendShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsSignExtendShift); pub const SpvImageOperandsZeroExtendShift = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsZeroExtendShift); pub const SpvImageOperandsMax = @enumToInt(enum_SpvImageOperandsShift_.SpvImageOperandsMax); pub const enum_SpvImageOperandsShift_ = extern enum(c_int) { SpvImageOperandsBiasShift = 0, SpvImageOperandsLodShift = 1, SpvImageOperandsGradShift = 2, SpvImageOperandsConstOffsetShift = 3, SpvImageOperandsOffsetShift = 4, SpvImageOperandsConstOffsetsShift = 5, SpvImageOperandsSampleShift = 6, SpvImageOperandsMinLodShift = 7, SpvImageOperandsMakeTexelAvailableShift = 8, SpvImageOperandsMakeTexelAvailableKHRShift = 8, SpvImageOperandsMakeTexelVisibleShift = 9, SpvImageOperandsMakeTexelVisibleKHRShift = 9, SpvImageOperandsNonPrivateTexelShift = 10, SpvImageOperandsNonPrivateTexelKHRShift = 10, SpvImageOperandsVolatileTexelShift = 11, SpvImageOperandsVolatileTexelKHRShift = 11, SpvImageOperandsSignExtendShift = 12, SpvImageOperandsZeroExtendShift = 13, SpvImageOperandsMax = 2147483647, _, }; pub const SpvImageOperandsShift = enum_SpvImageOperandsShift_; pub const SpvImageOperandsMaskNone = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsMaskNone); pub const SpvImageOperandsBiasMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsBiasMask); pub const SpvImageOperandsLodMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsLodMask); pub const SpvImageOperandsGradMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsGradMask); pub const SpvImageOperandsConstOffsetMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsConstOffsetMask); pub const SpvImageOperandsOffsetMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsOffsetMask); pub const SpvImageOperandsConstOffsetsMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsConstOffsetsMask); pub const SpvImageOperandsSampleMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsSampleMask); pub const SpvImageOperandsMinLodMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsMinLodMask); pub const SpvImageOperandsMakeTexelAvailableMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsMakeTexelAvailableMask); pub const SpvImageOperandsMakeTexelAvailableKHRMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsMakeTexelAvailableKHRMask); pub const SpvImageOperandsMakeTexelVisibleMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsMakeTexelVisibleMask); pub const SpvImageOperandsMakeTexelVisibleKHRMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsMakeTexelVisibleKHRMask); pub const SpvImageOperandsNonPrivateTexelMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsNonPrivateTexelMask); pub const SpvImageOperandsNonPrivateTexelKHRMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsNonPrivateTexelKHRMask); pub const SpvImageOperandsVolatileTexelMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsVolatileTexelMask); pub const SpvImageOperandsVolatileTexelKHRMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsVolatileTexelKHRMask); pub const SpvImageOperandsSignExtendMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsSignExtendMask); pub const SpvImageOperandsZeroExtendMask = @enumToInt(enum_SpvImageOperandsMask_.SpvImageOperandsZeroExtendMask); pub const enum_SpvImageOperandsMask_ = extern enum(c_int) { SpvImageOperandsMaskNone = 0, SpvImageOperandsBiasMask = 1, SpvImageOperandsLodMask = 2, SpvImageOperandsGradMask = 4, SpvImageOperandsConstOffsetMask = 8, SpvImageOperandsOffsetMask = 16, SpvImageOperandsConstOffsetsMask = 32, SpvImageOperandsSampleMask = 64, SpvImageOperandsMinLodMask = 128, SpvImageOperandsMakeTexelAvailableMask = 256, SpvImageOperandsMakeTexelAvailableKHRMask = 256, SpvImageOperandsMakeTexelVisibleMask = 512, SpvImageOperandsMakeTexelVisibleKHRMask = 512, SpvImageOperandsNonPrivateTexelMask = 1024, SpvImageOperandsNonPrivateTexelKHRMask = 1024, SpvImageOperandsVolatileTexelMask = 2048, SpvImageOperandsVolatileTexelKHRMask = 2048, SpvImageOperandsSignExtendMask = 4096, SpvImageOperandsZeroExtendMask = 8192, _, }; pub const SpvImageOperandsMask = enum_SpvImageOperandsMask_; pub const SpvFPFastMathModeNotNaNShift = @enumToInt(enum_SpvFPFastMathModeShift_.SpvFPFastMathModeNotNaNShift); pub const SpvFPFastMathModeNotInfShift = @enumToInt(enum_SpvFPFastMathModeShift_.SpvFPFastMathModeNotInfShift); pub const SpvFPFastMathModeNSZShift = @enumToInt(enum_SpvFPFastMathModeShift_.SpvFPFastMathModeNSZShift); pub const SpvFPFastMathModeAllowRecipShift = @enumToInt(enum_SpvFPFastMathModeShift_.SpvFPFastMathModeAllowRecipShift); pub const SpvFPFastMathModeFastShift = @enumToInt(enum_SpvFPFastMathModeShift_.SpvFPFastMathModeFastShift); pub const SpvFPFastMathModeMax = @enumToInt(enum_SpvFPFastMathModeShift_.SpvFPFastMathModeMax); pub const enum_SpvFPFastMathModeShift_ = extern enum(c_int) { SpvFPFastMathModeNotNaNShift = 0, SpvFPFastMathModeNotInfShift = 1, SpvFPFastMathModeNSZShift = 2, SpvFPFastMathModeAllowRecipShift = 3, SpvFPFastMathModeFastShift = 4, SpvFPFastMathModeMax = 2147483647, _, }; pub const SpvFPFastMathModeShift = enum_SpvFPFastMathModeShift_; pub const SpvFPFastMathModeMaskNone = @enumToInt(enum_SpvFPFastMathModeMask_.SpvFPFastMathModeMaskNone); pub const SpvFPFastMathModeNotNaNMask = @enumToInt(enum_SpvFPFastMathModeMask_.SpvFPFastMathModeNotNaNMask); pub const SpvFPFastMathModeNotInfMask = @enumToInt(enum_SpvFPFastMathModeMask_.SpvFPFastMathModeNotInfMask); pub const SpvFPFastMathModeNSZMask = @enumToInt(enum_SpvFPFastMathModeMask_.SpvFPFastMathModeNSZMask); pub const SpvFPFastMathModeAllowRecipMask = @enumToInt(enum_SpvFPFastMathModeMask_.SpvFPFastMathModeAllowRecipMask); pub const SpvFPFastMathModeFastMask = @enumToInt(enum_SpvFPFastMathModeMask_.SpvFPFastMathModeFastMask); pub const enum_SpvFPFastMathModeMask_ = extern enum(c_int) { SpvFPFastMathModeMaskNone = 0, SpvFPFastMathModeNotNaNMask = 1, SpvFPFastMathModeNotInfMask = 2, SpvFPFastMathModeNSZMask = 4, SpvFPFastMathModeAllowRecipMask = 8, SpvFPFastMathModeFastMask = 16, _, }; pub const SpvFPFastMathModeMask = enum_SpvFPFastMathModeMask_; pub const SpvFPRoundingModeRTE = @enumToInt(enum_SpvFPRoundingMode_.SpvFPRoundingModeRTE); pub const SpvFPRoundingModeRTZ = @enumToInt(enum_SpvFPRoundingMode_.SpvFPRoundingModeRTZ); pub const SpvFPRoundingModeRTP = @enumToInt(enum_SpvFPRoundingMode_.SpvFPRoundingModeRTP); pub const SpvFPRoundingModeRTN = @enumToInt(enum_SpvFPRoundingMode_.SpvFPRoundingModeRTN); pub const SpvFPRoundingModeMax = @enumToInt(enum_SpvFPRoundingMode_.SpvFPRoundingModeMax); pub const enum_SpvFPRoundingMode_ = extern enum(c_int) { SpvFPRoundingModeRTE = 0, SpvFPRoundingModeRTZ = 1, SpvFPRoundingModeRTP = 2, SpvFPRoundingModeRTN = 3, SpvFPRoundingModeMax = 2147483647, _, }; pub const SpvFPRoundingMode = enum_SpvFPRoundingMode_; pub const SpvLinkageTypeExport = @enumToInt(enum_SpvLinkageType_.SpvLinkageTypeExport); pub const SpvLinkageTypeImport = @enumToInt(enum_SpvLinkageType_.SpvLinkageTypeImport); pub const SpvLinkageTypeMax = @enumToInt(enum_SpvLinkageType_.SpvLinkageTypeMax); pub const enum_SpvLinkageType_ = extern enum(c_int) { SpvLinkageTypeExport = 0, SpvLinkageTypeImport = 1, SpvLinkageTypeMax = 2147483647, _, }; pub const SpvLinkageType = enum_SpvLinkageType_; pub const SpvAccessQualifierReadOnly = @enumToInt(enum_SpvAccessQualifier_.SpvAccessQualifierReadOnly); pub const SpvAccessQualifierWriteOnly = @enumToInt(enum_SpvAccessQualifier_.SpvAccessQualifierWriteOnly); pub const SpvAccessQualifierReadWrite = @enumToInt(enum_SpvAccessQualifier_.SpvAccessQualifierReadWrite); pub const SpvAccessQualifierMax = @enumToInt(enum_SpvAccessQualifier_.SpvAccessQualifierMax); pub const enum_SpvAccessQualifier_ = extern enum(c_int) { SpvAccessQualifierReadOnly = 0, SpvAccessQualifierWriteOnly = 1, SpvAccessQualifierReadWrite = 2, SpvAccessQualifierMax = 2147483647, _, }; pub const SpvAccessQualifier = enum_SpvAccessQualifier_; pub const SpvFunctionParameterAttributeZext = @enumToInt(enum_SpvFunctionParameterAttribute_.SpvFunctionParameterAttributeZext); pub const SpvFunctionParameterAttributeSext = @enumToInt(enum_SpvFunctionParameterAttribute_.SpvFunctionParameterAttributeSext); pub const SpvFunctionParameterAttributeByVal = @enumToInt(enum_SpvFunctionParameterAttribute_.SpvFunctionParameterAttributeByVal); pub const SpvFunctionParameterAttributeSret = @enumToInt(enum_SpvFunctionParameterAttribute_.SpvFunctionParameterAttributeSret); pub const SpvFunctionParameterAttributeNoAlias = @enumToInt(enum_SpvFunctionParameterAttribute_.SpvFunctionParameterAttributeNoAlias); pub const SpvFunctionParameterAttributeNoCapture = @enumToInt(enum_SpvFunctionParameterAttribute_.SpvFunctionParameterAttributeNoCapture); pub const SpvFunctionParameterAttributeNoWrite = @enumToInt(enum_SpvFunctionParameterAttribute_.SpvFunctionParameterAttributeNoWrite); pub const SpvFunctionParameterAttributeNoReadWrite = @enumToInt(enum_SpvFunctionParameterAttribute_.SpvFunctionParameterAttributeNoReadWrite); pub const SpvFunctionParameterAttributeMax = @enumToInt(enum_SpvFunctionParameterAttribute_.SpvFunctionParameterAttributeMax); pub const enum_SpvFunctionParameterAttribute_ = extern enum(c_int) { SpvFunctionParameterAttributeZext = 0, SpvFunctionParameterAttributeSext = 1, SpvFunctionParameterAttributeByVal = 2, SpvFunctionParameterAttributeSret = 3, SpvFunctionParameterAttributeNoAlias = 4, SpvFunctionParameterAttributeNoCapture = 5, SpvFunctionParameterAttributeNoWrite = 6, SpvFunctionParameterAttributeNoReadWrite = 7, SpvFunctionParameterAttributeMax = 2147483647, _, }; pub const SpvFunctionParameterAttribute = enum_SpvFunctionParameterAttribute_; pub const SpvDecorationRelaxedPrecision = @enumToInt(enum_SpvDecoration_.SpvDecorationRelaxedPrecision); pub const SpvDecorationSpecId = @enumToInt(enum_SpvDecoration_.SpvDecorationSpecId); pub const SpvDecorationBlock = @enumToInt(enum_SpvDecoration_.SpvDecorationBlock); pub const SpvDecorationBufferBlock = @enumToInt(enum_SpvDecoration_.SpvDecorationBufferBlock); pub const SpvDecorationRowMajor = @enumToInt(enum_SpvDecoration_.SpvDecorationRowMajor); pub const SpvDecorationColMajor = @enumToInt(enum_SpvDecoration_.SpvDecorationColMajor); pub const SpvDecorationArrayStride = @enumToInt(enum_SpvDecoration_.SpvDecorationArrayStride); pub const SpvDecorationMatrixStride = @enumToInt(enum_SpvDecoration_.SpvDecorationMatrixStride); pub const SpvDecorationGLSLShared = @enumToInt(enum_SpvDecoration_.SpvDecorationGLSLShared); pub const SpvDecorationGLSLPacked = @enumToInt(enum_SpvDecoration_.SpvDecorationGLSLPacked); pub const SpvDecorationCPacked = @enumToInt(enum_SpvDecoration_.SpvDecorationCPacked); pub const SpvDecorationBuiltIn = @enumToInt(enum_SpvDecoration_.SpvDecorationBuiltIn); pub const SpvDecorationNoPerspective = @enumToInt(enum_SpvDecoration_.SpvDecorationNoPerspective); pub const SpvDecorationFlat = @enumToInt(enum_SpvDecoration_.SpvDecorationFlat); pub const SpvDecorationPatch = @enumToInt(enum_SpvDecoration_.SpvDecorationPatch); pub const SpvDecorationCentroid = @enumToInt(enum_SpvDecoration_.SpvDecorationCentroid); pub const SpvDecorationSample = @enumToInt(enum_SpvDecoration_.SpvDecorationSample); pub const SpvDecorationInvariant = @enumToInt(enum_SpvDecoration_.SpvDecorationInvariant); pub const SpvDecorationRestrict = @enumToInt(enum_SpvDecoration_.SpvDecorationRestrict); pub const SpvDecorationAliased = @enumToInt(enum_SpvDecoration_.SpvDecorationAliased); pub const SpvDecorationVolatile = @enumToInt(enum_SpvDecoration_.SpvDecorationVolatile); pub const SpvDecorationConstant = @enumToInt(enum_SpvDecoration_.SpvDecorationConstant); pub const SpvDecorationCoherent = @enumToInt(enum_SpvDecoration_.SpvDecorationCoherent); pub const SpvDecorationNonWritable = @enumToInt(enum_SpvDecoration_.SpvDecorationNonWritable); pub const SpvDecorationNonReadable = @enumToInt(enum_SpvDecoration_.SpvDecorationNonReadable); pub const SpvDecorationUniform = @enumToInt(enum_SpvDecoration_.SpvDecorationUniform); pub const SpvDecorationUniformId = @enumToInt(enum_SpvDecoration_.SpvDecorationUniformId); pub const SpvDecorationSaturatedConversion = @enumToInt(enum_SpvDecoration_.SpvDecorationSaturatedConversion); pub const SpvDecorationStream = @enumToInt(enum_SpvDecoration_.SpvDecorationStream); pub const SpvDecorationLocation = @enumToInt(enum_SpvDecoration_.SpvDecorationLocation); pub const SpvDecorationComponent = @enumToInt(enum_SpvDecoration_.SpvDecorationComponent); pub const SpvDecorationIndex = @enumToInt(enum_SpvDecoration_.SpvDecorationIndex); pub const SpvDecorationBinding = @enumToInt(enum_SpvDecoration_.SpvDecorationBinding); pub const SpvDecorationDescriptorSet = @enumToInt(enum_SpvDecoration_.SpvDecorationDescriptorSet); pub const SpvDecorationOffset = @enumToInt(enum_SpvDecoration_.SpvDecorationOffset); pub const SpvDecorationXfbBuffer = @enumToInt(enum_SpvDecoration_.SpvDecorationXfbBuffer); pub const SpvDecorationXfbStride = @enumToInt(enum_SpvDecoration_.SpvDecorationXfbStride); pub const SpvDecorationFuncParamAttr = @enumToInt(enum_SpvDecoration_.SpvDecorationFuncParamAttr); pub const SpvDecorationFPRoundingMode = @enumToInt(enum_SpvDecoration_.SpvDecorationFPRoundingMode); pub const SpvDecorationFPFastMathMode = @enumToInt(enum_SpvDecoration_.SpvDecorationFPFastMathMode); pub const SpvDecorationLinkageAttributes = @enumToInt(enum_SpvDecoration_.SpvDecorationLinkageAttributes); pub const SpvDecorationNoContraction = @enumToInt(enum_SpvDecoration_.SpvDecorationNoContraction); pub const SpvDecorationInputAttachmentIndex = @enumToInt(enum_SpvDecoration_.SpvDecorationInputAttachmentIndex); pub const SpvDecorationAlignment = @enumToInt(enum_SpvDecoration_.SpvDecorationAlignment); pub const SpvDecorationMaxByteOffset = @enumToInt(enum_SpvDecoration_.SpvDecorationMaxByteOffset); pub const SpvDecorationAlignmentId = @enumToInt(enum_SpvDecoration_.SpvDecorationAlignmentId); pub const SpvDecorationMaxByteOffsetId = @enumToInt(enum_SpvDecoration_.SpvDecorationMaxByteOffsetId); pub const SpvDecorationNoSignedWrap = @enumToInt(enum_SpvDecoration_.SpvDecorationNoSignedWrap); pub const SpvDecorationNoUnsignedWrap = @enumToInt(enum_SpvDecoration_.SpvDecorationNoUnsignedWrap); pub const SpvDecorationExplicitInterpAMD = @enumToInt(enum_SpvDecoration_.SpvDecorationExplicitInterpAMD); pub const SpvDecorationOverrideCoverageNV = @enumToInt(enum_SpvDecoration_.SpvDecorationOverrideCoverageNV); pub const SpvDecorationPassthroughNV = @enumToInt(enum_SpvDecoration_.SpvDecorationPassthroughNV); pub const SpvDecorationViewportRelativeNV = @enumToInt(enum_SpvDecoration_.SpvDecorationViewportRelativeNV); pub const SpvDecorationSecondaryViewportRelativeNV = @enumToInt(enum_SpvDecoration_.SpvDecorationSecondaryViewportRelativeNV); pub const SpvDecorationPerPrimitiveNV = @enumToInt(enum_SpvDecoration_.SpvDecorationPerPrimitiveNV); pub const SpvDecorationPerViewNV = @enumToInt(enum_SpvDecoration_.SpvDecorationPerViewNV); pub const SpvDecorationPerTaskNV = @enumToInt(enum_SpvDecoration_.SpvDecorationPerTaskNV); pub const SpvDecorationPerVertexNV = @enumToInt(enum_SpvDecoration_.SpvDecorationPerVertexNV); pub const SpvDecorationNonUniform = @enumToInt(enum_SpvDecoration_.SpvDecorationNonUniform); pub const SpvDecorationNonUniformEXT = @enumToInt(enum_SpvDecoration_.SpvDecorationNonUniformEXT); pub const SpvDecorationRestrictPointer = @enumToInt(enum_SpvDecoration_.SpvDecorationRestrictPointer); pub const SpvDecorationRestrictPointerEXT = @enumToInt(enum_SpvDecoration_.SpvDecorationRestrictPointerEXT); pub const SpvDecorationAliasedPointer = @enumToInt(enum_SpvDecoration_.SpvDecorationAliasedPointer); pub const SpvDecorationAliasedPointerEXT = @enumToInt(enum_SpvDecoration_.SpvDecorationAliasedPointerEXT); pub const SpvDecorationReferencedIndirectlyINTEL = @enumToInt(enum_SpvDecoration_.SpvDecorationReferencedIndirectlyINTEL); pub const SpvDecorationCounterBuffer = @enumToInt(enum_SpvDecoration_.SpvDecorationCounterBuffer); pub const SpvDecorationHlslCounterBufferGOOGLE = @enumToInt(enum_SpvDecoration_.SpvDecorationHlslCounterBufferGOOGLE); pub const SpvDecorationHlslSemanticGOOGLE = @enumToInt(enum_SpvDecoration_.SpvDecorationHlslSemanticGOOGLE); pub const SpvDecorationUserSemantic = @enumToInt(enum_SpvDecoration_.SpvDecorationUserSemantic); pub const SpvDecorationUserTypeGOOGLE = @enumToInt(enum_SpvDecoration_.SpvDecorationUserTypeGOOGLE); pub const SpvDecorationRegisterINTEL = @enumToInt(enum_SpvDecoration_.SpvDecorationRegisterINTEL); pub const SpvDecorationMemoryINTEL = @enumToInt(enum_SpvDecoration_.SpvDecorationMemoryINTEL); pub const SpvDecorationNumbanksINTEL = @enumToInt(enum_SpvDecoration_.SpvDecorationNumbanksINTEL); pub const SpvDecorationBankwidthINTEL = @enumToInt(enum_SpvDecoration_.SpvDecorationBankwidthINTEL); pub const SpvDecorationMaxPrivateCopiesINTEL = @enumToInt(enum_SpvDecoration_.SpvDecorationMaxPrivateCopiesINTEL); pub const SpvDecorationSinglepumpINTEL = @enumToInt(enum_SpvDecoration_.SpvDecorationSinglepumpINTEL); pub const SpvDecorationDoublepumpINTEL = @enumToInt(enum_SpvDecoration_.SpvDecorationDoublepumpINTEL); pub const SpvDecorationMaxReplicatesINTEL = @enumToInt(enum_SpvDecoration_.SpvDecorationMaxReplicatesINTEL); pub const SpvDecorationSimpleDualPortINTEL = @enumToInt(enum_SpvDecoration_.SpvDecorationSimpleDualPortINTEL); pub const SpvDecorationMergeINTEL = @enumToInt(enum_SpvDecoration_.SpvDecorationMergeINTEL); pub const SpvDecorationBankBitsINTEL = @enumToInt(enum_SpvDecoration_.SpvDecorationBankBitsINTEL); pub const SpvDecorationForcePow2DepthINTEL = @enumToInt(enum_SpvDecoration_.SpvDecorationForcePow2DepthINTEL); pub const SpvDecorationMax = @enumToInt(enum_SpvDecoration_.SpvDecorationMax); pub const enum_SpvDecoration_ = extern enum(c_int) { SpvDecorationRelaxedPrecision = 0, SpvDecorationSpecId = 1, SpvDecorationBlock = 2, SpvDecorationBufferBlock = 3, SpvDecorationRowMajor = 4, SpvDecorationColMajor = 5, SpvDecorationArrayStride = 6, SpvDecorationMatrixStride = 7, SpvDecorationGLSLShared = 8, SpvDecorationGLSLPacked = 9, SpvDecorationCPacked = 10, SpvDecorationBuiltIn = 11, SpvDecorationNoPerspective = 13, SpvDecorationFlat = 14, SpvDecorationPatch = 15, SpvDecorationCentroid = 16, SpvDecorationSample = 17, SpvDecorationInvariant = 18, SpvDecorationRestrict = 19, SpvDecorationAliased = 20, SpvDecorationVolatile = 21, SpvDecorationConstant = 22, SpvDecorationCoherent = 23, SpvDecorationNonWritable = 24, SpvDecorationNonReadable = 25, SpvDecorationUniform = 26, SpvDecorationUniformId = 27, SpvDecorationSaturatedConversion = 28, SpvDecorationStream = 29, SpvDecorationLocation = 30, SpvDecorationComponent = 31, SpvDecorationIndex = 32, SpvDecorationBinding = 33, SpvDecorationDescriptorSet = 34, SpvDecorationOffset = 35, SpvDecorationXfbBuffer = 36, SpvDecorationXfbStride = 37, SpvDecorationFuncParamAttr = 38, SpvDecorationFPRoundingMode = 39, SpvDecorationFPFastMathMode = 40, SpvDecorationLinkageAttributes = 41, SpvDecorationNoContraction = 42, SpvDecorationInputAttachmentIndex = 43, SpvDecorationAlignment = 44, SpvDecorationMaxByteOffset = 45, SpvDecorationAlignmentId = 46, SpvDecorationMaxByteOffsetId = 47, SpvDecorationNoSignedWrap = 4469, SpvDecorationNoUnsignedWrap = 4470, SpvDecorationExplicitInterpAMD = 4999, SpvDecorationOverrideCoverageNV = 5248, SpvDecorationPassthroughNV = 5250, SpvDecorationViewportRelativeNV = 5252, SpvDecorationSecondaryViewportRelativeNV = 5256, SpvDecorationPerPrimitiveNV = 5271, SpvDecorationPerViewNV = 5272, SpvDecorationPerTaskNV = 5273, SpvDecorationPerVertexNV = 5285, SpvDecorationNonUniform = 5300, SpvDecorationNonUniformEXT = 5300, SpvDecorationRestrictPointer = 5355, SpvDecorationRestrictPointerEXT = 5355, SpvDecorationAliasedPointer = 5356, SpvDecorationAliasedPointerEXT = 5356, SpvDecorationReferencedIndirectlyINTEL = 5602, SpvDecorationCounterBuffer = 5634, SpvDecorationHlslCounterBufferGOOGLE = 5634, SpvDecorationHlslSemanticGOOGLE = 5635, SpvDecorationUserSemantic = 5635, SpvDecorationUserTypeGOOGLE = 5636, SpvDecorationRegisterINTEL = 5825, SpvDecorationMemoryINTEL = 5826, SpvDecorationNumbanksINTEL = 5827, SpvDecorationBankwidthINTEL = 5828, SpvDecorationMaxPrivateCopiesINTEL = 5829, SpvDecorationSinglepumpINTEL = 5830, SpvDecorationDoublepumpINTEL = 5831, SpvDecorationMaxReplicatesINTEL = 5832, SpvDecorationSimpleDualPortINTEL = 5833, SpvDecorationMergeINTEL = 5834, SpvDecorationBankBitsINTEL = 5835, SpvDecorationForcePow2DepthINTEL = 5836, SpvDecorationMax = 2147483647, _, }; pub const SpvDecoration = enum_SpvDecoration_; pub const SpvBuiltInPosition = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInPosition); pub const SpvBuiltInPointSize = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInPointSize); pub const SpvBuiltInClipDistance = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInClipDistance); pub const SpvBuiltInCullDistance = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInCullDistance); pub const SpvBuiltInVertexId = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInVertexId); pub const SpvBuiltInInstanceId = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInInstanceId); pub const SpvBuiltInPrimitiveId = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInPrimitiveId); pub const SpvBuiltInInvocationId = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInInvocationId); pub const SpvBuiltInLayer = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInLayer); pub const SpvBuiltInViewportIndex = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInViewportIndex); pub const SpvBuiltInTessLevelOuter = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInTessLevelOuter); pub const SpvBuiltInTessLevelInner = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInTessLevelInner); pub const SpvBuiltInTessCoord = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInTessCoord); pub const SpvBuiltInPatchVertices = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInPatchVertices); pub const SpvBuiltInFragCoord = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInFragCoord); pub const SpvBuiltInPointCoord = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInPointCoord); pub const SpvBuiltInFrontFacing = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInFrontFacing); pub const SpvBuiltInSampleId = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSampleId); pub const SpvBuiltInSamplePosition = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSamplePosition); pub const SpvBuiltInSampleMask = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSampleMask); pub const SpvBuiltInFragDepth = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInFragDepth); pub const SpvBuiltInHelperInvocation = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInHelperInvocation); pub const SpvBuiltInNumWorkgroups = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInNumWorkgroups); pub const SpvBuiltInWorkgroupSize = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInWorkgroupSize); pub const SpvBuiltInWorkgroupId = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInWorkgroupId); pub const SpvBuiltInLocalInvocationId = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInLocalInvocationId); pub const SpvBuiltInGlobalInvocationId = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInGlobalInvocationId); pub const SpvBuiltInLocalInvocationIndex = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInLocalInvocationIndex); pub const SpvBuiltInWorkDim = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInWorkDim); pub const SpvBuiltInGlobalSize = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInGlobalSize); pub const SpvBuiltInEnqueuedWorkgroupSize = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInEnqueuedWorkgroupSize); pub const SpvBuiltInGlobalOffset = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInGlobalOffset); pub const SpvBuiltInGlobalLinearId = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInGlobalLinearId); pub const SpvBuiltInSubgroupSize = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSubgroupSize); pub const SpvBuiltInSubgroupMaxSize = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSubgroupMaxSize); pub const SpvBuiltInNumSubgroups = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInNumSubgroups); pub const SpvBuiltInNumEnqueuedSubgroups = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInNumEnqueuedSubgroups); pub const SpvBuiltInSubgroupId = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSubgroupId); pub const SpvBuiltInSubgroupLocalInvocationId = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSubgroupLocalInvocationId); pub const SpvBuiltInVertexIndex = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInVertexIndex); pub const SpvBuiltInInstanceIndex = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInInstanceIndex); pub const SpvBuiltInSubgroupEqMask = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSubgroupEqMask); pub const SpvBuiltInSubgroupEqMaskKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSubgroupEqMaskKHR); pub const SpvBuiltInSubgroupGeMask = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSubgroupGeMask); pub const SpvBuiltInSubgroupGeMaskKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSubgroupGeMaskKHR); pub const SpvBuiltInSubgroupGtMask = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSubgroupGtMask); pub const SpvBuiltInSubgroupGtMaskKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSubgroupGtMaskKHR); pub const SpvBuiltInSubgroupLeMask = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSubgroupLeMask); pub const SpvBuiltInSubgroupLeMaskKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSubgroupLeMaskKHR); pub const SpvBuiltInSubgroupLtMask = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSubgroupLtMask); pub const SpvBuiltInSubgroupLtMaskKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSubgroupLtMaskKHR); pub const SpvBuiltInBaseVertex = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInBaseVertex); pub const SpvBuiltInBaseInstance = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInBaseInstance); pub const SpvBuiltInDrawIndex = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInDrawIndex); pub const SpvBuiltInDeviceIndex = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInDeviceIndex); pub const SpvBuiltInViewIndex = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInViewIndex); pub const SpvBuiltInBaryCoordNoPerspAMD = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInBaryCoordNoPerspAMD); pub const SpvBuiltInBaryCoordNoPerspCentroidAMD = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInBaryCoordNoPerspCentroidAMD); pub const SpvBuiltInBaryCoordNoPerspSampleAMD = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInBaryCoordNoPerspSampleAMD); pub const SpvBuiltInBaryCoordSmoothAMD = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInBaryCoordSmoothAMD); pub const SpvBuiltInBaryCoordSmoothCentroidAMD = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInBaryCoordSmoothCentroidAMD); pub const SpvBuiltInBaryCoordSmoothSampleAMD = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInBaryCoordSmoothSampleAMD); pub const SpvBuiltInBaryCoordPullModelAMD = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInBaryCoordPullModelAMD); pub const SpvBuiltInFragStencilRefEXT = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInFragStencilRefEXT); pub const SpvBuiltInViewportMaskNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInViewportMaskNV); pub const SpvBuiltInSecondaryPositionNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSecondaryPositionNV); pub const SpvBuiltInSecondaryViewportMaskNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSecondaryViewportMaskNV); pub const SpvBuiltInPositionPerViewNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInPositionPerViewNV); pub const SpvBuiltInViewportMaskPerViewNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInViewportMaskPerViewNV); pub const SpvBuiltInFullyCoveredEXT = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInFullyCoveredEXT); pub const SpvBuiltInTaskCountNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInTaskCountNV); pub const SpvBuiltInPrimitiveCountNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInPrimitiveCountNV); pub const SpvBuiltInPrimitiveIndicesNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInPrimitiveIndicesNV); pub const SpvBuiltInClipDistancePerViewNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInClipDistancePerViewNV); pub const SpvBuiltInCullDistancePerViewNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInCullDistancePerViewNV); pub const SpvBuiltInLayerPerViewNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInLayerPerViewNV); pub const SpvBuiltInMeshViewCountNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInMeshViewCountNV); pub const SpvBuiltInMeshViewIndicesNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInMeshViewIndicesNV); pub const SpvBuiltInBaryCoordNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInBaryCoordNV); pub const SpvBuiltInBaryCoordNoPerspNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInBaryCoordNoPerspNV); pub const SpvBuiltInFragSizeEXT = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInFragSizeEXT); pub const SpvBuiltInFragmentSizeNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInFragmentSizeNV); pub const SpvBuiltInFragInvocationCountEXT = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInFragInvocationCountEXT); pub const SpvBuiltInInvocationsPerPixelNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInInvocationsPerPixelNV); pub const SpvBuiltInLaunchIdKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInLaunchIdKHR); pub const SpvBuiltInLaunchIdNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInLaunchIdNV); pub const SpvBuiltInLaunchSizeKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInLaunchSizeKHR); pub const SpvBuiltInLaunchSizeNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInLaunchSizeNV); pub const SpvBuiltInWorldRayOriginKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInWorldRayOriginKHR); pub const SpvBuiltInWorldRayOriginNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInWorldRayOriginNV); pub const SpvBuiltInWorldRayDirectionKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInWorldRayDirectionKHR); pub const SpvBuiltInWorldRayDirectionNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInWorldRayDirectionNV); pub const SpvBuiltInObjectRayOriginKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInObjectRayOriginKHR); pub const SpvBuiltInObjectRayOriginNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInObjectRayOriginNV); pub const SpvBuiltInObjectRayDirectionKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInObjectRayDirectionKHR); pub const SpvBuiltInObjectRayDirectionNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInObjectRayDirectionNV); pub const SpvBuiltInRayTminKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInRayTminKHR); pub const SpvBuiltInRayTminNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInRayTminNV); pub const SpvBuiltInRayTmaxKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInRayTmaxKHR); pub const SpvBuiltInRayTmaxNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInRayTmaxNV); pub const SpvBuiltInInstanceCustomIndexKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInInstanceCustomIndexKHR); pub const SpvBuiltInInstanceCustomIndexNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInInstanceCustomIndexNV); pub const SpvBuiltInObjectToWorldKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInObjectToWorldKHR); pub const SpvBuiltInObjectToWorldNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInObjectToWorldNV); pub const SpvBuiltInWorldToObjectKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInWorldToObjectKHR); pub const SpvBuiltInWorldToObjectNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInWorldToObjectNV); pub const SpvBuiltInHitTKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInHitTKHR); pub const SpvBuiltInHitTNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInHitTNV); pub const SpvBuiltInHitKindKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInHitKindKHR); pub const SpvBuiltInHitKindNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInHitKindNV); pub const SpvBuiltInIncomingRayFlagsKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInIncomingRayFlagsKHR); pub const SpvBuiltInIncomingRayFlagsNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInIncomingRayFlagsNV); pub const SpvBuiltInRayGeometryIndexKHR = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInRayGeometryIndexKHR); pub const SpvBuiltInWarpsPerSMNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInWarpsPerSMNV); pub const SpvBuiltInSMCountNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSMCountNV); pub const SpvBuiltInWarpIDNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInWarpIDNV); pub const SpvBuiltInSMIDNV = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInSMIDNV); pub const SpvBuiltInMax = @enumToInt(enum_SpvBuiltIn_.SpvBuiltInMax); pub const enum_SpvBuiltIn_ = extern enum(c_int) { SpvBuiltInPosition = 0, SpvBuiltInPointSize = 1, SpvBuiltInClipDistance = 3, SpvBuiltInCullDistance = 4, SpvBuiltInVertexId = 5, SpvBuiltInInstanceId = 6, SpvBuiltInPrimitiveId = 7, SpvBuiltInInvocationId = 8, SpvBuiltInLayer = 9, SpvBuiltInViewportIndex = 10, SpvBuiltInTessLevelOuter = 11, SpvBuiltInTessLevelInner = 12, SpvBuiltInTessCoord = 13, SpvBuiltInPatchVertices = 14, SpvBuiltInFragCoord = 15, SpvBuiltInPointCoord = 16, SpvBuiltInFrontFacing = 17, SpvBuiltInSampleId = 18, SpvBuiltInSamplePosition = 19, SpvBuiltInSampleMask = 20, SpvBuiltInFragDepth = 22, SpvBuiltInHelperInvocation = 23, SpvBuiltInNumWorkgroups = 24, SpvBuiltInWorkgroupSize = 25, SpvBuiltInWorkgroupId = 26, SpvBuiltInLocalInvocationId = 27, SpvBuiltInGlobalInvocationId = 28, SpvBuiltInLocalInvocationIndex = 29, SpvBuiltInWorkDim = 30, SpvBuiltInGlobalSize = 31, SpvBuiltInEnqueuedWorkgroupSize = 32, SpvBuiltInGlobalOffset = 33, SpvBuiltInGlobalLinearId = 34, SpvBuiltInSubgroupSize = 36, SpvBuiltInSubgroupMaxSize = 37, SpvBuiltInNumSubgroups = 38, SpvBuiltInNumEnqueuedSubgroups = 39, SpvBuiltInSubgroupId = 40, SpvBuiltInSubgroupLocalInvocationId = 41, SpvBuiltInVertexIndex = 42, SpvBuiltInInstanceIndex = 43, SpvBuiltInSubgroupEqMask = 4416, SpvBuiltInSubgroupEqMaskKHR = 4416, SpvBuiltInSubgroupGeMask = 4417, SpvBuiltInSubgroupGeMaskKHR = 4417, SpvBuiltInSubgroupGtMask = 4418, SpvBuiltInSubgroupGtMaskKHR = 4418, SpvBuiltInSubgroupLeMask = 4419, SpvBuiltInSubgroupLeMaskKHR = 4419, SpvBuiltInSubgroupLtMask = 4420, SpvBuiltInSubgroupLtMaskKHR = 4420, SpvBuiltInBaseVertex = 4424, SpvBuiltInBaseInstance = 4425, SpvBuiltInDrawIndex = 4426, SpvBuiltInDeviceIndex = 4438, SpvBuiltInViewIndex = 4440, SpvBuiltInBaryCoordNoPerspAMD = 4992, SpvBuiltInBaryCoordNoPerspCentroidAMD = 4993, SpvBuiltInBaryCoordNoPerspSampleAMD = 4994, SpvBuiltInBaryCoordSmoothAMD = 4995, SpvBuiltInBaryCoordSmoothCentroidAMD = 4996, SpvBuiltInBaryCoordSmoothSampleAMD = 4997, SpvBuiltInBaryCoordPullModelAMD = 4998, SpvBuiltInFragStencilRefEXT = 5014, SpvBuiltInViewportMaskNV = 5253, SpvBuiltInSecondaryPositionNV = 5257, SpvBuiltInSecondaryViewportMaskNV = 5258, SpvBuiltInPositionPerViewNV = 5261, SpvBuiltInViewportMaskPerViewNV = 5262, SpvBuiltInFullyCoveredEXT = 5264, SpvBuiltInTaskCountNV = 5274, SpvBuiltInPrimitiveCountNV = 5275, SpvBuiltInPrimitiveIndicesNV = 5276, SpvBuiltInClipDistancePerViewNV = 5277, SpvBuiltInCullDistancePerViewNV = 5278, SpvBuiltInLayerPerViewNV = 5279, SpvBuiltInMeshViewCountNV = 5280, SpvBuiltInMeshViewIndicesNV = 5281, SpvBuiltInBaryCoordNV = 5286, SpvBuiltInBaryCoordNoPerspNV = 5287, SpvBuiltInFragSizeEXT = 5292, SpvBuiltInFragmentSizeNV = 5292, SpvBuiltInFragInvocationCountEXT = 5293, SpvBuiltInInvocationsPerPixelNV = 5293, SpvBuiltInLaunchIdKHR = 5319, SpvBuiltInLaunchIdNV = 5319, SpvBuiltInLaunchSizeKHR = 5320, SpvBuiltInLaunchSizeNV = 5320, SpvBuiltInWorldRayOriginKHR = 5321, SpvBuiltInWorldRayOriginNV = 5321, SpvBuiltInWorldRayDirectionKHR = 5322, SpvBuiltInWorldRayDirectionNV = 5322, SpvBuiltInObjectRayOriginKHR = 5323, SpvBuiltInObjectRayOriginNV = 5323, SpvBuiltInObjectRayDirectionKHR = 5324, SpvBuiltInObjectRayDirectionNV = 5324, SpvBuiltInRayTminKHR = 5325, SpvBuiltInRayTminNV = 5325, SpvBuiltInRayTmaxKHR = 5326, SpvBuiltInRayTmaxNV = 5326, SpvBuiltInInstanceCustomIndexKHR = 5327, SpvBuiltInInstanceCustomIndexNV = 5327, SpvBuiltInObjectToWorldKHR = 5330, SpvBuiltInObjectToWorldNV = 5330, SpvBuiltInWorldToObjectKHR = 5331, SpvBuiltInWorldToObjectNV = 5331, SpvBuiltInHitTKHR = 5332, SpvBuiltInHitTNV = 5332, SpvBuiltInHitKindKHR = 5333, SpvBuiltInHitKindNV = 5333, SpvBuiltInIncomingRayFlagsKHR = 5351, SpvBuiltInIncomingRayFlagsNV = 5351, SpvBuiltInRayGeometryIndexKHR = 5352, SpvBuiltInWarpsPerSMNV = 5374, SpvBuiltInSMCountNV = 5375, SpvBuiltInWarpIDNV = 5376, SpvBuiltInSMIDNV = 5377, SpvBuiltInMax = 2147483647, _, }; pub const SpvBuiltIn = enum_SpvBuiltIn_; pub const SpvSelectionControlFlattenShift = @enumToInt(enum_SpvSelectionControlShift_.SpvSelectionControlFlattenShift); pub const SpvSelectionControlDontFlattenShift = @enumToInt(enum_SpvSelectionControlShift_.SpvSelectionControlDontFlattenShift); pub const SpvSelectionControlMax = @enumToInt(enum_SpvSelectionControlShift_.SpvSelectionControlMax); pub const enum_SpvSelectionControlShift_ = extern enum(c_int) { SpvSelectionControlFlattenShift = 0, SpvSelectionControlDontFlattenShift = 1, SpvSelectionControlMax = 2147483647, _, }; pub const SpvSelectionControlShift = enum_SpvSelectionControlShift_; pub const SpvSelectionControlMaskNone = @enumToInt(enum_SpvSelectionControlMask_.SpvSelectionControlMaskNone); pub const SpvSelectionControlFlattenMask = @enumToInt(enum_SpvSelectionControlMask_.SpvSelectionControlFlattenMask); pub const SpvSelectionControlDontFlattenMask = @enumToInt(enum_SpvSelectionControlMask_.SpvSelectionControlDontFlattenMask); pub const enum_SpvSelectionControlMask_ = extern enum(c_int) { SpvSelectionControlMaskNone = 0, SpvSelectionControlFlattenMask = 1, SpvSelectionControlDontFlattenMask = 2, _, }; pub const SpvSelectionControlMask = enum_SpvSelectionControlMask_; pub const SpvLoopControlUnrollShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlUnrollShift); pub const SpvLoopControlDontUnrollShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlDontUnrollShift); pub const SpvLoopControlDependencyInfiniteShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlDependencyInfiniteShift); pub const SpvLoopControlDependencyLengthShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlDependencyLengthShift); pub const SpvLoopControlMinIterationsShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlMinIterationsShift); pub const SpvLoopControlMaxIterationsShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlMaxIterationsShift); pub const SpvLoopControlIterationMultipleShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlIterationMultipleShift); pub const SpvLoopControlPeelCountShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlPeelCountShift); pub const SpvLoopControlPartialCountShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlPartialCountShift); pub const SpvLoopControlInitiationIntervalINTELShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlInitiationIntervalINTELShift); pub const SpvLoopControlMaxConcurrencyINTELShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlMaxConcurrencyINTELShift); pub const SpvLoopControlDependencyArrayINTELShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlDependencyArrayINTELShift); pub const SpvLoopControlPipelineEnableINTELShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlPipelineEnableINTELShift); pub const SpvLoopControlLoopCoalesceINTELShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlLoopCoalesceINTELShift); pub const SpvLoopControlMaxInterleavingINTELShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlMaxInterleavingINTELShift); pub const SpvLoopControlSpeculatedIterationsINTELShift = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlSpeculatedIterationsINTELShift); pub const SpvLoopControlMax = @enumToInt(enum_SpvLoopControlShift_.SpvLoopControlMax); pub const enum_SpvLoopControlShift_ = extern enum(c_int) { SpvLoopControlUnrollShift = 0, SpvLoopControlDontUnrollShift = 1, SpvLoopControlDependencyInfiniteShift = 2, SpvLoopControlDependencyLengthShift = 3, SpvLoopControlMinIterationsShift = 4, SpvLoopControlMaxIterationsShift = 5, SpvLoopControlIterationMultipleShift = 6, SpvLoopControlPeelCountShift = 7, SpvLoopControlPartialCountShift = 8, SpvLoopControlInitiationIntervalINTELShift = 16, SpvLoopControlMaxConcurrencyINTELShift = 17, SpvLoopControlDependencyArrayINTELShift = 18, SpvLoopControlPipelineEnableINTELShift = 19, SpvLoopControlLoopCoalesceINTELShift = 20, SpvLoopControlMaxInterleavingINTELShift = 21, SpvLoopControlSpeculatedIterationsINTELShift = 22, SpvLoopControlMax = 2147483647, _, }; pub const SpvLoopControlShift = enum_SpvLoopControlShift_; pub const SpvLoopControlMaskNone = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlMaskNone); pub const SpvLoopControlUnrollMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlUnrollMask); pub const SpvLoopControlDontUnrollMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlDontUnrollMask); pub const SpvLoopControlDependencyInfiniteMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlDependencyInfiniteMask); pub const SpvLoopControlDependencyLengthMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlDependencyLengthMask); pub const SpvLoopControlMinIterationsMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlMinIterationsMask); pub const SpvLoopControlMaxIterationsMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlMaxIterationsMask); pub const SpvLoopControlIterationMultipleMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlIterationMultipleMask); pub const SpvLoopControlPeelCountMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlPeelCountMask); pub const SpvLoopControlPartialCountMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlPartialCountMask); pub const SpvLoopControlInitiationIntervalINTELMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlInitiationIntervalINTELMask); pub const SpvLoopControlMaxConcurrencyINTELMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlMaxConcurrencyINTELMask); pub const SpvLoopControlDependencyArrayINTELMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlDependencyArrayINTELMask); pub const SpvLoopControlPipelineEnableINTELMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlPipelineEnableINTELMask); pub const SpvLoopControlLoopCoalesceINTELMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlLoopCoalesceINTELMask); pub const SpvLoopControlMaxInterleavingINTELMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlMaxInterleavingINTELMask); pub const SpvLoopControlSpeculatedIterationsINTELMask = @enumToInt(enum_SpvLoopControlMask_.SpvLoopControlSpeculatedIterationsINTELMask); pub const enum_SpvLoopControlMask_ = extern enum(c_int) { SpvLoopControlMaskNone = 0, SpvLoopControlUnrollMask = 1, SpvLoopControlDontUnrollMask = 2, SpvLoopControlDependencyInfiniteMask = 4, SpvLoopControlDependencyLengthMask = 8, SpvLoopControlMinIterationsMask = 16, SpvLoopControlMaxIterationsMask = 32, SpvLoopControlIterationMultipleMask = 64, SpvLoopControlPeelCountMask = 128, SpvLoopControlPartialCountMask = 256, SpvLoopControlInitiationIntervalINTELMask = 65536, SpvLoopControlMaxConcurrencyINTELMask = 131072, SpvLoopControlDependencyArrayINTELMask = 262144, SpvLoopControlPipelineEnableINTELMask = 524288, SpvLoopControlLoopCoalesceINTELMask = 1048576, SpvLoopControlMaxInterleavingINTELMask = 2097152, SpvLoopControlSpeculatedIterationsINTELMask = 4194304, _, }; pub const SpvLoopControlMask = enum_SpvLoopControlMask_; pub const SpvFunctionControlInlineShift = @enumToInt(enum_SpvFunctionControlShift_.SpvFunctionControlInlineShift); pub const SpvFunctionControlDontInlineShift = @enumToInt(enum_SpvFunctionControlShift_.SpvFunctionControlDontInlineShift); pub const SpvFunctionControlPureShift = @enumToInt(enum_SpvFunctionControlShift_.SpvFunctionControlPureShift); pub const SpvFunctionControlConstShift = @enumToInt(enum_SpvFunctionControlShift_.SpvFunctionControlConstShift); pub const SpvFunctionControlMax = @enumToInt(enum_SpvFunctionControlShift_.SpvFunctionControlMax); pub const enum_SpvFunctionControlShift_ = extern enum(c_int) { SpvFunctionControlInlineShift = 0, SpvFunctionControlDontInlineShift = 1, SpvFunctionControlPureShift = 2, SpvFunctionControlConstShift = 3, SpvFunctionControlMax = 2147483647, _, }; pub const SpvFunctionControlShift = enum_SpvFunctionControlShift_; pub const SpvFunctionControlMaskNone = @enumToInt(enum_SpvFunctionControlMask_.SpvFunctionControlMaskNone); pub const SpvFunctionControlInlineMask = @enumToInt(enum_SpvFunctionControlMask_.SpvFunctionControlInlineMask); pub const SpvFunctionControlDontInlineMask = @enumToInt(enum_SpvFunctionControlMask_.SpvFunctionControlDontInlineMask); pub const SpvFunctionControlPureMask = @enumToInt(enum_SpvFunctionControlMask_.SpvFunctionControlPureMask); pub const SpvFunctionControlConstMask = @enumToInt(enum_SpvFunctionControlMask_.SpvFunctionControlConstMask); pub const enum_SpvFunctionControlMask_ = extern enum(c_int) { SpvFunctionControlMaskNone = 0, SpvFunctionControlInlineMask = 1, SpvFunctionControlDontInlineMask = 2, SpvFunctionControlPureMask = 4, SpvFunctionControlConstMask = 8, _, }; pub const SpvFunctionControlMask = enum_SpvFunctionControlMask_; pub const SpvMemorySemanticsAcquireShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsAcquireShift); pub const SpvMemorySemanticsReleaseShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsReleaseShift); pub const SpvMemorySemanticsAcquireReleaseShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsAcquireReleaseShift); pub const SpvMemorySemanticsSequentiallyConsistentShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsSequentiallyConsistentShift); pub const SpvMemorySemanticsUniformMemoryShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsUniformMemoryShift); pub const SpvMemorySemanticsSubgroupMemoryShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsSubgroupMemoryShift); pub const SpvMemorySemanticsWorkgroupMemoryShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsWorkgroupMemoryShift); pub const SpvMemorySemanticsCrossWorkgroupMemoryShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsCrossWorkgroupMemoryShift); pub const SpvMemorySemanticsAtomicCounterMemoryShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsAtomicCounterMemoryShift); pub const SpvMemorySemanticsImageMemoryShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsImageMemoryShift); pub const SpvMemorySemanticsOutputMemoryShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsOutputMemoryShift); pub const SpvMemorySemanticsOutputMemoryKHRShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsOutputMemoryKHRShift); pub const SpvMemorySemanticsMakeAvailableShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsMakeAvailableShift); pub const SpvMemorySemanticsMakeAvailableKHRShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsMakeAvailableKHRShift); pub const SpvMemorySemanticsMakeVisibleShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsMakeVisibleShift); pub const SpvMemorySemanticsMakeVisibleKHRShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsMakeVisibleKHRShift); pub const SpvMemorySemanticsVolatileShift = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsVolatileShift); pub const SpvMemorySemanticsMax = @enumToInt(enum_SpvMemorySemanticsShift_.SpvMemorySemanticsMax); pub const enum_SpvMemorySemanticsShift_ = extern enum(c_int) { SpvMemorySemanticsAcquireShift = 1, SpvMemorySemanticsReleaseShift = 2, SpvMemorySemanticsAcquireReleaseShift = 3, SpvMemorySemanticsSequentiallyConsistentShift = 4, SpvMemorySemanticsUniformMemoryShift = 6, SpvMemorySemanticsSubgroupMemoryShift = 7, SpvMemorySemanticsWorkgroupMemoryShift = 8, SpvMemorySemanticsCrossWorkgroupMemoryShift = 9, SpvMemorySemanticsAtomicCounterMemoryShift = 10, SpvMemorySemanticsImageMemoryShift = 11, SpvMemorySemanticsOutputMemoryShift = 12, SpvMemorySemanticsOutputMemoryKHRShift = 12, SpvMemorySemanticsMakeAvailableShift = 13, SpvMemorySemanticsMakeAvailableKHRShift = 13, SpvMemorySemanticsMakeVisibleShift = 14, SpvMemorySemanticsMakeVisibleKHRShift = 14, SpvMemorySemanticsVolatileShift = 15, SpvMemorySemanticsMax = 2147483647, _, }; pub const SpvMemorySemanticsShift = enum_SpvMemorySemanticsShift_; pub const SpvMemorySemanticsMaskNone = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsMaskNone); pub const SpvMemorySemanticsAcquireMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsAcquireMask); pub const SpvMemorySemanticsReleaseMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsReleaseMask); pub const SpvMemorySemanticsAcquireReleaseMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsAcquireReleaseMask); pub const SpvMemorySemanticsSequentiallyConsistentMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsSequentiallyConsistentMask); pub const SpvMemorySemanticsUniformMemoryMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsUniformMemoryMask); pub const SpvMemorySemanticsSubgroupMemoryMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsSubgroupMemoryMask); pub const SpvMemorySemanticsWorkgroupMemoryMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsWorkgroupMemoryMask); pub const SpvMemorySemanticsCrossWorkgroupMemoryMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsCrossWorkgroupMemoryMask); pub const SpvMemorySemanticsAtomicCounterMemoryMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsAtomicCounterMemoryMask); pub const SpvMemorySemanticsImageMemoryMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsImageMemoryMask); pub const SpvMemorySemanticsOutputMemoryMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsOutputMemoryMask); pub const SpvMemorySemanticsOutputMemoryKHRMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsOutputMemoryKHRMask); pub const SpvMemorySemanticsMakeAvailableMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsMakeAvailableMask); pub const SpvMemorySemanticsMakeAvailableKHRMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsMakeAvailableKHRMask); pub const SpvMemorySemanticsMakeVisibleMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsMakeVisibleMask); pub const SpvMemorySemanticsMakeVisibleKHRMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsMakeVisibleKHRMask); pub const SpvMemorySemanticsVolatileMask = @enumToInt(enum_SpvMemorySemanticsMask_.SpvMemorySemanticsVolatileMask); pub const enum_SpvMemorySemanticsMask_ = extern enum(c_int) { SpvMemorySemanticsMaskNone = 0, SpvMemorySemanticsAcquireMask = 2, SpvMemorySemanticsReleaseMask = 4, SpvMemorySemanticsAcquireReleaseMask = 8, SpvMemorySemanticsSequentiallyConsistentMask = 16, SpvMemorySemanticsUniformMemoryMask = 64, SpvMemorySemanticsSubgroupMemoryMask = 128, SpvMemorySemanticsWorkgroupMemoryMask = 256, SpvMemorySemanticsCrossWorkgroupMemoryMask = 512, SpvMemorySemanticsAtomicCounterMemoryMask = 1024, SpvMemorySemanticsImageMemoryMask = 2048, SpvMemorySemanticsOutputMemoryMask = 4096, SpvMemorySemanticsOutputMemoryKHRMask = 4096, SpvMemorySemanticsMakeAvailableMask = 8192, SpvMemorySemanticsMakeAvailableKHRMask = 8192, SpvMemorySemanticsMakeVisibleMask = 16384, SpvMemorySemanticsMakeVisibleKHRMask = 16384, SpvMemorySemanticsVolatileMask = 32768, _, }; pub const SpvMemorySemanticsMask = enum_SpvMemorySemanticsMask_; pub const SpvMemoryAccessVolatileShift = @enumToInt(enum_SpvMemoryAccessShift_.SpvMemoryAccessVolatileShift); pub const SpvMemoryAccessAlignedShift = @enumToInt(enum_SpvMemoryAccessShift_.SpvMemoryAccessAlignedShift); pub const SpvMemoryAccessNontemporalShift = @enumToInt(enum_SpvMemoryAccessShift_.SpvMemoryAccessNontemporalShift); pub const SpvMemoryAccessMakePointerAvailableShift = @enumToInt(enum_SpvMemoryAccessShift_.SpvMemoryAccessMakePointerAvailableShift); pub const SpvMemoryAccessMakePointerAvailableKHRShift = @enumToInt(enum_SpvMemoryAccessShift_.SpvMemoryAccessMakePointerAvailableKHRShift); pub const SpvMemoryAccessMakePointerVisibleShift = @enumToInt(enum_SpvMemoryAccessShift_.SpvMemoryAccessMakePointerVisibleShift); pub const SpvMemoryAccessMakePointerVisibleKHRShift = @enumToInt(enum_SpvMemoryAccessShift_.SpvMemoryAccessMakePointerVisibleKHRShift); pub const SpvMemoryAccessNonPrivatePointerShift = @enumToInt(enum_SpvMemoryAccessShift_.SpvMemoryAccessNonPrivatePointerShift); pub const SpvMemoryAccessNonPrivatePointerKHRShift = @enumToInt(enum_SpvMemoryAccessShift_.SpvMemoryAccessNonPrivatePointerKHRShift); pub const SpvMemoryAccessMax = @enumToInt(enum_SpvMemoryAccessShift_.SpvMemoryAccessMax); pub const enum_SpvMemoryAccessShift_ = extern enum(c_int) { SpvMemoryAccessVolatileShift = 0, SpvMemoryAccessAlignedShift = 1, SpvMemoryAccessNontemporalShift = 2, SpvMemoryAccessMakePointerAvailableShift = 3, SpvMemoryAccessMakePointerAvailableKHRShift = 3, SpvMemoryAccessMakePointerVisibleShift = 4, SpvMemoryAccessMakePointerVisibleKHRShift = 4, SpvMemoryAccessNonPrivatePointerShift = 5, SpvMemoryAccessNonPrivatePointerKHRShift = 5, SpvMemoryAccessMax = 2147483647, _, }; pub const SpvMemoryAccessShift = enum_SpvMemoryAccessShift_; pub const SpvMemoryAccessMaskNone = @enumToInt(enum_SpvMemoryAccessMask_.SpvMemoryAccessMaskNone); pub const SpvMemoryAccessVolatileMask = @enumToInt(enum_SpvMemoryAccessMask_.SpvMemoryAccessVolatileMask); pub const SpvMemoryAccessAlignedMask = @enumToInt(enum_SpvMemoryAccessMask_.SpvMemoryAccessAlignedMask); pub const SpvMemoryAccessNontemporalMask = @enumToInt(enum_SpvMemoryAccessMask_.SpvMemoryAccessNontemporalMask); pub const SpvMemoryAccessMakePointerAvailableMask = @enumToInt(enum_SpvMemoryAccessMask_.SpvMemoryAccessMakePointerAvailableMask); pub const SpvMemoryAccessMakePointerAvailableKHRMask = @enumToInt(enum_SpvMemoryAccessMask_.SpvMemoryAccessMakePointerAvailableKHRMask); pub const SpvMemoryAccessMakePointerVisibleMask = @enumToInt(enum_SpvMemoryAccessMask_.SpvMemoryAccessMakePointerVisibleMask); pub const SpvMemoryAccessMakePointerVisibleKHRMask = @enumToInt(enum_SpvMemoryAccessMask_.SpvMemoryAccessMakePointerVisibleKHRMask); pub const SpvMemoryAccessNonPrivatePointerMask = @enumToInt(enum_SpvMemoryAccessMask_.SpvMemoryAccessNonPrivatePointerMask); pub const SpvMemoryAccessNonPrivatePointerKHRMask = @enumToInt(enum_SpvMemoryAccessMask_.SpvMemoryAccessNonPrivatePointerKHRMask); pub const enum_SpvMemoryAccessMask_ = extern enum(c_int) { SpvMemoryAccessMaskNone = 0, SpvMemoryAccessVolatileMask = 1, SpvMemoryAccessAlignedMask = 2, SpvMemoryAccessNontemporalMask = 4, SpvMemoryAccessMakePointerAvailableMask = 8, SpvMemoryAccessMakePointerAvailableKHRMask = 8, SpvMemoryAccessMakePointerVisibleMask = 16, SpvMemoryAccessMakePointerVisibleKHRMask = 16, SpvMemoryAccessNonPrivatePointerMask = 32, SpvMemoryAccessNonPrivatePointerKHRMask = 32, _, }; pub const SpvMemoryAccessMask = enum_SpvMemoryAccessMask_; pub const SpvScopeCrossDevice = @enumToInt(enum_SpvScope_.SpvScopeCrossDevice); pub const SpvScopeDevice = @enumToInt(enum_SpvScope_.SpvScopeDevice); pub const SpvScopeWorkgroup = @enumToInt(enum_SpvScope_.SpvScopeWorkgroup); pub const SpvScopeSubgroup = @enumToInt(enum_SpvScope_.SpvScopeSubgroup); pub const SpvScopeInvocation = @enumToInt(enum_SpvScope_.SpvScopeInvocation); pub const SpvScopeQueueFamily = @enumToInt(enum_SpvScope_.SpvScopeQueueFamily); pub const SpvScopeQueueFamilyKHR = @enumToInt(enum_SpvScope_.SpvScopeQueueFamilyKHR); pub const SpvScopeShaderCallKHR = @enumToInt(enum_SpvScope_.SpvScopeShaderCallKHR); pub const SpvScopeMax = @enumToInt(enum_SpvScope_.SpvScopeMax); pub const enum_SpvScope_ = extern enum(c_int) { SpvScopeCrossDevice = 0, SpvScopeDevice = 1, SpvScopeWorkgroup = 2, SpvScopeSubgroup = 3, SpvScopeInvocation = 4, SpvScopeQueueFamily = 5, SpvScopeQueueFamilyKHR = 5, SpvScopeShaderCallKHR = 6, SpvScopeMax = 2147483647, _, }; pub const SpvScope = enum_SpvScope_; pub const SpvGroupOperationReduce = @enumToInt(enum_SpvGroupOperation_.SpvGroupOperationReduce); pub const SpvGroupOperationInclusiveScan = @enumToInt(enum_SpvGroupOperation_.SpvGroupOperationInclusiveScan); pub const SpvGroupOperationExclusiveScan = @enumToInt(enum_SpvGroupOperation_.SpvGroupOperationExclusiveScan); pub const SpvGroupOperationClusteredReduce = @enumToInt(enum_SpvGroupOperation_.SpvGroupOperationClusteredReduce); pub const SpvGroupOperationPartitionedReduceNV = @enumToInt(enum_SpvGroupOperation_.SpvGroupOperationPartitionedReduceNV); pub const SpvGroupOperationPartitionedInclusiveScanNV = @enumToInt(enum_SpvGroupOperation_.SpvGroupOperationPartitionedInclusiveScanNV); pub const SpvGroupOperationPartitionedExclusiveScanNV = @enumToInt(enum_SpvGroupOperation_.SpvGroupOperationPartitionedExclusiveScanNV); pub const SpvGroupOperationMax = @enumToInt(enum_SpvGroupOperation_.SpvGroupOperationMax); pub const enum_SpvGroupOperation_ = extern enum(c_int) { SpvGroupOperationReduce = 0, SpvGroupOperationInclusiveScan = 1, SpvGroupOperationExclusiveScan = 2, SpvGroupOperationClusteredReduce = 3, SpvGroupOperationPartitionedReduceNV = 6, SpvGroupOperationPartitionedInclusiveScanNV = 7, SpvGroupOperationPartitionedExclusiveScanNV = 8, SpvGroupOperationMax = 2147483647, _, }; pub const SpvGroupOperation = enum_SpvGroupOperation_; pub const SpvKernelEnqueueFlagsNoWait = @enumToInt(enum_SpvKernelEnqueueFlags_.SpvKernelEnqueueFlagsNoWait); pub const SpvKernelEnqueueFlagsWaitKernel = @enumToInt(enum_SpvKernelEnqueueFlags_.SpvKernelEnqueueFlagsWaitKernel); pub const SpvKernelEnqueueFlagsWaitWorkGroup = @enumToInt(enum_SpvKernelEnqueueFlags_.SpvKernelEnqueueFlagsWaitWorkGroup); pub const SpvKernelEnqueueFlagsMax = @enumToInt(enum_SpvKernelEnqueueFlags_.SpvKernelEnqueueFlagsMax); pub const enum_SpvKernelEnqueueFlags_ = extern enum(c_int) { SpvKernelEnqueueFlagsNoWait = 0, SpvKernelEnqueueFlagsWaitKernel = 1, SpvKernelEnqueueFlagsWaitWorkGroup = 2, SpvKernelEnqueueFlagsMax = 2147483647, _, }; pub const SpvKernelEnqueueFlags = enum_SpvKernelEnqueueFlags_; pub const SpvKernelProfilingInfoCmdExecTimeShift = @enumToInt(enum_SpvKernelProfilingInfoShift_.SpvKernelProfilingInfoCmdExecTimeShift); pub const SpvKernelProfilingInfoMax = @enumToInt(enum_SpvKernelProfilingInfoShift_.SpvKernelProfilingInfoMax); pub const enum_SpvKernelProfilingInfoShift_ = extern enum(c_int) { SpvKernelProfilingInfoCmdExecTimeShift = 0, SpvKernelProfilingInfoMax = 2147483647, _, }; pub const SpvKernelProfilingInfoShift = enum_SpvKernelProfilingInfoShift_; pub const SpvKernelProfilingInfoMaskNone = @enumToInt(enum_SpvKernelProfilingInfoMask_.SpvKernelProfilingInfoMaskNone); pub const SpvKernelProfilingInfoCmdExecTimeMask = @enumToInt(enum_SpvKernelProfilingInfoMask_.SpvKernelProfilingInfoCmdExecTimeMask); pub const enum_SpvKernelProfilingInfoMask_ = extern enum(c_int) { SpvKernelProfilingInfoMaskNone = 0, SpvKernelProfilingInfoCmdExecTimeMask = 1, _, }; pub const SpvKernelProfilingInfoMask = enum_SpvKernelProfilingInfoMask_; pub const SpvCapabilityMatrix = @enumToInt(enum_SpvCapability_.SpvCapabilityMatrix); pub const SpvCapabilityShader = @enumToInt(enum_SpvCapability_.SpvCapabilityShader); pub const SpvCapabilityGeometry = @enumToInt(enum_SpvCapability_.SpvCapabilityGeometry); pub const SpvCapabilityTessellation = @enumToInt(enum_SpvCapability_.SpvCapabilityTessellation); pub const SpvCapabilityAddresses = @enumToInt(enum_SpvCapability_.SpvCapabilityAddresses); pub const SpvCapabilityLinkage = @enumToInt(enum_SpvCapability_.SpvCapabilityLinkage); pub const SpvCapabilityKernel = @enumToInt(enum_SpvCapability_.SpvCapabilityKernel); pub const SpvCapabilityVector16 = @enumToInt(enum_SpvCapability_.SpvCapabilityVector16); pub const SpvCapabilityFloat16Buffer = @enumToInt(enum_SpvCapability_.SpvCapabilityFloat16Buffer); pub const SpvCapabilityFloat16 = @enumToInt(enum_SpvCapability_.SpvCapabilityFloat16); pub const SpvCapabilityFloat64 = @enumToInt(enum_SpvCapability_.SpvCapabilityFloat64); pub const SpvCapabilityInt64 = @enumToInt(enum_SpvCapability_.SpvCapabilityInt64); pub const SpvCapabilityInt64Atomics = @enumToInt(enum_SpvCapability_.SpvCapabilityInt64Atomics); pub const SpvCapabilityImageBasic = @enumToInt(enum_SpvCapability_.SpvCapabilityImageBasic); pub const SpvCapabilityImageReadWrite = @enumToInt(enum_SpvCapability_.SpvCapabilityImageReadWrite); pub const SpvCapabilityImageMipmap = @enumToInt(enum_SpvCapability_.SpvCapabilityImageMipmap); pub const SpvCapabilityPipes = @enumToInt(enum_SpvCapability_.SpvCapabilityPipes); pub const SpvCapabilityGroups = @enumToInt(enum_SpvCapability_.SpvCapabilityGroups); pub const SpvCapabilityDeviceEnqueue = @enumToInt(enum_SpvCapability_.SpvCapabilityDeviceEnqueue); pub const SpvCapabilityLiteralSampler = @enumToInt(enum_SpvCapability_.SpvCapabilityLiteralSampler); pub const SpvCapabilityAtomicStorage = @enumToInt(enum_SpvCapability_.SpvCapabilityAtomicStorage); pub const SpvCapabilityInt16 = @enumToInt(enum_SpvCapability_.SpvCapabilityInt16); pub const SpvCapabilityTessellationPointSize = @enumToInt(enum_SpvCapability_.SpvCapabilityTessellationPointSize); pub const SpvCapabilityGeometryPointSize = @enumToInt(enum_SpvCapability_.SpvCapabilityGeometryPointSize); pub const SpvCapabilityImageGatherExtended = @enumToInt(enum_SpvCapability_.SpvCapabilityImageGatherExtended); pub const SpvCapabilityStorageImageMultisample = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageImageMultisample); pub const SpvCapabilityUniformBufferArrayDynamicIndexing = @enumToInt(enum_SpvCapability_.SpvCapabilityUniformBufferArrayDynamicIndexing); pub const SpvCapabilitySampledImageArrayDynamicIndexing = @enumToInt(enum_SpvCapability_.SpvCapabilitySampledImageArrayDynamicIndexing); pub const SpvCapabilityStorageBufferArrayDynamicIndexing = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageBufferArrayDynamicIndexing); pub const SpvCapabilityStorageImageArrayDynamicIndexing = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageImageArrayDynamicIndexing); pub const SpvCapabilityClipDistance = @enumToInt(enum_SpvCapability_.SpvCapabilityClipDistance); pub const SpvCapabilityCullDistance = @enumToInt(enum_SpvCapability_.SpvCapabilityCullDistance); pub const SpvCapabilityImageCubeArray = @enumToInt(enum_SpvCapability_.SpvCapabilityImageCubeArray); pub const SpvCapabilitySampleRateShading = @enumToInt(enum_SpvCapability_.SpvCapabilitySampleRateShading); pub const SpvCapabilityImageRect = @enumToInt(enum_SpvCapability_.SpvCapabilityImageRect); pub const SpvCapabilitySampledRect = @enumToInt(enum_SpvCapability_.SpvCapabilitySampledRect); pub const SpvCapabilityGenericPointer = @enumToInt(enum_SpvCapability_.SpvCapabilityGenericPointer); pub const SpvCapabilityInt8 = @enumToInt(enum_SpvCapability_.SpvCapabilityInt8); pub const SpvCapabilityInputAttachment = @enumToInt(enum_SpvCapability_.SpvCapabilityInputAttachment); pub const SpvCapabilitySparseResidency = @enumToInt(enum_SpvCapability_.SpvCapabilitySparseResidency); pub const SpvCapabilityMinLod = @enumToInt(enum_SpvCapability_.SpvCapabilityMinLod); pub const SpvCapabilitySampled1D = @enumToInt(enum_SpvCapability_.SpvCapabilitySampled1D); pub const SpvCapabilityImage1D = @enumToInt(enum_SpvCapability_.SpvCapabilityImage1D); pub const SpvCapabilitySampledCubeArray = @enumToInt(enum_SpvCapability_.SpvCapabilitySampledCubeArray); pub const SpvCapabilitySampledBuffer = @enumToInt(enum_SpvCapability_.SpvCapabilitySampledBuffer); pub const SpvCapabilityImageBuffer = @enumToInt(enum_SpvCapability_.SpvCapabilityImageBuffer); pub const SpvCapabilityImageMSArray = @enumToInt(enum_SpvCapability_.SpvCapabilityImageMSArray); pub const SpvCapabilityStorageImageExtendedFormats = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageImageExtendedFormats); pub const SpvCapabilityImageQuery = @enumToInt(enum_SpvCapability_.SpvCapabilityImageQuery); pub const SpvCapabilityDerivativeControl = @enumToInt(enum_SpvCapability_.SpvCapabilityDerivativeControl); pub const SpvCapabilityInterpolationFunction = @enumToInt(enum_SpvCapability_.SpvCapabilityInterpolationFunction); pub const SpvCapabilityTransformFeedback = @enumToInt(enum_SpvCapability_.SpvCapabilityTransformFeedback); pub const SpvCapabilityGeometryStreams = @enumToInt(enum_SpvCapability_.SpvCapabilityGeometryStreams); pub const SpvCapabilityStorageImageReadWithoutFormat = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageImageReadWithoutFormat); pub const SpvCapabilityStorageImageWriteWithoutFormat = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageImageWriteWithoutFormat); pub const SpvCapabilityMultiViewport = @enumToInt(enum_SpvCapability_.SpvCapabilityMultiViewport); pub const SpvCapabilitySubgroupDispatch = @enumToInt(enum_SpvCapability_.SpvCapabilitySubgroupDispatch); pub const SpvCapabilityNamedBarrier = @enumToInt(enum_SpvCapability_.SpvCapabilityNamedBarrier); pub const SpvCapabilityPipeStorage = @enumToInt(enum_SpvCapability_.SpvCapabilityPipeStorage); pub const SpvCapabilityGroupNonUniform = @enumToInt(enum_SpvCapability_.SpvCapabilityGroupNonUniform); pub const SpvCapabilityGroupNonUniformVote = @enumToInt(enum_SpvCapability_.SpvCapabilityGroupNonUniformVote); pub const SpvCapabilityGroupNonUniformArithmetic = @enumToInt(enum_SpvCapability_.SpvCapabilityGroupNonUniformArithmetic); pub const SpvCapabilityGroupNonUniformBallot = @enumToInt(enum_SpvCapability_.SpvCapabilityGroupNonUniformBallot); pub const SpvCapabilityGroupNonUniformShuffle = @enumToInt(enum_SpvCapability_.SpvCapabilityGroupNonUniformShuffle); pub const SpvCapabilityGroupNonUniformShuffleRelative = @enumToInt(enum_SpvCapability_.SpvCapabilityGroupNonUniformShuffleRelative); pub const SpvCapabilityGroupNonUniformClustered = @enumToInt(enum_SpvCapability_.SpvCapabilityGroupNonUniformClustered); pub const SpvCapabilityGroupNonUniformQuad = @enumToInt(enum_SpvCapability_.SpvCapabilityGroupNonUniformQuad); pub const SpvCapabilityShaderLayer = @enumToInt(enum_SpvCapability_.SpvCapabilityShaderLayer); pub const SpvCapabilityShaderViewportIndex = @enumToInt(enum_SpvCapability_.SpvCapabilityShaderViewportIndex); pub const SpvCapabilitySubgroupBallotKHR = @enumToInt(enum_SpvCapability_.SpvCapabilitySubgroupBallotKHR); pub const SpvCapabilityDrawParameters = @enumToInt(enum_SpvCapability_.SpvCapabilityDrawParameters); pub const SpvCapabilitySubgroupVoteKHR = @enumToInt(enum_SpvCapability_.SpvCapabilitySubgroupVoteKHR); pub const SpvCapabilityStorageBuffer16BitAccess = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageBuffer16BitAccess); pub const SpvCapabilityStorageUniformBufferBlock16 = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageUniformBufferBlock16); pub const SpvCapabilityStorageUniform16 = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageUniform16); pub const SpvCapabilityUniformAndStorageBuffer16BitAccess = @enumToInt(enum_SpvCapability_.SpvCapabilityUniformAndStorageBuffer16BitAccess); pub const SpvCapabilityStoragePushConstant16 = @enumToInt(enum_SpvCapability_.SpvCapabilityStoragePushConstant16); pub const SpvCapabilityStorageInputOutput16 = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageInputOutput16); pub const SpvCapabilityDeviceGroup = @enumToInt(enum_SpvCapability_.SpvCapabilityDeviceGroup); pub const SpvCapabilityMultiView = @enumToInt(enum_SpvCapability_.SpvCapabilityMultiView); pub const SpvCapabilityVariablePointersStorageBuffer = @enumToInt(enum_SpvCapability_.SpvCapabilityVariablePointersStorageBuffer); pub const SpvCapabilityVariablePointers = @enumToInt(enum_SpvCapability_.SpvCapabilityVariablePointers); pub const SpvCapabilityAtomicStorageOps = @enumToInt(enum_SpvCapability_.SpvCapabilityAtomicStorageOps); pub const SpvCapabilitySampleMaskPostDepthCoverage = @enumToInt(enum_SpvCapability_.SpvCapabilitySampleMaskPostDepthCoverage); pub const SpvCapabilityStorageBuffer8BitAccess = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageBuffer8BitAccess); pub const SpvCapabilityUniformAndStorageBuffer8BitAccess = @enumToInt(enum_SpvCapability_.SpvCapabilityUniformAndStorageBuffer8BitAccess); pub const SpvCapabilityStoragePushConstant8 = @enumToInt(enum_SpvCapability_.SpvCapabilityStoragePushConstant8); pub const SpvCapabilityDenormPreserve = @enumToInt(enum_SpvCapability_.SpvCapabilityDenormPreserve); pub const SpvCapabilityDenormFlushToZero = @enumToInt(enum_SpvCapability_.SpvCapabilityDenormFlushToZero); pub const SpvCapabilitySignedZeroInfNanPreserve = @enumToInt(enum_SpvCapability_.SpvCapabilitySignedZeroInfNanPreserve); pub const SpvCapabilityRoundingModeRTE = @enumToInt(enum_SpvCapability_.SpvCapabilityRoundingModeRTE); pub const SpvCapabilityRoundingModeRTZ = @enumToInt(enum_SpvCapability_.SpvCapabilityRoundingModeRTZ); pub const SpvCapabilityRayQueryProvisionalKHR = @enumToInt(enum_SpvCapability_.SpvCapabilityRayQueryProvisionalKHR); pub const SpvCapabilityRayTraversalPrimitiveCullingProvisionalKHR = @enumToInt(enum_SpvCapability_.SpvCapabilityRayTraversalPrimitiveCullingProvisionalKHR); pub const SpvCapabilityFloat16ImageAMD = @enumToInt(enum_SpvCapability_.SpvCapabilityFloat16ImageAMD); pub const SpvCapabilityImageGatherBiasLodAMD = @enumToInt(enum_SpvCapability_.SpvCapabilityImageGatherBiasLodAMD); pub const SpvCapabilityFragmentMaskAMD = @enumToInt(enum_SpvCapability_.SpvCapabilityFragmentMaskAMD); pub const SpvCapabilityStencilExportEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityStencilExportEXT); pub const SpvCapabilityImageReadWriteLodAMD = @enumToInt(enum_SpvCapability_.SpvCapabilityImageReadWriteLodAMD); pub const SpvCapabilityShaderClockKHR = @enumToInt(enum_SpvCapability_.SpvCapabilityShaderClockKHR); pub const SpvCapabilitySampleMaskOverrideCoverageNV = @enumToInt(enum_SpvCapability_.SpvCapabilitySampleMaskOverrideCoverageNV); pub const SpvCapabilityGeometryShaderPassthroughNV = @enumToInt(enum_SpvCapability_.SpvCapabilityGeometryShaderPassthroughNV); pub const SpvCapabilityShaderViewportIndexLayerEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityShaderViewportIndexLayerEXT); pub const SpvCapabilityShaderViewportIndexLayerNV = @enumToInt(enum_SpvCapability_.SpvCapabilityShaderViewportIndexLayerNV); pub const SpvCapabilityShaderViewportMaskNV = @enumToInt(enum_SpvCapability_.SpvCapabilityShaderViewportMaskNV); pub const SpvCapabilityShaderStereoViewNV = @enumToInt(enum_SpvCapability_.SpvCapabilityShaderStereoViewNV); pub const SpvCapabilityPerViewAttributesNV = @enumToInt(enum_SpvCapability_.SpvCapabilityPerViewAttributesNV); pub const SpvCapabilityFragmentFullyCoveredEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityFragmentFullyCoveredEXT); pub const SpvCapabilityMeshShadingNV = @enumToInt(enum_SpvCapability_.SpvCapabilityMeshShadingNV); pub const SpvCapabilityImageFootprintNV = @enumToInt(enum_SpvCapability_.SpvCapabilityImageFootprintNV); pub const SpvCapabilityFragmentBarycentricNV = @enumToInt(enum_SpvCapability_.SpvCapabilityFragmentBarycentricNV); pub const SpvCapabilityComputeDerivativeGroupQuadsNV = @enumToInt(enum_SpvCapability_.SpvCapabilityComputeDerivativeGroupQuadsNV); pub const SpvCapabilityFragmentDensityEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityFragmentDensityEXT); pub const SpvCapabilityShadingRateNV = @enumToInt(enum_SpvCapability_.SpvCapabilityShadingRateNV); pub const SpvCapabilityGroupNonUniformPartitionedNV = @enumToInt(enum_SpvCapability_.SpvCapabilityGroupNonUniformPartitionedNV); pub const SpvCapabilityShaderNonUniform = @enumToInt(enum_SpvCapability_.SpvCapabilityShaderNonUniform); pub const SpvCapabilityShaderNonUniformEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityShaderNonUniformEXT); pub const SpvCapabilityRuntimeDescriptorArray = @enumToInt(enum_SpvCapability_.SpvCapabilityRuntimeDescriptorArray); pub const SpvCapabilityRuntimeDescriptorArrayEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityRuntimeDescriptorArrayEXT); pub const SpvCapabilityInputAttachmentArrayDynamicIndexing = @enumToInt(enum_SpvCapability_.SpvCapabilityInputAttachmentArrayDynamicIndexing); pub const SpvCapabilityInputAttachmentArrayDynamicIndexingEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityInputAttachmentArrayDynamicIndexingEXT); pub const SpvCapabilityUniformTexelBufferArrayDynamicIndexing = @enumToInt(enum_SpvCapability_.SpvCapabilityUniformTexelBufferArrayDynamicIndexing); pub const SpvCapabilityUniformTexelBufferArrayDynamicIndexingEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityUniformTexelBufferArrayDynamicIndexingEXT); pub const SpvCapabilityStorageTexelBufferArrayDynamicIndexing = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageTexelBufferArrayDynamicIndexing); pub const SpvCapabilityStorageTexelBufferArrayDynamicIndexingEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageTexelBufferArrayDynamicIndexingEXT); pub const SpvCapabilityUniformBufferArrayNonUniformIndexing = @enumToInt(enum_SpvCapability_.SpvCapabilityUniformBufferArrayNonUniformIndexing); pub const SpvCapabilityUniformBufferArrayNonUniformIndexingEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityUniformBufferArrayNonUniformIndexingEXT); pub const SpvCapabilitySampledImageArrayNonUniformIndexing = @enumToInt(enum_SpvCapability_.SpvCapabilitySampledImageArrayNonUniformIndexing); pub const SpvCapabilitySampledImageArrayNonUniformIndexingEXT = @enumToInt(enum_SpvCapability_.SpvCapabilitySampledImageArrayNonUniformIndexingEXT); pub const SpvCapabilityStorageBufferArrayNonUniformIndexing = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageBufferArrayNonUniformIndexing); pub const SpvCapabilityStorageBufferArrayNonUniformIndexingEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageBufferArrayNonUniformIndexingEXT); pub const SpvCapabilityStorageImageArrayNonUniformIndexing = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageImageArrayNonUniformIndexing); pub const SpvCapabilityStorageImageArrayNonUniformIndexingEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageImageArrayNonUniformIndexingEXT); pub const SpvCapabilityInputAttachmentArrayNonUniformIndexing = @enumToInt(enum_SpvCapability_.SpvCapabilityInputAttachmentArrayNonUniformIndexing); pub const SpvCapabilityInputAttachmentArrayNonUniformIndexingEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityInputAttachmentArrayNonUniformIndexingEXT); pub const SpvCapabilityUniformTexelBufferArrayNonUniformIndexing = @enumToInt(enum_SpvCapability_.SpvCapabilityUniformTexelBufferArrayNonUniformIndexing); pub const SpvCapabilityUniformTexelBufferArrayNonUniformIndexingEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityUniformTexelBufferArrayNonUniformIndexingEXT); pub const SpvCapabilityStorageTexelBufferArrayNonUniformIndexing = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageTexelBufferArrayNonUniformIndexing); pub const SpvCapabilityStorageTexelBufferArrayNonUniformIndexingEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityStorageTexelBufferArrayNonUniformIndexingEXT); pub const SpvCapabilityRayTracingNV = @enumToInt(enum_SpvCapability_.SpvCapabilityRayTracingNV); pub const SpvCapabilityVulkanMemoryModel = @enumToInt(enum_SpvCapability_.SpvCapabilityVulkanMemoryModel); pub const SpvCapabilityVulkanMemoryModelKHR = @enumToInt(enum_SpvCapability_.SpvCapabilityVulkanMemoryModelKHR); pub const SpvCapabilityVulkanMemoryModelDeviceScope = @enumToInt(enum_SpvCapability_.SpvCapabilityVulkanMemoryModelDeviceScope); pub const SpvCapabilityVulkanMemoryModelDeviceScopeKHR = @enumToInt(enum_SpvCapability_.SpvCapabilityVulkanMemoryModelDeviceScopeKHR); pub const SpvCapabilityPhysicalStorageBufferAddresses = @enumToInt(enum_SpvCapability_.SpvCapabilityPhysicalStorageBufferAddresses); pub const SpvCapabilityPhysicalStorageBufferAddressesEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityPhysicalStorageBufferAddressesEXT); pub const SpvCapabilityComputeDerivativeGroupLinearNV = @enumToInt(enum_SpvCapability_.SpvCapabilityComputeDerivativeGroupLinearNV); pub const SpvCapabilityRayTracingProvisionalKHR = @enumToInt(enum_SpvCapability_.SpvCapabilityRayTracingProvisionalKHR); pub const SpvCapabilityCooperativeMatrixNV = @enumToInt(enum_SpvCapability_.SpvCapabilityCooperativeMatrixNV); pub const SpvCapabilityFragmentShaderSampleInterlockEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityFragmentShaderSampleInterlockEXT); pub const SpvCapabilityFragmentShaderShadingRateInterlockEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityFragmentShaderShadingRateInterlockEXT); pub const SpvCapabilityShaderSMBuiltinsNV = @enumToInt(enum_SpvCapability_.SpvCapabilityShaderSMBuiltinsNV); pub const SpvCapabilityFragmentShaderPixelInterlockEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityFragmentShaderPixelInterlockEXT); pub const SpvCapabilityDemoteToHelperInvocationEXT = @enumToInt(enum_SpvCapability_.SpvCapabilityDemoteToHelperInvocationEXT); pub const SpvCapabilitySubgroupShuffleINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilitySubgroupShuffleINTEL); pub const SpvCapabilitySubgroupBufferBlockIOINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilitySubgroupBufferBlockIOINTEL); pub const SpvCapabilitySubgroupImageBlockIOINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilitySubgroupImageBlockIOINTEL); pub const SpvCapabilitySubgroupImageMediaBlockIOINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilitySubgroupImageMediaBlockIOINTEL); pub const SpvCapabilityIntegerFunctions2INTEL = @enumToInt(enum_SpvCapability_.SpvCapabilityIntegerFunctions2INTEL); pub const SpvCapabilityFunctionPointersINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilityFunctionPointersINTEL); pub const SpvCapabilityIndirectReferencesINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilityIndirectReferencesINTEL); pub const SpvCapabilitySubgroupAvcMotionEstimationINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilitySubgroupAvcMotionEstimationINTEL); pub const SpvCapabilitySubgroupAvcMotionEstimationIntraINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilitySubgroupAvcMotionEstimationIntraINTEL); pub const SpvCapabilitySubgroupAvcMotionEstimationChromaINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilitySubgroupAvcMotionEstimationChromaINTEL); pub const SpvCapabilityFPGAMemoryAttributesINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilityFPGAMemoryAttributesINTEL); pub const SpvCapabilityUnstructuredLoopControlsINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilityUnstructuredLoopControlsINTEL); pub const SpvCapabilityFPGALoopControlsINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilityFPGALoopControlsINTEL); pub const SpvCapabilityKernelAttributesINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilityKernelAttributesINTEL); pub const SpvCapabilityFPGAKernelAttributesINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilityFPGAKernelAttributesINTEL); pub const SpvCapabilityBlockingPipesINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilityBlockingPipesINTEL); pub const SpvCapabilityFPGARegINTEL = @enumToInt(enum_SpvCapability_.SpvCapabilityFPGARegINTEL); pub const SpvCapabilityMax = @enumToInt(enum_SpvCapability_.SpvCapabilityMax); pub const enum_SpvCapability_ = extern enum(c_int) { SpvCapabilityMatrix = 0, SpvCapabilityShader = 1, SpvCapabilityGeometry = 2, SpvCapabilityTessellation = 3, SpvCapabilityAddresses = 4, SpvCapabilityLinkage = 5, SpvCapabilityKernel = 6, SpvCapabilityVector16 = 7, SpvCapabilityFloat16Buffer = 8, SpvCapabilityFloat16 = 9, SpvCapabilityFloat64 = 10, SpvCapabilityInt64 = 11, SpvCapabilityInt64Atomics = 12, SpvCapabilityImageBasic = 13, SpvCapabilityImageReadWrite = 14, SpvCapabilityImageMipmap = 15, SpvCapabilityPipes = 17, SpvCapabilityGroups = 18, SpvCapabilityDeviceEnqueue = 19, SpvCapabilityLiteralSampler = 20, SpvCapabilityAtomicStorage = 21, SpvCapabilityInt16 = 22, SpvCapabilityTessellationPointSize = 23, SpvCapabilityGeometryPointSize = 24, SpvCapabilityImageGatherExtended = 25, SpvCapabilityStorageImageMultisample = 27, SpvCapabilityUniformBufferArrayDynamicIndexing = 28, SpvCapabilitySampledImageArrayDynamicIndexing = 29, SpvCapabilityStorageBufferArrayDynamicIndexing = 30, SpvCapabilityStorageImageArrayDynamicIndexing = 31, SpvCapabilityClipDistance = 32, SpvCapabilityCullDistance = 33, SpvCapabilityImageCubeArray = 34, SpvCapabilitySampleRateShading = 35, SpvCapabilityImageRect = 36, SpvCapabilitySampledRect = 37, SpvCapabilityGenericPointer = 38, SpvCapabilityInt8 = 39, SpvCapabilityInputAttachment = 40, SpvCapabilitySparseResidency = 41, SpvCapabilityMinLod = 42, SpvCapabilitySampled1D = 43, SpvCapabilityImage1D = 44, SpvCapabilitySampledCubeArray = 45, SpvCapabilitySampledBuffer = 46, SpvCapabilityImageBuffer = 47, SpvCapabilityImageMSArray = 48, SpvCapabilityStorageImageExtendedFormats = 49, SpvCapabilityImageQuery = 50, SpvCapabilityDerivativeControl = 51, SpvCapabilityInterpolationFunction = 52, SpvCapabilityTransformFeedback = 53, SpvCapabilityGeometryStreams = 54, SpvCapabilityStorageImageReadWithoutFormat = 55, SpvCapabilityStorageImageWriteWithoutFormat = 56, SpvCapabilityMultiViewport = 57, SpvCapabilitySubgroupDispatch = 58, SpvCapabilityNamedBarrier = 59, SpvCapabilityPipeStorage = 60, SpvCapabilityGroupNonUniform = 61, SpvCapabilityGroupNonUniformVote = 62, SpvCapabilityGroupNonUniformArithmetic = 63, SpvCapabilityGroupNonUniformBallot = 64, SpvCapabilityGroupNonUniformShuffle = 65, SpvCapabilityGroupNonUniformShuffleRelative = 66, SpvCapabilityGroupNonUniformClustered = 67, SpvCapabilityGroupNonUniformQuad = 68, SpvCapabilityShaderLayer = 69, SpvCapabilityShaderViewportIndex = 70, SpvCapabilitySubgroupBallotKHR = 4423, SpvCapabilityDrawParameters = 4427, SpvCapabilitySubgroupVoteKHR = 4431, SpvCapabilityStorageBuffer16BitAccess = 4433, SpvCapabilityStorageUniformBufferBlock16 = 4433, SpvCapabilityStorageUniform16 = 4434, SpvCapabilityUniformAndStorageBuffer16BitAccess = 4434, SpvCapabilityStoragePushConstant16 = 4435, SpvCapabilityStorageInputOutput16 = 4436, SpvCapabilityDeviceGroup = 4437, SpvCapabilityMultiView = 4439, SpvCapabilityVariablePointersStorageBuffer = 4441, SpvCapabilityVariablePointers = 4442, SpvCapabilityAtomicStorageOps = 4445, SpvCapabilitySampleMaskPostDepthCoverage = 4447, SpvCapabilityStorageBuffer8BitAccess = 4448, SpvCapabilityUniformAndStorageBuffer8BitAccess = 4449, SpvCapabilityStoragePushConstant8 = 4450, SpvCapabilityDenormPreserve = 4464, SpvCapabilityDenormFlushToZero = 4465, SpvCapabilitySignedZeroInfNanPreserve = 4466, SpvCapabilityRoundingModeRTE = 4467, SpvCapabilityRoundingModeRTZ = 4468, SpvCapabilityRayQueryProvisionalKHR = 4471, SpvCapabilityRayTraversalPrimitiveCullingProvisionalKHR = 4478, SpvCapabilityFloat16ImageAMD = 5008, SpvCapabilityImageGatherBiasLodAMD = 5009, SpvCapabilityFragmentMaskAMD = 5010, SpvCapabilityStencilExportEXT = 5013, SpvCapabilityImageReadWriteLodAMD = 5015, SpvCapabilityShaderClockKHR = 5055, SpvCapabilitySampleMaskOverrideCoverageNV = 5249, SpvCapabilityGeometryShaderPassthroughNV = 5251, SpvCapabilityShaderViewportIndexLayerEXT = 5254, SpvCapabilityShaderViewportIndexLayerNV = 5254, SpvCapabilityShaderViewportMaskNV = 5255, SpvCapabilityShaderStereoViewNV = 5259, SpvCapabilityPerViewAttributesNV = 5260, SpvCapabilityFragmentFullyCoveredEXT = 5265, SpvCapabilityMeshShadingNV = 5266, SpvCapabilityImageFootprintNV = 5282, SpvCapabilityFragmentBarycentricNV = 5284, SpvCapabilityComputeDerivativeGroupQuadsNV = 5288, SpvCapabilityFragmentDensityEXT = 5291, SpvCapabilityShadingRateNV = 5291, SpvCapabilityGroupNonUniformPartitionedNV = 5297, SpvCapabilityShaderNonUniform = 5301, SpvCapabilityShaderNonUniformEXT = 5301, SpvCapabilityRuntimeDescriptorArray = 5302, SpvCapabilityRuntimeDescriptorArrayEXT = 5302, SpvCapabilityInputAttachmentArrayDynamicIndexing = 5303, SpvCapabilityInputAttachmentArrayDynamicIndexingEXT = 5303, SpvCapabilityUniformTexelBufferArrayDynamicIndexing = 5304, SpvCapabilityUniformTexelBufferArrayDynamicIndexingEXT = 5304, SpvCapabilityStorageTexelBufferArrayDynamicIndexing = 5305, SpvCapabilityStorageTexelBufferArrayDynamicIndexingEXT = 5305, SpvCapabilityUniformBufferArrayNonUniformIndexing = 5306, SpvCapabilityUniformBufferArrayNonUniformIndexingEXT = 5306, SpvCapabilitySampledImageArrayNonUniformIndexing = 5307, SpvCapabilitySampledImageArrayNonUniformIndexingEXT = 5307, SpvCapabilityStorageBufferArrayNonUniformIndexing = 5308, SpvCapabilityStorageBufferArrayNonUniformIndexingEXT = 5308, SpvCapabilityStorageImageArrayNonUniformIndexing = 5309, SpvCapabilityStorageImageArrayNonUniformIndexingEXT = 5309, SpvCapabilityInputAttachmentArrayNonUniformIndexing = 5310, SpvCapabilityInputAttachmentArrayNonUniformIndexingEXT = 5310, SpvCapabilityUniformTexelBufferArrayNonUniformIndexing = 5311, SpvCapabilityUniformTexelBufferArrayNonUniformIndexingEXT = 5311, SpvCapabilityStorageTexelBufferArrayNonUniformIndexing = 5312, SpvCapabilityStorageTexelBufferArrayNonUniformIndexingEXT = 5312, SpvCapabilityRayTracingNV = 5340, SpvCapabilityVulkanMemoryModel = 5345, SpvCapabilityVulkanMemoryModelKHR = 5345, SpvCapabilityVulkanMemoryModelDeviceScope = 5346, SpvCapabilityVulkanMemoryModelDeviceScopeKHR = 5346, SpvCapabilityPhysicalStorageBufferAddresses = 5347, SpvCapabilityPhysicalStorageBufferAddressesEXT = 5347, SpvCapabilityComputeDerivativeGroupLinearNV = 5350, SpvCapabilityRayTracingProvisionalKHR = 5353, SpvCapabilityCooperativeMatrixNV = 5357, SpvCapabilityFragmentShaderSampleInterlockEXT = 5363, SpvCapabilityFragmentShaderShadingRateInterlockEXT = 5372, SpvCapabilityShaderSMBuiltinsNV = 5373, SpvCapabilityFragmentShaderPixelInterlockEXT = 5378, SpvCapabilityDemoteToHelperInvocationEXT = 5379, SpvCapabilitySubgroupShuffleINTEL = 5568, SpvCapabilitySubgroupBufferBlockIOINTEL = 5569, SpvCapabilitySubgroupImageBlockIOINTEL = 5570, SpvCapabilitySubgroupImageMediaBlockIOINTEL = 5579, SpvCapabilityIntegerFunctions2INTEL = 5584, SpvCapabilityFunctionPointersINTEL = 5603, SpvCapabilityIndirectReferencesINTEL = 5604, SpvCapabilitySubgroupAvcMotionEstimationINTEL = 5696, SpvCapabilitySubgroupAvcMotionEstimationIntraINTEL = 5697, SpvCapabilitySubgroupAvcMotionEstimationChromaINTEL = 5698, SpvCapabilityFPGAMemoryAttributesINTEL = 5824, SpvCapabilityUnstructuredLoopControlsINTEL = 5886, SpvCapabilityFPGALoopControlsINTEL = 5888, SpvCapabilityKernelAttributesINTEL = 5892, SpvCapabilityFPGAKernelAttributesINTEL = 5897, SpvCapabilityBlockingPipesINTEL = 5945, SpvCapabilityFPGARegINTEL = 5948, SpvCapabilityMax = 2147483647, _, }; pub const SpvCapability = enum_SpvCapability_; pub const SpvRayFlagsOpaqueKHRShift = @enumToInt(enum_SpvRayFlagsShift_.SpvRayFlagsOpaqueKHRShift); pub const SpvRayFlagsNoOpaqueKHRShift = @enumToInt(enum_SpvRayFlagsShift_.SpvRayFlagsNoOpaqueKHRShift); pub const SpvRayFlagsTerminateOnFirstHitKHRShift = @enumToInt(enum_SpvRayFlagsShift_.SpvRayFlagsTerminateOnFirstHitKHRShift); pub const SpvRayFlagsSkipClosestHitShaderKHRShift = @enumToInt(enum_SpvRayFlagsShift_.SpvRayFlagsSkipClosestHitShaderKHRShift); pub const SpvRayFlagsCullBackFacingTrianglesKHRShift = @enumToInt(enum_SpvRayFlagsShift_.SpvRayFlagsCullBackFacingTrianglesKHRShift); pub const SpvRayFlagsCullFrontFacingTrianglesKHRShift = @enumToInt(enum_SpvRayFlagsShift_.SpvRayFlagsCullFrontFacingTrianglesKHRShift); pub const SpvRayFlagsCullOpaqueKHRShift = @enumToInt(enum_SpvRayFlagsShift_.SpvRayFlagsCullOpaqueKHRShift); pub const SpvRayFlagsCullNoOpaqueKHRShift = @enumToInt(enum_SpvRayFlagsShift_.SpvRayFlagsCullNoOpaqueKHRShift); pub const SpvRayFlagsSkipTrianglesKHRShift = @enumToInt(enum_SpvRayFlagsShift_.SpvRayFlagsSkipTrianglesKHRShift); pub const SpvRayFlagsSkipAABBsKHRShift = @enumToInt(enum_SpvRayFlagsShift_.SpvRayFlagsSkipAABBsKHRShift); pub const SpvRayFlagsMax = @enumToInt(enum_SpvRayFlagsShift_.SpvRayFlagsMax); pub const enum_SpvRayFlagsShift_ = extern enum(c_int) { SpvRayFlagsOpaqueKHRShift = 0, SpvRayFlagsNoOpaqueKHRShift = 1, SpvRayFlagsTerminateOnFirstHitKHRShift = 2, SpvRayFlagsSkipClosestHitShaderKHRShift = 3, SpvRayFlagsCullBackFacingTrianglesKHRShift = 4, SpvRayFlagsCullFrontFacingTrianglesKHRShift = 5, SpvRayFlagsCullOpaqueKHRShift = 6, SpvRayFlagsCullNoOpaqueKHRShift = 7, SpvRayFlagsSkipTrianglesKHRShift = 8, SpvRayFlagsSkipAABBsKHRShift = 9, SpvRayFlagsMax = 2147483647, _, }; pub const SpvRayFlagsShift = enum_SpvRayFlagsShift_; pub const SpvRayFlagsMaskNone = @enumToInt(enum_SpvRayFlagsMask_.SpvRayFlagsMaskNone); pub const SpvRayFlagsOpaqueKHRMask = @enumToInt(enum_SpvRayFlagsMask_.SpvRayFlagsOpaqueKHRMask); pub const SpvRayFlagsNoOpaqueKHRMask = @enumToInt(enum_SpvRayFlagsMask_.SpvRayFlagsNoOpaqueKHRMask); pub const SpvRayFlagsTerminateOnFirstHitKHRMask = @enumToInt(enum_SpvRayFlagsMask_.SpvRayFlagsTerminateOnFirstHitKHRMask); pub const SpvRayFlagsSkipClosestHitShaderKHRMask = @enumToInt(enum_SpvRayFlagsMask_.SpvRayFlagsSkipClosestHitShaderKHRMask); pub const SpvRayFlagsCullBackFacingTrianglesKHRMask = @enumToInt(enum_SpvRayFlagsMask_.SpvRayFlagsCullBackFacingTrianglesKHRMask); pub const SpvRayFlagsCullFrontFacingTrianglesKHRMask = @enumToInt(enum_SpvRayFlagsMask_.SpvRayFlagsCullFrontFacingTrianglesKHRMask); pub const SpvRayFlagsCullOpaqueKHRMask = @enumToInt(enum_SpvRayFlagsMask_.SpvRayFlagsCullOpaqueKHRMask); pub const SpvRayFlagsCullNoOpaqueKHRMask = @enumToInt(enum_SpvRayFlagsMask_.SpvRayFlagsCullNoOpaqueKHRMask); pub const SpvRayFlagsSkipTrianglesKHRMask = @enumToInt(enum_SpvRayFlagsMask_.SpvRayFlagsSkipTrianglesKHRMask); pub const SpvRayFlagsSkipAABBsKHRMask = @enumToInt(enum_SpvRayFlagsMask_.SpvRayFlagsSkipAABBsKHRMask); pub const enum_SpvRayFlagsMask_ = extern enum(c_int) { SpvRayFlagsMaskNone = 0, SpvRayFlagsOpaqueKHRMask = 1, SpvRayFlagsNoOpaqueKHRMask = 2, SpvRayFlagsTerminateOnFirstHitKHRMask = 4, SpvRayFlagsSkipClosestHitShaderKHRMask = 8, SpvRayFlagsCullBackFacingTrianglesKHRMask = 16, SpvRayFlagsCullFrontFacingTrianglesKHRMask = 32, SpvRayFlagsCullOpaqueKHRMask = 64, SpvRayFlagsCullNoOpaqueKHRMask = 128, SpvRayFlagsSkipTrianglesKHRMask = 256, SpvRayFlagsSkipAABBsKHRMask = 512, _, }; pub const SpvRayFlagsMask = enum_SpvRayFlagsMask_; pub const SpvRayQueryIntersectionRayQueryCandidateIntersectionKHR = @enumToInt(enum_SpvRayQueryIntersection_.SpvRayQueryIntersectionRayQueryCandidateIntersectionKHR); pub const SpvRayQueryIntersectionRayQueryCommittedIntersectionKHR = @enumToInt(enum_SpvRayQueryIntersection_.SpvRayQueryIntersectionRayQueryCommittedIntersectionKHR); pub const SpvRayQueryIntersectionMax = @enumToInt(enum_SpvRayQueryIntersection_.SpvRayQueryIntersectionMax); pub const enum_SpvRayQueryIntersection_ = extern enum(c_int) { SpvRayQueryIntersectionRayQueryCandidateIntersectionKHR = 0, SpvRayQueryIntersectionRayQueryCommittedIntersectionKHR = 1, SpvRayQueryIntersectionMax = 2147483647, _, }; pub const SpvRayQueryIntersection = enum_SpvRayQueryIntersection_; pub const SpvRayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionNoneKHR = @enumToInt(enum_SpvRayQueryCommittedIntersectionType_.SpvRayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionNoneKHR); pub const SpvRayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionTriangleKHR = @enumToInt(enum_SpvRayQueryCommittedIntersectionType_.SpvRayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionTriangleKHR); pub const SpvRayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionGeneratedKHR = @enumToInt(enum_SpvRayQueryCommittedIntersectionType_.SpvRayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionGeneratedKHR); pub const SpvRayQueryCommittedIntersectionTypeMax = @enumToInt(enum_SpvRayQueryCommittedIntersectionType_.SpvRayQueryCommittedIntersectionTypeMax); pub const enum_SpvRayQueryCommittedIntersectionType_ = extern enum(c_int) { SpvRayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionNoneKHR = 0, SpvRayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionTriangleKHR = 1, SpvRayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionGeneratedKHR = 2, SpvRayQueryCommittedIntersectionTypeMax = 2147483647, _, }; pub const SpvRayQueryCommittedIntersectionType = enum_SpvRayQueryCommittedIntersectionType_; pub const SpvRayQueryCandidateIntersectionTypeRayQueryCandidateIntersectionTriangleKHR = @enumToInt(enum_SpvRayQueryCandidateIntersectionType_.SpvRayQueryCandidateIntersectionTypeRayQueryCandidateIntersectionTriangleKHR); pub const SpvRayQueryCandidateIntersectionTypeRayQueryCandidateIntersectionAABBKHR = @enumToInt(enum_SpvRayQueryCandidateIntersectionType_.SpvRayQueryCandidateIntersectionTypeRayQueryCandidateIntersectionAABBKHR); pub const SpvRayQueryCandidateIntersectionTypeMax = @enumToInt(enum_SpvRayQueryCandidateIntersectionType_.SpvRayQueryCandidateIntersectionTypeMax); pub const enum_SpvRayQueryCandidateIntersectionType_ = extern enum(c_int) { SpvRayQueryCandidateIntersectionTypeRayQueryCandidateIntersectionTriangleKHR = 0, SpvRayQueryCandidateIntersectionTypeRayQueryCandidateIntersectionAABBKHR = 1, SpvRayQueryCandidateIntersectionTypeMax = 2147483647, _, }; pub const SpvRayQueryCandidateIntersectionType = enum_SpvRayQueryCandidateIntersectionType_; pub const SpvOpNop = @enumToInt(enum_SpvOp_.SpvOpNop); pub const SpvOpUndef = @enumToInt(enum_SpvOp_.SpvOpUndef); pub const SpvOpSourceContinued = @enumToInt(enum_SpvOp_.SpvOpSourceContinued); pub const SpvOpSource = @enumToInt(enum_SpvOp_.SpvOpSource); pub const SpvOpSourceExtension = @enumToInt(enum_SpvOp_.SpvOpSourceExtension); pub const SpvOpName = @enumToInt(enum_SpvOp_.SpvOpName); pub const SpvOpMemberName = @enumToInt(enum_SpvOp_.SpvOpMemberName); pub const SpvOpString = @enumToInt(enum_SpvOp_.SpvOpString); pub const SpvOpLine = @enumToInt(enum_SpvOp_.SpvOpLine); pub const SpvOpExtension = @enumToInt(enum_SpvOp_.SpvOpExtension); pub const SpvOpExtInstImport = @enumToInt(enum_SpvOp_.SpvOpExtInstImport); pub const SpvOpExtInst = @enumToInt(enum_SpvOp_.SpvOpExtInst); pub const SpvOpMemoryModel = @enumToInt(enum_SpvOp_.SpvOpMemoryModel); pub const SpvOpEntryPoint = @enumToInt(enum_SpvOp_.SpvOpEntryPoint); pub const SpvOpExecutionMode = @enumToInt(enum_SpvOp_.SpvOpExecutionMode); pub const SpvOpCapability = @enumToInt(enum_SpvOp_.SpvOpCapability); pub const SpvOpTypeVoid = @enumToInt(enum_SpvOp_.SpvOpTypeVoid); pub const SpvOpTypeBool = @enumToInt(enum_SpvOp_.SpvOpTypeBool); pub const SpvOpTypeInt = @enumToInt(enum_SpvOp_.SpvOpTypeInt); pub const SpvOpTypeFloat = @enumToInt(enum_SpvOp_.SpvOpTypeFloat); pub const SpvOpTypeVector = @enumToInt(enum_SpvOp_.SpvOpTypeVector); pub const SpvOpTypeMatrix = @enumToInt(enum_SpvOp_.SpvOpTypeMatrix); pub const SpvOpTypeImage = @enumToInt(enum_SpvOp_.SpvOpTypeImage); pub const SpvOpTypeSampler = @enumToInt(enum_SpvOp_.SpvOpTypeSampler); pub const SpvOpTypeSampledImage = @enumToInt(enum_SpvOp_.SpvOpTypeSampledImage); pub const SpvOpTypeArray = @enumToInt(enum_SpvOp_.SpvOpTypeArray); pub const SpvOpTypeRuntimeArray = @enumToInt(enum_SpvOp_.SpvOpTypeRuntimeArray); pub const SpvOpTypeStruct = @enumToInt(enum_SpvOp_.SpvOpTypeStruct); pub const SpvOpTypeOpaque = @enumToInt(enum_SpvOp_.SpvOpTypeOpaque); pub const SpvOpTypePointer = @enumToInt(enum_SpvOp_.SpvOpTypePointer); pub const SpvOpTypeFunction = @enumToInt(enum_SpvOp_.SpvOpTypeFunction); pub const SpvOpTypeEvent = @enumToInt(enum_SpvOp_.SpvOpTypeEvent); pub const SpvOpTypeDeviceEvent = @enumToInt(enum_SpvOp_.SpvOpTypeDeviceEvent); pub const SpvOpTypeReserveId = @enumToInt(enum_SpvOp_.SpvOpTypeReserveId); pub const SpvOpTypeQueue = @enumToInt(enum_SpvOp_.SpvOpTypeQueue); pub const SpvOpTypePipe = @enumToInt(enum_SpvOp_.SpvOpTypePipe); pub const SpvOpTypeForwardPointer = @enumToInt(enum_SpvOp_.SpvOpTypeForwardPointer); pub const SpvOpConstantTrue = @enumToInt(enum_SpvOp_.SpvOpConstantTrue); pub const SpvOpConstantFalse = @enumToInt(enum_SpvOp_.SpvOpConstantFalse); pub const SpvOpConstant = @enumToInt(enum_SpvOp_.SpvOpConstant); pub const SpvOpConstantComposite = @enumToInt(enum_SpvOp_.SpvOpConstantComposite); pub const SpvOpConstantSampler = @enumToInt(enum_SpvOp_.SpvOpConstantSampler); pub const SpvOpConstantNull = @enumToInt(enum_SpvOp_.SpvOpConstantNull); pub const SpvOpSpecConstantTrue = @enumToInt(enum_SpvOp_.SpvOpSpecConstantTrue); pub const SpvOpSpecConstantFalse = @enumToInt(enum_SpvOp_.SpvOpSpecConstantFalse); pub const SpvOpSpecConstant = @enumToInt(enum_SpvOp_.SpvOpSpecConstant); pub const SpvOpSpecConstantComposite = @enumToInt(enum_SpvOp_.SpvOpSpecConstantComposite); pub const SpvOpSpecConstantOp = @enumToInt(enum_SpvOp_.SpvOpSpecConstantOp); pub const SpvOpFunction = @enumToInt(enum_SpvOp_.SpvOpFunction); pub const SpvOpFunctionParameter = @enumToInt(enum_SpvOp_.SpvOpFunctionParameter); pub const SpvOpFunctionEnd = @enumToInt(enum_SpvOp_.SpvOpFunctionEnd); pub const SpvOpFunctionCall = @enumToInt(enum_SpvOp_.SpvOpFunctionCall); pub const SpvOpVariable = @enumToInt(enum_SpvOp_.SpvOpVariable); pub const SpvOpImageTexelPointer = @enumToInt(enum_SpvOp_.SpvOpImageTexelPointer); pub const SpvOpLoad = @enumToInt(enum_SpvOp_.SpvOpLoad); pub const SpvOpStore = @enumToInt(enum_SpvOp_.SpvOpStore); pub const SpvOpCopyMemory = @enumToInt(enum_SpvOp_.SpvOpCopyMemory); pub const SpvOpCopyMemorySized = @enumToInt(enum_SpvOp_.SpvOpCopyMemorySized); pub const SpvOpAccessChain = @enumToInt(enum_SpvOp_.SpvOpAccessChain); pub const SpvOpInBoundsAccessChain = @enumToInt(enum_SpvOp_.SpvOpInBoundsAccessChain); pub const SpvOpPtrAccessChain = @enumToInt(enum_SpvOp_.SpvOpPtrAccessChain); pub const SpvOpArrayLength = @enumToInt(enum_SpvOp_.SpvOpArrayLength); pub const SpvOpGenericPtrMemSemantics = @enumToInt(enum_SpvOp_.SpvOpGenericPtrMemSemantics); pub const SpvOpInBoundsPtrAccessChain = @enumToInt(enum_SpvOp_.SpvOpInBoundsPtrAccessChain); pub const SpvOpDecorate = @enumToInt(enum_SpvOp_.SpvOpDecorate); pub const SpvOpMemberDecorate = @enumToInt(enum_SpvOp_.SpvOpMemberDecorate); pub const SpvOpDecorationGroup = @enumToInt(enum_SpvOp_.SpvOpDecorationGroup); pub const SpvOpGroupDecorate = @enumToInt(enum_SpvOp_.SpvOpGroupDecorate); pub const SpvOpGroupMemberDecorate = @enumToInt(enum_SpvOp_.SpvOpGroupMemberDecorate); pub const SpvOpVectorExtractDynamic = @enumToInt(enum_SpvOp_.SpvOpVectorExtractDynamic); pub const SpvOpVectorInsertDynamic = @enumToInt(enum_SpvOp_.SpvOpVectorInsertDynamic); pub const SpvOpVectorShuffle = @enumToInt(enum_SpvOp_.SpvOpVectorShuffle); pub const SpvOpCompositeConstruct = @enumToInt(enum_SpvOp_.SpvOpCompositeConstruct); pub const SpvOpCompositeExtract = @enumToInt(enum_SpvOp_.SpvOpCompositeExtract); pub const SpvOpCompositeInsert = @enumToInt(enum_SpvOp_.SpvOpCompositeInsert); pub const SpvOpCopyObject = @enumToInt(enum_SpvOp_.SpvOpCopyObject); pub const SpvOpTranspose = @enumToInt(enum_SpvOp_.SpvOpTranspose); pub const SpvOpSampledImage = @enumToInt(enum_SpvOp_.SpvOpSampledImage); pub const SpvOpImageSampleImplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSampleImplicitLod); pub const SpvOpImageSampleExplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSampleExplicitLod); pub const SpvOpImageSampleDrefImplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSampleDrefImplicitLod); pub const SpvOpImageSampleDrefExplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSampleDrefExplicitLod); pub const SpvOpImageSampleProjImplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSampleProjImplicitLod); pub const SpvOpImageSampleProjExplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSampleProjExplicitLod); pub const SpvOpImageSampleProjDrefImplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSampleProjDrefImplicitLod); pub const SpvOpImageSampleProjDrefExplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSampleProjDrefExplicitLod); pub const SpvOpImageFetch = @enumToInt(enum_SpvOp_.SpvOpImageFetch); pub const SpvOpImageGather = @enumToInt(enum_SpvOp_.SpvOpImageGather); pub const SpvOpImageDrefGather = @enumToInt(enum_SpvOp_.SpvOpImageDrefGather); pub const SpvOpImageRead = @enumToInt(enum_SpvOp_.SpvOpImageRead); pub const SpvOpImageWrite = @enumToInt(enum_SpvOp_.SpvOpImageWrite); pub const SpvOpImage = @enumToInt(enum_SpvOp_.SpvOpImage); pub const SpvOpImageQueryFormat = @enumToInt(enum_SpvOp_.SpvOpImageQueryFormat); pub const SpvOpImageQueryOrder = @enumToInt(enum_SpvOp_.SpvOpImageQueryOrder); pub const SpvOpImageQuerySizeLod = @enumToInt(enum_SpvOp_.SpvOpImageQuerySizeLod); pub const SpvOpImageQuerySize = @enumToInt(enum_SpvOp_.SpvOpImageQuerySize); pub const SpvOpImageQueryLod = @enumToInt(enum_SpvOp_.SpvOpImageQueryLod); pub const SpvOpImageQueryLevels = @enumToInt(enum_SpvOp_.SpvOpImageQueryLevels); pub const SpvOpImageQuerySamples = @enumToInt(enum_SpvOp_.SpvOpImageQuerySamples); pub const SpvOpConvertFToU = @enumToInt(enum_SpvOp_.SpvOpConvertFToU); pub const SpvOpConvertFToS = @enumToInt(enum_SpvOp_.SpvOpConvertFToS); pub const SpvOpConvertSToF = @enumToInt(enum_SpvOp_.SpvOpConvertSToF); pub const SpvOpConvertUToF = @enumToInt(enum_SpvOp_.SpvOpConvertUToF); pub const SpvOpUConvert = @enumToInt(enum_SpvOp_.SpvOpUConvert); pub const SpvOpSConvert = @enumToInt(enum_SpvOp_.SpvOpSConvert); pub const SpvOpFConvert = @enumToInt(enum_SpvOp_.SpvOpFConvert); pub const SpvOpQuantizeToF16 = @enumToInt(enum_SpvOp_.SpvOpQuantizeToF16); pub const SpvOpConvertPtrToU = @enumToInt(enum_SpvOp_.SpvOpConvertPtrToU); pub const SpvOpSatConvertSToU = @enumToInt(enum_SpvOp_.SpvOpSatConvertSToU); pub const SpvOpSatConvertUToS = @enumToInt(enum_SpvOp_.SpvOpSatConvertUToS); pub const SpvOpConvertUToPtr = @enumToInt(enum_SpvOp_.SpvOpConvertUToPtr); pub const SpvOpPtrCastToGeneric = @enumToInt(enum_SpvOp_.SpvOpPtrCastToGeneric); pub const SpvOpGenericCastToPtr = @enumToInt(enum_SpvOp_.SpvOpGenericCastToPtr); pub const SpvOpGenericCastToPtrExplicit = @enumToInt(enum_SpvOp_.SpvOpGenericCastToPtrExplicit); pub const SpvOpBitcast = @enumToInt(enum_SpvOp_.SpvOpBitcast); pub const SpvOpSNegate = @enumToInt(enum_SpvOp_.SpvOpSNegate); pub const SpvOpFNegate = @enumToInt(enum_SpvOp_.SpvOpFNegate); pub const SpvOpIAdd = @enumToInt(enum_SpvOp_.SpvOpIAdd); pub const SpvOpFAdd = @enumToInt(enum_SpvOp_.SpvOpFAdd); pub const SpvOpISub = @enumToInt(enum_SpvOp_.SpvOpISub); pub const SpvOpFSub = @enumToInt(enum_SpvOp_.SpvOpFSub); pub const SpvOpIMul = @enumToInt(enum_SpvOp_.SpvOpIMul); pub const SpvOpFMul = @enumToInt(enum_SpvOp_.SpvOpFMul); pub const SpvOpUDiv = @enumToInt(enum_SpvOp_.SpvOpUDiv); pub const SpvOpSDiv = @enumToInt(enum_SpvOp_.SpvOpSDiv); pub const SpvOpFDiv = @enumToInt(enum_SpvOp_.SpvOpFDiv); pub const SpvOpUMod = @enumToInt(enum_SpvOp_.SpvOpUMod); pub const SpvOpSRem = @enumToInt(enum_SpvOp_.SpvOpSRem); pub const SpvOpSMod = @enumToInt(enum_SpvOp_.SpvOpSMod); pub const SpvOpFRem = @enumToInt(enum_SpvOp_.SpvOpFRem); pub const SpvOpFMod = @enumToInt(enum_SpvOp_.SpvOpFMod); pub const SpvOpVectorTimesScalar = @enumToInt(enum_SpvOp_.SpvOpVectorTimesScalar); pub const SpvOpMatrixTimesScalar = @enumToInt(enum_SpvOp_.SpvOpMatrixTimesScalar); pub const SpvOpVectorTimesMatrix = @enumToInt(enum_SpvOp_.SpvOpVectorTimesMatrix); pub const SpvOpMatrixTimesVector = @enumToInt(enum_SpvOp_.SpvOpMatrixTimesVector); pub const SpvOpMatrixTimesMatrix = @enumToInt(enum_SpvOp_.SpvOpMatrixTimesMatrix); pub const SpvOpOuterProduct = @enumToInt(enum_SpvOp_.SpvOpOuterProduct); pub const SpvOpDot = @enumToInt(enum_SpvOp_.SpvOpDot); pub const SpvOpIAddCarry = @enumToInt(enum_SpvOp_.SpvOpIAddCarry); pub const SpvOpISubBorrow = @enumToInt(enum_SpvOp_.SpvOpISubBorrow); pub const SpvOpUMulExtended = @enumToInt(enum_SpvOp_.SpvOpUMulExtended); pub const SpvOpSMulExtended = @enumToInt(enum_SpvOp_.SpvOpSMulExtended); pub const SpvOpAny = @enumToInt(enum_SpvOp_.SpvOpAny); pub const SpvOpAll = @enumToInt(enum_SpvOp_.SpvOpAll); pub const SpvOpIsNan = @enumToInt(enum_SpvOp_.SpvOpIsNan); pub const SpvOpIsInf = @enumToInt(enum_SpvOp_.SpvOpIsInf); pub const SpvOpIsFinite = @enumToInt(enum_SpvOp_.SpvOpIsFinite); pub const SpvOpIsNormal = @enumToInt(enum_SpvOp_.SpvOpIsNormal); pub const SpvOpSignBitSet = @enumToInt(enum_SpvOp_.SpvOpSignBitSet); pub const SpvOpLessOrGreater = @enumToInt(enum_SpvOp_.SpvOpLessOrGreater); pub const SpvOpOrdered = @enumToInt(enum_SpvOp_.SpvOpOrdered); pub const SpvOpUnordered = @enumToInt(enum_SpvOp_.SpvOpUnordered); pub const SpvOpLogicalEqual = @enumToInt(enum_SpvOp_.SpvOpLogicalEqual); pub const SpvOpLogicalNotEqual = @enumToInt(enum_SpvOp_.SpvOpLogicalNotEqual); pub const SpvOpLogicalOr = @enumToInt(enum_SpvOp_.SpvOpLogicalOr); pub const SpvOpLogicalAnd = @enumToInt(enum_SpvOp_.SpvOpLogicalAnd); pub const SpvOpLogicalNot = @enumToInt(enum_SpvOp_.SpvOpLogicalNot); pub const SpvOpSelect = @enumToInt(enum_SpvOp_.SpvOpSelect); pub const SpvOpIEqual = @enumToInt(enum_SpvOp_.SpvOpIEqual); pub const SpvOpINotEqual = @enumToInt(enum_SpvOp_.SpvOpINotEqual); pub const SpvOpUGreaterThan = @enumToInt(enum_SpvOp_.SpvOpUGreaterThan); pub const SpvOpSGreaterThan = @enumToInt(enum_SpvOp_.SpvOpSGreaterThan); pub const SpvOpUGreaterThanEqual = @enumToInt(enum_SpvOp_.SpvOpUGreaterThanEqual); pub const SpvOpSGreaterThanEqual = @enumToInt(enum_SpvOp_.SpvOpSGreaterThanEqual); pub const SpvOpULessThan = @enumToInt(enum_SpvOp_.SpvOpULessThan); pub const SpvOpSLessThan = @enumToInt(enum_SpvOp_.SpvOpSLessThan); pub const SpvOpULessThanEqual = @enumToInt(enum_SpvOp_.SpvOpULessThanEqual); pub const SpvOpSLessThanEqual = @enumToInt(enum_SpvOp_.SpvOpSLessThanEqual); pub const SpvOpFOrdEqual = @enumToInt(enum_SpvOp_.SpvOpFOrdEqual); pub const SpvOpFUnordEqual = @enumToInt(enum_SpvOp_.SpvOpFUnordEqual); pub const SpvOpFOrdNotEqual = @enumToInt(enum_SpvOp_.SpvOpFOrdNotEqual); pub const SpvOpFUnordNotEqual = @enumToInt(enum_SpvOp_.SpvOpFUnordNotEqual); pub const SpvOpFOrdLessThan = @enumToInt(enum_SpvOp_.SpvOpFOrdLessThan); pub const SpvOpFUnordLessThan = @enumToInt(enum_SpvOp_.SpvOpFUnordLessThan); pub const SpvOpFOrdGreaterThan = @enumToInt(enum_SpvOp_.SpvOpFOrdGreaterThan); pub const SpvOpFUnordGreaterThan = @enumToInt(enum_SpvOp_.SpvOpFUnordGreaterThan); pub const SpvOpFOrdLessThanEqual = @enumToInt(enum_SpvOp_.SpvOpFOrdLessThanEqual); pub const SpvOpFUnordLessThanEqual = @enumToInt(enum_SpvOp_.SpvOpFUnordLessThanEqual); pub const SpvOpFOrdGreaterThanEqual = @enumToInt(enum_SpvOp_.SpvOpFOrdGreaterThanEqual); pub const SpvOpFUnordGreaterThanEqual = @enumToInt(enum_SpvOp_.SpvOpFUnordGreaterThanEqual); pub const SpvOpShiftRightLogical = @enumToInt(enum_SpvOp_.SpvOpShiftRightLogical); pub const SpvOpShiftRightArithmetic = @enumToInt(enum_SpvOp_.SpvOpShiftRightArithmetic); pub const SpvOpShiftLeftLogical = @enumToInt(enum_SpvOp_.SpvOpShiftLeftLogical); pub const SpvOpBitwiseOr = @enumToInt(enum_SpvOp_.SpvOpBitwiseOr); pub const SpvOpBitwiseXor = @enumToInt(enum_SpvOp_.SpvOpBitwiseXor); pub const SpvOpBitwiseAnd = @enumToInt(enum_SpvOp_.SpvOpBitwiseAnd); pub const SpvOpNot = @enumToInt(enum_SpvOp_.SpvOpNot); pub const SpvOpBitFieldInsert = @enumToInt(enum_SpvOp_.SpvOpBitFieldInsert); pub const SpvOpBitFieldSExtract = @enumToInt(enum_SpvOp_.SpvOpBitFieldSExtract); pub const SpvOpBitFieldUExtract = @enumToInt(enum_SpvOp_.SpvOpBitFieldUExtract); pub const SpvOpBitReverse = @enumToInt(enum_SpvOp_.SpvOpBitReverse); pub const SpvOpBitCount = @enumToInt(enum_SpvOp_.SpvOpBitCount); pub const SpvOpDPdx = @enumToInt(enum_SpvOp_.SpvOpDPdx); pub const SpvOpDPdy = @enumToInt(enum_SpvOp_.SpvOpDPdy); pub const SpvOpFwidth = @enumToInt(enum_SpvOp_.SpvOpFwidth); pub const SpvOpDPdxFine = @enumToInt(enum_SpvOp_.SpvOpDPdxFine); pub const SpvOpDPdyFine = @enumToInt(enum_SpvOp_.SpvOpDPdyFine); pub const SpvOpFwidthFine = @enumToInt(enum_SpvOp_.SpvOpFwidthFine); pub const SpvOpDPdxCoarse = @enumToInt(enum_SpvOp_.SpvOpDPdxCoarse); pub const SpvOpDPdyCoarse = @enumToInt(enum_SpvOp_.SpvOpDPdyCoarse); pub const SpvOpFwidthCoarse = @enumToInt(enum_SpvOp_.SpvOpFwidthCoarse); pub const SpvOpEmitVertex = @enumToInt(enum_SpvOp_.SpvOpEmitVertex); pub const SpvOpEndPrimitive = @enumToInt(enum_SpvOp_.SpvOpEndPrimitive); pub const SpvOpEmitStreamVertex = @enumToInt(enum_SpvOp_.SpvOpEmitStreamVertex); pub const SpvOpEndStreamPrimitive = @enumToInt(enum_SpvOp_.SpvOpEndStreamPrimitive); pub const SpvOpControlBarrier = @enumToInt(enum_SpvOp_.SpvOpControlBarrier); pub const SpvOpMemoryBarrier = @enumToInt(enum_SpvOp_.SpvOpMemoryBarrier); pub const SpvOpAtomicLoad = @enumToInt(enum_SpvOp_.SpvOpAtomicLoad); pub const SpvOpAtomicStore = @enumToInt(enum_SpvOp_.SpvOpAtomicStore); pub const SpvOpAtomicExchange = @enumToInt(enum_SpvOp_.SpvOpAtomicExchange); pub const SpvOpAtomicCompareExchange = @enumToInt(enum_SpvOp_.SpvOpAtomicCompareExchange); pub const SpvOpAtomicCompareExchangeWeak = @enumToInt(enum_SpvOp_.SpvOpAtomicCompareExchangeWeak); pub const SpvOpAtomicIIncrement = @enumToInt(enum_SpvOp_.SpvOpAtomicIIncrement); pub const SpvOpAtomicIDecrement = @enumToInt(enum_SpvOp_.SpvOpAtomicIDecrement); pub const SpvOpAtomicIAdd = @enumToInt(enum_SpvOp_.SpvOpAtomicIAdd); pub const SpvOpAtomicISub = @enumToInt(enum_SpvOp_.SpvOpAtomicISub); pub const SpvOpAtomicSMin = @enumToInt(enum_SpvOp_.SpvOpAtomicSMin); pub const SpvOpAtomicUMin = @enumToInt(enum_SpvOp_.SpvOpAtomicUMin); pub const SpvOpAtomicSMax = @enumToInt(enum_SpvOp_.SpvOpAtomicSMax); pub const SpvOpAtomicUMax = @enumToInt(enum_SpvOp_.SpvOpAtomicUMax); pub const SpvOpAtomicAnd = @enumToInt(enum_SpvOp_.SpvOpAtomicAnd); pub const SpvOpAtomicOr = @enumToInt(enum_SpvOp_.SpvOpAtomicOr); pub const SpvOpAtomicXor = @enumToInt(enum_SpvOp_.SpvOpAtomicXor); pub const SpvOpPhi = @enumToInt(enum_SpvOp_.SpvOpPhi); pub const SpvOpLoopMerge = @enumToInt(enum_SpvOp_.SpvOpLoopMerge); pub const SpvOpSelectionMerge = @enumToInt(enum_SpvOp_.SpvOpSelectionMerge); pub const SpvOpLabel = @enumToInt(enum_SpvOp_.SpvOpLabel); pub const SpvOpBranch = @enumToInt(enum_SpvOp_.SpvOpBranch); pub const SpvOpBranchConditional = @enumToInt(enum_SpvOp_.SpvOpBranchConditional); pub const SpvOpSwitch = @enumToInt(enum_SpvOp_.SpvOpSwitch); pub const SpvOpKill = @enumToInt(enum_SpvOp_.SpvOpKill); pub const SpvOpReturn = @enumToInt(enum_SpvOp_.SpvOpReturn); pub const SpvOpReturnValue = @enumToInt(enum_SpvOp_.SpvOpReturnValue); pub const SpvOpUnreachable = @enumToInt(enum_SpvOp_.SpvOpUnreachable); pub const SpvOpLifetimeStart = @enumToInt(enum_SpvOp_.SpvOpLifetimeStart); pub const SpvOpLifetimeStop = @enumToInt(enum_SpvOp_.SpvOpLifetimeStop); pub const SpvOpGroupAsyncCopy = @enumToInt(enum_SpvOp_.SpvOpGroupAsyncCopy); pub const SpvOpGroupWaitEvents = @enumToInt(enum_SpvOp_.SpvOpGroupWaitEvents); pub const SpvOpGroupAll = @enumToInt(enum_SpvOp_.SpvOpGroupAll); pub const SpvOpGroupAny = @enumToInt(enum_SpvOp_.SpvOpGroupAny); pub const SpvOpGroupBroadcast = @enumToInt(enum_SpvOp_.SpvOpGroupBroadcast); pub const SpvOpGroupIAdd = @enumToInt(enum_SpvOp_.SpvOpGroupIAdd); pub const SpvOpGroupFAdd = @enumToInt(enum_SpvOp_.SpvOpGroupFAdd); pub const SpvOpGroupFMin = @enumToInt(enum_SpvOp_.SpvOpGroupFMin); pub const SpvOpGroupUMin = @enumToInt(enum_SpvOp_.SpvOpGroupUMin); pub const SpvOpGroupSMin = @enumToInt(enum_SpvOp_.SpvOpGroupSMin); pub const SpvOpGroupFMax = @enumToInt(enum_SpvOp_.SpvOpGroupFMax); pub const SpvOpGroupUMax = @enumToInt(enum_SpvOp_.SpvOpGroupUMax); pub const SpvOpGroupSMax = @enumToInt(enum_SpvOp_.SpvOpGroupSMax); pub const SpvOpReadPipe = @enumToInt(enum_SpvOp_.SpvOpReadPipe); pub const SpvOpWritePipe = @enumToInt(enum_SpvOp_.SpvOpWritePipe); pub const SpvOpReservedReadPipe = @enumToInt(enum_SpvOp_.SpvOpReservedReadPipe); pub const SpvOpReservedWritePipe = @enumToInt(enum_SpvOp_.SpvOpReservedWritePipe); pub const SpvOpReserveReadPipePackets = @enumToInt(enum_SpvOp_.SpvOpReserveReadPipePackets); pub const SpvOpReserveWritePipePackets = @enumToInt(enum_SpvOp_.SpvOpReserveWritePipePackets); pub const SpvOpCommitReadPipe = @enumToInt(enum_SpvOp_.SpvOpCommitReadPipe); pub const SpvOpCommitWritePipe = @enumToInt(enum_SpvOp_.SpvOpCommitWritePipe); pub const SpvOpIsValidReserveId = @enumToInt(enum_SpvOp_.SpvOpIsValidReserveId); pub const SpvOpGetNumPipePackets = @enumToInt(enum_SpvOp_.SpvOpGetNumPipePackets); pub const SpvOpGetMaxPipePackets = @enumToInt(enum_SpvOp_.SpvOpGetMaxPipePackets); pub const SpvOpGroupReserveReadPipePackets = @enumToInt(enum_SpvOp_.SpvOpGroupReserveReadPipePackets); pub const SpvOpGroupReserveWritePipePackets = @enumToInt(enum_SpvOp_.SpvOpGroupReserveWritePipePackets); pub const SpvOpGroupCommitReadPipe = @enumToInt(enum_SpvOp_.SpvOpGroupCommitReadPipe); pub const SpvOpGroupCommitWritePipe = @enumToInt(enum_SpvOp_.SpvOpGroupCommitWritePipe); pub const SpvOpEnqueueMarker = @enumToInt(enum_SpvOp_.SpvOpEnqueueMarker); pub const SpvOpEnqueueKernel = @enumToInt(enum_SpvOp_.SpvOpEnqueueKernel); pub const SpvOpGetKernelNDrangeSubGroupCount = @enumToInt(enum_SpvOp_.SpvOpGetKernelNDrangeSubGroupCount); pub const SpvOpGetKernelNDrangeMaxSubGroupSize = @enumToInt(enum_SpvOp_.SpvOpGetKernelNDrangeMaxSubGroupSize); pub const SpvOpGetKernelWorkGroupSize = @enumToInt(enum_SpvOp_.SpvOpGetKernelWorkGroupSize); pub const SpvOpGetKernelPreferredWorkGroupSizeMultiple = @enumToInt(enum_SpvOp_.SpvOpGetKernelPreferredWorkGroupSizeMultiple); pub const SpvOpRetainEvent = @enumToInt(enum_SpvOp_.SpvOpRetainEvent); pub const SpvOpReleaseEvent = @enumToInt(enum_SpvOp_.SpvOpReleaseEvent); pub const SpvOpCreateUserEvent = @enumToInt(enum_SpvOp_.SpvOpCreateUserEvent); pub const SpvOpIsValidEvent = @enumToInt(enum_SpvOp_.SpvOpIsValidEvent); pub const SpvOpSetUserEventStatus = @enumToInt(enum_SpvOp_.SpvOpSetUserEventStatus); pub const SpvOpCaptureEventProfilingInfo = @enumToInt(enum_SpvOp_.SpvOpCaptureEventProfilingInfo); pub const SpvOpGetDefaultQueue = @enumToInt(enum_SpvOp_.SpvOpGetDefaultQueue); pub const SpvOpBuildNDRange = @enumToInt(enum_SpvOp_.SpvOpBuildNDRange); pub const SpvOpImageSparseSampleImplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSparseSampleImplicitLod); pub const SpvOpImageSparseSampleExplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSparseSampleExplicitLod); pub const SpvOpImageSparseSampleDrefImplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSparseSampleDrefImplicitLod); pub const SpvOpImageSparseSampleDrefExplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSparseSampleDrefExplicitLod); pub const SpvOpImageSparseSampleProjImplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSparseSampleProjImplicitLod); pub const SpvOpImageSparseSampleProjExplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSparseSampleProjExplicitLod); pub const SpvOpImageSparseSampleProjDrefImplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSparseSampleProjDrefImplicitLod); pub const SpvOpImageSparseSampleProjDrefExplicitLod = @enumToInt(enum_SpvOp_.SpvOpImageSparseSampleProjDrefExplicitLod); pub const SpvOpImageSparseFetch = @enumToInt(enum_SpvOp_.SpvOpImageSparseFetch); pub const SpvOpImageSparseGather = @enumToInt(enum_SpvOp_.SpvOpImageSparseGather); pub const SpvOpImageSparseDrefGather = @enumToInt(enum_SpvOp_.SpvOpImageSparseDrefGather); pub const SpvOpImageSparseTexelsResident = @enumToInt(enum_SpvOp_.SpvOpImageSparseTexelsResident); pub const SpvOpNoLine = @enumToInt(enum_SpvOp_.SpvOpNoLine); pub const SpvOpAtomicFlagTestAndSet = @enumToInt(enum_SpvOp_.SpvOpAtomicFlagTestAndSet); pub const SpvOpAtomicFlagClear = @enumToInt(enum_SpvOp_.SpvOpAtomicFlagClear); pub const SpvOpImageSparseRead = @enumToInt(enum_SpvOp_.SpvOpImageSparseRead); pub const SpvOpSizeOf = @enumToInt(enum_SpvOp_.SpvOpSizeOf); pub const SpvOpTypePipeStorage = @enumToInt(enum_SpvOp_.SpvOpTypePipeStorage); pub const SpvOpConstantPipeStorage = @enumToInt(enum_SpvOp_.SpvOpConstantPipeStorage); pub const SpvOpCreatePipeFromPipeStorage = @enumToInt(enum_SpvOp_.SpvOpCreatePipeFromPipeStorage); pub const SpvOpGetKernelLocalSizeForSubgroupCount = @enumToInt(enum_SpvOp_.SpvOpGetKernelLocalSizeForSubgroupCount); pub const SpvOpGetKernelMaxNumSubgroups = @enumToInt(enum_SpvOp_.SpvOpGetKernelMaxNumSubgroups); pub const SpvOpTypeNamedBarrier = @enumToInt(enum_SpvOp_.SpvOpTypeNamedBarrier); pub const SpvOpNamedBarrierInitialize = @enumToInt(enum_SpvOp_.SpvOpNamedBarrierInitialize); pub const SpvOpMemoryNamedBarrier = @enumToInt(enum_SpvOp_.SpvOpMemoryNamedBarrier); pub const SpvOpModuleProcessed = @enumToInt(enum_SpvOp_.SpvOpModuleProcessed); pub const SpvOpExecutionModeId = @enumToInt(enum_SpvOp_.SpvOpExecutionModeId); pub const SpvOpDecorateId = @enumToInt(enum_SpvOp_.SpvOpDecorateId); pub const SpvOpGroupNonUniformElect = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformElect); pub const SpvOpGroupNonUniformAll = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformAll); pub const SpvOpGroupNonUniformAny = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformAny); pub const SpvOpGroupNonUniformAllEqual = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformAllEqual); pub const SpvOpGroupNonUniformBroadcast = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformBroadcast); pub const SpvOpGroupNonUniformBroadcastFirst = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformBroadcastFirst); pub const SpvOpGroupNonUniformBallot = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformBallot); pub const SpvOpGroupNonUniformInverseBallot = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformInverseBallot); pub const SpvOpGroupNonUniformBallotBitExtract = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformBallotBitExtract); pub const SpvOpGroupNonUniformBallotBitCount = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformBallotBitCount); pub const SpvOpGroupNonUniformBallotFindLSB = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformBallotFindLSB); pub const SpvOpGroupNonUniformBallotFindMSB = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformBallotFindMSB); pub const SpvOpGroupNonUniformShuffle = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformShuffle); pub const SpvOpGroupNonUniformShuffleXor = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformShuffleXor); pub const SpvOpGroupNonUniformShuffleUp = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformShuffleUp); pub const SpvOpGroupNonUniformShuffleDown = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformShuffleDown); pub const SpvOpGroupNonUniformIAdd = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformIAdd); pub const SpvOpGroupNonUniformFAdd = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformFAdd); pub const SpvOpGroupNonUniformIMul = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformIMul); pub const SpvOpGroupNonUniformFMul = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformFMul); pub const SpvOpGroupNonUniformSMin = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformSMin); pub const SpvOpGroupNonUniformUMin = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformUMin); pub const SpvOpGroupNonUniformFMin = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformFMin); pub const SpvOpGroupNonUniformSMax = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformSMax); pub const SpvOpGroupNonUniformUMax = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformUMax); pub const SpvOpGroupNonUniformFMax = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformFMax); pub const SpvOpGroupNonUniformBitwiseAnd = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformBitwiseAnd); pub const SpvOpGroupNonUniformBitwiseOr = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformBitwiseOr); pub const SpvOpGroupNonUniformBitwiseXor = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformBitwiseXor); pub const SpvOpGroupNonUniformLogicalAnd = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformLogicalAnd); pub const SpvOpGroupNonUniformLogicalOr = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformLogicalOr); pub const SpvOpGroupNonUniformLogicalXor = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformLogicalXor); pub const SpvOpGroupNonUniformQuadBroadcast = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformQuadBroadcast); pub const SpvOpGroupNonUniformQuadSwap = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformQuadSwap); pub const SpvOpCopyLogical = @enumToInt(enum_SpvOp_.SpvOpCopyLogical); pub const SpvOpPtrEqual = @enumToInt(enum_SpvOp_.SpvOpPtrEqual); pub const SpvOpPtrNotEqual = @enumToInt(enum_SpvOp_.SpvOpPtrNotEqual); pub const SpvOpPtrDiff = @enumToInt(enum_SpvOp_.SpvOpPtrDiff); pub const SpvOpSubgroupBallotKHR = @enumToInt(enum_SpvOp_.SpvOpSubgroupBallotKHR); pub const SpvOpSubgroupFirstInvocationKHR = @enumToInt(enum_SpvOp_.SpvOpSubgroupFirstInvocationKHR); pub const SpvOpSubgroupAllKHR = @enumToInt(enum_SpvOp_.SpvOpSubgroupAllKHR); pub const SpvOpSubgroupAnyKHR = @enumToInt(enum_SpvOp_.SpvOpSubgroupAnyKHR); pub const SpvOpSubgroupAllEqualKHR = @enumToInt(enum_SpvOp_.SpvOpSubgroupAllEqualKHR); pub const SpvOpSubgroupReadInvocationKHR = @enumToInt(enum_SpvOp_.SpvOpSubgroupReadInvocationKHR); pub const SpvOpTypeRayQueryProvisionalKHR = @enumToInt(enum_SpvOp_.SpvOpTypeRayQueryProvisionalKHR); pub const SpvOpRayQueryInitializeKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryInitializeKHR); pub const SpvOpRayQueryTerminateKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryTerminateKHR); pub const SpvOpRayQueryGenerateIntersectionKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGenerateIntersectionKHR); pub const SpvOpRayQueryConfirmIntersectionKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryConfirmIntersectionKHR); pub const SpvOpRayQueryProceedKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryProceedKHR); pub const SpvOpRayQueryGetIntersectionTypeKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetIntersectionTypeKHR); pub const SpvOpGroupIAddNonUniformAMD = @enumToInt(enum_SpvOp_.SpvOpGroupIAddNonUniformAMD); pub const SpvOpGroupFAddNonUniformAMD = @enumToInt(enum_SpvOp_.SpvOpGroupFAddNonUniformAMD); pub const SpvOpGroupFMinNonUniformAMD = @enumToInt(enum_SpvOp_.SpvOpGroupFMinNonUniformAMD); pub const SpvOpGroupUMinNonUniformAMD = @enumToInt(enum_SpvOp_.SpvOpGroupUMinNonUniformAMD); pub const SpvOpGroupSMinNonUniformAMD = @enumToInt(enum_SpvOp_.SpvOpGroupSMinNonUniformAMD); pub const SpvOpGroupFMaxNonUniformAMD = @enumToInt(enum_SpvOp_.SpvOpGroupFMaxNonUniformAMD); pub const SpvOpGroupUMaxNonUniformAMD = @enumToInt(enum_SpvOp_.SpvOpGroupUMaxNonUniformAMD); pub const SpvOpGroupSMaxNonUniformAMD = @enumToInt(enum_SpvOp_.SpvOpGroupSMaxNonUniformAMD); pub const SpvOpFragmentMaskFetchAMD = @enumToInt(enum_SpvOp_.SpvOpFragmentMaskFetchAMD); pub const SpvOpFragmentFetchAMD = @enumToInt(enum_SpvOp_.SpvOpFragmentFetchAMD); pub const SpvOpReadClockKHR = @enumToInt(enum_SpvOp_.SpvOpReadClockKHR); pub const SpvOpImageSampleFootprintNV = @enumToInt(enum_SpvOp_.SpvOpImageSampleFootprintNV); pub const SpvOpGroupNonUniformPartitionNV = @enumToInt(enum_SpvOp_.SpvOpGroupNonUniformPartitionNV); pub const SpvOpWritePackedPrimitiveIndices4x8NV = @enumToInt(enum_SpvOp_.SpvOpWritePackedPrimitiveIndices4x8NV); pub const SpvOpReportIntersectionKHR = @enumToInt(enum_SpvOp_.SpvOpReportIntersectionKHR); pub const SpvOpReportIntersectionNV = @enumToInt(enum_SpvOp_.SpvOpReportIntersectionNV); pub const SpvOpIgnoreIntersectionKHR = @enumToInt(enum_SpvOp_.SpvOpIgnoreIntersectionKHR); pub const SpvOpIgnoreIntersectionNV = @enumToInt(enum_SpvOp_.SpvOpIgnoreIntersectionNV); pub const SpvOpTerminateRayKHR = @enumToInt(enum_SpvOp_.SpvOpTerminateRayKHR); pub const SpvOpTerminateRayNV = @enumToInt(enum_SpvOp_.SpvOpTerminateRayNV); pub const SpvOpTraceNV = @enumToInt(enum_SpvOp_.SpvOpTraceNV); pub const SpvOpTraceRayKHR = @enumToInt(enum_SpvOp_.SpvOpTraceRayKHR); pub const SpvOpTypeAccelerationStructureKHR = @enumToInt(enum_SpvOp_.SpvOpTypeAccelerationStructureKHR); pub const SpvOpTypeAccelerationStructureNV = @enumToInt(enum_SpvOp_.SpvOpTypeAccelerationStructureNV); pub const SpvOpExecuteCallableKHR = @enumToInt(enum_SpvOp_.SpvOpExecuteCallableKHR); pub const SpvOpExecuteCallableNV = @enumToInt(enum_SpvOp_.SpvOpExecuteCallableNV); pub const SpvOpTypeCooperativeMatrixNV = @enumToInt(enum_SpvOp_.SpvOpTypeCooperativeMatrixNV); pub const SpvOpCooperativeMatrixLoadNV = @enumToInt(enum_SpvOp_.SpvOpCooperativeMatrixLoadNV); pub const SpvOpCooperativeMatrixStoreNV = @enumToInt(enum_SpvOp_.SpvOpCooperativeMatrixStoreNV); pub const SpvOpCooperativeMatrixMulAddNV = @enumToInt(enum_SpvOp_.SpvOpCooperativeMatrixMulAddNV); pub const SpvOpCooperativeMatrixLengthNV = @enumToInt(enum_SpvOp_.SpvOpCooperativeMatrixLengthNV); pub const SpvOpBeginInvocationInterlockEXT = @enumToInt(enum_SpvOp_.SpvOpBeginInvocationInterlockEXT); pub const SpvOpEndInvocationInterlockEXT = @enumToInt(enum_SpvOp_.SpvOpEndInvocationInterlockEXT); pub const SpvOpDemoteToHelperInvocationEXT = @enumToInt(enum_SpvOp_.SpvOpDemoteToHelperInvocationEXT); pub const SpvOpIsHelperInvocationEXT = @enumToInt(enum_SpvOp_.SpvOpIsHelperInvocationEXT); pub const SpvOpSubgroupShuffleINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupShuffleINTEL); pub const SpvOpSubgroupShuffleDownINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupShuffleDownINTEL); pub const SpvOpSubgroupShuffleUpINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupShuffleUpINTEL); pub const SpvOpSubgroupShuffleXorINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupShuffleXorINTEL); pub const SpvOpSubgroupBlockReadINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupBlockReadINTEL); pub const SpvOpSubgroupBlockWriteINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupBlockWriteINTEL); pub const SpvOpSubgroupImageBlockReadINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupImageBlockReadINTEL); pub const SpvOpSubgroupImageBlockWriteINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupImageBlockWriteINTEL); pub const SpvOpSubgroupImageMediaBlockReadINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupImageMediaBlockReadINTEL); pub const SpvOpSubgroupImageMediaBlockWriteINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupImageMediaBlockWriteINTEL); pub const SpvOpUCountLeadingZerosINTEL = @enumToInt(enum_SpvOp_.SpvOpUCountLeadingZerosINTEL); pub const SpvOpUCountTrailingZerosINTEL = @enumToInt(enum_SpvOp_.SpvOpUCountTrailingZerosINTEL); pub const SpvOpAbsISubINTEL = @enumToInt(enum_SpvOp_.SpvOpAbsISubINTEL); pub const SpvOpAbsUSubINTEL = @enumToInt(enum_SpvOp_.SpvOpAbsUSubINTEL); pub const SpvOpIAddSatINTEL = @enumToInt(enum_SpvOp_.SpvOpIAddSatINTEL); pub const SpvOpUAddSatINTEL = @enumToInt(enum_SpvOp_.SpvOpUAddSatINTEL); pub const SpvOpIAverageINTEL = @enumToInt(enum_SpvOp_.SpvOpIAverageINTEL); pub const SpvOpUAverageINTEL = @enumToInt(enum_SpvOp_.SpvOpUAverageINTEL); pub const SpvOpIAverageRoundedINTEL = @enumToInt(enum_SpvOp_.SpvOpIAverageRoundedINTEL); pub const SpvOpUAverageRoundedINTEL = @enumToInt(enum_SpvOp_.SpvOpUAverageRoundedINTEL); pub const SpvOpISubSatINTEL = @enumToInt(enum_SpvOp_.SpvOpISubSatINTEL); pub const SpvOpUSubSatINTEL = @enumToInt(enum_SpvOp_.SpvOpUSubSatINTEL); pub const SpvOpIMul32x16INTEL = @enumToInt(enum_SpvOp_.SpvOpIMul32x16INTEL); pub const SpvOpUMul32x16INTEL = @enumToInt(enum_SpvOp_.SpvOpUMul32x16INTEL); pub const SpvOpFunctionPointerINTEL = @enumToInt(enum_SpvOp_.SpvOpFunctionPointerINTEL); pub const SpvOpFunctionPointerCallINTEL = @enumToInt(enum_SpvOp_.SpvOpFunctionPointerCallINTEL); pub const SpvOpDecorateString = @enumToInt(enum_SpvOp_.SpvOpDecorateString); pub const SpvOpDecorateStringGOOGLE = @enumToInt(enum_SpvOp_.SpvOpDecorateStringGOOGLE); pub const SpvOpMemberDecorateString = @enumToInt(enum_SpvOp_.SpvOpMemberDecorateString); pub const SpvOpMemberDecorateStringGOOGLE = @enumToInt(enum_SpvOp_.SpvOpMemberDecorateStringGOOGLE); pub const SpvOpVmeImageINTEL = @enumToInt(enum_SpvOp_.SpvOpVmeImageINTEL); pub const SpvOpTypeVmeImageINTEL = @enumToInt(enum_SpvOp_.SpvOpTypeVmeImageINTEL); pub const SpvOpTypeAvcImePayloadINTEL = @enumToInt(enum_SpvOp_.SpvOpTypeAvcImePayloadINTEL); pub const SpvOpTypeAvcRefPayloadINTEL = @enumToInt(enum_SpvOp_.SpvOpTypeAvcRefPayloadINTEL); pub const SpvOpTypeAvcSicPayloadINTEL = @enumToInt(enum_SpvOp_.SpvOpTypeAvcSicPayloadINTEL); pub const SpvOpTypeAvcMcePayloadINTEL = @enumToInt(enum_SpvOp_.SpvOpTypeAvcMcePayloadINTEL); pub const SpvOpTypeAvcMceResultINTEL = @enumToInt(enum_SpvOp_.SpvOpTypeAvcMceResultINTEL); pub const SpvOpTypeAvcImeResultINTEL = @enumToInt(enum_SpvOp_.SpvOpTypeAvcImeResultINTEL); pub const SpvOpTypeAvcImeResultSingleReferenceStreamoutINTEL = @enumToInt(enum_SpvOp_.SpvOpTypeAvcImeResultSingleReferenceStreamoutINTEL); pub const SpvOpTypeAvcImeResultDualReferenceStreamoutINTEL = @enumToInt(enum_SpvOp_.SpvOpTypeAvcImeResultDualReferenceStreamoutINTEL); pub const SpvOpTypeAvcImeSingleReferenceStreaminINTEL = @enumToInt(enum_SpvOp_.SpvOpTypeAvcImeSingleReferenceStreaminINTEL); pub const SpvOpTypeAvcImeDualReferenceStreaminINTEL = @enumToInt(enum_SpvOp_.SpvOpTypeAvcImeDualReferenceStreaminINTEL); pub const SpvOpTypeAvcRefResultINTEL = @enumToInt(enum_SpvOp_.SpvOpTypeAvcRefResultINTEL); pub const SpvOpTypeAvcSicResultINTEL = @enumToInt(enum_SpvOp_.SpvOpTypeAvcSicResultINTEL); pub const SpvOpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL); pub const SpvOpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL); pub const SpvOpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL); pub const SpvOpSubgroupAvcMceSetInterShapePenaltyINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceSetInterShapePenaltyINTEL); pub const SpvOpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL); pub const SpvOpSubgroupAvcMceSetInterDirectionPenaltyINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceSetInterDirectionPenaltyINTEL); pub const SpvOpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL); pub const SpvOpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL); pub const SpvOpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL); pub const SpvOpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL); pub const SpvOpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL); pub const SpvOpSubgroupAvcMceSetMotionVectorCostFunctionINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceSetMotionVectorCostFunctionINTEL); pub const SpvOpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL); pub const SpvOpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL); pub const SpvOpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL); pub const SpvOpSubgroupAvcMceSetAcOnlyHaarINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceSetAcOnlyHaarINTEL); pub const SpvOpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL); pub const SpvOpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL); pub const SpvOpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL); pub const SpvOpSubgroupAvcMceConvertToImePayloadINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceConvertToImePayloadINTEL); pub const SpvOpSubgroupAvcMceConvertToImeResultINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceConvertToImeResultINTEL); pub const SpvOpSubgroupAvcMceConvertToRefPayloadINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceConvertToRefPayloadINTEL); pub const SpvOpSubgroupAvcMceConvertToRefResultINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceConvertToRefResultINTEL); pub const SpvOpSubgroupAvcMceConvertToSicPayloadINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceConvertToSicPayloadINTEL); pub const SpvOpSubgroupAvcMceConvertToSicResultINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceConvertToSicResultINTEL); pub const SpvOpSubgroupAvcMceGetMotionVectorsINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetMotionVectorsINTEL); pub const SpvOpSubgroupAvcMceGetInterDistortionsINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetInterDistortionsINTEL); pub const SpvOpSubgroupAvcMceGetBestInterDistortionsINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetBestInterDistortionsINTEL); pub const SpvOpSubgroupAvcMceGetInterMajorShapeINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetInterMajorShapeINTEL); pub const SpvOpSubgroupAvcMceGetInterMinorShapeINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetInterMinorShapeINTEL); pub const SpvOpSubgroupAvcMceGetInterDirectionsINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetInterDirectionsINTEL); pub const SpvOpSubgroupAvcMceGetInterMotionVectorCountINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetInterMotionVectorCountINTEL); pub const SpvOpSubgroupAvcMceGetInterReferenceIdsINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetInterReferenceIdsINTEL); pub const SpvOpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL); pub const SpvOpSubgroupAvcImeInitializeINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeInitializeINTEL); pub const SpvOpSubgroupAvcImeSetSingleReferenceINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeSetSingleReferenceINTEL); pub const SpvOpSubgroupAvcImeSetDualReferenceINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeSetDualReferenceINTEL); pub const SpvOpSubgroupAvcImeRefWindowSizeINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeRefWindowSizeINTEL); pub const SpvOpSubgroupAvcImeAdjustRefOffsetINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeAdjustRefOffsetINTEL); pub const SpvOpSubgroupAvcImeConvertToMcePayloadINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeConvertToMcePayloadINTEL); pub const SpvOpSubgroupAvcImeSetMaxMotionVectorCountINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeSetMaxMotionVectorCountINTEL); pub const SpvOpSubgroupAvcImeSetUnidirectionalMixDisableINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeSetUnidirectionalMixDisableINTEL); pub const SpvOpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL); pub const SpvOpSubgroupAvcImeSetWeightedSadINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeSetWeightedSadINTEL); pub const SpvOpSubgroupAvcImeEvaluateWithSingleReferenceINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeEvaluateWithSingleReferenceINTEL); pub const SpvOpSubgroupAvcImeEvaluateWithDualReferenceINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeEvaluateWithDualReferenceINTEL); pub const SpvOpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL); pub const SpvOpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL); pub const SpvOpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL); pub const SpvOpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL); pub const SpvOpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL); pub const SpvOpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL); pub const SpvOpSubgroupAvcImeConvertToMceResultINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeConvertToMceResultINTEL); pub const SpvOpSubgroupAvcImeGetSingleReferenceStreaminINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeGetSingleReferenceStreaminINTEL); pub const SpvOpSubgroupAvcImeGetDualReferenceStreaminINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeGetDualReferenceStreaminINTEL); pub const SpvOpSubgroupAvcImeStripSingleReferenceStreamoutINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeStripSingleReferenceStreamoutINTEL); pub const SpvOpSubgroupAvcImeStripDualReferenceStreamoutINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeStripDualReferenceStreamoutINTEL); pub const SpvOpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL); pub const SpvOpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL); pub const SpvOpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL); pub const SpvOpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL); pub const SpvOpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL); pub const SpvOpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL); pub const SpvOpSubgroupAvcImeGetBorderReachedINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeGetBorderReachedINTEL); pub const SpvOpSubgroupAvcImeGetTruncatedSearchIndicationINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeGetTruncatedSearchIndicationINTEL); pub const SpvOpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL); pub const SpvOpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL); pub const SpvOpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL); pub const SpvOpSubgroupAvcFmeInitializeINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcFmeInitializeINTEL); pub const SpvOpSubgroupAvcBmeInitializeINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcBmeInitializeINTEL); pub const SpvOpSubgroupAvcRefConvertToMcePayloadINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcRefConvertToMcePayloadINTEL); pub const SpvOpSubgroupAvcRefSetBidirectionalMixDisableINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcRefSetBidirectionalMixDisableINTEL); pub const SpvOpSubgroupAvcRefSetBilinearFilterEnableINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcRefSetBilinearFilterEnableINTEL); pub const SpvOpSubgroupAvcRefEvaluateWithSingleReferenceINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcRefEvaluateWithSingleReferenceINTEL); pub const SpvOpSubgroupAvcRefEvaluateWithDualReferenceINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcRefEvaluateWithDualReferenceINTEL); pub const SpvOpSubgroupAvcRefEvaluateWithMultiReferenceINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcRefEvaluateWithMultiReferenceINTEL); pub const SpvOpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL); pub const SpvOpSubgroupAvcRefConvertToMceResultINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcRefConvertToMceResultINTEL); pub const SpvOpSubgroupAvcSicInitializeINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicInitializeINTEL); pub const SpvOpSubgroupAvcSicConfigureSkcINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicConfigureSkcINTEL); pub const SpvOpSubgroupAvcSicConfigureIpeLumaINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicConfigureIpeLumaINTEL); pub const SpvOpSubgroupAvcSicConfigureIpeLumaChromaINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicConfigureIpeLumaChromaINTEL); pub const SpvOpSubgroupAvcSicGetMotionVectorMaskINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicGetMotionVectorMaskINTEL); pub const SpvOpSubgroupAvcSicConvertToMcePayloadINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicConvertToMcePayloadINTEL); pub const SpvOpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL); pub const SpvOpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL); pub const SpvOpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL); pub const SpvOpSubgroupAvcSicSetBilinearFilterEnableINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicSetBilinearFilterEnableINTEL); pub const SpvOpSubgroupAvcSicSetSkcForwardTransformEnableINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicSetSkcForwardTransformEnableINTEL); pub const SpvOpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL); pub const SpvOpSubgroupAvcSicEvaluateIpeINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicEvaluateIpeINTEL); pub const SpvOpSubgroupAvcSicEvaluateWithSingleReferenceINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicEvaluateWithSingleReferenceINTEL); pub const SpvOpSubgroupAvcSicEvaluateWithDualReferenceINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicEvaluateWithDualReferenceINTEL); pub const SpvOpSubgroupAvcSicEvaluateWithMultiReferenceINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicEvaluateWithMultiReferenceINTEL); pub const SpvOpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL); pub const SpvOpSubgroupAvcSicConvertToMceResultINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicConvertToMceResultINTEL); pub const SpvOpSubgroupAvcSicGetIpeLumaShapeINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicGetIpeLumaShapeINTEL); pub const SpvOpSubgroupAvcSicGetBestIpeLumaDistortionINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicGetBestIpeLumaDistortionINTEL); pub const SpvOpSubgroupAvcSicGetBestIpeChromaDistortionINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicGetBestIpeChromaDistortionINTEL); pub const SpvOpSubgroupAvcSicGetPackedIpeLumaModesINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicGetPackedIpeLumaModesINTEL); pub const SpvOpSubgroupAvcSicGetIpeChromaModeINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicGetIpeChromaModeINTEL); pub const SpvOpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL); pub const SpvOpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL); pub const SpvOpSubgroupAvcSicGetInterRawSadsINTEL = @enumToInt(enum_SpvOp_.SpvOpSubgroupAvcSicGetInterRawSadsINTEL); pub const SpvOpLoopControlINTEL = @enumToInt(enum_SpvOp_.SpvOpLoopControlINTEL); pub const SpvOpReadPipeBlockingINTEL = @enumToInt(enum_SpvOp_.SpvOpReadPipeBlockingINTEL); pub const SpvOpWritePipeBlockingINTEL = @enumToInt(enum_SpvOp_.SpvOpWritePipeBlockingINTEL); pub const SpvOpFPGARegINTEL = @enumToInt(enum_SpvOp_.SpvOpFPGARegINTEL); pub const SpvOpRayQueryGetRayTMinKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetRayTMinKHR); pub const SpvOpRayQueryGetRayFlagsKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetRayFlagsKHR); pub const SpvOpRayQueryGetIntersectionTKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetIntersectionTKHR); pub const SpvOpRayQueryGetIntersectionInstanceCustomIndexKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetIntersectionInstanceCustomIndexKHR); pub const SpvOpRayQueryGetIntersectionInstanceIdKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetIntersectionInstanceIdKHR); pub const SpvOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR); pub const SpvOpRayQueryGetIntersectionGeometryIndexKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetIntersectionGeometryIndexKHR); pub const SpvOpRayQueryGetIntersectionPrimitiveIndexKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetIntersectionPrimitiveIndexKHR); pub const SpvOpRayQueryGetIntersectionBarycentricsKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetIntersectionBarycentricsKHR); pub const SpvOpRayQueryGetIntersectionFrontFaceKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetIntersectionFrontFaceKHR); pub const SpvOpRayQueryGetIntersectionCandidateAABBOpaqueKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetIntersectionCandidateAABBOpaqueKHR); pub const SpvOpRayQueryGetIntersectionObjectRayDirectionKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetIntersectionObjectRayDirectionKHR); pub const SpvOpRayQueryGetIntersectionObjectRayOriginKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetIntersectionObjectRayOriginKHR); pub const SpvOpRayQueryGetWorldRayDirectionKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetWorldRayDirectionKHR); pub const SpvOpRayQueryGetWorldRayOriginKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetWorldRayOriginKHR); pub const SpvOpRayQueryGetIntersectionObjectToWorldKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetIntersectionObjectToWorldKHR); pub const SpvOpRayQueryGetIntersectionWorldToObjectKHR = @enumToInt(enum_SpvOp_.SpvOpRayQueryGetIntersectionWorldToObjectKHR); pub const SpvOpMax = @enumToInt(enum_SpvOp_.SpvOpMax); pub const enum_SpvOp_ = extern enum(c_int) { SpvOpNop = 0, SpvOpUndef = 1, SpvOpSourceContinued = 2, SpvOpSource = 3, SpvOpSourceExtension = 4, SpvOpName = 5, SpvOpMemberName = 6, SpvOpString = 7, SpvOpLine = 8, SpvOpExtension = 10, SpvOpExtInstImport = 11, SpvOpExtInst = 12, SpvOpMemoryModel = 14, SpvOpEntryPoint = 15, SpvOpExecutionMode = 16, SpvOpCapability = 17, SpvOpTypeVoid = 19, SpvOpTypeBool = 20, SpvOpTypeInt = 21, SpvOpTypeFloat = 22, SpvOpTypeVector = 23, SpvOpTypeMatrix = 24, SpvOpTypeImage = 25, SpvOpTypeSampler = 26, SpvOpTypeSampledImage = 27, SpvOpTypeArray = 28, SpvOpTypeRuntimeArray = 29, SpvOpTypeStruct = 30, SpvOpTypeOpaque = 31, SpvOpTypePointer = 32, SpvOpTypeFunction = 33, SpvOpTypeEvent = 34, SpvOpTypeDeviceEvent = 35, SpvOpTypeReserveId = 36, SpvOpTypeQueue = 37, SpvOpTypePipe = 38, SpvOpTypeForwardPointer = 39, SpvOpConstantTrue = 41, SpvOpConstantFalse = 42, SpvOpConstant = 43, SpvOpConstantComposite = 44, SpvOpConstantSampler = 45, SpvOpConstantNull = 46, SpvOpSpecConstantTrue = 48, SpvOpSpecConstantFalse = 49, SpvOpSpecConstant = 50, SpvOpSpecConstantComposite = 51, SpvOpSpecConstantOp = 52, SpvOpFunction = 54, SpvOpFunctionParameter = 55, SpvOpFunctionEnd = 56, SpvOpFunctionCall = 57, SpvOpVariable = 59, SpvOpImageTexelPointer = 60, SpvOpLoad = 61, SpvOpStore = 62, SpvOpCopyMemory = 63, SpvOpCopyMemorySized = 64, SpvOpAccessChain = 65, SpvOpInBoundsAccessChain = 66, SpvOpPtrAccessChain = 67, SpvOpArrayLength = 68, SpvOpGenericPtrMemSemantics = 69, SpvOpInBoundsPtrAccessChain = 70, SpvOpDecorate = 71, SpvOpMemberDecorate = 72, SpvOpDecorationGroup = 73, SpvOpGroupDecorate = 74, SpvOpGroupMemberDecorate = 75, SpvOpVectorExtractDynamic = 77, SpvOpVectorInsertDynamic = 78, SpvOpVectorShuffle = 79, SpvOpCompositeConstruct = 80, SpvOpCompositeExtract = 81, SpvOpCompositeInsert = 82, SpvOpCopyObject = 83, SpvOpTranspose = 84, SpvOpSampledImage = 86, SpvOpImageSampleImplicitLod = 87, SpvOpImageSampleExplicitLod = 88, SpvOpImageSampleDrefImplicitLod = 89, SpvOpImageSampleDrefExplicitLod = 90, SpvOpImageSampleProjImplicitLod = 91, SpvOpImageSampleProjExplicitLod = 92, SpvOpImageSampleProjDrefImplicitLod = 93, SpvOpImageSampleProjDrefExplicitLod = 94, SpvOpImageFetch = 95, SpvOpImageGather = 96, SpvOpImageDrefGather = 97, SpvOpImageRead = 98, SpvOpImageWrite = 99, SpvOpImage = 100, SpvOpImageQueryFormat = 101, SpvOpImageQueryOrder = 102, SpvOpImageQuerySizeLod = 103, SpvOpImageQuerySize = 104, SpvOpImageQueryLod = 105, SpvOpImageQueryLevels = 106, SpvOpImageQuerySamples = 107, SpvOpConvertFToU = 109, SpvOpConvertFToS = 110, SpvOpConvertSToF = 111, SpvOpConvertUToF = 112, SpvOpUConvert = 113, SpvOpSConvert = 114, SpvOpFConvert = 115, SpvOpQuantizeToF16 = 116, SpvOpConvertPtrToU = 117, SpvOpSatConvertSToU = 118, SpvOpSatConvertUToS = 119, SpvOpConvertUToPtr = 120, SpvOpPtrCastToGeneric = 121, SpvOpGenericCastToPtr = 122, SpvOpGenericCastToPtrExplicit = 123, SpvOpBitcast = 124, SpvOpSNegate = 126, SpvOpFNegate = 127, SpvOpIAdd = 128, SpvOpFAdd = 129, SpvOpISub = 130, SpvOpFSub = 131, SpvOpIMul = 132, SpvOpFMul = 133, SpvOpUDiv = 134, SpvOpSDiv = 135, SpvOpFDiv = 136, SpvOpUMod = 137, SpvOpSRem = 138, SpvOpSMod = 139, SpvOpFRem = 140, SpvOpFMod = 141, SpvOpVectorTimesScalar = 142, SpvOpMatrixTimesScalar = 143, SpvOpVectorTimesMatrix = 144, SpvOpMatrixTimesVector = 145, SpvOpMatrixTimesMatrix = 146, SpvOpOuterProduct = 147, SpvOpDot = 148, SpvOpIAddCarry = 149, SpvOpISubBorrow = 150, SpvOpUMulExtended = 151, SpvOpSMulExtended = 152, SpvOpAny = 154, SpvOpAll = 155, SpvOpIsNan = 156, SpvOpIsInf = 157, SpvOpIsFinite = 158, SpvOpIsNormal = 159, SpvOpSignBitSet = 160, SpvOpLessOrGreater = 161, SpvOpOrdered = 162, SpvOpUnordered = 163, SpvOpLogicalEqual = 164, SpvOpLogicalNotEqual = 165, SpvOpLogicalOr = 166, SpvOpLogicalAnd = 167, SpvOpLogicalNot = 168, SpvOpSelect = 169, SpvOpIEqual = 170, SpvOpINotEqual = 171, SpvOpUGreaterThan = 172, SpvOpSGreaterThan = 173, SpvOpUGreaterThanEqual = 174, SpvOpSGreaterThanEqual = 175, SpvOpULessThan = 176, SpvOpSLessThan = 177, SpvOpULessThanEqual = 178, SpvOpSLessThanEqual = 179, SpvOpFOrdEqual = 180, SpvOpFUnordEqual = 181, SpvOpFOrdNotEqual = 182, SpvOpFUnordNotEqual = 183, SpvOpFOrdLessThan = 184, SpvOpFUnordLessThan = 185, SpvOpFOrdGreaterThan = 186, SpvOpFUnordGreaterThan = 187, SpvOpFOrdLessThanEqual = 188, SpvOpFUnordLessThanEqual = 189, SpvOpFOrdGreaterThanEqual = 190, SpvOpFUnordGreaterThanEqual = 191, SpvOpShiftRightLogical = 194, SpvOpShiftRightArithmetic = 195, SpvOpShiftLeftLogical = 196, SpvOpBitwiseOr = 197, SpvOpBitwiseXor = 198, SpvOpBitwiseAnd = 199, SpvOpNot = 200, SpvOpBitFieldInsert = 201, SpvOpBitFieldSExtract = 202, SpvOpBitFieldUExtract = 203, SpvOpBitReverse = 204, SpvOpBitCount = 205, SpvOpDPdx = 207, SpvOpDPdy = 208, SpvOpFwidth = 209, SpvOpDPdxFine = 210, SpvOpDPdyFine = 211, SpvOpFwidthFine = 212, SpvOpDPdxCoarse = 213, SpvOpDPdyCoarse = 214, SpvOpFwidthCoarse = 215, SpvOpEmitVertex = 218, SpvOpEndPrimitive = 219, SpvOpEmitStreamVertex = 220, SpvOpEndStreamPrimitive = 221, SpvOpControlBarrier = 224, SpvOpMemoryBarrier = 225, SpvOpAtomicLoad = 227, SpvOpAtomicStore = 228, SpvOpAtomicExchange = 229, SpvOpAtomicCompareExchange = 230, SpvOpAtomicCompareExchangeWeak = 231, SpvOpAtomicIIncrement = 232, SpvOpAtomicIDecrement = 233, SpvOpAtomicIAdd = 234, SpvOpAtomicISub = 235, SpvOpAtomicSMin = 236, SpvOpAtomicUMin = 237, SpvOpAtomicSMax = 238, SpvOpAtomicUMax = 239, SpvOpAtomicAnd = 240, SpvOpAtomicOr = 241, SpvOpAtomicXor = 242, SpvOpPhi = 245, SpvOpLoopMerge = 246, SpvOpSelectionMerge = 247, SpvOpLabel = 248, SpvOpBranch = 249, SpvOpBranchConditional = 250, SpvOpSwitch = 251, SpvOpKill = 252, SpvOpReturn = 253, SpvOpReturnValue = 254, SpvOpUnreachable = 255, SpvOpLifetimeStart = 256, SpvOpLifetimeStop = 257, SpvOpGroupAsyncCopy = 259, SpvOpGroupWaitEvents = 260, SpvOpGroupAll = 261, SpvOpGroupAny = 262, SpvOpGroupBroadcast = 263, SpvOpGroupIAdd = 264, SpvOpGroupFAdd = 265, SpvOpGroupFMin = 266, SpvOpGroupUMin = 267, SpvOpGroupSMin = 268, SpvOpGroupFMax = 269, SpvOpGroupUMax = 270, SpvOpGroupSMax = 271, SpvOpReadPipe = 274, SpvOpWritePipe = 275, SpvOpReservedReadPipe = 276, SpvOpReservedWritePipe = 277, SpvOpReserveReadPipePackets = 278, SpvOpReserveWritePipePackets = 279, SpvOpCommitReadPipe = 280, SpvOpCommitWritePipe = 281, SpvOpIsValidReserveId = 282, SpvOpGetNumPipePackets = 283, SpvOpGetMaxPipePackets = 284, SpvOpGroupReserveReadPipePackets = 285, SpvOpGroupReserveWritePipePackets = 286, SpvOpGroupCommitReadPipe = 287, SpvOpGroupCommitWritePipe = 288, SpvOpEnqueueMarker = 291, SpvOpEnqueueKernel = 292, SpvOpGetKernelNDrangeSubGroupCount = 293, SpvOpGetKernelNDrangeMaxSubGroupSize = 294, SpvOpGetKernelWorkGroupSize = 295, SpvOpGetKernelPreferredWorkGroupSizeMultiple = 296, SpvOpRetainEvent = 297, SpvOpReleaseEvent = 298, SpvOpCreateUserEvent = 299, SpvOpIsValidEvent = 300, SpvOpSetUserEventStatus = 301, SpvOpCaptureEventProfilingInfo = 302, SpvOpGetDefaultQueue = 303, SpvOpBuildNDRange = 304, SpvOpImageSparseSampleImplicitLod = 305, SpvOpImageSparseSampleExplicitLod = 306, SpvOpImageSparseSampleDrefImplicitLod = 307, SpvOpImageSparseSampleDrefExplicitLod = 308, SpvOpImageSparseSampleProjImplicitLod = 309, SpvOpImageSparseSampleProjExplicitLod = 310, SpvOpImageSparseSampleProjDrefImplicitLod = 311, SpvOpImageSparseSampleProjDrefExplicitLod = 312, SpvOpImageSparseFetch = 313, SpvOpImageSparseGather = 314, SpvOpImageSparseDrefGather = 315, SpvOpImageSparseTexelsResident = 316, SpvOpNoLine = 317, SpvOpAtomicFlagTestAndSet = 318, SpvOpAtomicFlagClear = 319, SpvOpImageSparseRead = 320, SpvOpSizeOf = 321, SpvOpTypePipeStorage = 322, SpvOpConstantPipeStorage = 323, SpvOpCreatePipeFromPipeStorage = 324, SpvOpGetKernelLocalSizeForSubgroupCount = 325, SpvOpGetKernelMaxNumSubgroups = 326, SpvOpTypeNamedBarrier = 327, SpvOpNamedBarrierInitialize = 328, SpvOpMemoryNamedBarrier = 329, SpvOpModuleProcessed = 330, SpvOpExecutionModeId = 331, SpvOpDecorateId = 332, SpvOpGroupNonUniformElect = 333, SpvOpGroupNonUniformAll = 334, SpvOpGroupNonUniformAny = 335, SpvOpGroupNonUniformAllEqual = 336, SpvOpGroupNonUniformBroadcast = 337, SpvOpGroupNonUniformBroadcastFirst = 338, SpvOpGroupNonUniformBallot = 339, SpvOpGroupNonUniformInverseBallot = 340, SpvOpGroupNonUniformBallotBitExtract = 341, SpvOpGroupNonUniformBallotBitCount = 342, SpvOpGroupNonUniformBallotFindLSB = 343, SpvOpGroupNonUniformBallotFindMSB = 344, SpvOpGroupNonUniformShuffle = 345, SpvOpGroupNonUniformShuffleXor = 346, SpvOpGroupNonUniformShuffleUp = 347, SpvOpGroupNonUniformShuffleDown = 348, SpvOpGroupNonUniformIAdd = 349, SpvOpGroupNonUniformFAdd = 350, SpvOpGroupNonUniformIMul = 351, SpvOpGroupNonUniformFMul = 352, SpvOpGroupNonUniformSMin = 353, SpvOpGroupNonUniformUMin = 354, SpvOpGroupNonUniformFMin = 355, SpvOpGroupNonUniformSMax = 356, SpvOpGroupNonUniformUMax = 357, SpvOpGroupNonUniformFMax = 358, SpvOpGroupNonUniformBitwiseAnd = 359, SpvOpGroupNonUniformBitwiseOr = 360, SpvOpGroupNonUniformBitwiseXor = 361, SpvOpGroupNonUniformLogicalAnd = 362, SpvOpGroupNonUniformLogicalOr = 363, SpvOpGroupNonUniformLogicalXor = 364, SpvOpGroupNonUniformQuadBroadcast = 365, SpvOpGroupNonUniformQuadSwap = 366, SpvOpCopyLogical = 400, SpvOpPtrEqual = 401, SpvOpPtrNotEqual = 402, SpvOpPtrDiff = 403, SpvOpSubgroupBallotKHR = 4421, SpvOpSubgroupFirstInvocationKHR = 4422, SpvOpSubgroupAllKHR = 4428, SpvOpSubgroupAnyKHR = 4429, SpvOpSubgroupAllEqualKHR = 4430, SpvOpSubgroupReadInvocationKHR = 4432, SpvOpTypeRayQueryProvisionalKHR = 4472, SpvOpRayQueryInitializeKHR = 4473, SpvOpRayQueryTerminateKHR = 4474, SpvOpRayQueryGenerateIntersectionKHR = 4475, SpvOpRayQueryConfirmIntersectionKHR = 4476, SpvOpRayQueryProceedKHR = 4477, SpvOpRayQueryGetIntersectionTypeKHR = 4479, SpvOpGroupIAddNonUniformAMD = 5000, SpvOpGroupFAddNonUniformAMD = 5001, SpvOpGroupFMinNonUniformAMD = 5002, SpvOpGroupUMinNonUniformAMD = 5003, SpvOpGroupSMinNonUniformAMD = 5004, SpvOpGroupFMaxNonUniformAMD = 5005, SpvOpGroupUMaxNonUniformAMD = 5006, SpvOpGroupSMaxNonUniformAMD = 5007, SpvOpFragmentMaskFetchAMD = 5011, SpvOpFragmentFetchAMD = 5012, SpvOpReadClockKHR = 5056, SpvOpImageSampleFootprintNV = 5283, SpvOpGroupNonUniformPartitionNV = 5296, SpvOpWritePackedPrimitiveIndices4x8NV = 5299, SpvOpReportIntersectionKHR = 5334, SpvOpReportIntersectionNV = 5334, SpvOpIgnoreIntersectionKHR = 5335, SpvOpIgnoreIntersectionNV = 5335, SpvOpTerminateRayKHR = 5336, SpvOpTerminateRayNV = 5336, SpvOpTraceNV = 5337, SpvOpTraceRayKHR = 5337, SpvOpTypeAccelerationStructureKHR = 5341, SpvOpTypeAccelerationStructureNV = 5341, SpvOpExecuteCallableKHR = 5344, SpvOpExecuteCallableNV = 5344, SpvOpTypeCooperativeMatrixNV = 5358, SpvOpCooperativeMatrixLoadNV = 5359, SpvOpCooperativeMatrixStoreNV = 5360, SpvOpCooperativeMatrixMulAddNV = 5361, SpvOpCooperativeMatrixLengthNV = 5362, SpvOpBeginInvocationInterlockEXT = 5364, SpvOpEndInvocationInterlockEXT = 5365, SpvOpDemoteToHelperInvocationEXT = 5380, SpvOpIsHelperInvocationEXT = 5381, SpvOpSubgroupShuffleINTEL = 5571, SpvOpSubgroupShuffleDownINTEL = 5572, SpvOpSubgroupShuffleUpINTEL = 5573, SpvOpSubgroupShuffleXorINTEL = 5574, SpvOpSubgroupBlockReadINTEL = 5575, SpvOpSubgroupBlockWriteINTEL = 5576, SpvOpSubgroupImageBlockReadINTEL = 5577, SpvOpSubgroupImageBlockWriteINTEL = 5578, SpvOpSubgroupImageMediaBlockReadINTEL = 5580, SpvOpSubgroupImageMediaBlockWriteINTEL = 5581, SpvOpUCountLeadingZerosINTEL = 5585, SpvOpUCountTrailingZerosINTEL = 5586, SpvOpAbsISubINTEL = 5587, SpvOpAbsUSubINTEL = 5588, SpvOpIAddSatINTEL = 5589, SpvOpUAddSatINTEL = 5590, SpvOpIAverageINTEL = 5591, SpvOpUAverageINTEL = 5592, SpvOpIAverageRoundedINTEL = 5593, SpvOpUAverageRoundedINTEL = 5594, SpvOpISubSatINTEL = 5595, SpvOpUSubSatINTEL = 5596, SpvOpIMul32x16INTEL = 5597, SpvOpUMul32x16INTEL = 5598, SpvOpFunctionPointerINTEL = 5600, SpvOpFunctionPointerCallINTEL = 5601, SpvOpDecorateString = 5632, SpvOpDecorateStringGOOGLE = 5632, SpvOpMemberDecorateString = 5633, SpvOpMemberDecorateStringGOOGLE = 5633, SpvOpVmeImageINTEL = 5699, SpvOpTypeVmeImageINTEL = 5700, SpvOpTypeAvcImePayloadINTEL = 5701, SpvOpTypeAvcRefPayloadINTEL = 5702, SpvOpTypeAvcSicPayloadINTEL = 5703, SpvOpTypeAvcMcePayloadINTEL = 5704, SpvOpTypeAvcMceResultINTEL = 5705, SpvOpTypeAvcImeResultINTEL = 5706, SpvOpTypeAvcImeResultSingleReferenceStreamoutINTEL = 5707, SpvOpTypeAvcImeResultDualReferenceStreamoutINTEL = 5708, SpvOpTypeAvcImeSingleReferenceStreaminINTEL = 5709, SpvOpTypeAvcImeDualReferenceStreaminINTEL = 5710, SpvOpTypeAvcRefResultINTEL = 5711, SpvOpTypeAvcSicResultINTEL = 5712, SpvOpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL = 5713, SpvOpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL = 5714, SpvOpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL = 5715, SpvOpSubgroupAvcMceSetInterShapePenaltyINTEL = 5716, SpvOpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL = 5717, SpvOpSubgroupAvcMceSetInterDirectionPenaltyINTEL = 5718, SpvOpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL = 5719, SpvOpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL = 5720, SpvOpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL = 5721, SpvOpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL = 5722, SpvOpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL = 5723, SpvOpSubgroupAvcMceSetMotionVectorCostFunctionINTEL = 5724, SpvOpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL = 5725, SpvOpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL = 5726, SpvOpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL = 5727, SpvOpSubgroupAvcMceSetAcOnlyHaarINTEL = 5728, SpvOpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL = 5729, SpvOpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL = 5730, SpvOpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL = 5731, SpvOpSubgroupAvcMceConvertToImePayloadINTEL = 5732, SpvOpSubgroupAvcMceConvertToImeResultINTEL = 5733, SpvOpSubgroupAvcMceConvertToRefPayloadINTEL = 5734, SpvOpSubgroupAvcMceConvertToRefResultINTEL = 5735, SpvOpSubgroupAvcMceConvertToSicPayloadINTEL = 5736, SpvOpSubgroupAvcMceConvertToSicResultINTEL = 5737, SpvOpSubgroupAvcMceGetMotionVectorsINTEL = 5738, SpvOpSubgroupAvcMceGetInterDistortionsINTEL = 5739, SpvOpSubgroupAvcMceGetBestInterDistortionsINTEL = 5740, SpvOpSubgroupAvcMceGetInterMajorShapeINTEL = 5741, SpvOpSubgroupAvcMceGetInterMinorShapeINTEL = 5742, SpvOpSubgroupAvcMceGetInterDirectionsINTEL = 5743, SpvOpSubgroupAvcMceGetInterMotionVectorCountINTEL = 5744, SpvOpSubgroupAvcMceGetInterReferenceIdsINTEL = 5745, SpvOpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL = 5746, SpvOpSubgroupAvcImeInitializeINTEL = 5747, SpvOpSubgroupAvcImeSetSingleReferenceINTEL = 5748, SpvOpSubgroupAvcImeSetDualReferenceINTEL = 5749, SpvOpSubgroupAvcImeRefWindowSizeINTEL = 5750, SpvOpSubgroupAvcImeAdjustRefOffsetINTEL = 5751, SpvOpSubgroupAvcImeConvertToMcePayloadINTEL = 5752, SpvOpSubgroupAvcImeSetMaxMotionVectorCountINTEL = 5753, SpvOpSubgroupAvcImeSetUnidirectionalMixDisableINTEL = 5754, SpvOpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL = 5755, SpvOpSubgroupAvcImeSetWeightedSadINTEL = 5756, SpvOpSubgroupAvcImeEvaluateWithSingleReferenceINTEL = 5757, SpvOpSubgroupAvcImeEvaluateWithDualReferenceINTEL = 5758, SpvOpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL = 5759, SpvOpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL = 5760, SpvOpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL = 5761, SpvOpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL = 5762, SpvOpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL = 5763, SpvOpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL = 5764, SpvOpSubgroupAvcImeConvertToMceResultINTEL = 5765, SpvOpSubgroupAvcImeGetSingleReferenceStreaminINTEL = 5766, SpvOpSubgroupAvcImeGetDualReferenceStreaminINTEL = 5767, SpvOpSubgroupAvcImeStripSingleReferenceStreamoutINTEL = 5768, SpvOpSubgroupAvcImeStripDualReferenceStreamoutINTEL = 5769, SpvOpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL = 5770, SpvOpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL = 5771, SpvOpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL = 5772, SpvOpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL = 5773, SpvOpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL = 5774, SpvOpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL = 5775, SpvOpSubgroupAvcImeGetBorderReachedINTEL = 5776, SpvOpSubgroupAvcImeGetTruncatedSearchIndicationINTEL = 5777, SpvOpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL = 5778, SpvOpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL = 5779, SpvOpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL = 5780, SpvOpSubgroupAvcFmeInitializeINTEL = 5781, SpvOpSubgroupAvcBmeInitializeINTEL = 5782, SpvOpSubgroupAvcRefConvertToMcePayloadINTEL = 5783, SpvOpSubgroupAvcRefSetBidirectionalMixDisableINTEL = 5784, SpvOpSubgroupAvcRefSetBilinearFilterEnableINTEL = 5785, SpvOpSubgroupAvcRefEvaluateWithSingleReferenceINTEL = 5786, SpvOpSubgroupAvcRefEvaluateWithDualReferenceINTEL = 5787, SpvOpSubgroupAvcRefEvaluateWithMultiReferenceINTEL = 5788, SpvOpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL = 5789, SpvOpSubgroupAvcRefConvertToMceResultINTEL = 5790, SpvOpSubgroupAvcSicInitializeINTEL = 5791, SpvOpSubgroupAvcSicConfigureSkcINTEL = 5792, SpvOpSubgroupAvcSicConfigureIpeLumaINTEL = 5793, SpvOpSubgroupAvcSicConfigureIpeLumaChromaINTEL = 5794, SpvOpSubgroupAvcSicGetMotionVectorMaskINTEL = 5795, SpvOpSubgroupAvcSicConvertToMcePayloadINTEL = 5796, SpvOpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL = 5797, SpvOpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL = 5798, SpvOpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL = 5799, SpvOpSubgroupAvcSicSetBilinearFilterEnableINTEL = 5800, SpvOpSubgroupAvcSicSetSkcForwardTransformEnableINTEL = 5801, SpvOpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL = 5802, SpvOpSubgroupAvcSicEvaluateIpeINTEL = 5803, SpvOpSubgroupAvcSicEvaluateWithSingleReferenceINTEL = 5804, SpvOpSubgroupAvcSicEvaluateWithDualReferenceINTEL = 5805, SpvOpSubgroupAvcSicEvaluateWithMultiReferenceINTEL = 5806, SpvOpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL = 5807, SpvOpSubgroupAvcSicConvertToMceResultINTEL = 5808, SpvOpSubgroupAvcSicGetIpeLumaShapeINTEL = 5809, SpvOpSubgroupAvcSicGetBestIpeLumaDistortionINTEL = 5810, SpvOpSubgroupAvcSicGetBestIpeChromaDistortionINTEL = 5811, SpvOpSubgroupAvcSicGetPackedIpeLumaModesINTEL = 5812, SpvOpSubgroupAvcSicGetIpeChromaModeINTEL = 5813, SpvOpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = 5814, SpvOpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = 5815, SpvOpSubgroupAvcSicGetInterRawSadsINTEL = 5816, SpvOpLoopControlINTEL = 5887, SpvOpReadPipeBlockingINTEL = 5946, SpvOpWritePipeBlockingINTEL = 5947, SpvOpFPGARegINTEL = 5949, SpvOpRayQueryGetRayTMinKHR = 6016, SpvOpRayQueryGetRayFlagsKHR = 6017, SpvOpRayQueryGetIntersectionTKHR = 6018, SpvOpRayQueryGetIntersectionInstanceCustomIndexKHR = 6019, SpvOpRayQueryGetIntersectionInstanceIdKHR = 6020, SpvOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR = 6021, SpvOpRayQueryGetIntersectionGeometryIndexKHR = 6022, SpvOpRayQueryGetIntersectionPrimitiveIndexKHR = 6023, SpvOpRayQueryGetIntersectionBarycentricsKHR = 6024, SpvOpRayQueryGetIntersectionFrontFaceKHR = 6025, SpvOpRayQueryGetIntersectionCandidateAABBOpaqueKHR = 6026, SpvOpRayQueryGetIntersectionObjectRayDirectionKHR = 6027, SpvOpRayQueryGetIntersectionObjectRayOriginKHR = 6028, SpvOpRayQueryGetWorldRayDirectionKHR = 6029, SpvOpRayQueryGetWorldRayOriginKHR = 6030, SpvOpRayQueryGetIntersectionObjectToWorldKHR = 6031, SpvOpRayQueryGetIntersectionWorldToObjectKHR = 6032, SpvOpMax = 2147483647, _, }; pub const SpvOp = enum_SpvOp_;
render/src/include/spirv.zig
const std = @import("std"); const Arena = std.heap.ArenaAllocator; const expectEqual = std.testing.expectEqual; const expectEqualStrings = std.testing.expectEqualStrings; const yeti = @import("yeti"); const initCodebase = yeti.initCodebase; const tokenize = yeti.tokenize; const parse = yeti.parse; const analyzeSemantics = yeti.analyzeSemantics; const codegen = yeti.codegen; const printWasm = yeti.printWasm; const components = yeti.components; const literalOf = yeti.query.literalOf; const typeOf = yeti.query.typeOf; const MockFileSystem = yeti.FileSystem; const Entity = yeti.ecs.Entity; test "parse import" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const module = try codebase.createEntity(.{}); const code = \\import "math.yeti" \\ \\start() f64 { \\ clamp(7, low=0, high=5) \\} ; var tokens = try tokenize(module, code); try parse(module, &tokens); const imports = module.get(components.Imports).slice(); try expectEqual(imports.len, 1); const math = imports[0]; try expectEqual(math.get(components.AstKind), .import); try expectEqualStrings(literalOf(math.get(components.Path).entity), "math.yeti"); const top_level = module.get(components.TopLevel); const start = top_level.findString("start"); const overloads = start.get(components.Overloads).slice(); try expectEqual(overloads.len, 1); const body = overloads[0].get(components.Body).slice(); try expectEqual(body.len, 1); const clamp = body[0]; const callable = clamp.get(components.Callable).entity; try expectEqualStrings(literalOf(callable), "clamp"); const arguments = clamp.get(components.Arguments).slice(); try expectEqual(arguments.len, 1); try expectEqualStrings(literalOf(arguments[0]), "7"); const named_arguments = clamp.get(components.NamedArguments); try expectEqual(named_arguments.count(), 2); try expectEqualStrings(literalOf(named_arguments.findString("low")), "0"); try expectEqualStrings(literalOf(named_arguments.findString("high")), "5"); } test "analyze semantics of import" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const builtins = codebase.get(components.Builtins); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("start.yeti", \\import "math.yeti" \\ \\start() f64 { \\ clamp(7, low=0, high=5) \\} ); _ = try fs.newFile("math.yeti", \\min(x: f64, y: f64) f64 { \\ if x < y { x } else { y } \\} \\ \\max(x: f64, y: f64) f64 { \\ if x > y { x } else { y } \\} \\ \\clamp(x: f64, low: f64, high: f64) f64 { \\ x.min(high).max(low) \\} ); const module = try analyzeSemantics(codebase, fs, "start.yeti"); const top_level = module.get(components.TopLevel); const clamp = blk: { const start = top_level.findString("start").get(components.Overloads).slice()[0]; try expectEqualStrings(literalOf(start.get(components.Module).entity), "start"); try expectEqualStrings(literalOf(start.get(components.Name).entity), "start"); try expectEqual(start.get(components.Parameters).len(), 0); try expectEqual(start.get(components.ReturnType).entity, builtins.F64); const body = start.get(components.Body).slice(); try expectEqual(body.len, 1); const call = body[0]; try expectEqual(call.get(components.AstKind), .call); try expectEqual(call.get(components.Arguments).len(), 1); try expectEqual(call.get(components.OrderedNamedArguments).len(), 2); try expectEqual(typeOf(call), builtins.F64); const callable = call.get(components.Callable).entity; break :blk callable; }; const max = blk: { try expectEqualStrings(literalOf(clamp.get(components.Module).entity), "math"); try expectEqualStrings(literalOf(clamp.get(components.Name).entity), "clamp"); try expectEqual(clamp.get(components.AstKind), .function); try expectEqual(clamp.get(components.Parameters).len(), 3); try expectEqual(clamp.get(components.ReturnType).entity, builtins.F64); const body = clamp.get(components.Body).slice(); try expectEqual(body.len, 1); const call = body[0]; try expectEqual(call.get(components.AstKind), .call); try expectEqual(call.get(components.Arguments).len(), 2); try expectEqual(call.get(components.OrderedNamedArguments).len(), 0); try expectEqual(typeOf(call), builtins.F64); const callable = call.get(components.Callable).entity; break :blk callable; }; { try expectEqualStrings(literalOf(max.get(components.Module).entity), "math"); try expectEqualStrings(literalOf(max.get(components.Name).entity), "max"); try expectEqual(max.get(components.AstKind), .function); try expectEqual(max.get(components.Parameters).len(), 2); try expectEqual(max.get(components.ReturnType).entity, builtins.F64); const body = max.get(components.Body).slice(); try expectEqual(body.len, 1); try expectEqual(body[0].get(components.AstKind), .if_); } }
src/tests/test_import.zig
const std = @import("std"); const windows = @import("windows.zig"); const IUnknown = windows.IUnknown; const BYTE = windows.BYTE; const HRESULT = windows.HRESULT; const WINAPI = windows.WINAPI; const UINT32 = windows.UINT32; const BOOL = windows.BOOL; const FALSE = windows.FALSE; const L = std.unicode.utf8ToUtf16LeStringLiteral; pub const VOLUMEMETER_LEVELS = packed struct { pPeakLevels: ?[*]f32, pRMSLevels: ?[*]f32, ChannelCount: UINT32, }; pub const REVERB_MIN_FRAMERATE: UINT32 = 20000; pub const REVERB_MAX_FRAMERATE: UINT32 = 48000; pub const REVERB_PARAMETERS = packed struct { WetDryMix: f32, ReflectionsDelay: UINT32, ReverbDelay: BYTE, RearDelay: BYTE, SideDelay: BYTE, PositionLeft: BYTE, PositionRight: BYTE, PositionMatrixLeft: BYTE, PositionMatrixRight: BYTE, EarlyDiffusion: BYTE, LateDiffusion: BYTE, LowEQGain: BYTE, LowEQCutoff: BYTE, HighEQGain: BYTE, HighEQCutoff: BYTE, RoomFilterFreq: f32, RoomFilterMain: f32, RoomFilterHF: f32, ReflectionsGain: f32, ReverbGain: f32, DecayTime: f32, Density: f32, RoomSize: f32, DisableLateField: BOOL, pub fn initDefault() REVERB_PARAMETERS { return .{ .WetDryMix = REVERB_DEFAULT_WET_DRY_MIX, .ReflectionsDelay = REVERB_DEFAULT_REFLECTIONS_DELAY, .ReverbDelay = REVERB_DEFAULT_REVERB_DELAY, .RearDelay = REVERB_DEFAULT_REAR_DELAY, .SideDelay = REVERB_DEFAULT_REAR_DELAY, .PositionLeft = REVERB_DEFAULT_POSITION, .PositionRight = REVERB_DEFAULT_POSITION, .PositionMatrixLeft = REVERB_DEFAULT_POSITION_MATRIX, .PositionMatrixRight = REVERB_DEFAULT_POSITION_MATRIX, .EarlyDiffusion = REVERB_DEFAULT_EARLY_DIFFUSION, .LateDiffusion = REVERB_DEFAULT_LATE_DIFFUSION, .LowEQGain = REVERB_DEFAULT_LOW_EQ_GAIN, .LowEQCutoff = REVERB_DEFAULT_LOW_EQ_CUTOFF, .HighEQGain = REVERB_DEFAULT_HIGH_EQ_CUTOFF, .HighEQCutoff = REVERB_DEFAULT_HIGH_EQ_GAIN, .RoomFilterFreq = REVERB_DEFAULT_ROOM_FILTER_FREQ, .RoomFilterMain = REVERB_DEFAULT_ROOM_FILTER_MAIN, .RoomFilterHF = REVERB_DEFAULT_ROOM_FILTER_HF, .ReflectionsGain = REVERB_DEFAULT_REFLECTIONS_GAIN, .ReverbGain = REVERB_DEFAULT_REVERB_GAIN, .DecayTime = REVERB_DEFAULT_DECAY_TIME, .Density = REVERB_DEFAULT_DENSITY, .RoomSize = REVERB_DEFAULT_ROOM_SIZE, .DisableLateField = REVERB_DEFAULT_DISABLE_LATE_FIELD, }; } }; pub const REVERB_MIN_WET_DRY_MIX: f32 = 0.0; pub const REVERB_MIN_REFLECTIONS_DELAY: UINT32 = 0; pub const REVERB_MIN_REVERB_DELAY: BYTE = 0; pub const REVERB_MIN_REAR_DELAY: BYTE = 0; pub const REVERB_MIN_7POINT1_SIDE_DELAY: BYTE = 0; pub const REVERB_MIN_7POINT1_REAR_DELAY: BYTE = 0; pub const REVERB_MIN_POSITION: BYTE = 0; pub const REVERB_MIN_DIFFUSION: BYTE = 0; pub const REVERB_MIN_LOW_EQ_GAIN: BYTE = 0; pub const REVERB_MIN_LOW_EQ_CUTOFF: BYTE = 0; pub const REVERB_MIN_HIGH_EQ_GAIN: BYTE = 0; pub const REVERB_MIN_HIGH_EQ_CUTOFF: BYTE = 0; pub const REVERB_MIN_ROOM_FILTER_FREQ: f32 = 20.0; pub const REVERB_MIN_ROOM_FILTER_MAIN: f32 = -100.0; pub const REVERB_MIN_ROOM_FILTER_HF: f32 = -100.0; pub const REVERB_MIN_REFLECTIONS_GAIN: f32 = -100.0; pub const REVERB_MIN_REVERB_GAIN: f32 = -100.0; pub const REVERB_MIN_DECAY_TIME: f32 = 0.1; pub const REVERB_MIN_DENSITY: f32 = 0.0; pub const REVERB_MIN_ROOM_SIZE: f32 = 0.0; pub const REVERB_MAX_WET_DRY_MIX: f32 = 100.0; pub const REVERB_MAX_REFLECTIONS_DELAY: UINT32 = 300; pub const REVERB_MAX_REVERB_DELAY: BYTE = 85; pub const REVERB_MAX_REAR_DELAY: BYTE = 5; pub const REVERB_MAX_7POINT1_SIDE_DELAY: BYTE = 5; pub const REVERB_MAX_7POINT1_REAR_DELAY: BYTE = 20; pub const REVERB_MAX_POSITION: BYTE = 30; pub const REVERB_MAX_DIFFUSION: BYTE = 15; pub const REVERB_MAX_LOW_EQ_GAIN: BYTE = 12; pub const REVERB_MAX_LOW_EQ_CUTOFF: BYTE = 9; pub const REVERB_MAX_HIGH_EQ_GAIN: BYTE = 8; pub const REVERB_MAX_HIGH_EQ_CUTOFF: BYTE = 14; pub const REVERB_MAX_ROOM_FILTER_FREQ: f32 = 20000.0; pub const REVERB_MAX_ROOM_FILTER_MAIN: f32 = 0.0; pub const REVERB_MAX_ROOM_FILTER_HF: f32 = 0.0; pub const REVERB_MAX_REFLECTIONS_GAIN: f32 = 20.0; pub const REVERB_MAX_REVERB_GAIN: f32 = 20.0; pub const REVERB_MAX_DENSITY: f32 = 100.0; pub const REVERB_MAX_ROOM_SIZE: f32 = 100.0; pub const REVERB_DEFAULT_WET_DRY_MIX: f32 = 100.0; pub const REVERB_DEFAULT_REFLECTIONS_DELAY: UINT32 = 5; pub const REVERB_DEFAULT_REVERB_DELAY: BYTE = 5; pub const REVERB_DEFAULT_REAR_DELAY: BYTE = 5; pub const REVERB_DEFAULT_7POINT1_SIDE_DELAY: BYTE = 5; pub const REVERB_DEFAULT_7POINT1_REAR_DELAY: BYTE = 20; pub const REVERB_DEFAULT_POSITION: BYTE = 6; pub const REVERB_DEFAULT_POSITION_MATRIX: BYTE = 27; pub const REVERB_DEFAULT_EARLY_DIFFUSION: BYTE = 8; pub const REVERB_DEFAULT_LATE_DIFFUSION: BYTE = 8; pub const REVERB_DEFAULT_LOW_EQ_GAIN: BYTE = 8; pub const REVERB_DEFAULT_LOW_EQ_CUTOFF: BYTE = 4; pub const REVERB_DEFAULT_HIGH_EQ_GAIN: BYTE = 8; pub const REVERB_DEFAULT_HIGH_EQ_CUTOFF: BYTE = 4; pub const REVERB_DEFAULT_ROOM_FILTER_FREQ: f32 = 5000.0; pub const REVERB_DEFAULT_ROOM_FILTER_MAIN: f32 = 0.0; pub const REVERB_DEFAULT_ROOM_FILTER_HF: f32 = 0.0; pub const REVERB_DEFAULT_REFLECTIONS_GAIN: f32 = 0.0; pub const REVERB_DEFAULT_REVERB_GAIN: f32 = 0.0; pub const REVERB_DEFAULT_DECAY_TIME: f32 = 1.0; pub const REVERB_DEFAULT_DENSITY: f32 = 100.0; pub const REVERB_DEFAULT_ROOM_SIZE: f32 = 100.0; pub const REVERB_DEFAULT_DISABLE_LATE_FIELD: BOOL = FALSE; pub fn createVolumeMeter(apo: *?*IUnknown, _: UINT32) HRESULT { var xaudio2_dll = windows.kernel32.GetModuleHandleW(L("xaudio2_9redist.dll")); if (xaudio2_dll == null) { xaudio2_dll = (std.DynLib.openZ("d3d12/xaudio2_9redist.dll") catch unreachable).dll; } var CreateAudioVolumeMeter: fn (*?*IUnknown) callconv(WINAPI) HRESULT = undefined; CreateAudioVolumeMeter = @ptrCast( @TypeOf(CreateAudioVolumeMeter), windows.kernel32.GetProcAddress(xaudio2_dll.?, "CreateAudioVolumeMeter").?, ); return CreateAudioVolumeMeter(apo); } pub fn createReverb(apo: *?*IUnknown, _: UINT32) HRESULT { var xaudio2_dll = windows.kernel32.GetModuleHandleW(L("xaudio2_9redist.dll")); if (xaudio2_dll == null) { xaudio2_dll = (std.DynLib.openZ("d3d12/xaudio2_9redist.dll") catch unreachable).dll; } var CreateAudioReverb: fn (*?*IUnknown) callconv(WINAPI) HRESULT = undefined; CreateAudioReverb = @ptrCast( @TypeOf(CreateAudioReverb), windows.kernel32.GetProcAddress(xaudio2_dll.?, "CreateAudioReverb").?, ); return CreateAudioReverb(apo); }
modules/platform/vendored/zwin32/src/xaudio2fx.zig
const builtin = @import("builtin"); const IsWasm = builtin.target.isWasm(); const stdx = @import("stdx"); const Vec2 = stdx.math.Vec2; const Mat4 = stdx.math.Mat4; const gl = @import("gl"); const graphics = @import("../../graphics.zig"); const Shader = graphics.gl.Shader; const Color = graphics.Color; const tex_vert = @embedFile("shaders/tex_vert.glsl"); const tex_frag = @embedFile("shaders/tex_frag.glsl"); const tex_vert_webgl2 = @embedFile("shaders/tex_vert_webgl2.glsl"); const tex_frag_webgl2 = @embedFile("shaders/tex_frag_webgl2.glsl"); const gradient_vert = @embedFile("shaders/gradient_vert.glsl"); const gradient_frag = @embedFile("shaders/gradient_frag.glsl"); pub const TexShader = struct { shader: Shader, u_mvp: gl.GLint, u_tex: gl.GLint, const Self = @This(); pub fn init(vert_buf_id: gl.GLuint) Self { var shader: Shader = undefined; if (IsWasm) { shader = Shader.init(tex_vert_webgl2, tex_frag_webgl2) catch unreachable; } else { shader = Shader.init(tex_vert, tex_frag) catch unreachable; } gl.bindVertexArray(shader.vao_id); gl.bindBuffer(gl.GL_ARRAY_BUFFER, vert_buf_id); // a_pos gl.enableVertexAttribArray(0); vertexAttribPointer(0, 4, gl.GL_FLOAT, 10 * 4, u32ToVoidPtr(0)); // a_uv gl.enableVertexAttribArray(1); vertexAttribPointer(1, 2, gl.GL_FLOAT, 10 * 4, u32ToVoidPtr(4 * 4)); // a_color gl.enableVertexAttribArray(2); vertexAttribPointer(2, 4, gl.GL_FLOAT, 10 * 4, u32ToVoidPtr(6 * 4)); gl.bindVertexArray(0); return .{ .shader = shader, .u_mvp = shader.getUniformLocation("u_mvp"), .u_tex = shader.getUniformLocation("u_tex"), }; } pub fn deinit(self: Self) void { self.shader.deinit(); } pub fn bind(self: Self, mvp: Mat4, tex_id: gl.GLuint) void { gl.useProgram(self.shader.prog_id); // set u_mvp, since transpose is false, it expects to receive in column major order. gl.uniformMatrix4fv(self.u_mvp, 1, gl.GL_FALSE, &mvp); gl.activeTexture(gl.GL_TEXTURE0); gl.bindTexture(gl.GL_TEXTURE_2D, tex_id); // set tex to active texture. gl.uniform1i(self.u_tex, 0); } }; pub const GradientShader = struct { shader: Shader, u_mvp: gl.GLint, u_start_pos: gl.GLint, u_start_color: gl.GLint, u_end_pos: gl.GLint, u_end_color: gl.GLint, const Self = @This(); pub fn init(vert_buf_id: gl.GLuint) Self { var shader: Shader = undefined; shader = Shader.init(gradient_vert, gradient_frag) catch unreachable; gl.bindVertexArray(shader.vao_id); gl.bindBuffer(gl.GL_ARRAY_BUFFER, vert_buf_id); // a_pos gl.enableVertexAttribArray(0); vertexAttribPointer(0, 4, gl.GL_FLOAT, 10 * 4, u32ToVoidPtr(0)); gl.bindVertexArray(0); return .{ .shader = shader, .u_mvp = shader.getUniformLocation("u_mvp"), .u_start_pos = shader.getUniformLocation("u_start_pos"), .u_start_color = shader.getUniformLocation("u_start_color"), .u_end_pos = shader.getUniformLocation("u_end_pos"), .u_end_color = shader.getUniformLocation("u_end_color"), }; } pub fn deinit(self: Self) void { self.shader.deinit(); } pub fn bind(self: Self, mvp: Mat4, start_pos: Vec2, start_color: Color, end_pos: Vec2, end_color: Color) void { gl.useProgram(self.shader.prog_id); // set u_mvp, since transpose is false, it expects to receive in column major order. gl.uniformMatrix4fv(self.u_mvp, 1, gl.GL_FALSE, &mvp); gl.uniform2fv(self.u_start_pos, 1, @ptrCast([*]const f32, &start_pos)); gl.uniform2fv(self.u_end_pos, 1, @ptrCast([*]const f32, &end_pos)); const start_color_arr = start_color.toFloatArray(); gl.uniform4fv(self.u_start_color, 1, &start_color_arr); const end_color_arr = end_color.toFloatArray(); gl.uniform4fv(self.u_end_color, 1, &end_color_arr); } }; fn u32ToVoidPtr(val: u32) ?*const gl.GLvoid { return @intToPtr(?*const gl.GLvoid, val); } // Define how to get attribute data out of vertex buffer. Eg. an attribute a_pos could be a vec4 meaning 4 components. // size - num of components for the attribute. // type - component data type. // normalized - normally false, only relevant for non GL_FLOAT types anyway. // stride - number of bytes for each vertex. 0 indicates that the stride is size * sizeof(type) // offset - offset in bytes of the first component of first vertex. fn vertexAttribPointer(attr_idx: gl.GLuint, size: gl.GLint, data_type: gl.GLenum, stride: gl.GLsizei, offset: ?*const gl.GLvoid) void { gl.vertexAttribPointer(attr_idx, size, data_type, gl.GL_FALSE, stride, offset); }
graphics/src/backend/gl/shaders.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const ArrayList = std.ArrayList; const Builder = std.build.Builder; const File = std.fs.File; const InstallDir = std.build.InstallDir; const LibExeObjStep = std.build.LibExeObjStep; const Step = std.build.Step; const elf = std.elf; const fs = std.fs; const io = std.io; const sort = std.sort; const warn = std.debug.warn; const BinaryElfSection = struct { elfOffset: u64, binaryOffset: u64, fileSize: usize, segment: ?*BinaryElfSegment, }; const BinaryElfSegment = struct { physicalAddress: u64, virtualAddress: u64, elfOffset: u64, binaryOffset: u64, fileSize: usize, firstSection: ?*BinaryElfSection, }; const BinaryElfOutput = struct { segments: ArrayList(*BinaryElfSegment), sections: ArrayList(*BinaryElfSection), const Self = @This(); pub fn deinit(self: *Self) void { self.sections.deinit(); self.segments.deinit(); } pub fn parse(allocator: *Allocator, elf_file: File) !Self { var self: Self = .{ .segments = ArrayList(*BinaryElfSegment).init(allocator), .sections = ArrayList(*BinaryElfSection).init(allocator), }; const elf_hdr = try std.elf.readHeader(elf_file); var section_headers = elf_hdr.section_header_iterator(elf_file); while (try section_headers.next()) |section| { if (sectionValidForOutput(section)) { const newSection = try allocator.create(BinaryElfSection); newSection.binaryOffset = 0; newSection.elfOffset = section.sh_offset; newSection.fileSize = @intCast(usize, section.sh_size); newSection.segment = null; try self.sections.append(newSection); } } var program_headers = elf_hdr.program_header_iterator(elf_file); while (try program_headers.next()) |phdr| { if (phdr.p_type == elf.PT_LOAD) { const newSegment = try allocator.create(BinaryElfSegment); newSegment.physicalAddress = if (phdr.p_paddr != 0) phdr.p_paddr else phdr.p_vaddr; newSegment.virtualAddress = phdr.p_vaddr; newSegment.fileSize = @intCast(usize, phdr.p_filesz); newSegment.elfOffset = phdr.p_offset; newSegment.binaryOffset = 0; newSegment.firstSection = null; for (self.sections.items) |section| { if (sectionWithinSegment(section, phdr)) { if (section.segment) |sectionSegment| { if (sectionSegment.elfOffset > newSegment.elfOffset) { section.segment = newSegment; } } else { section.segment = newSegment; } if (newSegment.firstSection == null) { newSegment.firstSection = section; } } } try self.segments.append(newSegment); } } sort.sort(*BinaryElfSegment, self.segments.items, {}, segmentSortCompare); if (self.segments.items.len > 0) { const firstSegment = self.segments.items[0]; if (firstSegment.firstSection) |firstSection| { const diff = firstSection.elfOffset - firstSegment.elfOffset; firstSegment.elfOffset += diff; firstSegment.fileSize += diff; firstSegment.physicalAddress += diff; const basePhysicalAddress = firstSegment.physicalAddress; for (self.segments.items) |segment| { segment.binaryOffset = segment.physicalAddress - basePhysicalAddress; } } } for (self.sections.items) |section| { if (section.segment) |segment| { section.binaryOffset = segment.binaryOffset + (section.elfOffset - segment.elfOffset); } } sort.sort(*BinaryElfSection, self.sections.items, {}, sectionSortCompare); return self; } fn sectionWithinSegment(section: *BinaryElfSection, segment: elf.Elf64_Phdr) bool { return segment.p_offset <= section.elfOffset and (segment.p_offset + segment.p_filesz) >= (section.elfOffset + section.fileSize); } fn sectionValidForOutput(shdr: anytype) bool { return shdr.sh_size > 0 and shdr.sh_type != elf.SHT_NOBITS and ((shdr.sh_flags & elf.SHF_ALLOC) == elf.SHF_ALLOC); } fn segmentSortCompare(context: void, left: *BinaryElfSegment, right: *BinaryElfSegment) bool { if (left.physicalAddress < right.physicalAddress) { return true; } if (left.physicalAddress > right.physicalAddress) { return false; } return false; } fn sectionSortCompare(context: void, left: *BinaryElfSection, right: *BinaryElfSection) bool { return left.binaryOffset < right.binaryOffset; } }; fn writeBinaryElfSection(elf_file: File, out_file: File, section: *BinaryElfSection) !void { try out_file.seekTo(section.binaryOffset); try out_file.writeFileAll(elf_file, .{ .in_offset = section.elfOffset, .in_len = section.fileSize, }); } fn emitRaw(allocator: *Allocator, elf_path: []const u8, raw_path: []const u8) !void { var elf_file = try fs.cwd().openFile(elf_path, .{}); defer elf_file.close(); var out_file = try fs.cwd().createFile(raw_path, .{}); defer out_file.close(); var binary_elf_output = try BinaryElfOutput.parse(allocator, elf_file); defer binary_elf_output.deinit(); for (binary_elf_output.sections.items) |section| { try writeBinaryElfSection(elf_file, out_file, section); } } pub const InstallRawStep = struct { step: Step, builder: *Builder, artifact: *LibExeObjStep, dest_dir: InstallDir, dest_filename: []const u8, const Self = @This(); pub fn create(builder: *Builder, artifact: *LibExeObjStep, dest_filename: []const u8) *Self { const self = builder.allocator.create(Self) catch unreachable; self.* = Self{ .step = Step.init(.InstallRaw, builder.fmt("install raw binary {}", .{artifact.step.name}), builder.allocator, make), .builder = builder, .artifact = artifact, .dest_dir = switch (artifact.kind) { .Obj => unreachable, .Test => unreachable, .Exe => .Bin, .Lib => unreachable, }, .dest_filename = dest_filename, }; self.step.dependOn(&artifact.step); builder.pushInstalledFile(self.dest_dir, dest_filename); return self; } fn make(step: *Step) !void { const self = @fieldParentPtr(Self, "step", step); const builder = self.builder; if (self.artifact.target.getObjectFormat() != .elf) { warn("InstallRawStep only works with ELF format.\n", .{}); return error.InvalidObjectFormat; } const full_src_path = self.artifact.getOutputPath(); const full_dest_path = builder.getInstallPath(self.dest_dir, self.dest_filename); fs.cwd().makePath(builder.getInstallPath(self.dest_dir, "")) catch unreachable; try emitRaw(builder.allocator, full_src_path, full_dest_path); } }; test "" { std.testing.refAllDecls(InstallRawStep); }
lib/std/build/emit_raw.zig
const CodeSignature = @This(); const std = @import("std"); const assert = std.debug.assert; const fs = std.fs; const log = std.log.scoped(.macho); const macho = std.macho; const mem = std.mem; const testing = std.testing; const Allocator = mem.Allocator; const Sha256 = std.crypto.hash.sha2.Sha256; const Zld = @import("../Zld.zig"); const hash_size: u8 = 32; const CodeDirectory = struct { inner: macho.CodeDirectory, data: std.ArrayListUnmanaged(u8) = .{}, fn size(self: CodeDirectory) u32 { return self.inner.length; } fn write(self: CodeDirectory, writer: anytype) !void { try writer.writeIntBig(u32, self.inner.magic); try writer.writeIntBig(u32, self.inner.length); try writer.writeIntBig(u32, self.inner.version); try writer.writeIntBig(u32, self.inner.flags); try writer.writeIntBig(u32, self.inner.hashOffset); try writer.writeIntBig(u32, self.inner.identOffset); try writer.writeIntBig(u32, self.inner.nSpecialSlots); try writer.writeIntBig(u32, self.inner.nCodeSlots); try writer.writeIntBig(u32, self.inner.codeLimit); try writer.writeByte(self.inner.hashSize); try writer.writeByte(self.inner.hashType); try writer.writeByte(self.inner.platform); try writer.writeByte(self.inner.pageSize); try writer.writeIntBig(u32, self.inner.spare2); try writer.writeIntBig(u32, self.inner.scatterOffset); try writer.writeIntBig(u32, self.inner.teamOffset); try writer.writeIntBig(u32, self.inner.spare3); try writer.writeIntBig(u64, self.inner.codeLimit64); try writer.writeIntBig(u64, self.inner.execSegBase); try writer.writeIntBig(u64, self.inner.execSegLimit); try writer.writeIntBig(u64, self.inner.execSegFlags); try writer.writeAll(self.data.items); } }; /// Code signature blob header. inner: macho.SuperBlob = .{ .magic = macho.CSMAGIC_EMBEDDED_SIGNATURE, .length = @sizeOf(macho.SuperBlob), .count = 0, }, /// CodeDirectory header which holds the hash of the binary. cdir: ?CodeDirectory = null, pub fn calcAdhocSignature( self: *CodeSignature, allocator: *Allocator, file: fs.File, id: []const u8, text_segment: macho.segment_command_64, code_sig_cmd: macho.linkedit_data_command, output_mode: Zld.OutputMode, page_size: u16, ) !void { const execSegBase: u64 = text_segment.fileoff; const execSegLimit: u64 = text_segment.filesize; const execSegFlags: u64 = if (output_mode == .exe) macho.CS_EXECSEG_MAIN_BINARY else 0; const file_size = code_sig_cmd.dataoff; var cdir = CodeDirectory{ .inner = .{ .magic = macho.CSMAGIC_CODEDIRECTORY, .length = @sizeOf(macho.CodeDirectory), .version = macho.CS_SUPPORTSEXECSEG, .flags = macho.CS_ADHOC, .hashOffset = 0, .identOffset = 0, .nSpecialSlots = 0, .nCodeSlots = 0, .codeLimit = file_size, .hashSize = hash_size, .hashType = macho.CS_HASHTYPE_SHA256, .platform = 0, .pageSize = @truncate(u8, std.math.log2(page_size)), .spare2 = 0, .scatterOffset = 0, .teamOffset = 0, .spare3 = 0, .codeLimit64 = 0, .execSegBase = execSegBase, .execSegLimit = execSegLimit, .execSegFlags = execSegFlags, }, }; const total_pages = mem.alignForward(file_size, page_size) / page_size; var hash: [hash_size]u8 = undefined; var buffer = try allocator.alloc(u8, page_size); defer allocator.free(buffer); try cdir.data.ensureTotalCapacity(allocator, total_pages * hash_size + id.len + 1); // 1. Save the identifier and update offsets cdir.inner.identOffset = cdir.inner.length; cdir.data.appendSliceAssumeCapacity(id); cdir.data.appendAssumeCapacity(0); // 2. Calculate hash for each page (in file) and write it to the buffer // TODO figure out how we can cache several hashes since we won't update // every page during incremental linking cdir.inner.hashOffset = cdir.inner.identOffset + @intCast(u32, id.len) + 1; var i: usize = 0; while (i < total_pages) : (i += 1) { const fstart = i * page_size; const fsize = if (fstart + page_size > file_size) file_size - fstart else page_size; const len = try file.preadAll(buffer, fstart); assert(fsize <= len); Sha256.hash(buffer[0..fsize], &hash, .{}); cdir.data.appendSliceAssumeCapacity(&hash); cdir.inner.nCodeSlots += 1; } // 3. Update CodeDirectory length cdir.inner.length += @intCast(u32, cdir.data.items.len); self.inner.length += @sizeOf(macho.BlobIndex) + cdir.size(); self.inner.count = 1; self.cdir = cdir; } pub fn size(self: CodeSignature) u32 { return self.inner.length; } pub fn write(self: CodeSignature, writer: anytype) !void { try self.writeHeader(writer); const offset: u32 = @sizeOf(macho.SuperBlob) + @sizeOf(macho.BlobIndex); try writeBlobIndex(macho.CSSLOT_CODEDIRECTORY, offset, writer); try self.cdir.?.write(writer); } pub fn deinit(self: *CodeSignature, allocator: *Allocator) void { if (self.cdir) |*cdir| { cdir.data.deinit(allocator); } } fn writeHeader(self: CodeSignature, writer: anytype) !void { try writer.writeIntBig(u32, self.inner.magic); try writer.writeIntBig(u32, self.inner.length); try writer.writeIntBig(u32, self.inner.count); } fn writeBlobIndex(tt: u32, offset: u32, writer: anytype) !void { try writer.writeIntBig(u32, tt); try writer.writeIntBig(u32, offset); } test "CodeSignature header" { var code_sig: CodeSignature = .{}; defer code_sig.deinit(testing.allocator); var buffer: [@sizeOf(macho.SuperBlob)]u8 = undefined; var stream = std.io.fixedBufferStream(&buffer); try code_sig.writeHeader(stream.writer()); const expected = &[_]u8{ 0xfa, 0xde, 0x0c, 0xc0, 0x0, 0x0, 0x0, 0xc, 0x0, 0x0, 0x0, 0x0 }; try testing.expect(mem.eql(u8, expected, &buffer)); } pub fn calcCodeSignaturePaddingSize(id: []const u8, file_size: u64, page_size: u16) u32 { const ident_size = id.len + 1; const total_pages = mem.alignForwardGeneric(u64, file_size, page_size) / page_size; const hashed_size = total_pages * hash_size; const codesig_header = @sizeOf(macho.SuperBlob) + @sizeOf(macho.BlobIndex) + @sizeOf(macho.CodeDirectory); return @intCast(u32, mem.alignForwardGeneric(u64, codesig_header + ident_size + hashed_size, @sizeOf(u64))); }
src/MachO/CodeSignature.zig
const std = @import("std"); pub fn __builtin_bswap16(val: u16) callconv(.Inline) u16 { return @byteSwap(u16, val); } pub fn __builtin_bswap32(val: u32) callconv(.Inline) u32 { return @byteSwap(u32, val); } pub fn __builtin_bswap64(val: u64) callconv(.Inline) u64 { return @byteSwap(u64, val); } pub fn __builtin_signbit(val: f64) callconv(.Inline) c_int { return @boolToInt(std.math.signbit(val)); } pub fn __builtin_signbitf(val: f32) callconv(.Inline) c_int { return @boolToInt(std.math.signbit(val)); } pub fn __builtin_popcount(val: c_uint) callconv(.Inline) c_int { // popcount of a c_uint will never exceed the capacity of a c_int @setRuntimeSafety(false); return @bitCast(c_int, @as(c_uint, @popCount(c_uint, val))); } pub fn __builtin_ctz(val: c_uint) callconv(.Inline) c_int { // Returns the number of trailing 0-bits in val, starting at the least significant bit position. // In C if `val` is 0, the result is undefined; in zig it's the number of bits in a c_uint @setRuntimeSafety(false); return @bitCast(c_int, @as(c_uint, @ctz(c_uint, val))); } pub fn __builtin_clz(val: c_uint) callconv(.Inline) c_int { // Returns the number of leading 0-bits in x, starting at the most significant bit position. // In C if `val` is 0, the result is undefined; in zig it's the number of bits in a c_uint @setRuntimeSafety(false); return @bitCast(c_int, @as(c_uint, @clz(c_uint, val))); } pub fn __builtin_sqrt(val: f64) callconv(.Inline) f64 { return @sqrt(val); } pub fn __builtin_sqrtf(val: f32) callconv(.Inline) f32 { return @sqrt(val); } pub fn __builtin_sin(val: f64) callconv(.Inline) f64 { return @sin(val); } pub fn __builtin_sinf(val: f32) callconv(.Inline) f32 { return @sin(val); } pub fn __builtin_cos(val: f64) callconv(.Inline) f64 { return @cos(val); } pub fn __builtin_cosf(val: f32) callconv(.Inline) f32 { return @cos(val); } pub fn __builtin_exp(val: f64) callconv(.Inline) f64 { return @exp(val); } pub fn __builtin_expf(val: f32) callconv(.Inline) f32 { return @exp(val); } pub fn __builtin_exp2(val: f64) callconv(.Inline) f64 { return @exp2(val); } pub fn __builtin_exp2f(val: f32) callconv(.Inline) f32 { return @exp2(val); } pub fn __builtin_log(val: f64) callconv(.Inline) f64 { return @log(val); } pub fn __builtin_logf(val: f32) callconv(.Inline) f32 { return @log(val); } pub fn __builtin_log2(val: f64) callconv(.Inline) f64 { return @log2(val); } pub fn __builtin_log2f(val: f32) callconv(.Inline) f32 { return @log2(val); } pub fn __builtin_log10(val: f64) callconv(.Inline) f64 { return @log10(val); } pub fn __builtin_log10f(val: f32) callconv(.Inline) f32 { return @log10(val); } // Standard C Library bug: The absolute value of the most negative integer remains negative. pub fn __builtin_abs(val: c_int) callconv(.Inline) c_int { return std.math.absInt(val) catch std.math.minInt(c_int); } pub fn __builtin_fabs(val: f64) callconv(.Inline) f64 { return @fabs(val); } pub fn __builtin_fabsf(val: f32) callconv(.Inline) f32 { return @fabs(val); } pub fn __builtin_floor(val: f64) callconv(.Inline) f64 { return @floor(val); } pub fn __builtin_floorf(val: f32) callconv(.Inline) f32 { return @floor(val); } pub fn __builtin_ceil(val: f64) callconv(.Inline) f64 { return @ceil(val); } pub fn __builtin_ceilf(val: f32) callconv(.Inline) f32 { return @ceil(val); } pub fn __builtin_trunc(val: f64) callconv(.Inline) f64 { return @trunc(val); } pub fn __builtin_truncf(val: f32) callconv(.Inline) f32 { return @trunc(val); } pub fn __builtin_round(val: f64) callconv(.Inline) f64 { return @round(val); } pub fn __builtin_roundf(val: f32) callconv(.Inline) f32 { return @round(val); } pub fn __builtin_strlen(s: [*c]const u8) callconv(.Inline) usize { return std.mem.lenZ(s); } pub fn __builtin_strcmp(s1: [*c]const u8, s2: [*c]const u8) callconv(.Inline) c_int { return @as(c_int, std.cstr.cmp(s1, s2)); } pub fn __builtin_object_size(ptr: ?*const c_void, ty: c_int) callconv(.Inline) usize { // clang semantics match gcc's: https://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html // If it is not possible to determine which objects ptr points to at compile time, // __builtin_object_size should return (size_t) -1 for type 0 or 1 and (size_t) 0 // for type 2 or 3. if (ty == 0 or ty == 1) return @bitCast(usize, -@as(c_long, 1)); if (ty == 2 or ty == 3) return 0; unreachable; } pub fn __builtin___memset_chk( dst: ?*c_void, val: c_int, len: usize, remaining: usize, ) callconv(.Inline) ?*c_void { if (len > remaining) @panic("std.c.builtins.memset_chk called with len > remaining"); return __builtin_memset(dst, val, len); } pub fn __builtin_memset(dst: ?*c_void, val: c_int, len: usize) callconv(.Inline) ?*c_void { const dst_cast = @ptrCast([*c]u8, dst); @memset(dst_cast, @bitCast(u8, @truncate(i8, val)), len); return dst; } pub fn __builtin___memcpy_chk( noalias dst: ?*c_void, noalias src: ?*const c_void, len: usize, remaining: usize, ) callconv(.Inline) ?*c_void { if (len > remaining) @panic("std.c.builtins.memcpy_chk called with len > remaining"); return __builtin_memcpy(dst, src, len); } pub fn __builtin_memcpy( noalias dst: ?*c_void, noalias src: ?*const c_void, len: usize, ) callconv(.Inline) ?*c_void { const dst_cast = @ptrCast([*c]u8, dst); const src_cast = @ptrCast([*c]const u8, src); @memcpy(dst_cast, src_cast, len); return dst; } /// The return value of __builtin_expect is `expr`. `c` is the expected value /// of `expr` and is used as a hint to the compiler in C. Here it is unused. pub fn __builtin_expect(expr: c_long, c: c_long) callconv(.Inline) c_long { return expr; }
lib/std/c/builtins.zig
const std = @import("std"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; const Compilation = @import("../Compilation.zig"); const llvm = @import("llvm/bindings.zig"); const link = @import("../link.zig"); const log = std.log.scoped(.codegen); const math = std.math; const Module = @import("../Module.zig"); const TypedValue = @import("../TypedValue.zig"); const ir = @import("../ir.zig"); const Inst = ir.Inst; const Value = @import("../value.zig").Value; const Type = @import("../type.zig").Type; pub fn targetTriple(allocator: *Allocator, target: std.Target) ![:0]u8 { const llvm_arch = switch (target.cpu.arch) { .arm => "arm", .armeb => "armeb", .aarch64 => "aarch64", .aarch64_be => "aarch64_be", .aarch64_32 => "aarch64_32", .arc => "arc", .avr => "avr", .bpfel => "bpfel", .bpfeb => "bpfeb", .hexagon => "hexagon", .mips => "mips", .mipsel => "mipsel", .mips64 => "mips64", .mips64el => "mips64el", .msp430 => "msp430", .powerpc => "powerpc", .powerpc64 => "powerpc64", .powerpc64le => "powerpc64le", .r600 => "r600", .amdgcn => "amdgcn", .riscv32 => "riscv32", .riscv64 => "riscv64", .sparc => "sparc", .sparcv9 => "sparcv9", .sparcel => "sparcel", .s390x => "s390x", .tce => "tce", .tcele => "tcele", .thumb => "thumb", .thumbeb => "thumbeb", .i386 => "i386", .x86_64 => "x86_64", .xcore => "xcore", .nvptx => "nvptx", .nvptx64 => "nvptx64", .le32 => "le32", .le64 => "le64", .amdil => "amdil", .amdil64 => "amdil64", .hsail => "hsail", .hsail64 => "hsail64", .spir => "spir", .spir64 => "spir64", .kalimba => "kalimba", .shave => "shave", .lanai => "lanai", .wasm32 => "wasm32", .wasm64 => "wasm64", .renderscript32 => "renderscript32", .renderscript64 => "renderscript64", .ve => "ve", .spu_2 => return error.LLVMBackendDoesNotSupportSPUMarkII, .spirv32 => return error.LLVMBackendDoesNotSupportSPIRV, .spirv64 => return error.LLVMBackendDoesNotSupportSPIRV, }; // TODO Add a sub-arch for some architectures depending on CPU features. const llvm_os = switch (target.os.tag) { .freestanding => "unknown", .ananas => "ananas", .cloudabi => "cloudabi", .dragonfly => "dragonfly", .freebsd => "freebsd", .fuchsia => "fuchsia", .ios => "ios", .kfreebsd => "kfreebsd", .linux => "linux", .lv2 => "lv2", .macos => "macosx", .netbsd => "netbsd", .openbsd => "openbsd", .solaris => "solaris", .windows => "windows", .haiku => "haiku", .minix => "minix", .rtems => "rtems", .nacl => "nacl", .cnk => "cnk", .aix => "aix", .cuda => "cuda", .nvcl => "nvcl", .amdhsa => "amdhsa", .ps4 => "ps4", .elfiamcu => "elfiamcu", .tvos => "tvos", .watchos => "watchos", .mesa3d => "mesa3d", .contiki => "contiki", .amdpal => "amdpal", .hermit => "hermit", .hurd => "hurd", .wasi => "wasi", .emscripten => "emscripten", .uefi => "windows", .opencl => return error.LLVMBackendDoesNotSupportOpenCL, .glsl450 => return error.LLVMBackendDoesNotSupportGLSL450, .vulkan => return error.LLVMBackendDoesNotSupportVulkan, .other => "unknown", }; const llvm_abi = switch (target.abi) { .none => "unknown", .gnu => "gnu", .gnuabin32 => "gnuabin32", .gnuabi64 => "gnuabi64", .gnueabi => "gnueabi", .gnueabihf => "gnueabihf", .gnux32 => "gnux32", .code16 => "code16", .eabi => "eabi", .eabihf => "eabihf", .android => "android", .musl => "musl", .musleabi => "musleabi", .musleabihf => "musleabihf", .msvc => "msvc", .itanium => "itanium", .cygnus => "cygnus", .coreclr => "coreclr", .simulator => "simulator", .macabi => "macabi", }; return std.fmt.allocPrintZ(allocator, "{s}-unknown-{s}-{s}", .{ llvm_arch, llvm_os, llvm_abi }); } pub const LLVMIRModule = struct { module: *Module, llvm_module: *const llvm.Module, context: *const llvm.Context, target_machine: *const llvm.TargetMachine, builder: *const llvm.Builder, object_path: []const u8, gpa: *Allocator, err_msg: ?*Module.ErrorMsg = null, // TODO: The fields below should really move into a different struct, // because they are only valid when generating a function /// This stores the LLVM values used in a function, such that they can be /// referred to in other instructions. This table is cleared before every function is generated. /// TODO: Change this to a stack of Branch. Currently we store all the values from all the blocks /// in here, however if a block ends, the instructions can be thrown away. func_inst_table: std.AutoHashMapUnmanaged(*Inst, *const llvm.Value) = .{}, /// These fields are used to refer to the LLVM value of the function paramaters in an Arg instruction. args: []*const llvm.Value = &[_]*const llvm.Value{}, arg_index: usize = 0, entry_block: *const llvm.BasicBlock = undefined, /// This fields stores the last alloca instruction, such that we can append more alloca instructions /// to the top of the function. latest_alloca_inst: ?*const llvm.Value = null, llvm_func: *const llvm.Value = undefined, /// This data structure is used to implement breaking to blocks. blocks: std.AutoHashMapUnmanaged(*Inst.Block, struct { parent_bb: *const llvm.BasicBlock, break_bbs: *BreakBasicBlocks, break_vals: *BreakValues, }) = .{}, src_loc: Module.SrcLoc, const BreakBasicBlocks = std.ArrayListUnmanaged(*const llvm.BasicBlock); const BreakValues = std.ArrayListUnmanaged(*const llvm.Value); pub fn create(allocator: *Allocator, sub_path: []const u8, options: link.Options) !*LLVMIRModule { const self = try allocator.create(LLVMIRModule); errdefer allocator.destroy(self); const gpa = options.module.?.gpa; const obj_basename = try std.zig.binNameAlloc(gpa, .{ .root_name = options.root_name, .target = options.target, .output_mode = .Obj, }); defer gpa.free(obj_basename); const o_directory = options.module.?.zig_cache_artifact_directory; const object_path = try o_directory.join(gpa, &[_][]const u8{obj_basename}); errdefer gpa.free(object_path); const context = llvm.Context.create(); errdefer context.dispose(); initializeLLVMTargets(); const root_nameZ = try gpa.dupeZ(u8, options.root_name); defer gpa.free(root_nameZ); const llvm_module = llvm.Module.createWithName(root_nameZ.ptr, context); errdefer llvm_module.dispose(); const llvm_target_triple = try targetTriple(gpa, options.target); defer gpa.free(llvm_target_triple); var error_message: [*:0]const u8 = undefined; var target: *const llvm.Target = undefined; if (llvm.Target.getFromTriple(llvm_target_triple.ptr, &target, &error_message)) { defer llvm.disposeMessage(error_message); const stderr = std.io.getStdErr().writer(); try stderr.print( \\Zig is expecting LLVM to understand this target: '{s}' \\However LLVM responded with: "{s}" \\Zig is unable to continue. This is a bug in Zig: \\https://github.com/ziglang/zig/issues/438 \\ , .{ llvm_target_triple, error_message, }, ); return error.InvalidLLVMTriple; } const opt_level: llvm.CodeGenOptLevel = if (options.optimize_mode == .Debug) .None else .Aggressive; const target_machine = llvm.TargetMachine.create( target, llvm_target_triple.ptr, "", "", opt_level, .Static, .Default, ); errdefer target_machine.dispose(); const builder = context.createBuilder(); errdefer builder.dispose(); self.* = .{ .module = options.module.?, .llvm_module = llvm_module, .context = context, .target_machine = target_machine, .builder = builder, .object_path = object_path, .gpa = gpa, // TODO move this field into a struct that is only instantiated per gen() call .src_loc = undefined, }; return self; } pub fn deinit(self: *LLVMIRModule, allocator: *Allocator) void { self.builder.dispose(); self.target_machine.dispose(); self.llvm_module.dispose(); self.context.dispose(); self.func_inst_table.deinit(self.gpa); self.gpa.free(self.object_path); self.blocks.deinit(self.gpa); allocator.destroy(self); } fn initializeLLVMTargets() void { llvm.initializeAllTargets(); llvm.initializeAllTargetInfos(); llvm.initializeAllTargetMCs(); llvm.initializeAllAsmPrinters(); llvm.initializeAllAsmParsers(); } pub fn flushModule(self: *LLVMIRModule, comp: *Compilation) !void { if (comp.verbose_llvm_ir) { const dump = self.llvm_module.printToString(); defer llvm.disposeMessage(dump); const stderr = std.io.getStdErr().writer(); try stderr.writeAll(std.mem.spanZ(dump)); } { var error_message: [*:0]const u8 = undefined; // verifyModule always allocs the error_message even if there is no error defer llvm.disposeMessage(error_message); if (self.llvm_module.verify(.ReturnStatus, &error_message)) { const stderr = std.io.getStdErr().writer(); try stderr.print("broken LLVM module found: {s}\nThis is a bug in the Zig compiler.", .{error_message}); return error.BrokenLLVMModule; } } const object_pathZ = try self.gpa.dupeZ(u8, self.object_path); defer self.gpa.free(object_pathZ); var error_message: [*:0]const u8 = undefined; if (self.target_machine.emitToFile( self.llvm_module, object_pathZ.ptr, .ObjectFile, &error_message, )) { defer llvm.disposeMessage(error_message); const stderr = std.io.getStdErr().writer(); try stderr.print("LLVM failed to emit file: {s}\n", .{error_message}); return error.FailedToEmit; } } pub fn updateDecl(self: *LLVMIRModule, module: *Module, decl: *Module.Decl) !void { self.gen(module, decl) catch |err| switch (err) { error.CodegenFail => { decl.analysis = .codegen_failure; try module.failed_decls.put(module.gpa, decl, self.err_msg.?); self.err_msg = null; return; }, else => |e| return e, }; } fn gen(self: *LLVMIRModule, module: *Module, decl: *Module.Decl) !void { const typed_value = decl.typed_value.most_recent.typed_value; const src = decl.src(); self.src_loc = decl.srcLoc(); log.debug("gen: {s} type: {}, value: {}", .{ decl.name, typed_value.ty, typed_value.val }); if (typed_value.val.castTag(.function)) |func_payload| { const func = func_payload.data; const llvm_func = try self.resolveLLVMFunction(func.owner_decl, src); // This gets the LLVM values from the function and stores them in `self.args`. const fn_param_len = func.owner_decl.typed_value.most_recent.typed_value.ty.fnParamLen(); var args = try self.gpa.alloc(*const llvm.Value, fn_param_len); defer self.gpa.free(args); for (args) |*arg, i| { arg.* = llvm.getParam(llvm_func, @intCast(c_uint, i)); } self.args = args; self.arg_index = 0; // Make sure no other LLVM values from other functions can be referenced self.func_inst_table.clearRetainingCapacity(); // We remove all the basic blocks of a function to support incremental // compilation! // TODO: remove all basic blocks if functions can have more than one if (llvm_func.getFirstBasicBlock()) |bb| { bb.deleteBasicBlock(); } self.entry_block = self.context.appendBasicBlock(llvm_func, "Entry"); self.builder.positionBuilderAtEnd(self.entry_block); self.latest_alloca_inst = null; self.llvm_func = llvm_func; try self.genBody(func.body); } else if (typed_value.val.castTag(.extern_fn)) |extern_fn| { _ = try self.resolveLLVMFunction(extern_fn.data, src); } else { _ = try self.resolveGlobalDecl(decl, src); } } fn genBody(self: *LLVMIRModule, body: ir.Body) error{ OutOfMemory, CodegenFail }!void { for (body.instructions) |inst| { const opt_value = switch (inst.tag) { .add => try self.genAdd(inst.castTag(.add).?), .alloc => try self.genAlloc(inst.castTag(.alloc).?), .arg => try self.genArg(inst.castTag(.arg).?), .bitcast => try self.genBitCast(inst.castTag(.bitcast).?), .block => try self.genBlock(inst.castTag(.block).?), .br => try self.genBr(inst.castTag(.br).?), .breakpoint => try self.genBreakpoint(inst.castTag(.breakpoint).?), .call => try self.genCall(inst.castTag(.call).?), .cmp_eq => try self.genCmp(inst.castTag(.cmp_eq).?, .eq), .cmp_gt => try self.genCmp(inst.castTag(.cmp_gt).?, .gt), .cmp_gte => try self.genCmp(inst.castTag(.cmp_gte).?, .gte), .cmp_lt => try self.genCmp(inst.castTag(.cmp_lt).?, .lt), .cmp_lte => try self.genCmp(inst.castTag(.cmp_lte).?, .lte), .cmp_neq => try self.genCmp(inst.castTag(.cmp_neq).?, .neq), .condbr => try self.genCondBr(inst.castTag(.condbr).?), .intcast => try self.genIntCast(inst.castTag(.intcast).?), .load => try self.genLoad(inst.castTag(.load).?), .loop => try self.genLoop(inst.castTag(.loop).?), .not => try self.genNot(inst.castTag(.not).?), .ret => try self.genRet(inst.castTag(.ret).?), .retvoid => self.genRetVoid(inst.castTag(.retvoid).?), .store => try self.genStore(inst.castTag(.store).?), .sub => try self.genSub(inst.castTag(.sub).?), .unreach => self.genUnreach(inst.castTag(.unreach).?), .dbg_stmt => blk: { // TODO: implement debug info break :blk null; }, else => |tag| return self.fail(inst.src, "TODO implement LLVM codegen for Zir instruction: {}", .{tag}), }; if (opt_value) |val| try self.func_inst_table.putNoClobber(self.gpa, inst, val); } } fn genCall(self: *LLVMIRModule, inst: *Inst.Call) !?*const llvm.Value { if (inst.func.value()) |func_value| { const fn_decl = if (func_value.castTag(.extern_fn)) |extern_fn| extern_fn.data else if (func_value.castTag(.function)) |func_payload| func_payload.data.owner_decl else unreachable; const zig_fn_type = fn_decl.typed_value.most_recent.typed_value.ty; const llvm_fn = try self.resolveLLVMFunction(fn_decl, inst.base.src); const num_args = inst.args.len; const llvm_param_vals = try self.gpa.alloc(*const llvm.Value, num_args); defer self.gpa.free(llvm_param_vals); for (inst.args) |arg, i| { llvm_param_vals[i] = try self.resolveInst(arg); } // TODO: LLVMBuildCall2 handles opaque function pointers, according to llvm docs // Do we need that? const call = self.builder.buildCall( llvm_fn, if (num_args == 0) null else llvm_param_vals.ptr, @intCast(c_uint, num_args), "", ); const return_type = zig_fn_type.fnReturnType(); if (return_type.tag() == .noreturn) { _ = self.builder.buildUnreachable(); } // No need to store the LLVM value if the return type is void or noreturn if (!return_type.hasCodeGenBits()) return null; return call; } else { return self.fail(inst.base.src, "TODO implement calling runtime known function pointer LLVM backend", .{}); } } fn genRetVoid(self: *LLVMIRModule, inst: *Inst.NoOp) ?*const llvm.Value { _ = self.builder.buildRetVoid(); return null; } fn genRet(self: *LLVMIRModule, inst: *Inst.UnOp) !?*const llvm.Value { _ = self.builder.buildRet(try self.resolveInst(inst.operand)); return null; } fn genCmp(self: *LLVMIRModule, inst: *Inst.BinOp, op: math.CompareOperator) !?*const llvm.Value { const lhs = try self.resolveInst(inst.lhs); const rhs = try self.resolveInst(inst.rhs); if (!inst.base.ty.isInt()) if (inst.base.ty.tag() != .bool) return self.fail(inst.base.src, "TODO implement 'genCmp' for type {}", .{inst.base.ty}); const is_signed = inst.base.ty.isSignedInt(); const operation = switch (op) { .eq => .EQ, .neq => .NE, .lt => @as(llvm.IntPredicate, if (is_signed) .SLT else .ULT), .lte => @as(llvm.IntPredicate, if (is_signed) .SLE else .ULE), .gt => @as(llvm.IntPredicate, if (is_signed) .SGT else .UGT), .gte => @as(llvm.IntPredicate, if (is_signed) .SGE else .UGE), }; return self.builder.buildICmp(operation, lhs, rhs, ""); } fn genBlock(self: *LLVMIRModule, inst: *Inst.Block) !?*const llvm.Value { const parent_bb = self.context.createBasicBlock("Block"); // 5 breaks to a block seems like a reasonable default. var break_bbs = try BreakBasicBlocks.initCapacity(self.gpa, 5); var break_vals = try BreakValues.initCapacity(self.gpa, 5); try self.blocks.putNoClobber(self.gpa, inst, .{ .parent_bb = parent_bb, .break_bbs = &break_bbs, .break_vals = &break_vals, }); defer { self.blocks.removeAssertDiscard(inst); break_bbs.deinit(self.gpa); break_vals.deinit(self.gpa); } try self.genBody(inst.body); self.llvm_func.appendExistingBasicBlock(parent_bb); self.builder.positionBuilderAtEnd(parent_bb); // If the block does not return a value, we dont have to create a phi node. if (!inst.base.ty.hasCodeGenBits()) return null; const phi_node = self.builder.buildPhi(try self.getLLVMType(inst.base.ty, inst.base.src), ""); phi_node.addIncoming( break_vals.items.ptr, break_bbs.items.ptr, @intCast(c_uint, break_vals.items.len), ); return phi_node; } fn genBr(self: *LLVMIRModule, inst: *Inst.Br) !?*const llvm.Value { // Get the block that we want to break to. var block = self.blocks.get(inst.block).?; _ = self.builder.buildBr(block.parent_bb); // If the break doesn't break a value, then we don't have to add // the values to the lists. if (!inst.operand.ty.hasCodeGenBits()) return null; // For the phi node, we need the basic blocks and the values of the // break instructions. try block.break_bbs.append(self.gpa, self.builder.getInsertBlock()); const val = try self.resolveInst(inst.operand); try block.break_vals.append(self.gpa, val); return null; } fn genCondBr(self: *LLVMIRModule, inst: *Inst.CondBr) !?*const llvm.Value { const condition_value = try self.resolveInst(inst.condition); const then_block = self.context.appendBasicBlock(self.llvm_func, "Then"); const else_block = self.context.appendBasicBlock(self.llvm_func, "Else"); { const prev_block = self.builder.getInsertBlock(); defer self.builder.positionBuilderAtEnd(prev_block); self.builder.positionBuilderAtEnd(then_block); try self.genBody(inst.then_body); self.builder.positionBuilderAtEnd(else_block); try self.genBody(inst.else_body); } _ = self.builder.buildCondBr(condition_value, then_block, else_block); return null; } fn genLoop(self: *LLVMIRModule, inst: *Inst.Loop) !?*const llvm.Value { const loop_block = self.context.appendBasicBlock(self.llvm_func, "Loop"); _ = self.builder.buildBr(loop_block); self.builder.positionBuilderAtEnd(loop_block); try self.genBody(inst.body); _ = self.builder.buildBr(loop_block); return null; } fn genNot(self: *LLVMIRModule, inst: *Inst.UnOp) !?*const llvm.Value { return self.builder.buildNot(try self.resolveInst(inst.operand), ""); } fn genUnreach(self: *LLVMIRModule, inst: *Inst.NoOp) ?*const llvm.Value { _ = self.builder.buildUnreachable(); return null; } fn genAdd(self: *LLVMIRModule, inst: *Inst.BinOp) !?*const llvm.Value { const lhs = try self.resolveInst(inst.lhs); const rhs = try self.resolveInst(inst.rhs); if (!inst.base.ty.isInt()) return self.fail(inst.base.src, "TODO implement 'genAdd' for type {}", .{inst.base.ty}); return if (inst.base.ty.isSignedInt()) self.builder.buildNSWAdd(lhs, rhs, "") else self.builder.buildNUWAdd(lhs, rhs, ""); } fn genSub(self: *LLVMIRModule, inst: *Inst.BinOp) !?*const llvm.Value { const lhs = try self.resolveInst(inst.lhs); const rhs = try self.resolveInst(inst.rhs); if (!inst.base.ty.isInt()) return self.fail(inst.base.src, "TODO implement 'genSub' for type {}", .{inst.base.ty}); return if (inst.base.ty.isSignedInt()) self.builder.buildNSWSub(lhs, rhs, "") else self.builder.buildNUWSub(lhs, rhs, ""); } fn genIntCast(self: *LLVMIRModule, inst: *Inst.UnOp) !?*const llvm.Value { const val = try self.resolveInst(inst.operand); const signed = inst.base.ty.isSignedInt(); // TODO: Should we use intcast here or just a simple bitcast? // LLVM does truncation vs bitcast (+signed extension) in the intcast depending on the sizes return self.builder.buildIntCast2(val, try self.getLLVMType(inst.base.ty, inst.base.src), signed, ""); } fn genBitCast(self: *LLVMIRModule, inst: *Inst.UnOp) !?*const llvm.Value { const val = try self.resolveInst(inst.operand); const dest_type = try self.getLLVMType(inst.base.ty, inst.base.src); return self.builder.buildBitCast(val, dest_type, ""); } fn genArg(self: *LLVMIRModule, inst: *Inst.Arg) !?*const llvm.Value { const arg_val = self.args[self.arg_index]; self.arg_index += 1; const ptr_val = self.buildAlloca(try self.getLLVMType(inst.base.ty, inst.base.src)); _ = self.builder.buildStore(arg_val, ptr_val); return self.builder.buildLoad(ptr_val, ""); } fn genAlloc(self: *LLVMIRModule, inst: *Inst.NoOp) !?*const llvm.Value { // buildAlloca expects the pointee type, not the pointer type, so assert that // a Payload.PointerSimple is passed to the alloc instruction. const pointee_type = inst.base.ty.castPointer().?.data; // TODO: figure out a way to get the name of the var decl. // TODO: set alignment and volatile return self.buildAlloca(try self.getLLVMType(pointee_type, inst.base.src)); } /// Use this instead of builder.buildAlloca, because this function makes sure to /// put the alloca instruction at the top of the function! fn buildAlloca(self: *LLVMIRModule, t: *const llvm.Type) *const llvm.Value { const prev_block = self.builder.getInsertBlock(); defer self.builder.positionBuilderAtEnd(prev_block); if (self.latest_alloca_inst) |latest_alloc| { // builder.positionBuilder adds it before the instruction, // but we want to put it after the last alloca instruction. self.builder.positionBuilder(self.entry_block, latest_alloc.getNextInstruction().?); } else { // There might have been other instructions emitted before the // first alloca has been generated. However the alloca should still // be first in the function. if (self.entry_block.getFirstInstruction()) |first_inst| { self.builder.positionBuilder(self.entry_block, first_inst); } } const val = self.builder.buildAlloca(t, ""); self.latest_alloca_inst = val; return val; } fn genStore(self: *LLVMIRModule, inst: *Inst.BinOp) !?*const llvm.Value { const val = try self.resolveInst(inst.rhs); const ptr = try self.resolveInst(inst.lhs); _ = self.builder.buildStore(val, ptr); return null; } fn genLoad(self: *LLVMIRModule, inst: *Inst.UnOp) !?*const llvm.Value { const ptr_val = try self.resolveInst(inst.operand); return self.builder.buildLoad(ptr_val, ""); } fn genBreakpoint(self: *LLVMIRModule, inst: *Inst.NoOp) !?*const llvm.Value { const llvn_fn = self.getIntrinsic("llvm.debugtrap"); _ = self.builder.buildCall(llvn_fn, null, 0, ""); return null; } fn getIntrinsic(self: *LLVMIRModule, name: []const u8) *const llvm.Value { const id = llvm.lookupIntrinsicID(name.ptr, name.len); assert(id != 0); // TODO: add support for overload intrinsics by passing the prefix of the intrinsic // to `lookupIntrinsicID` and then passing the correct types to // `getIntrinsicDeclaration` return self.llvm_module.getIntrinsicDeclaration(id, null, 0); } fn resolveInst(self: *LLVMIRModule, inst: *ir.Inst) !*const llvm.Value { if (inst.value()) |val| { return self.genTypedValue(inst.src, .{ .ty = inst.ty, .val = val }); } if (self.func_inst_table.get(inst)) |value| return value; return self.fail(inst.src, "TODO implement global llvm values (or the value is not in the func_inst_table table)", .{}); } fn genTypedValue(self: *LLVMIRModule, src: usize, tv: TypedValue) error{ OutOfMemory, CodegenFail }!*const llvm.Value { const llvm_type = try self.getLLVMType(tv.ty, src); if (tv.val.isUndef()) return llvm_type.getUndef(); switch (tv.ty.zigTypeTag()) { .Bool => return if (tv.val.toBool()) llvm_type.constAllOnes() else llvm_type.constNull(), .Int => { var bigint_space: Value.BigIntSpace = undefined; const bigint = tv.val.toBigInt(&bigint_space); if (bigint.eqZero()) return llvm_type.constNull(); if (bigint.limbs.len != 1) { return self.fail(src, "TODO implement bigger bigint", .{}); } const llvm_int = llvm_type.constInt(bigint.limbs[0], false); if (!bigint.positive) { return llvm.constNeg(llvm_int); } return llvm_int; }, .Pointer => switch (tv.val.tag()) { .decl_ref => { const decl = tv.val.castTag(.decl_ref).?.data; const val = try self.resolveGlobalDecl(decl, src); const usize_type = try self.getLLVMType(Type.initTag(.usize), src); // TODO: second index should be the index into the memory! var indices: [2]*const llvm.Value = .{ usize_type.constNull(), usize_type.constNull(), }; // TODO: consider using buildInBoundsGEP2 for opaque pointers return self.builder.buildInBoundsGEP(val, &indices, 2, ""); }, else => return self.fail(src, "TODO implement const of pointer type '{}'", .{tv.ty}), }, .Array => { if (tv.val.castTag(.bytes)) |payload| { const zero_sentinel = if (tv.ty.sentinel()) |sentinel| blk: { if (sentinel.tag() == .zero) break :blk true; return self.fail(src, "TODO handle other sentinel values", .{}); } else false; return self.context.constString(payload.data.ptr, @intCast(c_uint, payload.data.len), !zero_sentinel); } else { return self.fail(src, "TODO handle more array values", .{}); } }, else => return self.fail(src, "TODO implement const of type '{}'", .{tv.ty}), } } fn getLLVMType(self: *LLVMIRModule, t: Type, src: usize) error{ OutOfMemory, CodegenFail }!*const llvm.Type { switch (t.zigTypeTag()) { .Void => return self.context.voidType(), .NoReturn => return self.context.voidType(), .Int => { const info = t.intInfo(self.module.getTarget()); return self.context.intType(info.bits); }, .Bool => return self.context.intType(1), .Pointer => { if (t.isSlice()) { return self.fail(src, "TODO: LLVM backend: implement slices", .{}); } else { const elem_type = try self.getLLVMType(t.elemType(), src); return elem_type.pointerType(0); } }, .Array => { const elem_type = try self.getLLVMType(t.elemType(), src); return elem_type.arrayType(@intCast(c_uint, t.abiSize(self.module.getTarget()))); }, else => return self.fail(src, "TODO implement getLLVMType for type '{}'", .{t}), } } fn resolveGlobalDecl(self: *LLVMIRModule, decl: *Module.Decl, src: usize) error{ OutOfMemory, CodegenFail }!*const llvm.Value { // TODO: do we want to store this in our own datastructure? if (self.llvm_module.getNamedGlobal(decl.name)) |val| return val; const typed_value = decl.typed_value.most_recent.typed_value; // TODO: remove this redundant `getLLVMType`, it is also called in `genTypedValue`. const llvm_type = try self.getLLVMType(typed_value.ty, src); const val = try self.genTypedValue(src, typed_value); const global = self.llvm_module.addGlobal(llvm_type, decl.name); llvm.setInitializer(global, val); // TODO ask the Decl if it is const // https://github.com/ziglang/zig/issues/7582 return global; } /// If the llvm function does not exist, create it fn resolveLLVMFunction(self: *LLVMIRModule, func: *Module.Decl, src: usize) !*const llvm.Value { // TODO: do we want to store this in our own datastructure? if (self.llvm_module.getNamedFunction(func.name)) |llvm_fn| return llvm_fn; const zig_fn_type = func.typed_value.most_recent.typed_value.ty; const return_type = zig_fn_type.fnReturnType(); const fn_param_len = zig_fn_type.fnParamLen(); const fn_param_types = try self.gpa.alloc(Type, fn_param_len); defer self.gpa.free(fn_param_types); zig_fn_type.fnParamTypes(fn_param_types); const llvm_param = try self.gpa.alloc(*const llvm.Type, fn_param_len); defer self.gpa.free(llvm_param); for (fn_param_types) |fn_param, i| { llvm_param[i] = try self.getLLVMType(fn_param, src); } const fn_type = llvm.Type.functionType( try self.getLLVMType(return_type, src), if (fn_param_len == 0) null else llvm_param.ptr, @intCast(c_uint, fn_param_len), false, ); const llvm_fn = self.llvm_module.addFunction(func.name, fn_type); if (return_type.tag() == .noreturn) { self.addFnAttr(llvm_fn, "noreturn"); } return llvm_fn; } // Helper functions fn addAttr(self: LLVMIRModule, val: *const llvm.Value, index: llvm.AttributeIndex, name: []const u8) void { const kind_id = llvm.getEnumAttributeKindForName(name.ptr, name.len); assert(kind_id != 0); const llvm_attr = self.context.createEnumAttribute(kind_id, 0); val.addAttributeAtIndex(index, llvm_attr); } fn addFnAttr(self: *LLVMIRModule, val: *const llvm.Value, attr_name: []const u8) void { // TODO: improve this API, `addAttr(-1, attr_name)` self.addAttr(val, std.math.maxInt(llvm.AttributeIndex), attr_name); } pub fn fail(self: *LLVMIRModule, src: usize, comptime format: []const u8, args: anytype) error{ OutOfMemory, CodegenFail } { @setCold(true); assert(self.err_msg == null); self.err_msg = try Module.ErrorMsg.create(self.gpa, .{ .file_scope = self.src_loc.file_scope, .byte_offset = src, }, format, args); return error.CodegenFail; } };
src/codegen/llvm.zig
const std = @import("std"); const mem = std.mem; usingnamespace @import("crypto.zig"); const Chacha20Poly1305 = std.crypto.aead.chacha_poly.ChaCha20Poly1305; const Aes128Gcm = std.crypto.aead.aes_gcm.Aes128Gcm; const main = @import("main.zig"); const alert_byte_to_error = main.alert_byte_to_error; const record_tag_length = main.record_tag_length; const record_length = main.record_length; pub const suites = struct { pub const ECDHE_RSA_Chacha20_Poly1305 = struct { pub const name = "ECDHE-RSA-CHACHA20-POLY1305"; pub const tag = 0xCCA8; pub const key_exchange = .ecdhe; pub const hash = .sha256; pub const Keys = struct { client_key: [32]u8, server_key: [32]u8, client_iv: [12]u8, server_iv: [12]u8, }; pub const State = union(enum) { none, in_record: struct { left: usize, context: ChaCha20Stream.BlockVec, idx: usize, buf: [64]u8, }, }; pub const default_state: State = .none; pub fn raw_write( comptime buffer_size: usize, rand: *std.rand.Random, key_data: anytype, writer: anytype, prefix: [3]u8, seq: u64, buffer: []const u8, ) !void { std.debug.assert(buffer.len <= buffer_size); try writer.writeAll(&prefix); try writer.writeIntBig(u16, @intCast(u16, buffer.len + 16)); var additional_data: [13]u8 = undefined; mem.writeIntBig(u64, additional_data[0..8], seq); additional_data[8..11].* = prefix; mem.writeIntBig(u16, additional_data[11..13], @intCast(u16, buffer.len)); var encrypted_data: [buffer_size]u8 = undefined; var tag_data: [16]u8 = undefined; var nonce: [12]u8 = ([1]u8{0} ** 4) ++ ([1]u8{undefined} ** 8); mem.writeIntBig(u64, nonce[4..12], seq); for (nonce) |*n, i| { n.* ^= key_data.client_iv(@This())[i]; } Chacha20Poly1305.encrypt( encrypted_data[0..buffer.len], &tag_data, buffer, &additional_data, nonce, key_data.client_key(@This()).*, ); try writer.writeAll(encrypted_data[0..buffer.len]); try writer.writeAll(&tag_data); } pub fn check_verify_message( key_data: anytype, length: usize, reader: anytype, verify_message: [16]u8, ) !bool { if (length != 32) return false; var msg_in: [32]u8 = undefined; try reader.readNoEof(&msg_in); const additional_data: [13]u8 = ([1]u8{0} ** 8) ++ [5]u8{ 0x16, 0x03, 0x03, 0x00, 0x10 }; var decrypted: [16]u8 = undefined; Chacha20Poly1305.decrypt( &decrypted, msg_in[0..16], msg_in[16..].*, &additional_data, key_data.server_iv(@This()).*, key_data.server_key(@This()).*, ) catch return false; return mem.eql(u8, &decrypted, &verify_message); } pub fn read( comptime buf_size: usize, state: *State, key_data: anytype, reader: anytype, server_seq: *u64, buffer: []u8, ) !usize { switch (state.*) { .none => { const tag_length = record_tag_length(reader) catch |err| switch (err) { error.EndOfStream => return 0, else => |e| return e, }; if (tag_length.length < 16) return error.ServerMalformedResponse; const len = tag_length.length - 16; if ((tag_length.tag != 0x17 and tag_length.tag != 0x15) or (tag_length.tag == 0x15 and len != 2)) { return error.ServerMalformedResponse; } const curr_bytes = if (tag_length.tag == 0x15) 2 else std.math.min(std.math.min(len, buf_size), buffer.len); var nonce: [12]u8 = ([1]u8{0} ** 4) ++ ([1]u8{undefined} ** 8); mem.writeIntBig(u64, nonce[4..12], server_seq.*); for (nonce) |*n, i| { n.* ^= key_data.server_iv(@This())[i]; } var c: [4]u32 = undefined; c[0] = 1; c[1] = mem.readIntLittle(u32, nonce[0..4]); c[2] = mem.readIntLittle(u32, nonce[4..8]); c[3] = mem.readIntLittle(u32, nonce[8..12]); const server_key = keyToWords(key_data.server_key(@This()).*); var context = ChaCha20Stream.initContext(server_key, c); var idx: usize = 0; var buf: [64]u8 = undefined; if (tag_length.tag == 0x15) { var encrypted: [2]u8 = undefined; reader.readNoEof(&encrypted) catch |err| switch (err) { error.EndOfStream => return error.ServerMalformedResponse, else => |e| return e, }; var result: [2]u8 = undefined; ChaCha20Stream.chacha20Xor( &result, &encrypted, server_key, &context, &idx, &buf, ); reader.skipBytes(16, .{}) catch |err| switch (err) { error.EndOfStream => return error.ServerMalformedResponse, else => |e| return e, }; server_seq.* += 1; // CloseNotify if (result[1] == 0) return 0; return alert_byte_to_error(result[1]); } else if (tag_length.tag == 0x17) { // Partially decrypt the data. var encrypted: [buf_size]u8 = undefined; const actually_read = try reader.read(encrypted[0..curr_bytes]); ChaCha20Stream.chacha20Xor( buffer[0..actually_read], encrypted[0..actually_read], server_key, &context, &idx, &buf, ); if (actually_read < len) { state.* = .{ .in_record = .{ .left = len - actually_read, .context = context, .idx = idx, .buf = buf, }, }; } else { // @TODO Verify Poly1305. reader.skipBytes(16, .{}) catch |err| switch (err) { error.EndOfStream => return error.ServerMalformedResponse, else => |e| return e, }; server_seq.* += 1; } return actually_read; } else unreachable; }, .in_record => |*record_info| { const curr_bytes = std.math.min(std.math.min(buf_size, buffer.len), record_info.left); // Partially decrypt the data. var encrypted: [buf_size]u8 = undefined; const actually_read = try reader.read(encrypted[0..curr_bytes]); ChaCha20Stream.chacha20Xor( buffer[0..actually_read], encrypted[0..actually_read], keyToWords(key_data.server_key(@This()).*), &record_info.context, &record_info.idx, &record_info.buf, ); record_info.left -= actually_read; if (record_info.left == 0) { // @TODO Verify Poly1305. reader.skipBytes(16, .{}) catch |err| switch (err) { error.EndOfStream => return error.ServerMalformedResponse, else => |e| return e, }; state.* = .none; server_seq.* += 1; } return actually_read; }, } } }; pub const ECDHE_RSA_AES128_GCM_SHA256 = struct { pub const name = "ECDHE-RSA-AES128-GCM-SHA256"; pub const tag = 0xC02F; pub const key_exchange = .ecdhe; pub const hash = .sha256; pub const Keys = struct { client_key: [16]u8, server_key: [16]u8, client_iv: [4]u8, server_iv: [4]u8, }; const Aes = std.crypto.core.aes.Aes128; pub const State = union(enum) { none, in_record: struct { left: usize, aes: @typeInfo(@TypeOf(Aes.initEnc)).Fn.return_type.?, // ctr state counterInt: u128, idx: usize, }, }; pub const default_state: State = .none; pub fn check_verify_message( key_data: anytype, length: usize, reader: anytype, verify_message: [16]u8, ) !bool { if (length != 40) return false; var iv: [12]u8 = undefined; iv[0..4].* = key_data.server_iv(@This()).*; try reader.readNoEof(iv[4..12]); var msg_in: [32]u8 = undefined; try reader.readNoEof(&msg_in); const additional_data: [13]u8 = ([1]u8{0} ** 8) ++ [5]u8{ 0x16, 0x03, 0x03, 0x00, 0x10 }; var decrypted: [16]u8 = undefined; Aes128Gcm.decrypt( &decrypted, msg_in[0..16], msg_in[16..].*, &additional_data, iv, key_data.server_key(@This()).*, ) catch return false; return mem.eql(u8, &decrypted, &verify_message); } pub fn raw_write( comptime buffer_size: usize, rand: *std.rand.Random, key_data: anytype, writer: anytype, prefix: [3]u8, seq: u64, buffer: []const u8, ) !void { std.debug.assert(buffer.len <= buffer_size); var iv: [12]u8 = undefined; iv[0..4].* = key_data.client_iv(@This()).*; rand.bytes(iv[4..12]); var additional_data: [13]u8 = undefined; mem.writeIntBig(u64, additional_data[0..8], seq); additional_data[8..11].* = prefix; mem.writeIntBig(u16, additional_data[11..13], @intCast(u16, buffer.len)); try writer.writeAll(&prefix); try writer.writeIntBig(u16, @intCast(u16, buffer.len + 24)); try writer.writeAll(iv[4..12]); var encrypted_data: [buffer_size]u8 = undefined; var tag_data: [16]u8 = undefined; Aes128Gcm.encrypt( encrypted_data[0..buffer.len], &tag_data, buffer, &additional_data, iv, key_data.client_key(@This()).*, ); try writer.writeAll(encrypted_data[0..buffer.len]); try writer.writeAll(&tag_data); } pub fn read( comptime buf_size: usize, state: *State, key_data: anytype, reader: anytype, server_seq: *u64, buffer: []u8, ) !usize { switch (state.*) { .none => { const tag_length = record_tag_length(reader) catch |err| switch (err) { error.EndOfStream => return 0, else => |e| return e, }; if (tag_length.length < 24) return error.ServerMalformedResponse; const len = tag_length.length - 24; if ((tag_length.tag != 0x17 and tag_length.tag != 0x15) or (tag_length.tag == 0x15 and len != 2)) { return error.ServerMalformedResponse; } const curr_bytes = if (tag_length.tag == 0x15) 2 else std.math.min(std.math.min(len, buf_size), buffer.len); var iv: [12]u8 = undefined; iv[0..4].* = key_data.server_iv(@This()).*; reader.readNoEof(iv[4..12]) catch |err| switch (err) { error.EndOfStream => return 0, else => |e| return e, }; const aes = Aes.initEnc(key_data.server_key(@This()).*); var j: [16]u8 = undefined; mem.copy(u8, j[0..12], iv[0..]); mem.writeIntBig(u32, j[12..][0..4], 2); var counterInt = mem.readInt(u128, &j, .Big); var idx: usize = 0; if (tag_length.tag == 0x15) { var encrypted: [2]u8 = undefined; reader.readNoEof(&encrypted) catch |err| switch (err) { error.EndOfStream => return error.ServerMalformedResponse, else => |e| return e, }; var result: [2]u8 = undefined; ctr( @TypeOf(aes), aes, &result, &encrypted, &counterInt, &idx, .Big, ); reader.skipBytes(16, .{}) catch |err| switch (err) { error.EndOfStream => return error.ServerMalformedResponse, else => |e| return e, }; server_seq.* += 1; // CloseNotify if (result[1] == 0) return 0; return alert_byte_to_error(result[1]); } else if (tag_length.tag == 0x17) { // Partially decrypt the data. var encrypted: [buf_size]u8 = undefined; const actually_read = try reader.read(encrypted[0..curr_bytes]); ctr( @TypeOf(aes), aes, buffer[0..actually_read], encrypted[0..actually_read], &counterInt, &idx, .Big, ); if (actually_read < len) { state.* = .{ .in_record = .{ .left = len - actually_read, .aes = aes, .counterInt = counterInt, .idx = idx, }, }; } else { // @TODO Verify the message reader.skipBytes(16, .{}) catch |err| switch (err) { error.EndOfStream => return error.ServerMalformedResponse, else => |e| return e, }; server_seq.* += 1; } return actually_read; } else unreachable; }, .in_record => |*record_info| { const curr_bytes = std.math.min(std.math.min(buf_size, buffer.len), record_info.left); // Partially decrypt the data. var encrypted: [buf_size]u8 = undefined; const actually_read = try reader.read(encrypted[0..curr_bytes]); ctr( @TypeOf(record_info.aes), record_info.aes, buffer[0..actually_read], encrypted[0..actually_read], &record_info.counterInt, &record_info.idx, .Big, ); record_info.left -= actually_read; if (record_info.left == 0) { // @TODO Verify Poly1305. reader.skipBytes(16, .{}) catch |err| switch (err) { error.EndOfStream => return error.ServerMalformedResponse, else => |e| return e, }; state.* = .none; server_seq.* += 1; } return actually_read; }, } } }; pub const all = &[_]type{ ECDHE_RSA_Chacha20_Poly1305, ECDHE_RSA_AES128_GCM_SHA256 }; }; fn key_field_width(comptime T: type, comptime field: anytype) ?usize { if (!@hasField(T, @tagName(field))) return null; const field_info = std.meta.fieldInfo(T, field); if (!comptime std.meta.trait.is(.Array)(field_info.field_type) or std.meta.Elem(field_info.field_type) != u8) @compileError("Field '" ++ field ++ "' of type '" ++ @typeName(T) ++ "' should be an array of u8."); return @typeInfo(field_info.field_type).Array.len; } pub fn key_data_size(comptime ciphersuites: anytype) usize { var max: usize = 0; for (ciphersuites) |cs| { const curr = (key_field_width(cs.Keys, .client_mac) orelse 0) + (key_field_width(cs.Keys, .server_mac) orelse 0) + key_field_width(cs.Keys, .client_key).? + key_field_width(cs.Keys, .server_key).? + key_field_width(cs.Keys, .client_iv).? + key_field_width(cs.Keys, .server_iv).?; if (curr > max) max = curr; } return max; } pub fn KeyData(comptime ciphersuites: anytype) type { return struct { data: [key_data_size(ciphersuites)]u8, pub fn client_mac(self: *@This(), comptime cs: type) *[key_field_width(cs.Keys, .client_mac) orelse 0]u8 { return self.data[0..comptime (key_field_width(cs.Keys, .client_mac) orelse 0)]; } pub fn server_mac(self: *@This(), comptime cs: type) *[key_field_width(cs.Keys, .server_mac) orelse 0]u8 { const start = key_field_width(cs.Keys, .client_mac) orelse 0; return self.data[start..][0..comptime (key_field_width(cs.Keys, .server_mac) orelse 0)]; } pub fn client_key(self: *@This(), comptime cs: type) *[key_field_width(cs.Keys, .client_key).?]u8 { const start = (key_field_width(cs.Keys, .client_mac) orelse 0) + (key_field_width(cs.Keys, .server_mac) orelse 0); return self.data[start..][0..comptime key_field_width(cs.Keys, .client_key).?]; } pub fn server_key(self: *@This(), comptime cs: type) *[key_field_width(cs.Keys, .server_key).?]u8 { const start = (key_field_width(cs.Keys, .client_mac) orelse 0) + (key_field_width(cs.Keys, .server_mac) orelse 0) + key_field_width(cs.Keys, .client_key).?; return self.data[start..][0..comptime key_field_width(cs.Keys, .server_key).?]; } pub fn client_iv(self: *@This(), comptime cs: type) *[key_field_width(cs.Keys, .client_iv).?]u8 { const start = (key_field_width(cs.Keys, .client_mac) orelse 0) + (key_field_width(cs.Keys, .server_mac) orelse 0) + key_field_width(cs.Keys, .client_key).? + key_field_width(cs.Keys, .server_key).?; return self.data[start..][0..comptime key_field_width(cs.Keys, .client_iv).?]; } pub fn server_iv(self: *@This(), comptime cs: type) *[key_field_width(cs.Keys, .server_iv).?]u8 { const start = (key_field_width(cs.Keys, .client_mac) orelse 0) + (key_field_width(cs.Keys, .server_mac) orelse 0) + key_field_width(cs.Keys, .client_key).? + key_field_width(cs.Keys, .server_key).? + key_field_width(cs.Keys, .client_iv).?; return self.data[start..][0..comptime key_field_width(cs.Keys, .server_iv).?]; } }; } pub fn key_expansion( comptime ciphersuites: anytype, tag: u16, context: anytype, comptime next_32_bytes: anytype, ) KeyData(ciphersuites) { var res: KeyData(ciphersuites) = undefined; inline for (ciphersuites) |cs| { if (cs.tag == tag) { var chunk: [32]u8 = undefined; next_32_bytes(context, 0, &chunk); comptime var chunk_idx = 1; comptime var data_cursor = 0; comptime var chunk_cursor = 0; const fields = .{ .client_mac, .server_mac, .client_key, .server_key, .client_iv, .server_iv, }; inline for (fields) |field| { if (chunk_cursor == 32) { next_32_bytes(context, chunk_idx, &chunk); chunk_idx += 1; chunk_cursor = 0; } const field_width = comptime (key_field_width(cs.Keys, field) orelse 0); const first_read = comptime std.math.min(32 - chunk_cursor, field_width); const second_read = field_width - first_read; res.data[data_cursor..][0..first_read].* = chunk[chunk_cursor..][0..first_read].*; data_cursor += first_read; chunk_cursor += first_read; if (second_read != 0) { next_32_bytes(context, chunk_idx, &chunk); chunk_idx += 1; res.data[data_cursor..][0..second_read].* = chunk[chunk_cursor..][0..second_read].*; data_cursor += second_read; chunk_cursor = second_read; comptime std.debug.assert(chunk_cursor != 32); } } return res; } } unreachable; } pub fn ClientState(comptime ciphersuites: anytype) type { var fields: [ciphersuites.len]std.builtin.TypeInfo.UnionField = undefined; for (ciphersuites) |cs, i| { fields[i] = .{ .name = cs.name, .field_type = cs.State, .alignment = if (@sizeOf(cs.State) > 0) @alignOf(cs.State) else 0, }; } return @Type(.{ .Union = .{ .layout = .Extern, .tag_type = null, .fields = &fields, .decls = &[0]std.builtin.TypeInfo.Declaration{}, }, }); } pub fn client_state_default(comptime ciphersuites: anytype, tag: u16) ClientState(ciphersuites) { inline for (ciphersuites) |cs| { if (cs.tag == tag) { return @unionInit(ClientState(ciphersuites), cs.name, cs.default_state); } } unreachable; }
src/ciphersuites.zig
const std = @import("std"); const mem = std.mem; const Alphabetic = @This(); allocator: *mem.Allocator, array: []bool, lo: u21 = 65, hi: u21 = 201546, pub fn init(allocator: *mem.Allocator) !Alphabetic { var instance = Alphabetic{ .allocator = allocator, .array = try allocator.alloc(bool, 201482), }; mem.set(bool, instance.array, false); var index: u21 = 0; index = 0; while (index <= 25) : (index += 1) { instance.array[index] = true; } index = 32; while (index <= 57) : (index += 1) { instance.array[index] = true; } instance.array[105] = true; instance.array[116] = true; instance.array[121] = true; index = 127; while (index <= 149) : (index += 1) { instance.array[index] = true; } index = 151; while (index <= 181) : (index += 1) { instance.array[index] = true; } index = 183; while (index <= 377) : (index += 1) { instance.array[index] = true; } instance.array[378] = true; index = 379; while (index <= 382) : (index += 1) { instance.array[index] = true; } index = 383; while (index <= 386) : (index += 1) { instance.array[index] = true; } index = 387; while (index <= 594) : (index += 1) { instance.array[index] = true; } instance.array[595] = true; index = 596; while (index <= 622) : (index += 1) { instance.array[index] = true; } index = 623; while (index <= 640) : (index += 1) { instance.array[index] = true; } index = 645; while (index <= 656) : (index += 1) { instance.array[index] = true; } index = 671; while (index <= 675) : (index += 1) { instance.array[index] = true; } instance.array[683] = true; instance.array[685] = true; instance.array[772] = true; index = 815; while (index <= 818) : (index += 1) { instance.array[index] = true; } instance.array[819] = true; index = 821; while (index <= 822) : (index += 1) { instance.array[index] = true; } instance.array[825] = true; index = 826; while (index <= 828) : (index += 1) { instance.array[index] = true; } instance.array[830] = true; instance.array[837] = true; index = 839; while (index <= 841) : (index += 1) { instance.array[index] = true; } instance.array[843] = true; index = 845; while (index <= 864) : (index += 1) { instance.array[index] = true; } index = 866; while (index <= 948) : (index += 1) { instance.array[index] = true; } index = 950; while (index <= 1088) : (index += 1) { instance.array[index] = true; } index = 1097; while (index <= 1262) : (index += 1) { instance.array[index] = true; } index = 1264; while (index <= 1301) : (index += 1) { instance.array[index] = true; } instance.array[1304] = true; index = 1311; while (index <= 1351) : (index += 1) { instance.array[index] = true; } index = 1391; while (index <= 1404) : (index += 1) { instance.array[index] = true; } instance.array[1406] = true; index = 1408; while (index <= 1409) : (index += 1) { instance.array[index] = true; } index = 1411; while (index <= 1412) : (index += 1) { instance.array[index] = true; } instance.array[1414] = true; index = 1423; while (index <= 1449) : (index += 1) { instance.array[index] = true; } index = 1454; while (index <= 1457) : (index += 1) { instance.array[index] = true; } index = 1487; while (index <= 1497) : (index += 1) { instance.array[index] = true; } index = 1503; while (index <= 1534) : (index += 1) { instance.array[index] = true; } instance.array[1535] = true; index = 1536; while (index <= 1545) : (index += 1) { instance.array[index] = true; } index = 1546; while (index <= 1558) : (index += 1) { instance.array[index] = true; } index = 1560; while (index <= 1566) : (index += 1) { instance.array[index] = true; } index = 1581; while (index <= 1582) : (index += 1) { instance.array[index] = true; } instance.array[1583] = true; index = 1584; while (index <= 1682) : (index += 1) { instance.array[index] = true; } instance.array[1684] = true; index = 1685; while (index <= 1691) : (index += 1) { instance.array[index] = true; } index = 1696; while (index <= 1699) : (index += 1) { instance.array[index] = true; } index = 1700; while (index <= 1701) : (index += 1) { instance.array[index] = true; } index = 1702; while (index <= 1703) : (index += 1) { instance.array[index] = true; } instance.array[1708] = true; index = 1709; while (index <= 1710) : (index += 1) { instance.array[index] = true; } index = 1721; while (index <= 1723) : (index += 1) { instance.array[index] = true; } instance.array[1726] = true; instance.array[1743] = true; instance.array[1744] = true; index = 1745; while (index <= 1774) : (index += 1) { instance.array[index] = true; } index = 1775; while (index <= 1790) : (index += 1) { instance.array[index] = true; } index = 1804; while (index <= 1892) : (index += 1) { instance.array[index] = true; } index = 1893; while (index <= 1903) : (index += 1) { instance.array[index] = true; } instance.array[1904] = true; index = 1929; while (index <= 1961) : (index += 1) { instance.array[index] = true; } index = 1971; while (index <= 1972) : (index += 1) { instance.array[index] = true; } instance.array[1977] = true; index = 1983; while (index <= 2004) : (index += 1) { instance.array[index] = true; } index = 2005; while (index <= 2006) : (index += 1) { instance.array[index] = true; } instance.array[2009] = true; index = 2010; while (index <= 2018) : (index += 1) { instance.array[index] = true; } instance.array[2019] = true; index = 2020; while (index <= 2022) : (index += 1) { instance.array[index] = true; } instance.array[2023] = true; index = 2024; while (index <= 2027) : (index += 1) { instance.array[index] = true; } index = 2047; while (index <= 2071) : (index += 1) { instance.array[index] = true; } index = 2079; while (index <= 2089) : (index += 1) { instance.array[index] = true; } index = 2143; while (index <= 2163) : (index += 1) { instance.array[index] = true; } index = 2165; while (index <= 2182) : (index += 1) { instance.array[index] = true; } index = 2195; while (index <= 2206) : (index += 1) { instance.array[index] = true; } index = 2210; while (index <= 2216) : (index += 1) { instance.array[index] = true; } index = 2223; while (index <= 2241) : (index += 1) { instance.array[index] = true; } instance.array[2242] = true; index = 2243; while (index <= 2296) : (index += 1) { instance.array[index] = true; } instance.array[2297] = true; instance.array[2298] = true; instance.array[2300] = true; index = 2301; while (index <= 2303) : (index += 1) { instance.array[index] = true; } index = 2304; while (index <= 2311) : (index += 1) { instance.array[index] = true; } index = 2312; while (index <= 2315) : (index += 1) { instance.array[index] = true; } index = 2317; while (index <= 2318) : (index += 1) { instance.array[index] = true; } instance.array[2319] = true; index = 2324; while (index <= 2326) : (index += 1) { instance.array[index] = true; } index = 2327; while (index <= 2336) : (index += 1) { instance.array[index] = true; } index = 2337; while (index <= 2338) : (index += 1) { instance.array[index] = true; } instance.array[2352] = true; index = 2353; while (index <= 2367) : (index += 1) { instance.array[index] = true; } instance.array[2368] = true; index = 2369; while (index <= 2370) : (index += 1) { instance.array[index] = true; } index = 2372; while (index <= 2379) : (index += 1) { instance.array[index] = true; } index = 2382; while (index <= 2383) : (index += 1) { instance.array[index] = true; } index = 2386; while (index <= 2407) : (index += 1) { instance.array[index] = true; } index = 2409; while (index <= 2415) : (index += 1) { instance.array[index] = true; } instance.array[2417] = true; index = 2421; while (index <= 2424) : (index += 1) { instance.array[index] = true; } instance.array[2428] = true; index = 2429; while (index <= 2431) : (index += 1) { instance.array[index] = true; } index = 2432; while (index <= 2435) : (index += 1) { instance.array[index] = true; } index = 2438; while (index <= 2439) : (index += 1) { instance.array[index] = true; } index = 2442; while (index <= 2443) : (index += 1) { instance.array[index] = true; } instance.array[2445] = true; instance.array[2454] = true; index = 2459; while (index <= 2460) : (index += 1) { instance.array[index] = true; } index = 2462; while (index <= 2464) : (index += 1) { instance.array[index] = true; } index = 2465; while (index <= 2466) : (index += 1) { instance.array[index] = true; } index = 2479; while (index <= 2480) : (index += 1) { instance.array[index] = true; } instance.array[2491] = true; index = 2496; while (index <= 2497) : (index += 1) { instance.array[index] = true; } instance.array[2498] = true; index = 2500; while (index <= 2505) : (index += 1) { instance.array[index] = true; } index = 2510; while (index <= 2511) : (index += 1) { instance.array[index] = true; } index = 2514; while (index <= 2535) : (index += 1) { instance.array[index] = true; } index = 2537; while (index <= 2543) : (index += 1) { instance.array[index] = true; } index = 2545; while (index <= 2546) : (index += 1) { instance.array[index] = true; } index = 2548; while (index <= 2549) : (index += 1) { instance.array[index] = true; } index = 2551; while (index <= 2552) : (index += 1) { instance.array[index] = true; } index = 2557; while (index <= 2559) : (index += 1) { instance.array[index] = true; } index = 2560; while (index <= 2561) : (index += 1) { instance.array[index] = true; } index = 2566; while (index <= 2567) : (index += 1) { instance.array[index] = true; } index = 2570; while (index <= 2571) : (index += 1) { instance.array[index] = true; } instance.array[2576] = true; index = 2584; while (index <= 2587) : (index += 1) { instance.array[index] = true; } instance.array[2589] = true; index = 2607; while (index <= 2608) : (index += 1) { instance.array[index] = true; } index = 2609; while (index <= 2611) : (index += 1) { instance.array[index] = true; } instance.array[2612] = true; index = 2624; while (index <= 2625) : (index += 1) { instance.array[index] = true; } instance.array[2626] = true; index = 2628; while (index <= 2636) : (index += 1) { instance.array[index] = true; } index = 2638; while (index <= 2640) : (index += 1) { instance.array[index] = true; } index = 2642; while (index <= 2663) : (index += 1) { instance.array[index] = true; } index = 2665; while (index <= 2671) : (index += 1) { instance.array[index] = true; } index = 2673; while (index <= 2674) : (index += 1) { instance.array[index] = true; } index = 2676; while (index <= 2680) : (index += 1) { instance.array[index] = true; } instance.array[2684] = true; index = 2685; while (index <= 2687) : (index += 1) { instance.array[index] = true; } index = 2688; while (index <= 2692) : (index += 1) { instance.array[index] = true; } index = 2694; while (index <= 2695) : (index += 1) { instance.array[index] = true; } instance.array[2696] = true; index = 2698; while (index <= 2699) : (index += 1) { instance.array[index] = true; } instance.array[2703] = true; index = 2719; while (index <= 2720) : (index += 1) { instance.array[index] = true; } index = 2721; while (index <= 2722) : (index += 1) { instance.array[index] = true; } instance.array[2744] = true; index = 2745; while (index <= 2747) : (index += 1) { instance.array[index] = true; } instance.array[2752] = true; index = 2753; while (index <= 2754) : (index += 1) { instance.array[index] = true; } index = 2756; while (index <= 2763) : (index += 1) { instance.array[index] = true; } index = 2766; while (index <= 2767) : (index += 1) { instance.array[index] = true; } index = 2770; while (index <= 2791) : (index += 1) { instance.array[index] = true; } index = 2793; while (index <= 2799) : (index += 1) { instance.array[index] = true; } index = 2801; while (index <= 2802) : (index += 1) { instance.array[index] = true; } index = 2804; while (index <= 2808) : (index += 1) { instance.array[index] = true; } instance.array[2812] = true; instance.array[2813] = true; instance.array[2814] = true; instance.array[2815] = true; index = 2816; while (index <= 2819) : (index += 1) { instance.array[index] = true; } index = 2822; while (index <= 2823) : (index += 1) { instance.array[index] = true; } index = 2826; while (index <= 2827) : (index += 1) { instance.array[index] = true; } instance.array[2837] = true; instance.array[2838] = true; index = 2843; while (index <= 2844) : (index += 1) { instance.array[index] = true; } index = 2846; while (index <= 2848) : (index += 1) { instance.array[index] = true; } index = 2849; while (index <= 2850) : (index += 1) { instance.array[index] = true; } instance.array[2864] = true; instance.array[2881] = true; instance.array[2882] = true; index = 2884; while (index <= 2889) : (index += 1) { instance.array[index] = true; } index = 2893; while (index <= 2895) : (index += 1) { instance.array[index] = true; } index = 2897; while (index <= 2900) : (index += 1) { instance.array[index] = true; } index = 2904; while (index <= 2905) : (index += 1) { instance.array[index] = true; } instance.array[2907] = true; index = 2909; while (index <= 2910) : (index += 1) { instance.array[index] = true; } index = 2914; while (index <= 2915) : (index += 1) { instance.array[index] = true; } index = 2919; while (index <= 2921) : (index += 1) { instance.array[index] = true; } index = 2925; while (index <= 2936) : (index += 1) { instance.array[index] = true; } index = 2941; while (index <= 2942) : (index += 1) { instance.array[index] = true; } instance.array[2943] = true; index = 2944; while (index <= 2945) : (index += 1) { instance.array[index] = true; } index = 2949; while (index <= 2951) : (index += 1) { instance.array[index] = true; } index = 2953; while (index <= 2955) : (index += 1) { instance.array[index] = true; } instance.array[2959] = true; instance.array[2966] = true; instance.array[3007] = true; index = 3008; while (index <= 3010) : (index += 1) { instance.array[index] = true; } index = 3012; while (index <= 3019) : (index += 1) { instance.array[index] = true; } index = 3021; while (index <= 3023) : (index += 1) { instance.array[index] = true; } index = 3025; while (index <= 3047) : (index += 1) { instance.array[index] = true; } index = 3049; while (index <= 3064) : (index += 1) { instance.array[index] = true; } instance.array[3068] = true; index = 3069; while (index <= 3071) : (index += 1) { instance.array[index] = true; } index = 3072; while (index <= 3075) : (index += 1) { instance.array[index] = true; } index = 3077; while (index <= 3079) : (index += 1) { instance.array[index] = true; } index = 3081; while (index <= 3083) : (index += 1) { instance.array[index] = true; } index = 3092; while (index <= 3093) : (index += 1) { instance.array[index] = true; } index = 3095; while (index <= 3097) : (index += 1) { instance.array[index] = true; } index = 3103; while (index <= 3104) : (index += 1) { instance.array[index] = true; } index = 3105; while (index <= 3106) : (index += 1) { instance.array[index] = true; } instance.array[3135] = true; instance.array[3136] = true; index = 3137; while (index <= 3138) : (index += 1) { instance.array[index] = true; } index = 3140; while (index <= 3147) : (index += 1) { instance.array[index] = true; } index = 3149; while (index <= 3151) : (index += 1) { instance.array[index] = true; } index = 3153; while (index <= 3175) : (index += 1) { instance.array[index] = true; } index = 3177; while (index <= 3186) : (index += 1) { instance.array[index] = true; } index = 3188; while (index <= 3192) : (index += 1) { instance.array[index] = true; } instance.array[3196] = true; instance.array[3197] = true; instance.array[3198] = true; index = 3199; while (index <= 3203) : (index += 1) { instance.array[index] = true; } instance.array[3205] = true; index = 3206; while (index <= 3207) : (index += 1) { instance.array[index] = true; } index = 3209; while (index <= 3210) : (index += 1) { instance.array[index] = true; } instance.array[3211] = true; index = 3220; while (index <= 3221) : (index += 1) { instance.array[index] = true; } instance.array[3229] = true; index = 3231; while (index <= 3232) : (index += 1) { instance.array[index] = true; } index = 3233; while (index <= 3234) : (index += 1) { instance.array[index] = true; } index = 3248; while (index <= 3249) : (index += 1) { instance.array[index] = true; } index = 3263; while (index <= 3264) : (index += 1) { instance.array[index] = true; } index = 3265; while (index <= 3266) : (index += 1) { instance.array[index] = true; } index = 3267; while (index <= 3275) : (index += 1) { instance.array[index] = true; } index = 3277; while (index <= 3279) : (index += 1) { instance.array[index] = true; } index = 3281; while (index <= 3321) : (index += 1) { instance.array[index] = true; } instance.array[3324] = true; index = 3325; while (index <= 3327) : (index += 1) { instance.array[index] = true; } index = 3328; while (index <= 3331) : (index += 1) { instance.array[index] = true; } index = 3333; while (index <= 3335) : (index += 1) { instance.array[index] = true; } index = 3337; while (index <= 3339) : (index += 1) { instance.array[index] = true; } instance.array[3341] = true; index = 3347; while (index <= 3349) : (index += 1) { instance.array[index] = true; } instance.array[3350] = true; index = 3358; while (index <= 3360) : (index += 1) { instance.array[index] = true; } index = 3361; while (index <= 3362) : (index += 1) { instance.array[index] = true; } index = 3385; while (index <= 3390) : (index += 1) { instance.array[index] = true; } instance.array[3392] = true; index = 3393; while (index <= 3394) : (index += 1) { instance.array[index] = true; } index = 3396; while (index <= 3413) : (index += 1) { instance.array[index] = true; } index = 3417; while (index <= 3440) : (index += 1) { instance.array[index] = true; } index = 3442; while (index <= 3450) : (index += 1) { instance.array[index] = true; } instance.array[3452] = true; index = 3455; while (index <= 3461) : (index += 1) { instance.array[index] = true; } index = 3470; while (index <= 3472) : (index += 1) { instance.array[index] = true; } index = 3473; while (index <= 3475) : (index += 1) { instance.array[index] = true; } instance.array[3477] = true; index = 3479; while (index <= 3486) : (index += 1) { instance.array[index] = true; } index = 3505; while (index <= 3506) : (index += 1) { instance.array[index] = true; } index = 3520; while (index <= 3567) : (index += 1) { instance.array[index] = true; } instance.array[3568] = true; index = 3569; while (index <= 3570) : (index += 1) { instance.array[index] = true; } index = 3571; while (index <= 3577) : (index += 1) { instance.array[index] = true; } index = 3583; while (index <= 3588) : (index += 1) { instance.array[index] = true; } instance.array[3589] = true; instance.array[3596] = true; index = 3648; while (index <= 3649) : (index += 1) { instance.array[index] = true; } instance.array[3651] = true; index = 3653; while (index <= 3657) : (index += 1) { instance.array[index] = true; } index = 3659; while (index <= 3682) : (index += 1) { instance.array[index] = true; } instance.array[3684] = true; index = 3686; while (index <= 3695) : (index += 1) { instance.array[index] = true; } instance.array[3696] = true; index = 3697; while (index <= 3698) : (index += 1) { instance.array[index] = true; } index = 3699; while (index <= 3704) : (index += 1) { instance.array[index] = true; } index = 3706; while (index <= 3707) : (index += 1) { instance.array[index] = true; } instance.array[3708] = true; index = 3711; while (index <= 3715) : (index += 1) { instance.array[index] = true; } instance.array[3717] = true; instance.array[3724] = true; index = 3739; while (index <= 3742) : (index += 1) { instance.array[index] = true; } instance.array[3775] = true; index = 3839; while (index <= 3846) : (index += 1) { instance.array[index] = true; } index = 3848; while (index <= 3883) : (index += 1) { instance.array[index] = true; } index = 3888; while (index <= 3901) : (index += 1) { instance.array[index] = true; } instance.array[3902] = true; index = 3903; while (index <= 3904) : (index += 1) { instance.array[index] = true; } index = 3911; while (index <= 3915) : (index += 1) { instance.array[index] = true; } index = 3916; while (index <= 3926) : (index += 1) { instance.array[index] = true; } index = 3928; while (index <= 3963) : (index += 1) { instance.array[index] = true; } index = 4031; while (index <= 4073) : (index += 1) { instance.array[index] = true; } index = 4074; while (index <= 4075) : (index += 1) { instance.array[index] = true; } index = 4076; while (index <= 4079) : (index += 1) { instance.array[index] = true; } instance.array[4080] = true; index = 4081; while (index <= 4085) : (index += 1) { instance.array[index] = true; } instance.array[4087] = true; index = 4090; while (index <= 4091) : (index += 1) { instance.array[index] = true; } index = 4092; while (index <= 4093) : (index += 1) { instance.array[index] = true; } instance.array[4094] = true; index = 4111; while (index <= 4116) : (index += 1) { instance.array[index] = true; } index = 4117; while (index <= 4118) : (index += 1) { instance.array[index] = true; } index = 4119; while (index <= 4120) : (index += 1) { instance.array[index] = true; } index = 4121; while (index <= 4124) : (index += 1) { instance.array[index] = true; } index = 4125; while (index <= 4127) : (index += 1) { instance.array[index] = true; } instance.array[4128] = true; index = 4129; while (index <= 4131) : (index += 1) { instance.array[index] = true; } index = 4132; while (index <= 4133) : (index += 1) { instance.array[index] = true; } index = 4134; while (index <= 4140) : (index += 1) { instance.array[index] = true; } index = 4141; while (index <= 4143) : (index += 1) { instance.array[index] = true; } index = 4144; while (index <= 4147) : (index += 1) { instance.array[index] = true; } index = 4148; while (index <= 4160) : (index += 1) { instance.array[index] = true; } instance.array[4161] = true; index = 4162; while (index <= 4163) : (index += 1) { instance.array[index] = true; } index = 4164; while (index <= 4165) : (index += 1) { instance.array[index] = true; } index = 4166; while (index <= 4171) : (index += 1) { instance.array[index] = true; } instance.array[4172] = true; instance.array[4173] = true; instance.array[4174] = true; index = 4185; while (index <= 4187) : (index += 1) { instance.array[index] = true; } instance.array[4188] = true; index = 4191; while (index <= 4228) : (index += 1) { instance.array[index] = true; } instance.array[4230] = true; instance.array[4236] = true; index = 4239; while (index <= 4281) : (index += 1) { instance.array[index] = true; } instance.array[4283] = true; index = 4284; while (index <= 4286) : (index += 1) { instance.array[index] = true; } index = 4287; while (index <= 4615) : (index += 1) { instance.array[index] = true; } index = 4617; while (index <= 4620) : (index += 1) { instance.array[index] = true; } index = 4623; while (index <= 4629) : (index += 1) { instance.array[index] = true; } instance.array[4631] = true; index = 4633; while (index <= 4636) : (index += 1) { instance.array[index] = true; } index = 4639; while (index <= 4679) : (index += 1) { instance.array[index] = true; } index = 4681; while (index <= 4684) : (index += 1) { instance.array[index] = true; } index = 4687; while (index <= 4719) : (index += 1) { instance.array[index] = true; } index = 4721; while (index <= 4724) : (index += 1) { instance.array[index] = true; } index = 4727; while (index <= 4733) : (index += 1) { instance.array[index] = true; } instance.array[4735] = true; index = 4737; while (index <= 4740) : (index += 1) { instance.array[index] = true; } index = 4743; while (index <= 4757) : (index += 1) { instance.array[index] = true; } index = 4759; while (index <= 4815) : (index += 1) { instance.array[index] = true; } index = 4817; while (index <= 4820) : (index += 1) { instance.array[index] = true; } index = 4823; while (index <= 4889) : (index += 1) { instance.array[index] = true; } index = 4927; while (index <= 4942) : (index += 1) { instance.array[index] = true; } index = 4959; while (index <= 5044) : (index += 1) { instance.array[index] = true; } index = 5047; while (index <= 5052) : (index += 1) { instance.array[index] = true; } index = 5056; while (index <= 5675) : (index += 1) { instance.array[index] = true; } index = 5678; while (index <= 5694) : (index += 1) { instance.array[index] = true; } index = 5696; while (index <= 5721) : (index += 1) { instance.array[index] = true; } index = 5727; while (index <= 5801) : (index += 1) { instance.array[index] = true; } index = 5805; while (index <= 5807) : (index += 1) { instance.array[index] = true; } index = 5808; while (index <= 5815) : (index += 1) { instance.array[index] = true; } index = 5823; while (index <= 5835) : (index += 1) { instance.array[index] = true; } index = 5837; while (index <= 5840) : (index += 1) { instance.array[index] = true; } index = 5841; while (index <= 5842) : (index += 1) { instance.array[index] = true; } index = 5855; while (index <= 5872) : (index += 1) { instance.array[index] = true; } index = 5873; while (index <= 5874) : (index += 1) { instance.array[index] = true; } index = 5887; while (index <= 5904) : (index += 1) { instance.array[index] = true; } index = 5905; while (index <= 5906) : (index += 1) { instance.array[index] = true; } index = 5919; while (index <= 5931) : (index += 1) { instance.array[index] = true; } index = 5933; while (index <= 5935) : (index += 1) { instance.array[index] = true; } index = 5937; while (index <= 5938) : (index += 1) { instance.array[index] = true; } index = 5951; while (index <= 6002) : (index += 1) { instance.array[index] = true; } instance.array[6005] = true; index = 6006; while (index <= 6012) : (index += 1) { instance.array[index] = true; } index = 6013; while (index <= 6020) : (index += 1) { instance.array[index] = true; } instance.array[6021] = true; index = 6022; while (index <= 6023) : (index += 1) { instance.array[index] = true; } instance.array[6038] = true; instance.array[6043] = true; index = 6111; while (index <= 6145) : (index += 1) { instance.array[index] = true; } instance.array[6146] = true; index = 6147; while (index <= 6199) : (index += 1) { instance.array[index] = true; } index = 6207; while (index <= 6211) : (index += 1) { instance.array[index] = true; } index = 6212; while (index <= 6213) : (index += 1) { instance.array[index] = true; } index = 6214; while (index <= 6247) : (index += 1) { instance.array[index] = true; } instance.array[6248] = true; instance.array[6249] = true; index = 6255; while (index <= 6324) : (index += 1) { instance.array[index] = true; } index = 6335; while (index <= 6365) : (index += 1) { instance.array[index] = true; } index = 6367; while (index <= 6369) : (index += 1) { instance.array[index] = true; } index = 6370; while (index <= 6373) : (index += 1) { instance.array[index] = true; } index = 6374; while (index <= 6375) : (index += 1) { instance.array[index] = true; } index = 6376; while (index <= 6378) : (index += 1) { instance.array[index] = true; } index = 6383; while (index <= 6384) : (index += 1) { instance.array[index] = true; } instance.array[6385] = true; index = 6386; while (index <= 6391) : (index += 1) { instance.array[index] = true; } index = 6415; while (index <= 6444) : (index += 1) { instance.array[index] = true; } index = 6447; while (index <= 6451) : (index += 1) { instance.array[index] = true; } index = 6463; while (index <= 6506) : (index += 1) { instance.array[index] = true; } index = 6511; while (index <= 6536) : (index += 1) { instance.array[index] = true; } index = 6591; while (index <= 6613) : (index += 1) { instance.array[index] = true; } index = 6614; while (index <= 6615) : (index += 1) { instance.array[index] = true; } index = 6616; while (index <= 6617) : (index += 1) { instance.array[index] = true; } instance.array[6618] = true; index = 6623; while (index <= 6675) : (index += 1) { instance.array[index] = true; } instance.array[6676] = true; instance.array[6677] = true; instance.array[6678] = true; index = 6679; while (index <= 6685) : (index += 1) { instance.array[index] = true; } instance.array[6688] = true; instance.array[6689] = true; index = 6690; while (index <= 6691) : (index += 1) { instance.array[index] = true; } index = 6692; while (index <= 6699) : (index += 1) { instance.array[index] = true; } index = 6700; while (index <= 6705) : (index += 1) { instance.array[index] = true; } index = 6706; while (index <= 6707) : (index += 1) { instance.array[index] = true; } instance.array[6758] = true; index = 6782; while (index <= 6783) : (index += 1) { instance.array[index] = true; } index = 6847; while (index <= 6850) : (index += 1) { instance.array[index] = true; } instance.array[6851] = true; index = 6852; while (index <= 6898) : (index += 1) { instance.array[index] = true; } instance.array[6900] = true; index = 6901; while (index <= 6905) : (index += 1) { instance.array[index] = true; } instance.array[6906] = true; instance.array[6907] = true; index = 6908; while (index <= 6912) : (index += 1) { instance.array[index] = true; } instance.array[6913] = true; instance.array[6914] = true; index = 6916; while (index <= 6922) : (index += 1) { instance.array[index] = true; } index = 6975; while (index <= 6976) : (index += 1) { instance.array[index] = true; } instance.array[6977] = true; index = 6978; while (index <= 7007) : (index += 1) { instance.array[index] = true; } instance.array[7008] = true; index = 7009; while (index <= 7012) : (index += 1) { instance.array[index] = true; } index = 7013; while (index <= 7014) : (index += 1) { instance.array[index] = true; } index = 7015; while (index <= 7016) : (index += 1) { instance.array[index] = true; } index = 7019; while (index <= 7020) : (index += 1) { instance.array[index] = true; } index = 7021; while (index <= 7022) : (index += 1) { instance.array[index] = true; } index = 7033; while (index <= 7076) : (index += 1) { instance.array[index] = true; } instance.array[7078] = true; index = 7079; while (index <= 7080) : (index += 1) { instance.array[index] = true; } index = 7081; while (index <= 7083) : (index += 1) { instance.array[index] = true; } instance.array[7084] = true; instance.array[7085] = true; index = 7086; while (index <= 7088) : (index += 1) { instance.array[index] = true; } index = 7103; while (index <= 7138) : (index += 1) { instance.array[index] = true; } index = 7139; while (index <= 7146) : (index += 1) { instance.array[index] = true; } index = 7147; while (index <= 7154) : (index += 1) { instance.array[index] = true; } index = 7155; while (index <= 7156) : (index += 1) { instance.array[index] = true; } instance.array[7157] = true; index = 7180; while (index <= 7182) : (index += 1) { instance.array[index] = true; } index = 7193; while (index <= 7222) : (index += 1) { instance.array[index] = true; } index = 7223; while (index <= 7228) : (index += 1) { instance.array[index] = true; } index = 7231; while (index <= 7239) : (index += 1) { instance.array[index] = true; } index = 7247; while (index <= 7289) : (index += 1) { instance.array[index] = true; } index = 7292; while (index <= 7294) : (index += 1) { instance.array[index] = true; } index = 7336; while (index <= 7339) : (index += 1) { instance.array[index] = true; } index = 7341; while (index <= 7346) : (index += 1) { instance.array[index] = true; } index = 7348; while (index <= 7349) : (index += 1) { instance.array[index] = true; } instance.array[7353] = true; index = 7359; while (index <= 7402) : (index += 1) { instance.array[index] = true; } index = 7403; while (index <= 7465) : (index += 1) { instance.array[index] = true; } index = 7466; while (index <= 7478) : (index += 1) { instance.array[index] = true; } instance.array[7479] = true; index = 7480; while (index <= 7513) : (index += 1) { instance.array[index] = true; } index = 7514; while (index <= 7550) : (index += 1) { instance.array[index] = true; } index = 7590; while (index <= 7603) : (index += 1) { instance.array[index] = true; } index = 7615; while (index <= 7892) : (index += 1) { instance.array[index] = true; } index = 7895; while (index <= 7900) : (index += 1) { instance.array[index] = true; } index = 7903; while (index <= 7940) : (index += 1) { instance.array[index] = true; } index = 7943; while (index <= 7948) : (index += 1) { instance.array[index] = true; } index = 7951; while (index <= 7958) : (index += 1) { instance.array[index] = true; } instance.array[7960] = true; instance.array[7962] = true; instance.array[7964] = true; index = 7966; while (index <= 7996) : (index += 1) { instance.array[index] = true; } index = 7999; while (index <= 8051) : (index += 1) { instance.array[index] = true; } index = 8053; while (index <= 8059) : (index += 1) { instance.array[index] = true; } instance.array[8061] = true; index = 8065; while (index <= 8067) : (index += 1) { instance.array[index] = true; } index = 8069; while (index <= 8075) : (index += 1) { instance.array[index] = true; } index = 8079; while (index <= 8082) : (index += 1) { instance.array[index] = true; } index = 8085; while (index <= 8090) : (index += 1) { instance.array[index] = true; } index = 8095; while (index <= 8107) : (index += 1) { instance.array[index] = true; } index = 8113; while (index <= 8115) : (index += 1) { instance.array[index] = true; } index = 8117; while (index <= 8123) : (index += 1) { instance.array[index] = true; } instance.array[8240] = true; instance.array[8254] = true; index = 8271; while (index <= 8283) : (index += 1) { instance.array[index] = true; } instance.array[8385] = true; instance.array[8390] = true; index = 8393; while (index <= 8402) : (index += 1) { instance.array[index] = true; } instance.array[8404] = true; index = 8408; while (index <= 8412) : (index += 1) { instance.array[index] = true; } instance.array[8419] = true; instance.array[8421] = true; instance.array[8423] = true; index = 8425; while (index <= 8428) : (index += 1) { instance.array[index] = true; } index = 8430; while (index <= 8435) : (index += 1) { instance.array[index] = true; } index = 8436; while (index <= 8439) : (index += 1) { instance.array[index] = true; } instance.array[8440] = true; index = 8443; while (index <= 8446) : (index += 1) { instance.array[index] = true; } index = 8452; while (index <= 8456) : (index += 1) { instance.array[index] = true; } instance.array[8461] = true; index = 8479; while (index <= 8513) : (index += 1) { instance.array[index] = true; } index = 8514; while (index <= 8515) : (index += 1) { instance.array[index] = true; } index = 8516; while (index <= 8519) : (index += 1) { instance.array[index] = true; } index = 9333; while (index <= 9384) : (index += 1) { instance.array[index] = true; } index = 11199; while (index <= 11245) : (index += 1) { instance.array[index] = true; } index = 11247; while (index <= 11293) : (index += 1) { instance.array[index] = true; } index = 11295; while (index <= 11322) : (index += 1) { instance.array[index] = true; } index = 11323; while (index <= 11324) : (index += 1) { instance.array[index] = true; } index = 11325; while (index <= 11427) : (index += 1) { instance.array[index] = true; } index = 11434; while (index <= 11437) : (index += 1) { instance.array[index] = true; } index = 11441; while (index <= 11442) : (index += 1) { instance.array[index] = true; } index = 11455; while (index <= 11492) : (index += 1) { instance.array[index] = true; } instance.array[11494] = true; instance.array[11500] = true; index = 11503; while (index <= 11558) : (index += 1) { instance.array[index] = true; } instance.array[11566] = true; index = 11583; while (index <= 11605) : (index += 1) { instance.array[index] = true; } index = 11615; while (index <= 11621) : (index += 1) { instance.array[index] = true; } index = 11623; while (index <= 11629) : (index += 1) { instance.array[index] = true; } index = 11631; while (index <= 11637) : (index += 1) { instance.array[index] = true; } index = 11639; while (index <= 11645) : (index += 1) { instance.array[index] = true; } index = 11647; while (index <= 11653) : (index += 1) { instance.array[index] = true; } index = 11655; while (index <= 11661) : (index += 1) { instance.array[index] = true; } index = 11663; while (index <= 11669) : (index += 1) { instance.array[index] = true; } index = 11671; while (index <= 11677) : (index += 1) { instance.array[index] = true; } index = 11679; while (index <= 11710) : (index += 1) { instance.array[index] = true; } instance.array[11758] = true; instance.array[12228] = true; instance.array[12229] = true; instance.array[12230] = true; index = 12256; while (index <= 12264) : (index += 1) { instance.array[index] = true; } index = 12272; while (index <= 12276) : (index += 1) { instance.array[index] = true; } index = 12279; while (index <= 12281) : (index += 1) { instance.array[index] = true; } instance.array[12282] = true; instance.array[12283] = true; index = 12288; while (index <= 12373) : (index += 1) { instance.array[index] = true; } index = 12380; while (index <= 12381) : (index += 1) { instance.array[index] = true; } instance.array[12382] = true; index = 12384; while (index <= 12473) : (index += 1) { instance.array[index] = true; } index = 12475; while (index <= 12477) : (index += 1) { instance.array[index] = true; } instance.array[12478] = true; index = 12484; while (index <= 12526) : (index += 1) { instance.array[index] = true; } index = 12528; while (index <= 12621) : (index += 1) { instance.array[index] = true; } index = 12639; while (index <= 12670) : (index += 1) { instance.array[index] = true; } index = 12719; while (index <= 12734) : (index += 1) { instance.array[index] = true; } index = 13247; while (index <= 19838) : (index += 1) { instance.array[index] = true; } index = 19903; while (index <= 40891) : (index += 1) { instance.array[index] = true; } index = 40895; while (index <= 40915) : (index += 1) { instance.array[index] = true; } instance.array[40916] = true; index = 40917; while (index <= 42059) : (index += 1) { instance.array[index] = true; } index = 42127; while (index <= 42166) : (index += 1) { instance.array[index] = true; } index = 42167; while (index <= 42172) : (index += 1) { instance.array[index] = true; } index = 42175; while (index <= 42442) : (index += 1) { instance.array[index] = true; } instance.array[42443] = true; index = 42447; while (index <= 42462) : (index += 1) { instance.array[index] = true; } index = 42473; while (index <= 42474) : (index += 1) { instance.array[index] = true; } index = 42495; while (index <= 42540) : (index += 1) { instance.array[index] = true; } instance.array[42541] = true; index = 42547; while (index <= 42554) : (index += 1) { instance.array[index] = true; } instance.array[42558] = true; index = 42559; while (index <= 42586) : (index += 1) { instance.array[index] = true; } index = 42587; while (index <= 42588) : (index += 1) { instance.array[index] = true; } index = 42589; while (index <= 42590) : (index += 1) { instance.array[index] = true; } index = 42591; while (index <= 42660) : (index += 1) { instance.array[index] = true; } index = 42661; while (index <= 42670) : (index += 1) { instance.array[index] = true; } index = 42710; while (index <= 42718) : (index += 1) { instance.array[index] = true; } index = 42721; while (index <= 42798) : (index += 1) { instance.array[index] = true; } instance.array[42799] = true; index = 42800; while (index <= 42822) : (index += 1) { instance.array[index] = true; } instance.array[42823] = true; index = 42826; while (index <= 42829) : (index += 1) { instance.array[index] = true; } instance.array[42830] = true; index = 42831; while (index <= 42878) : (index += 1) { instance.array[index] = true; } index = 42881; while (index <= 42889) : (index += 1) { instance.array[index] = true; } index = 42932; while (index <= 42933) : (index += 1) { instance.array[index] = true; } instance.array[42934] = true; index = 42935; while (index <= 42936) : (index += 1) { instance.array[index] = true; } instance.array[42937] = true; index = 42938; while (index <= 42944) : (index += 1) { instance.array[index] = true; } instance.array[42945] = true; index = 42946; while (index <= 42948) : (index += 1) { instance.array[index] = true; } index = 42950; while (index <= 42953) : (index += 1) { instance.array[index] = true; } instance.array[42954] = true; index = 42955; while (index <= 42977) : (index += 1) { instance.array[index] = true; } index = 42978; while (index <= 42979) : (index += 1) { instance.array[index] = true; } index = 42980; while (index <= 42981) : (index += 1) { instance.array[index] = true; } instance.array[42982] = true; index = 43007; while (index <= 43058) : (index += 1) { instance.array[index] = true; } index = 43071; while (index <= 43072) : (index += 1) { instance.array[index] = true; } index = 43073; while (index <= 43122) : (index += 1) { instance.array[index] = true; } index = 43123; while (index <= 43138) : (index += 1) { instance.array[index] = true; } instance.array[43140] = true; index = 43185; while (index <= 43190) : (index += 1) { instance.array[index] = true; } instance.array[43194] = true; index = 43196; while (index <= 43197) : (index += 1) { instance.array[index] = true; } instance.array[43198] = true; index = 43209; while (index <= 43236) : (index += 1) { instance.array[index] = true; } index = 43237; while (index <= 43241) : (index += 1) { instance.array[index] = true; } index = 43247; while (index <= 43269) : (index += 1) { instance.array[index] = true; } index = 43270; while (index <= 43280) : (index += 1) { instance.array[index] = true; } instance.array[43281] = true; index = 43295; while (index <= 43323) : (index += 1) { instance.array[index] = true; } index = 43327; while (index <= 43329) : (index += 1) { instance.array[index] = true; } instance.array[43330] = true; index = 43331; while (index <= 43377) : (index += 1) { instance.array[index] = true; } index = 43379; while (index <= 43380) : (index += 1) { instance.array[index] = true; } index = 43381; while (index <= 43384) : (index += 1) { instance.array[index] = true; } index = 43385; while (index <= 43386) : (index += 1) { instance.array[index] = true; } index = 43387; while (index <= 43388) : (index += 1) { instance.array[index] = true; } index = 43389; while (index <= 43390) : (index += 1) { instance.array[index] = true; } instance.array[43406] = true; index = 43423; while (index <= 43427) : (index += 1) { instance.array[index] = true; } instance.array[43428] = true; instance.array[43429] = true; index = 43430; while (index <= 43438) : (index += 1) { instance.array[index] = true; } index = 43449; while (index <= 43453) : (index += 1) { instance.array[index] = true; } index = 43455; while (index <= 43495) : (index += 1) { instance.array[index] = true; } index = 43496; while (index <= 43501) : (index += 1) { instance.array[index] = true; } index = 43502; while (index <= 43503) : (index += 1) { instance.array[index] = true; } index = 43504; while (index <= 43505) : (index += 1) { instance.array[index] = true; } index = 43506; while (index <= 43507) : (index += 1) { instance.array[index] = true; } index = 43508; while (index <= 43509) : (index += 1) { instance.array[index] = true; } index = 43519; while (index <= 43521) : (index += 1) { instance.array[index] = true; } instance.array[43522] = true; index = 43523; while (index <= 43530) : (index += 1) { instance.array[index] = true; } instance.array[43531] = true; instance.array[43532] = true; index = 43551; while (index <= 43566) : (index += 1) { instance.array[index] = true; } instance.array[43567] = true; index = 43568; while (index <= 43573) : (index += 1) { instance.array[index] = true; } instance.array[43577] = true; instance.array[43578] = true; instance.array[43579] = true; instance.array[43580] = true; index = 43581; while (index <= 43630) : (index += 1) { instance.array[index] = true; } instance.array[43631] = true; instance.array[43632] = true; index = 43633; while (index <= 43635) : (index += 1) { instance.array[index] = true; } index = 43636; while (index <= 43637) : (index += 1) { instance.array[index] = true; } index = 43638; while (index <= 43639) : (index += 1) { instance.array[index] = true; } index = 43640; while (index <= 43644) : (index += 1) { instance.array[index] = true; } instance.array[43645] = true; instance.array[43647] = true; instance.array[43649] = true; index = 43674; while (index <= 43675) : (index += 1) { instance.array[index] = true; } instance.array[43676] = true; index = 43679; while (index <= 43689) : (index += 1) { instance.array[index] = true; } instance.array[43690] = true; index = 43691; while (index <= 43692) : (index += 1) { instance.array[index] = true; } index = 43693; while (index <= 43694) : (index += 1) { instance.array[index] = true; } instance.array[43697] = true; index = 43698; while (index <= 43699) : (index += 1) { instance.array[index] = true; } instance.array[43700] = true; index = 43712; while (index <= 43717) : (index += 1) { instance.array[index] = true; } index = 43720; while (index <= 43725) : (index += 1) { instance.array[index] = true; } index = 43728; while (index <= 43733) : (index += 1) { instance.array[index] = true; } index = 43743; while (index <= 43749) : (index += 1) { instance.array[index] = true; } index = 43751; while (index <= 43757) : (index += 1) { instance.array[index] = true; } index = 43759; while (index <= 43801) : (index += 1) { instance.array[index] = true; } index = 43803; while (index <= 43806) : (index += 1) { instance.array[index] = true; } index = 43807; while (index <= 43815) : (index += 1) { instance.array[index] = true; } instance.array[43816] = true; index = 43823; while (index <= 43902) : (index += 1) { instance.array[index] = true; } index = 43903; while (index <= 43937) : (index += 1) { instance.array[index] = true; } index = 43938; while (index <= 43939) : (index += 1) { instance.array[index] = true; } instance.array[43940] = true; index = 43941; while (index <= 43942) : (index += 1) { instance.array[index] = true; } instance.array[43943] = true; index = 43944; while (index <= 43945) : (index += 1) { instance.array[index] = true; } index = 43967; while (index <= 55138) : (index += 1) { instance.array[index] = true; } index = 55151; while (index <= 55173) : (index += 1) { instance.array[index] = true; } index = 55178; while (index <= 55226) : (index += 1) { instance.array[index] = true; } index = 63679; while (index <= 64044) : (index += 1) { instance.array[index] = true; } index = 64047; while (index <= 64152) : (index += 1) { instance.array[index] = true; } index = 64191; while (index <= 64197) : (index += 1) { instance.array[index] = true; } index = 64210; while (index <= 64214) : (index += 1) { instance.array[index] = true; } instance.array[64220] = true; instance.array[64221] = true; index = 64222; while (index <= 64231) : (index += 1) { instance.array[index] = true; } index = 64233; while (index <= 64245) : (index += 1) { instance.array[index] = true; } index = 64247; while (index <= 64251) : (index += 1) { instance.array[index] = true; } instance.array[64253] = true; index = 64255; while (index <= 64256) : (index += 1) { instance.array[index] = true; } index = 64258; while (index <= 64259) : (index += 1) { instance.array[index] = true; } index = 64261; while (index <= 64368) : (index += 1) { instance.array[index] = true; } index = 64402; while (index <= 64764) : (index += 1) { instance.array[index] = true; } index = 64783; while (index <= 64846) : (index += 1) { instance.array[index] = true; } index = 64849; while (index <= 64902) : (index += 1) { instance.array[index] = true; } index = 64943; while (index <= 64954) : (index += 1) { instance.array[index] = true; } index = 65071; while (index <= 65075) : (index += 1) { instance.array[index] = true; } index = 65077; while (index <= 65211) : (index += 1) { instance.array[index] = true; } index = 65248; while (index <= 65273) : (index += 1) { instance.array[index] = true; } index = 65280; while (index <= 65305) : (index += 1) { instance.array[index] = true; } index = 65317; while (index <= 65326) : (index += 1) { instance.array[index] = true; } instance.array[65327] = true; index = 65328; while (index <= 65372) : (index += 1) { instance.array[index] = true; } index = 65373; while (index <= 65374) : (index += 1) { instance.array[index] = true; } index = 65375; while (index <= 65405) : (index += 1) { instance.array[index] = true; } index = 65409; while (index <= 65414) : (index += 1) { instance.array[index] = true; } index = 65417; while (index <= 65422) : (index += 1) { instance.array[index] = true; } index = 65425; while (index <= 65430) : (index += 1) { instance.array[index] = true; } index = 65433; while (index <= 65435) : (index += 1) { instance.array[index] = true; } index = 65471; while (index <= 65482) : (index += 1) { instance.array[index] = true; } index = 65484; while (index <= 65509) : (index += 1) { instance.array[index] = true; } index = 65511; while (index <= 65529) : (index += 1) { instance.array[index] = true; } index = 65531; while (index <= 65532) : (index += 1) { instance.array[index] = true; } index = 65534; while (index <= 65548) : (index += 1) { instance.array[index] = true; } index = 65551; while (index <= 65564) : (index += 1) { instance.array[index] = true; } index = 65599; while (index <= 65721) : (index += 1) { instance.array[index] = true; } index = 65791; while (index <= 65843) : (index += 1) { instance.array[index] = true; } index = 66111; while (index <= 66139) : (index += 1) { instance.array[index] = true; } index = 66143; while (index <= 66191) : (index += 1) { instance.array[index] = true; } index = 66239; while (index <= 66270) : (index += 1) { instance.array[index] = true; } index = 66284; while (index <= 66303) : (index += 1) { instance.array[index] = true; } instance.array[66304] = true; index = 66305; while (index <= 66312) : (index += 1) { instance.array[index] = true; } instance.array[66313] = true; index = 66319; while (index <= 66356) : (index += 1) { instance.array[index] = true; } index = 66357; while (index <= 66361) : (index += 1) { instance.array[index] = true; } index = 66367; while (index <= 66396) : (index += 1) { instance.array[index] = true; } index = 66399; while (index <= 66434) : (index += 1) { instance.array[index] = true; } index = 66439; while (index <= 66446) : (index += 1) { instance.array[index] = true; } index = 66448; while (index <= 66452) : (index += 1) { instance.array[index] = true; } index = 66495; while (index <= 66574) : (index += 1) { instance.array[index] = true; } index = 66575; while (index <= 66652) : (index += 1) { instance.array[index] = true; } index = 66671; while (index <= 66706) : (index += 1) { instance.array[index] = true; } index = 66711; while (index <= 66746) : (index += 1) { instance.array[index] = true; } index = 66751; while (index <= 66790) : (index += 1) { instance.array[index] = true; } index = 66799; while (index <= 66850) : (index += 1) { instance.array[index] = true; } index = 67007; while (index <= 67317) : (index += 1) { instance.array[index] = true; } index = 67327; while (index <= 67348) : (index += 1) { instance.array[index] = true; } index = 67359; while (index <= 67366) : (index += 1) { instance.array[index] = true; } index = 67519; while (index <= 67524) : (index += 1) { instance.array[index] = true; } instance.array[67527] = true; index = 67529; while (index <= 67572) : (index += 1) { instance.array[index] = true; } index = 67574; while (index <= 67575) : (index += 1) { instance.array[index] = true; } instance.array[67579] = true; index = 67582; while (index <= 67604) : (index += 1) { instance.array[index] = true; } index = 67615; while (index <= 67637) : (index += 1) { instance.array[index] = true; } index = 67647; while (index <= 67677) : (index += 1) { instance.array[index] = true; } index = 67743; while (index <= 67761) : (index += 1) { instance.array[index] = true; } index = 67763; while (index <= 67764) : (index += 1) { instance.array[index] = true; } index = 67775; while (index <= 67796) : (index += 1) { instance.array[index] = true; } index = 67807; while (index <= 67832) : (index += 1) { instance.array[index] = true; } index = 67903; while (index <= 67958) : (index += 1) { instance.array[index] = true; } index = 67965; while (index <= 67966) : (index += 1) { instance.array[index] = true; } instance.array[68031] = true; index = 68032; while (index <= 68034) : (index += 1) { instance.array[index] = true; } index = 68036; while (index <= 68037) : (index += 1) { instance.array[index] = true; } index = 68043; while (index <= 68046) : (index += 1) { instance.array[index] = true; } index = 68047; while (index <= 68050) : (index += 1) { instance.array[index] = true; } index = 68052; while (index <= 68054) : (index += 1) { instance.array[index] = true; } index = 68056; while (index <= 68084) : (index += 1) { instance.array[index] = true; } index = 68127; while (index <= 68155) : (index += 1) { instance.array[index] = true; } index = 68159; while (index <= 68187) : (index += 1) { instance.array[index] = true; } index = 68223; while (index <= 68230) : (index += 1) { instance.array[index] = true; } index = 68232; while (index <= 68259) : (index += 1) { instance.array[index] = true; } index = 68287; while (index <= 68340) : (index += 1) { instance.array[index] = true; } index = 68351; while (index <= 68372) : (index += 1) { instance.array[index] = true; } index = 68383; while (index <= 68401) : (index += 1) { instance.array[index] = true; } index = 68415; while (index <= 68432) : (index += 1) { instance.array[index] = true; } index = 68543; while (index <= 68615) : (index += 1) { instance.array[index] = true; } index = 68671; while (index <= 68721) : (index += 1) { instance.array[index] = true; } index = 68735; while (index <= 68785) : (index += 1) { instance.array[index] = true; } index = 68799; while (index <= 68834) : (index += 1) { instance.array[index] = true; } index = 68835; while (index <= 68838) : (index += 1) { instance.array[index] = true; } index = 69183; while (index <= 69224) : (index += 1) { instance.array[index] = true; } index = 69226; while (index <= 69227) : (index += 1) { instance.array[index] = true; } index = 69231; while (index <= 69232) : (index += 1) { instance.array[index] = true; } index = 69311; while (index <= 69339) : (index += 1) { instance.array[index] = true; } instance.array[69350] = true; index = 69359; while (index <= 69380) : (index += 1) { instance.array[index] = true; } index = 69487; while (index <= 69507) : (index += 1) { instance.array[index] = true; } index = 69535; while (index <= 69557) : (index += 1) { instance.array[index] = true; } instance.array[69567] = true; instance.array[69568] = true; instance.array[69569] = true; index = 69570; while (index <= 69622) : (index += 1) { instance.array[index] = true; } index = 69623; while (index <= 69636) : (index += 1) { instance.array[index] = true; } instance.array[69697] = true; index = 69698; while (index <= 69742) : (index += 1) { instance.array[index] = true; } index = 69743; while (index <= 69745) : (index += 1) { instance.array[index] = true; } index = 69746; while (index <= 69749) : (index += 1) { instance.array[index] = true; } index = 69750; while (index <= 69751) : (index += 1) { instance.array[index] = true; } index = 69775; while (index <= 69799) : (index += 1) { instance.array[index] = true; } index = 69823; while (index <= 69825) : (index += 1) { instance.array[index] = true; } index = 69826; while (index <= 69861) : (index += 1) { instance.array[index] = true; } index = 69862; while (index <= 69866) : (index += 1) { instance.array[index] = true; } instance.array[69867] = true; index = 69868; while (index <= 69873) : (index += 1) { instance.array[index] = true; } instance.array[69891] = true; index = 69892; while (index <= 69893) : (index += 1) { instance.array[index] = true; } instance.array[69894] = true; index = 69903; while (index <= 69937) : (index += 1) { instance.array[index] = true; } instance.array[69941] = true; index = 69951; while (index <= 69952) : (index += 1) { instance.array[index] = true; } instance.array[69953] = true; index = 69954; while (index <= 70001) : (index += 1) { instance.array[index] = true; } index = 70002; while (index <= 70004) : (index += 1) { instance.array[index] = true; } index = 70005; while (index <= 70013) : (index += 1) { instance.array[index] = true; } instance.array[70014] = true; index = 70016; while (index <= 70019) : (index += 1) { instance.array[index] = true; } instance.array[70029] = true; instance.array[70030] = true; instance.array[70041] = true; instance.array[70043] = true; index = 70079; while (index <= 70096) : (index += 1) { instance.array[index] = true; } index = 70098; while (index <= 70122) : (index += 1) { instance.array[index] = true; } index = 70123; while (index <= 70125) : (index += 1) { instance.array[index] = true; } index = 70126; while (index <= 70128) : (index += 1) { instance.array[index] = true; } index = 70129; while (index <= 70130) : (index += 1) { instance.array[index] = true; } instance.array[70131] = true; instance.array[70134] = true; instance.array[70141] = true; index = 70207; while (index <= 70213) : (index += 1) { instance.array[index] = true; } instance.array[70215] = true; index = 70217; while (index <= 70220) : (index += 1) { instance.array[index] = true; } index = 70222; while (index <= 70236) : (index += 1) { instance.array[index] = true; } index = 70238; while (index <= 70247) : (index += 1) { instance.array[index] = true; } index = 70255; while (index <= 70301) : (index += 1) { instance.array[index] = true; } instance.array[70302] = true; index = 70303; while (index <= 70305) : (index += 1) { instance.array[index] = true; } index = 70306; while (index <= 70311) : (index += 1) { instance.array[index] = true; } index = 70335; while (index <= 70336) : (index += 1) { instance.array[index] = true; } index = 70337; while (index <= 70338) : (index += 1) { instance.array[index] = true; } index = 70340; while (index <= 70347) : (index += 1) { instance.array[index] = true; } index = 70350; while (index <= 70351) : (index += 1) { instance.array[index] = true; } index = 70354; while (index <= 70375) : (index += 1) { instance.array[index] = true; } index = 70377; while (index <= 70383) : (index += 1) { instance.array[index] = true; } index = 70385; while (index <= 70386) : (index += 1) { instance.array[index] = true; } index = 70388; while (index <= 70392) : (index += 1) { instance.array[index] = true; } instance.array[70396] = true; index = 70397; while (index <= 70398) : (index += 1) { instance.array[index] = true; } instance.array[70399] = true; index = 70400; while (index <= 70403) : (index += 1) { instance.array[index] = true; } index = 70406; while (index <= 70407) : (index += 1) { instance.array[index] = true; } index = 70410; while (index <= 70411) : (index += 1) { instance.array[index] = true; } instance.array[70415] = true; instance.array[70422] = true; index = 70428; while (index <= 70432) : (index += 1) { instance.array[index] = true; } index = 70433; while (index <= 70434) : (index += 1) { instance.array[index] = true; } index = 70591; while (index <= 70643) : (index += 1) { instance.array[index] = true; } index = 70644; while (index <= 70646) : (index += 1) { instance.array[index] = true; } index = 70647; while (index <= 70654) : (index += 1) { instance.array[index] = true; } index = 70655; while (index <= 70656) : (index += 1) { instance.array[index] = true; } index = 70658; while (index <= 70659) : (index += 1) { instance.array[index] = true; } instance.array[70660] = true; index = 70662; while (index <= 70665) : (index += 1) { instance.array[index] = true; } index = 70686; while (index <= 70688) : (index += 1) { instance.array[index] = true; } index = 70719; while (index <= 70766) : (index += 1) { instance.array[index] = true; } index = 70767; while (index <= 70769) : (index += 1) { instance.array[index] = true; } index = 70770; while (index <= 70775) : (index += 1) { instance.array[index] = true; } instance.array[70776] = true; instance.array[70777] = true; index = 70778; while (index <= 70781) : (index += 1) { instance.array[index] = true; } index = 70782; while (index <= 70783) : (index += 1) { instance.array[index] = true; } instance.array[70784] = true; index = 70787; while (index <= 70788) : (index += 1) { instance.array[index] = true; } instance.array[70790] = true; index = 70975; while (index <= 71021) : (index += 1) { instance.array[index] = true; } index = 71022; while (index <= 71024) : (index += 1) { instance.array[index] = true; } index = 71025; while (index <= 71028) : (index += 1) { instance.array[index] = true; } index = 71031; while (index <= 71034) : (index += 1) { instance.array[index] = true; } index = 71035; while (index <= 71036) : (index += 1) { instance.array[index] = true; } instance.array[71037] = true; index = 71063; while (index <= 71066) : (index += 1) { instance.array[index] = true; } index = 71067; while (index <= 71068) : (index += 1) { instance.array[index] = true; } index = 71103; while (index <= 71150) : (index += 1) { instance.array[index] = true; } index = 71151; while (index <= 71153) : (index += 1) { instance.array[index] = true; } index = 71154; while (index <= 71161) : (index += 1) { instance.array[index] = true; } index = 71162; while (index <= 71163) : (index += 1) { instance.array[index] = true; } instance.array[71164] = true; instance.array[71165] = true; instance.array[71167] = true; instance.array[71171] = true; index = 71231; while (index <= 71273) : (index += 1) { instance.array[index] = true; } instance.array[71274] = true; instance.array[71275] = true; instance.array[71276] = true; index = 71277; while (index <= 71278) : (index += 1) { instance.array[index] = true; } index = 71279; while (index <= 71284) : (index += 1) { instance.array[index] = true; } instance.array[71287] = true; index = 71359; while (index <= 71385) : (index += 1) { instance.array[index] = true; } index = 71388; while (index <= 71390) : (index += 1) { instance.array[index] = true; } index = 71391; while (index <= 71392) : (index += 1) { instance.array[index] = true; } index = 71393; while (index <= 71396) : (index += 1) { instance.array[index] = true; } instance.array[71397] = true; index = 71398; while (index <= 71401) : (index += 1) { instance.array[index] = true; } index = 71615; while (index <= 71658) : (index += 1) { instance.array[index] = true; } index = 71659; while (index <= 71661) : (index += 1) { instance.array[index] = true; } index = 71662; while (index <= 71670) : (index += 1) { instance.array[index] = true; } instance.array[71671] = true; index = 71775; while (index <= 71838) : (index += 1) { instance.array[index] = true; } index = 71870; while (index <= 71877) : (index += 1) { instance.array[index] = true; } instance.array[71880] = true; index = 71883; while (index <= 71890) : (index += 1) { instance.array[index] = true; } index = 71892; while (index <= 71893) : (index += 1) { instance.array[index] = true; } index = 71895; while (index <= 71918) : (index += 1) { instance.array[index] = true; } index = 71919; while (index <= 71924) : (index += 1) { instance.array[index] = true; } index = 71926; while (index <= 71927) : (index += 1) { instance.array[index] = true; } index = 71930; while (index <= 71931) : (index += 1) { instance.array[index] = true; } instance.array[71934] = true; instance.array[71935] = true; instance.array[71936] = true; instance.array[71937] = true; index = 72031; while (index <= 72038) : (index += 1) { instance.array[index] = true; } index = 72041; while (index <= 72079) : (index += 1) { instance.array[index] = true; } index = 72080; while (index <= 72082) : (index += 1) { instance.array[index] = true; } index = 72083; while (index <= 72086) : (index += 1) { instance.array[index] = true; } index = 72089; while (index <= 72090) : (index += 1) { instance.array[index] = true; } index = 72091; while (index <= 72094) : (index += 1) { instance.array[index] = true; } instance.array[72096] = true; instance.array[72098] = true; instance.array[72099] = true; instance.array[72127] = true; index = 72128; while (index <= 72137) : (index += 1) { instance.array[index] = true; } index = 72138; while (index <= 72177) : (index += 1) { instance.array[index] = true; } index = 72180; while (index <= 72183) : (index += 1) { instance.array[index] = true; } instance.array[72184] = true; instance.array[72185] = true; index = 72186; while (index <= 72189) : (index += 1) { instance.array[index] = true; } instance.array[72207] = true; index = 72208; while (index <= 72213) : (index += 1) { instance.array[index] = true; } index = 72214; while (index <= 72215) : (index += 1) { instance.array[index] = true; } index = 72216; while (index <= 72218) : (index += 1) { instance.array[index] = true; } index = 72219; while (index <= 72264) : (index += 1) { instance.array[index] = true; } index = 72265; while (index <= 72277) : (index += 1) { instance.array[index] = true; } instance.array[72278] = true; instance.array[72284] = true; index = 72319; while (index <= 72375) : (index += 1) { instance.array[index] = true; } index = 72639; while (index <= 72647) : (index += 1) { instance.array[index] = true; } index = 72649; while (index <= 72685) : (index += 1) { instance.array[index] = true; } instance.array[72686] = true; index = 72687; while (index <= 72693) : (index += 1) { instance.array[index] = true; } index = 72695; while (index <= 72700) : (index += 1) { instance.array[index] = true; } instance.array[72701] = true; instance.array[72703] = true; index = 72753; while (index <= 72782) : (index += 1) { instance.array[index] = true; } index = 72785; while (index <= 72806) : (index += 1) { instance.array[index] = true; } instance.array[72808] = true; index = 72809; while (index <= 72815) : (index += 1) { instance.array[index] = true; } instance.array[72816] = true; index = 72817; while (index <= 72818) : (index += 1) { instance.array[index] = true; } instance.array[72819] = true; index = 72820; while (index <= 72821) : (index += 1) { instance.array[index] = true; } index = 72895; while (index <= 72901) : (index += 1) { instance.array[index] = true; } index = 72903; while (index <= 72904) : (index += 1) { instance.array[index] = true; } index = 72906; while (index <= 72943) : (index += 1) { instance.array[index] = true; } index = 72944; while (index <= 72949) : (index += 1) { instance.array[index] = true; } instance.array[72953] = true; index = 72955; while (index <= 72956) : (index += 1) { instance.array[index] = true; } index = 72958; while (index <= 72960) : (index += 1) { instance.array[index] = true; } instance.array[72962] = true; instance.array[72965] = true; instance.array[72966] = true; index = 72991; while (index <= 72996) : (index += 1) { instance.array[index] = true; } index = 72998; while (index <= 72999) : (index += 1) { instance.array[index] = true; } index = 73001; while (index <= 73032) : (index += 1) { instance.array[index] = true; } index = 73033; while (index <= 73037) : (index += 1) { instance.array[index] = true; } index = 73039; while (index <= 73040) : (index += 1) { instance.array[index] = true; } index = 73042; while (index <= 73043) : (index += 1) { instance.array[index] = true; } instance.array[73044] = true; instance.array[73045] = true; instance.array[73047] = true; index = 73375; while (index <= 73393) : (index += 1) { instance.array[index] = true; } index = 73394; while (index <= 73395) : (index += 1) { instance.array[index] = true; } index = 73396; while (index <= 73397) : (index += 1) { instance.array[index] = true; } instance.array[73583] = true; index = 73663; while (index <= 74584) : (index += 1) { instance.array[index] = true; } index = 74687; while (index <= 74797) : (index += 1) { instance.array[index] = true; } index = 74815; while (index <= 75010) : (index += 1) { instance.array[index] = true; } index = 77759; while (index <= 78829) : (index += 1) { instance.array[index] = true; } index = 82879; while (index <= 83461) : (index += 1) { instance.array[index] = true; } index = 92095; while (index <= 92663) : (index += 1) { instance.array[index] = true; } index = 92671; while (index <= 92701) : (index += 1) { instance.array[index] = true; } index = 92815; while (index <= 92844) : (index += 1) { instance.array[index] = true; } index = 92863; while (index <= 92910) : (index += 1) { instance.array[index] = true; } index = 92927; while (index <= 92930) : (index += 1) { instance.array[index] = true; } index = 92962; while (index <= 92982) : (index += 1) { instance.array[index] = true; } index = 92988; while (index <= 93006) : (index += 1) { instance.array[index] = true; } index = 93695; while (index <= 93758) : (index += 1) { instance.array[index] = true; } index = 93887; while (index <= 93961) : (index += 1) { instance.array[index] = true; } instance.array[93966] = true; instance.array[93967] = true; index = 93968; while (index <= 94022) : (index += 1) { instance.array[index] = true; } index = 94030; while (index <= 94033) : (index += 1) { instance.array[index] = true; } index = 94034; while (index <= 94046) : (index += 1) { instance.array[index] = true; } index = 94111; while (index <= 94112) : (index += 1) { instance.array[index] = true; } instance.array[94114] = true; index = 94127; while (index <= 94128) : (index += 1) { instance.array[index] = true; } index = 94143; while (index <= 100278) : (index += 1) { instance.array[index] = true; } index = 100287; while (index <= 101524) : (index += 1) { instance.array[index] = true; } index = 101567; while (index <= 101575) : (index += 1) { instance.array[index] = true; } index = 110527; while (index <= 110813) : (index += 1) { instance.array[index] = true; } index = 110863; while (index <= 110865) : (index += 1) { instance.array[index] = true; } index = 110883; while (index <= 110886) : (index += 1) { instance.array[index] = true; } index = 110895; while (index <= 111290) : (index += 1) { instance.array[index] = true; } index = 113599; while (index <= 113705) : (index += 1) { instance.array[index] = true; } index = 113711; while (index <= 113723) : (index += 1) { instance.array[index] = true; } index = 113727; while (index <= 113735) : (index += 1) { instance.array[index] = true; } index = 113743; while (index <= 113752) : (index += 1) { instance.array[index] = true; } instance.array[113757] = true; index = 119743; while (index <= 119827) : (index += 1) { instance.array[index] = true; } index = 119829; while (index <= 119899) : (index += 1) { instance.array[index] = true; } index = 119901; while (index <= 119902) : (index += 1) { instance.array[index] = true; } instance.array[119905] = true; index = 119908; while (index <= 119909) : (index += 1) { instance.array[index] = true; } index = 119912; while (index <= 119915) : (index += 1) { instance.array[index] = true; } index = 119917; while (index <= 119928) : (index += 1) { instance.array[index] = true; } instance.array[119930] = true; index = 119932; while (index <= 119938) : (index += 1) { instance.array[index] = true; } index = 119940; while (index <= 120004) : (index += 1) { instance.array[index] = true; } index = 120006; while (index <= 120009) : (index += 1) { instance.array[index] = true; } index = 120012; while (index <= 120019) : (index += 1) { instance.array[index] = true; } index = 120021; while (index <= 120027) : (index += 1) { instance.array[index] = true; } index = 120029; while (index <= 120056) : (index += 1) { instance.array[index] = true; } index = 120058; while (index <= 120061) : (index += 1) { instance.array[index] = true; } index = 120063; while (index <= 120067) : (index += 1) { instance.array[index] = true; } instance.array[120069] = true; index = 120073; while (index <= 120079) : (index += 1) { instance.array[index] = true; } index = 120081; while (index <= 120420) : (index += 1) { instance.array[index] = true; } index = 120423; while (index <= 120447) : (index += 1) { instance.array[index] = true; } index = 120449; while (index <= 120473) : (index += 1) { instance.array[index] = true; } index = 120475; while (index <= 120505) : (index += 1) { instance.array[index] = true; } index = 120507; while (index <= 120531) : (index += 1) { instance.array[index] = true; } index = 120533; while (index <= 120563) : (index += 1) { instance.array[index] = true; } index = 120565; while (index <= 120589) : (index += 1) { instance.array[index] = true; } index = 120591; while (index <= 120621) : (index += 1) { instance.array[index] = true; } index = 120623; while (index <= 120647) : (index += 1) { instance.array[index] = true; } index = 120649; while (index <= 120679) : (index += 1) { instance.array[index] = true; } index = 120681; while (index <= 120705) : (index += 1) { instance.array[index] = true; } index = 120707; while (index <= 120714) : (index += 1) { instance.array[index] = true; } index = 122815; while (index <= 122821) : (index += 1) { instance.array[index] = true; } index = 122823; while (index <= 122839) : (index += 1) { instance.array[index] = true; } index = 122842; while (index <= 122848) : (index += 1) { instance.array[index] = true; } index = 122850; while (index <= 122851) : (index += 1) { instance.array[index] = true; } index = 122853; while (index <= 122857) : (index += 1) { instance.array[index] = true; } index = 123071; while (index <= 123115) : (index += 1) { instance.array[index] = true; } index = 123126; while (index <= 123132) : (index += 1) { instance.array[index] = true; } instance.array[123149] = true; index = 123519; while (index <= 123562) : (index += 1) { instance.array[index] = true; } index = 124863; while (index <= 125059) : (index += 1) { instance.array[index] = true; } index = 125119; while (index <= 125186) : (index += 1) { instance.array[index] = true; } instance.array[125190] = true; instance.array[125194] = true; index = 126399; while (index <= 126402) : (index += 1) { instance.array[index] = true; } index = 126404; while (index <= 126430) : (index += 1) { instance.array[index] = true; } index = 126432; while (index <= 126433) : (index += 1) { instance.array[index] = true; } instance.array[126435] = true; instance.array[126438] = true; index = 126440; while (index <= 126449) : (index += 1) { instance.array[index] = true; } index = 126451; while (index <= 126454) : (index += 1) { instance.array[index] = true; } instance.array[126456] = true; instance.array[126458] = true; instance.array[126465] = true; instance.array[126470] = true; instance.array[126472] = true; instance.array[126474] = true; index = 126476; while (index <= 126478) : (index += 1) { instance.array[index] = true; } index = 126480; while (index <= 126481) : (index += 1) { instance.array[index] = true; } instance.array[126483] = true; instance.array[126486] = true; instance.array[126488] = true; instance.array[126490] = true; instance.array[126492] = true; instance.array[126494] = true; index = 126496; while (index <= 126497) : (index += 1) { instance.array[index] = true; } instance.array[126499] = true; index = 126502; while (index <= 126505) : (index += 1) { instance.array[index] = true; } index = 126507; while (index <= 126513) : (index += 1) { instance.array[index] = true; } index = 126515; while (index <= 126518) : (index += 1) { instance.array[index] = true; } index = 126520; while (index <= 126523) : (index += 1) { instance.array[index] = true; } instance.array[126525] = true; index = 126527; while (index <= 126536) : (index += 1) { instance.array[index] = true; } index = 126538; while (index <= 126554) : (index += 1) { instance.array[index] = true; } index = 126560; while (index <= 126562) : (index += 1) { instance.array[index] = true; } index = 126564; while (index <= 126568) : (index += 1) { instance.array[index] = true; } index = 126570; while (index <= 126586) : (index += 1) { instance.array[index] = true; } index = 127215; while (index <= 127240) : (index += 1) { instance.array[index] = true; } index = 127247; while (index <= 127272) : (index += 1) { instance.array[index] = true; } index = 127279; while (index <= 127304) : (index += 1) { instance.array[index] = true; } index = 131007; while (index <= 173724) : (index += 1) { instance.array[index] = true; } index = 173759; while (index <= 177907) : (index += 1) { instance.array[index] = true; } index = 177919; while (index <= 178140) : (index += 1) { instance.array[index] = true; } index = 178143; while (index <= 183904) : (index += 1) { instance.array[index] = true; } index = 183919; while (index <= 191391) : (index += 1) { instance.array[index] = true; } index = 194495; while (index <= 195036) : (index += 1) { instance.array[index] = true; } index = 196543; while (index <= 201481) : (index += 1) { instance.array[index] = true; } // Placeholder: 0. Struct name, 1. Code point kind return instance; } pub fn deinit(self: *Alphabetic) void { self.allocator.free(self.array); } // isAlphabetic checks if cp is of the kind Alphabetic. pub fn isAlphabetic(self: Alphabetic, 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/Alphabetic.zig
const std = @import("std"); const debug = std.debug; const io = std.io; const mem = std.mem; const testing = std.testing; pub const args = @import("clap/args.zig"); test "clap" { testing.refAllDecls(@This()); } pub const ComptimeClap = @import("clap/comptime.zig").ComptimeClap; pub const StreamingClap = @import("clap/streaming.zig").StreamingClap; /// The names a ::Param can have. pub const Names = struct { /// '-' prefix short: ?u8 = null, /// '--' prefix long: ?[]const u8 = null, }; /// Whether a param takes no value (a flag), one value, or can be specified multiple times. pub const Values = enum { None, One, Many, }; /// Represents a parameter for the command line. /// Parameters come in three kinds: /// * Short ("-a"): Should be used for the most commonly used parameters in your program. /// * They can take a value three different ways. /// * "-a value" /// * "-a=value" /// * "-avalue" /// * They chain if they don't take values: "-abc". /// * The last given parameter can take a value in the same way that a single parameter can: /// * "-abc value" /// * "-abc=value" /// * "-abcvalue" /// * Long ("--long-param"): Should be used for less common parameters, or when no single character /// can describe the paramter. /// * They can take a value two different ways. /// * "--long-param value" /// * "--long-param=value" /// * Positional: Should be used as the primary parameter of the program, like a filename or /// an expression to parse. /// * Positional parameters have both names.long and names.short == null. /// * Positional parameters must take a value. pub fn Param(comptime Id: type) type { return struct { id: Id = Id{}, names: Names = Names{}, takes_value: Values = .None, }; } /// Takes a string and parses it to a Param(Help). /// This is the reverse of 'help' but for at single parameter only. pub fn parseParam(line: []const u8) !Param(Help) { var found_comma = false; var it = mem.tokenize(line, " \t"); var param_str = it.next() orelse return error.NoParamFound; const short_name = if (!mem.startsWith(u8, param_str, "--") and mem.startsWith(u8, param_str, "-")) blk: { found_comma = param_str[param_str.len - 1] == ','; if (found_comma) param_str = param_str[0 .. param_str.len - 1]; if (param_str.len != 2) return error.InvalidShortParam; const short_name = param_str[1]; if (!found_comma) { var res = parseParamRest(it.rest()); res.names.short = short_name; return res; } param_str = it.next() orelse return error.NoParamFound; break :blk short_name; } else null; const long_name = if (mem.startsWith(u8, param_str, "--")) blk: { if (param_str[param_str.len - 1] == ',') return error.TrailingComma; break :blk param_str[2..]; } else if (found_comma) { return error.TrailingComma; } else if (short_name == null) { return parseParamRest(mem.trimLeft(u8, line, " \t")); } else null; var res = parseParamRest(it.rest()); res.names.long = param_str[2..]; res.names.short = short_name; return res; } fn parseParamRest(line: []const u8) Param(Help) { if (mem.startsWith(u8, line, "<")) blk: { const len = mem.indexOfScalar(u8, line, '>') orelse break :blk; const takes_many = mem.startsWith(u8, line[len + 1 ..], "..."); const help_start = len + 1 + @as(usize, 3) * @boolToInt(takes_many); return Param(Help){ .takes_value = if (takes_many) .Many else .One, .id = .{ .msg = mem.trim(u8, line[help_start..], " \t"), .value = line[1..len], }, }; } return Param(Help){ .id = .{ .msg = mem.trim(u8, line, " \t") } }; } fn expectParam(expect: Param(Help), actual: Param(Help)) void { testing.expectEqualStrings(expect.id.msg, actual.id.msg); testing.expectEqualStrings(expect.id.value, actual.id.value); testing.expectEqual(expect.names.short, actual.names.short); testing.expectEqual(expect.takes_value, actual.takes_value); if (expect.names.long) |long| { testing.expectEqualStrings(long, actual.names.long.?); } else { testing.expectEqual(@as(?[]const u8, null), actual.names.long); } } test "parseParam" { expectParam(Param(Help){ .id = Help{ .msg = "Help text", .value = "value", }, .names = Names{ .short = 's', .long = "long", }, .takes_value = .One, }, try parseParam("-s, --long <value> Help text")); expectParam(Param(Help){ .id = Help{ .msg = "Help text", .value = "value", }, .names = Names{ .short = 's', .long = "long", }, .takes_value = .Many, }, try parseParam("-s, --long <value>... Help text")); expectParam(Param(Help){ .id = Help{ .msg = "Help text", .value = "value", }, .names = Names{ .short = null, .long = "long", }, .takes_value = .One, }, try parseParam("--long <value> Help text")); expectParam(Param(Help){ .id = Help{ .msg = "Help text", .value = "value", }, .names = Names{ .short = 's', .long = null, }, .takes_value = .One, }, try parseParam("-s <value> Help text")); expectParam(Param(Help){ .id = Help{ .msg = "Help text", .value = "", }, .names = Names{ .short = 's', .long = "long", }, .takes_value = .None, }, try parseParam("-s, --long Help text")); expectParam(Param(Help){ .id = Help{ .msg = "Help text", .value = "", }, .names = Names{ .short = 's', .long = null, }, .takes_value = .None, }, try parseParam("-s Help text")); expectParam(Param(Help){ .id = Help{ .msg = "Help text", .value = "", }, .names = Names{ .short = null, .long = "long", }, .takes_value = .None, }, try parseParam("--long Help text")); expectParam(Param(Help){ .id = Help{ .msg = "Help text", .value = "A | B", }, .names = Names{ .short = null, .long = "long", }, .takes_value = .One, }, try parseParam("--long <A | B> Help text")); expectParam(Param(Help){ .id = Help{ .msg = "Help text", .value = "A", }, .names = Names{ .short = null, .long = null, }, .takes_value = .One, }, try parseParam("<A> Help text")); expectParam(Param(Help){ .id = Help{ .msg = "Help text", .value = "A", }, .names = Names{ .short = null, .long = null, }, .takes_value = .Many, }, try parseParam("<A>... Help text")); testing.expectError(error.TrailingComma, parseParam("--long, Help")); testing.expectError(error.TrailingComma, parseParam("-s, Help")); testing.expectError(error.InvalidShortParam, parseParam("-ss Help")); testing.expectError(error.InvalidShortParam, parseParam("-ss <value> Help")); testing.expectError(error.InvalidShortParam, parseParam("- Help")); } /// Optional diagnostics used for reporting useful errors pub const Diagnostic = struct { arg: []const u8 = "", name: Names = Names{}, /// Default diagnostics reporter when all you want is English with no colors. /// Use this as a reference for implementing your own if needed. pub fn report(diag: Diagnostic, stream: anytype, err: anyerror) !void { const Arg = struct { prefix: []const u8, name: []const u8, }; const a = if (diag.name.short) |*c| Arg{ .prefix = "-", .name = @as(*const [1]u8, c)[0..] } else if (diag.name.long) |l| Arg{ .prefix = "--", .name = l } else Arg{ .prefix = "", .name = diag.arg }; switch (err) { error.DoesntTakeValue => try stream.print("The argument '{}{}' does not take a value\n", .{ a.prefix, a.name }), error.MissingValue => try stream.print("The argument '{}{}' requires a value but none was supplied\n", .{ a.prefix, a.name }), error.InvalidArgument => try stream.print("Invalid argument '{}{}'\n", .{ a.prefix, a.name }), else => try stream.print("Error while parsing arguments: {}\n", .{@errorName(err)}), } } }; fn testDiag(diag: Diagnostic, err: anyerror, expected: []const u8) void { var buf: [1024]u8 = undefined; var slice_stream = io.fixedBufferStream(&buf); diag.report(slice_stream.outStream(), err) catch unreachable; testing.expectEqualStrings(expected, slice_stream.getWritten()); } test "Diagnostic.report" { testDiag(.{ .arg = "c" }, error.InvalidArgument, "Invalid argument 'c'\n"); testDiag(.{ .name = .{ .long = "cc" } }, error.InvalidArgument, "Invalid argument '--cc'\n"); testDiag(.{ .name = .{ .short = 'c' } }, error.DoesntTakeValue, "The argument '-c' does not take a value\n"); testDiag(.{ .name = .{ .long = "cc" } }, error.DoesntTakeValue, "The argument '--cc' does not take a value\n"); testDiag(.{ .name = .{ .short = 'c' } }, error.MissingValue, "The argument '-c' requires a value but none was supplied\n"); testDiag(.{ .name = .{ .long = "cc" } }, error.MissingValue, "The argument '--cc' requires a value but none was supplied\n"); testDiag(.{ .name = .{ .short = 'c' } }, error.InvalidArgument, "Invalid argument '-c'\n"); testDiag(.{ .name = .{ .long = "cc" } }, error.InvalidArgument, "Invalid argument '--cc'\n"); testDiag(.{ .name = .{ .short = 'c' } }, error.SomethingElse, "Error while parsing arguments: SomethingElse\n"); testDiag(.{ .name = .{ .long = "cc" } }, error.SomethingElse, "Error while parsing arguments: SomethingElse\n"); } pub fn Args(comptime Id: type, comptime params: []const Param(Id)) type { return struct { arena: std.heap.ArenaAllocator, clap: ComptimeClap(Id, params), exe_arg: ?[]const u8, pub fn deinit(a: *@This()) void { a.clap.deinit(); a.arena.deinit(); } pub fn flag(a: @This(), comptime name: []const u8) bool { return a.clap.flag(name); } pub fn option(a: @This(), comptime name: []const u8) ?[]const u8 { return a.clap.option(name); } pub fn options(a: @This(), comptime name: []const u8) []const []const u8 { return a.clap.options(name); } pub fn positionals(a: @This()) []const []const u8 { return a.clap.positionals(); } }; } /// Same as `parseEx` but uses the `args.OsIterator` by default. pub fn parse( comptime Id: type, comptime params: []const Param(Id), allocator: *mem.Allocator, diag: ?*Diagnostic, ) !Args(Id, params) { var iter = try args.OsIterator.init(allocator); const clap = try parseEx(Id, params, allocator, &iter, diag); return Args(Id, params){ .arena = iter.arena, .clap = clap, .exe_arg = iter.exe_arg, }; } /// Parses the command line arguments passed into the program based on an /// array of `Param`s. pub fn parseEx( comptime Id: type, comptime params: []const Param(Id), allocator: *mem.Allocator, iter: anytype, diag: ?*Diagnostic, ) !ComptimeClap(Id, params) { const Clap = ComptimeClap(Id, params); return try Clap.parse(allocator, iter, diag); } /// Will print a help message in the following format: /// -s, --long <valueText> helpText /// -s, helpText /// -s <valueText> helpText /// --long helpText /// --long <valueText> helpText pub fn helpFull( stream: anytype, comptime Id: type, params: []const Param(Id), comptime Error: type, context: anytype, helpText: fn (@TypeOf(context), Param(Id)) Error![]const u8, valueText: fn (@TypeOf(context), Param(Id)) Error![]const u8, ) !void { const max_spacing = blk: { var res: usize = 0; for (params) |param| { var counting_stream = io.countingOutStream(io.null_out_stream); try printParam(counting_stream.outStream(), Id, param, Error, context, valueText); if (res < counting_stream.bytes_written) res = @intCast(usize, counting_stream.bytes_written); } break :blk res; }; for (params) |param| { if (param.names.short == null and param.names.long == null) continue; var counting_stream = io.countingOutStream(stream); try stream.print("\t", .{}); try printParam(counting_stream.outStream(), Id, param, Error, context, valueText); try stream.writeByteNTimes(' ', max_spacing - @intCast(usize, counting_stream.bytes_written)); try stream.print("\t{}\n", .{try helpText(context, param)}); } } fn printParam( stream: anytype, comptime Id: type, param: Param(Id), comptime Error: type, context: anytype, valueText: fn (@TypeOf(context), Param(Id)) Error![]const u8, ) !void { if (param.names.short) |s| { try stream.print("-{c}", .{s}); } else { try stream.print(" ", .{}); } if (param.names.long) |l| { if (param.names.short) |_| { try stream.print(", ", .{}); } else { try stream.print(" ", .{}); } try stream.print("--{}", .{l}); } switch (param.takes_value) { .None => {}, .One => try stream.print(" <{}>", .{valueText(context, param)}), .Many => try stream.print(" <{}>...", .{valueText(context, param)}), } } /// A wrapper around helpFull for simple helpText and valueText functions that /// cant return an error or take a context. pub fn helpEx( stream: anytype, comptime Id: type, params: []const Param(Id), helpText: fn (Param(Id)) []const u8, valueText: fn (Param(Id)) []const u8, ) !void { const Context = struct { helpText: fn (Param(Id)) []const u8, valueText: fn (Param(Id)) []const u8, pub fn help(c: @This(), p: Param(Id)) error{}![]const u8 { return c.helpText(p); } pub fn value(c: @This(), p: Param(Id)) error{}![]const u8 { return c.valueText(p); } }; return helpFull( stream, Id, params, error{}, Context{ .helpText = helpText, .valueText = valueText, }, Context.help, Context.value, ); } pub const Help = struct { msg: []const u8 = "", value: []const u8 = "", }; /// A wrapper around helpEx that takes a Param(Help). pub fn help(stream: anytype, params: []const Param(Help)) !void { try helpEx(stream, Help, params, getHelpSimple, getValueSimple); } fn getHelpSimple(param: Param(Help)) []const u8 { return param.id.msg; } fn getValueSimple(param: Param(Help)) []const u8 { return param.id.value; } test "clap.help" { var buf: [1024]u8 = undefined; var slice_stream = io.fixedBufferStream(&buf); @setEvalBranchQuota(10000); try help( slice_stream.outStream(), comptime &[_]Param(Help){ parseParam("-a Short flag. ") catch unreachable, parseParam("-b <V1> Short option.") catch unreachable, parseParam("--aa Long flag. ") catch unreachable, parseParam("--bb <V2> Long option. ") catch unreachable, parseParam("-c, --cc Both flag. ") catch unreachable, parseParam("-d, --dd <V3> Both option. ") catch unreachable, parseParam("-d, --dd <V3>... Both repeated option. ") catch unreachable, Param(Help){ .id = Help{ .msg = "Positional. This should not appear in the help message.", }, .takes_value = .One, }, }, ); const expected = "" ++ "\t-a \tShort flag.\n" ++ "\t-b <V1> \tShort option.\n" ++ "\t --aa \tLong flag.\n" ++ "\t --bb <V2> \tLong option.\n" ++ "\t-c, --cc \tBoth flag.\n" ++ "\t-d, --dd <V3> \tBoth option.\n" ++ "\t-d, --dd <V3>...\tBoth repeated option.\n"; testing.expectEqualStrings(expected, slice_stream.getWritten()); } /// Will print a usage message in the following format: /// [-abc] [--longa] [-d <valueText>] [--longb <valueText>] <valueText> /// /// First all none value taking parameters, which have a short name are /// printed, then non positional parameters and finally the positinal. pub fn usageFull( stream: anytype, comptime Id: type, params: []const Param(Id), comptime Error: type, context: anytype, valueText: fn (@TypeOf(context), Param(Id)) Error![]const u8, ) !void { var cos = io.countingOutStream(stream); const cs = cos.outStream(); for (params) |param| { const name = param.names.short orelse continue; if (param.takes_value != .None) continue; if (cos.bytes_written == 0) try stream.writeAll("[-"); try cs.writeByte(name); } if (cos.bytes_written != 0) try cs.writeByte(']'); var positional: ?Param(Id) = null; for (params) |param| { if (param.takes_value == .None and param.names.short != null) continue; const prefix = if (param.names.short) |_| "-" else "--"; // Seems the zig compiler is being a little wierd. I doesn't allow me to write // @as(*const [1]u8, s) VVVVVVVVVVVVVVVVVVVVVVVVVVVVVV const name = if (param.names.short) |*s| @ptrCast([*]const u8, s)[0..1] else param.names.long orelse { positional = param; continue; }; if (cos.bytes_written != 0) try cs.writeByte(' '); try cs.print("[{}{}", .{ prefix, name }); switch (param.takes_value) { .None => {}, .One => try cs.print(" <{}>", .{try valueText(context, param)}), .Many => try cs.print(" <{}>...", .{try valueText(context, param)}), } try cs.writeByte(']'); } if (positional) |p| { if (cos.bytes_written != 0) try cs.writeByte(' '); try cs.print("<{}>", .{try valueText(context, p)}); } } /// A wrapper around usageFull for a simple valueText functions that /// cant return an error or take a context. pub fn usageEx( stream: anytype, comptime Id: type, params: []const Param(Id), valueText: fn (Param(Id)) []const u8, ) !void { const Context = struct { valueText: fn (Param(Id)) []const u8, pub fn value(c: @This(), p: Param(Id)) error{}![]const u8 { return c.valueText(p); } }; return usageFull( stream, Id, params, error{}, Context{ .valueText = valueText }, Context.value, ); } /// A wrapper around usageEx that takes a Param(Help). pub fn usage(stream: anytype, params: []const Param(Help)) !void { try usageEx(stream, Help, params, getValueSimple); } fn testUsage(expected: []const u8, params: []const Param(Help)) !void { var buf: [1024]u8 = undefined; var fbs = io.fixedBufferStream(&buf); try usage(fbs.outStream(), params); testing.expectEqualStrings(expected, fbs.getWritten()); } test "usage" { @setEvalBranchQuota(100000); try testUsage("[-ab]", comptime &[_]Param(Help){ parseParam("-a") catch unreachable, parseParam("-b") catch unreachable, }); try testUsage("[-a <value>] [-b <v>]", comptime &[_]Param(Help){ parseParam("-a <value>") catch unreachable, parseParam("-b <v>") catch unreachable, }); try testUsage("[--a] [--b]", comptime &[_]Param(Help){ parseParam("--a") catch unreachable, parseParam("--b") catch unreachable, }); try testUsage("[--a <value>] [--b <v>]", comptime &[_]Param(Help){ parseParam("--a <value>") catch unreachable, parseParam("--b <v>") catch unreachable, }); try testUsage("<file>", comptime &[_]Param(Help){ Param(Help){ .id = Help{ .value = "file", }, .takes_value = .One, }, }); try testUsage("[-ab] [-c <value>] [-d <v>] [--e] [--f] [--g <value>] [--h <v>] [-i <v>...] <file>", comptime &[_]Param(Help){ parseParam("-a") catch unreachable, parseParam("-b") catch unreachable, parseParam("-c <value>") catch unreachable, parseParam("-d <v>") catch unreachable, parseParam("--e") catch unreachable, parseParam("--f") catch unreachable, parseParam("--g <value>") catch unreachable, parseParam("--h <v>") catch unreachable, parseParam("-i <v>...") catch unreachable, Param(Help){ .id = Help{ .value = "file", }, .takes_value = .One, }, }); }
clap.zig
const std = @import("std"); const Context = @import("context.zig").Context; const SourceRange = @import("context.zig").SourceRange; const fail = @import("fail.zig").fail; const Token = @import("tokenize.zig").Token; const NumberLiteral = @import("parse.zig").NumberLiteral; const ParsedModuleInfo = @import("parse.zig").ParsedModuleInfo; const ParseResult = @import("parse.zig").ParseResult; const Global = @import("parse.zig").Global; const Curve = @import("parse.zig").Curve; const Track = @import("parse.zig").Track; const Module = @import("parse.zig").Module; const ModuleParam = @import("parse.zig").ModuleParam; const ParamType = @import("parse.zig").ParamType; const Call = @import("parse.zig").Call; const CallArg = @import("parse.zig").CallArg; const UnArithOp = @import("parse.zig").UnArithOp; const BinArithOp = @import("parse.zig").BinArithOp; const TrackCall = @import("parse.zig").TrackCall; const Delay = @import("parse.zig").Delay; const Local = @import("parse.zig").Local; const Expression = @import("parse.zig").Expression; const Statement = @import("parse.zig").Statement; const BuiltinEnumValue = @import("builtins.zig").BuiltinEnumValue; const printBytecode = @import("codegen_print.zig").printBytecode; pub const TempRef = struct { index: usize, // temp index is_weak: bool, // if true, someone else owns the temp, so don't release it fn strong(index: usize) TempRef { return .{ .index = index, .is_weak = false }; } fn weak(index: usize) TempRef { return .{ .index = index, .is_weak = true }; } }; // expression will return how it stored its result. // caller needs to make sure to release it (by calling releaseExpressionResult), which will release any temps that were being used. pub const ExpressionResult = union(enum) { nothing, // this means the result was already written into a result location temp_buffer: TempRef, temp_float: TempRef, literal_boolean: bool, literal_number: NumberLiteral, literal_enum_value: struct { label: []const u8, payload: ?*const ExpressionResult }, literal_curve: usize, literal_track: usize, literal_module: usize, self_param: usize, track_param: struct { track_index: usize, param_index: usize }, }; pub const FloatDest = struct { temp_float_index: usize, }; pub const BufferDest = union(enum) { temp_buffer_index: usize, output_index: usize, }; pub const InstrCopyBuffer = struct { out: BufferDest, in: ExpressionResult }; pub const InstrFloatToBuffer = struct { out: BufferDest, in: ExpressionResult }; pub const InstrCobToBuffer = struct { out: BufferDest, in_self_param: usize }; pub const InstrArithFloat = struct { out: FloatDest, op: UnArithOp, a: ExpressionResult }; pub const InstrArithBuffer = struct { out: BufferDest, op: UnArithOp, a: ExpressionResult }; pub const InstrArithFloatFloat = struct { out: FloatDest, op: BinArithOp, a: ExpressionResult, b: ExpressionResult }; pub const InstrArithFloatBuffer = struct { out: BufferDest, op: BinArithOp, a: ExpressionResult, b: ExpressionResult }; pub const InstrArithBufferFloat = struct { out: BufferDest, op: BinArithOp, a: ExpressionResult, b: ExpressionResult }; pub const InstrArithBufferBuffer = struct { out: BufferDest, op: BinArithOp, a: ExpressionResult, b: ExpressionResult }; pub const InstrCall = struct { // paint always results in a buffer. out: BufferDest, // which field of the "self" module we are calling field_index: usize, // list of temp buffers passed along for the callee's internal use temps: []const usize, // list of argument param values (in the order of the callee module's params) args: []const ExpressionResult, }; pub const InstrTrackCall = struct { out: BufferDest, track_index: usize, speed: ExpressionResult, trigger_index: usize, note_tracker_index: usize, instructions: []const Instruction, }; pub const InstrDelay = struct { delay_index: usize, out: BufferDest, feedback_out_temp_buffer_index: usize, feedback_temp_buffer_index: usize, instructions: []const Instruction, }; pub const Instruction = union(enum) { copy_buffer: InstrCopyBuffer, float_to_buffer: InstrFloatToBuffer, cob_to_buffer: InstrCobToBuffer, arith_float: InstrArithFloat, arith_buffer: InstrArithBuffer, arith_float_float: InstrArithFloatFloat, arith_float_buffer: InstrArithFloatBuffer, arith_buffer_float: InstrArithBufferFloat, arith_buffer_buffer: InstrArithBufferBuffer, call: InstrCall, track_call: InstrTrackCall, delay: InstrDelay, }; pub const Field = struct { module_index: usize, }; pub const DelayDecl = struct { num_samples: usize, }; pub const TriggerDecl = struct { track_index: usize, }; pub const NoteTrackerDecl = struct { track_index: usize, }; pub const CurrentDelay = struct { feedback_temp_index: usize, instructions: std.ArrayList(Instruction), }; pub const CurrentTrackCall = struct { track_index: usize, instructions: std.ArrayList(Instruction), }; pub const CodegenState = struct { arena_allocator: *std.mem.Allocator, inner_allocator: *std.mem.Allocator, ctx: Context, globals: []const Global, curves: []const Curve, tracks: []const Track, modules: []const Module, global_results: []?ExpressionResult, global_visited: []bool, track_results: []?CodeGenTrackResult, module_results: []?CodeGenModuleResult, dump_codegen_out: ?std.io.StreamSource.OutStream, }; pub const CodegenModuleState = struct { module_index: usize, locals: []const Local, instructions: std.ArrayList(Instruction), temp_buffers: TempManager, temp_floats: TempManager, local_results: []?ExpressionResult, fields: std.ArrayList(Field), delays: std.ArrayList(DelayDecl), triggers: std.ArrayList(TriggerDecl), note_trackers: std.ArrayList(NoteTrackerDecl), // only one of these can be set at a time, for now (i'll improve it later) current_delay: ?*CurrentDelay, current_track_call: ?*CurrentTrackCall, }; const CodegenContext = union(enum) { global, module: *CodegenModuleState, }; const TempManager = struct { reuse_slots: bool, slot_claimed: std.ArrayList(bool), fn init(allocator: *std.mem.Allocator, reuse_slots: bool) TempManager { return .{ .reuse_slots = reuse_slots, .slot_claimed = std.ArrayList(bool).init(allocator), }; } fn deinit(self: *TempManager) void { self.slot_claimed.deinit(); } fn reportLeaks(self: *const TempManager) void { // if we're cleaning up because an error occurred, don't complain // about leaks. i don't care about releasing every temp in an // error situation. var num_leaked: usize = 0; for (self.slot_claimed.items) |in_use| { if (in_use) num_leaked += 1; } if (num_leaked > 0) { std.debug.warn("error - {} temp(s) leaked in codegen\n", .{num_leaked}); } } fn claim(self: *TempManager) !usize { if (self.reuse_slots) { for (self.slot_claimed.items) |*in_use, index| { if (in_use.*) continue; in_use.* = true; return index; } } const index = self.slot_claimed.items.len; try self.slot_claimed.append(true); return index; } fn release(self: *TempManager, index: usize) void { std.debug.assert(self.slot_claimed.items[index]); self.slot_claimed.items[index] = false; } pub fn finalCount(self: *const TempManager) usize { return self.slot_claimed.items.len; } }; fn releaseExpressionResult(cms: *CodegenModuleState, result: ExpressionResult) void { switch (result) { .temp_buffer => |temp_ref| { if (!temp_ref.is_weak) cms.temp_buffers.release(temp_ref.index); }, .temp_float => |temp_ref| { if (!temp_ref.is_weak) cms.temp_floats.release(temp_ref.index); }, .literal_enum_value => |literal| { if (literal.payload) |payload| { releaseExpressionResult(cms, payload.*); } }, else => {}, } } fn isResultBoolean(cs: *const CodegenState, cc: CodegenContext, result: ExpressionResult) bool { return switch (result) { .nothing => unreachable, .literal_boolean => true, .self_param => |param_index| switch (cc) { .global => unreachable, .module => |cms| cs.modules[cms.module_index].params[param_index].param_type == .boolean, }, .track_param => |x| switch (cc) { .global => unreachable, .module => |cms| cs.tracks[x.track_index].params[x.param_index].param_type == .boolean, }, .literal_number, .literal_enum_value, .literal_curve, .literal_track, .literal_module, .temp_buffer, .temp_float => false, }; } fn isResultFloat(cs: *const CodegenState, cc: CodegenContext, result: ExpressionResult) bool { return switch (result) { .nothing => unreachable, .temp_float, .literal_number => true, .self_param => |param_index| switch (cc) { .global => unreachable, .module => |cms| cs.modules[cms.module_index].params[param_index].param_type == .constant, }, .track_param => |x| switch (cc) { .global => unreachable, .module => |cms| cs.tracks[x.track_index].params[x.param_index].param_type == .constant, }, .literal_boolean, .literal_enum_value, .literal_curve, .literal_track, .literal_module, .temp_buffer => false, }; } fn isResultBuffer(cs: *const CodegenState, cc: CodegenContext, result: ExpressionResult) bool { return switch (result) { .nothing => unreachable, .temp_buffer => true, .self_param => |param_index| switch (cc) { .global => unreachable, .module => |cms| cs.modules[cms.module_index].params[param_index].param_type == .buffer, }, .track_param => |x| switch (cc) { .global => unreachable, .module => |cms| cs.tracks[x.track_index].params[x.param_index].param_type == .buffer, }, .temp_float, .literal_boolean, .literal_number, .literal_enum_value, .literal_curve, .literal_track, .literal_module => false, }; } fn isResultCurve(cs: *const CodegenState, cc: CodegenContext, result: ExpressionResult) bool { return switch (result) { .nothing => unreachable, .literal_curve => true, .self_param => |param_index| switch (cc) { .global => unreachable, .module => |cms| cs.modules[cms.module_index].params[param_index].param_type == .curve, }, .track_param => |x| switch (cc) { .global => unreachable, .module => |cms| cs.tracks[x.track_index].params[x.param_index].param_type == .curve, }, .temp_buffer, .temp_float, .literal_boolean, .literal_number, .literal_enum_value, .literal_track, .literal_module => false, }; } fn isResultTrack(cs: *const CodegenState, cc: CodegenContext, result: ExpressionResult) ?usize { return switch (result) { .nothing => unreachable, .literal_track => |track_index| track_index, .self_param, .track_param, .temp_buffer, .temp_float, .literal_boolean, .literal_number, .literal_enum_value, .literal_curve, .literal_module => null, }; } fn isResultModule(cs: *const CodegenState, cc: CodegenContext, result: ExpressionResult) ?usize { return switch (result) { .nothing => unreachable, .literal_module => |module_index| module_index, .self_param, .track_param, .temp_buffer, .temp_float, .literal_boolean, .literal_number, .literal_enum_value, .literal_curve, .literal_track => null, }; } fn enumAllowsValue(allowed_values: []const BuiltinEnumValue, label: []const u8, has_float_payload: bool) bool { const allowed_value = for (allowed_values) |value| { if (std.mem.eql(u8, label, value.label)) break value; } else return false; return switch (allowed_value.payload_type) { .none => !has_float_payload, .f32 => has_float_payload, }; } fn isResultEnumValue(cs: *const CodegenState, cc: CodegenContext, result: ExpressionResult, allowed_values: []const BuiltinEnumValue) bool { switch (result) { .nothing => unreachable, .literal_enum_value => |v| { const has_float_payload = if (v.payload) |p| isResultFloat(cs, cc, p.*) else false; return enumAllowsValue(allowed_values, v.label, has_float_payload); }, .self_param => |param_index| { const cms = switch (cc) { .global => unreachable, .module => |x| x, }; const possible_values = switch (cs.modules[cms.module_index].params[param_index].param_type) { .one_of => |e| e.values, else => return false, }; // each of the possible values must be in the allowed_values for (possible_values) |possible_value| { const has_float_payload = switch (possible_value.payload_type) { .none => false, .f32 => true, }; if (!enumAllowsValue(allowed_values, possible_value.label, has_float_payload)) return false; } return true; }, .track_param => |x| { const cms = switch (cc) { .global => unreachable, .module => |m| m, }; const possible_values = switch (cs.tracks[x.track_index].params[x.param_index].param_type) { .one_of => |e| e.values, else => return false, }; // each of the possible values must be in the allowed_values for (possible_values) |possible_value| { const has_float_payload = switch (possible_value.payload_type) { .none => false, .f32 => true, }; if (!enumAllowsValue(allowed_values, possible_value.label, has_float_payload)) return false; } return true; }, .literal_boolean, .literal_number, .literal_curve, .literal_track, .literal_module, .temp_buffer, .temp_float => return false, } } // caller wants to return a float-typed result fn requestFloatDest(cms: *CodegenModuleState) !FloatDest { // float-typed result locs don't exist for now const temp_float_index = try cms.temp_floats.claim(); return FloatDest{ .temp_float_index = temp_float_index }; } fn commitFloatDest(fd: FloatDest) !ExpressionResult { // since result_loc can never be float-typed, just do the simple thing return ExpressionResult{ .temp_float = TempRef.strong(fd.temp_float_index) }; } // caller wants to return a buffer-typed result fn requestBufferDest(cms: *CodegenModuleState, maybe_result_loc: ?BufferDest) !BufferDest { if (maybe_result_loc) |result_loc| { return result_loc; } const temp_buffer_index = try cms.temp_buffers.claim(); return BufferDest{ .temp_buffer_index = temp_buffer_index }; } fn commitBufferDest(maybe_result_loc: ?BufferDest, buffer_dest: BufferDest) !ExpressionResult { if (maybe_result_loc != null) { return ExpressionResult.nothing; } const temp_buffer_index = switch (buffer_dest) { .temp_buffer_index => |i| i, .output_index => unreachable, }; return ExpressionResult{ .temp_buffer = TempRef.strong(temp_buffer_index) }; } fn addInstruction(cms: *CodegenModuleState, instruction: Instruction) !void { if (cms.current_track_call) |current_track_call| { try current_track_call.instructions.append(instruction); } else if (cms.current_delay) |current_delay| { try current_delay.instructions.append(instruction); } else { try cms.instructions.append(instruction); } } fn genLiteralEnum(cs: *CodegenState, cc: CodegenContext, label: []const u8, payload: ?*const Expression) !ExpressionResult { if (payload) |payload_expr| { const payload_result = try genExpression(cs, cc, payload_expr, null); // the payload_result is now owned by the enum result, and will be released with it by releaseExpressionResult var payload_result_ptr = try cs.arena_allocator.create(ExpressionResult); payload_result_ptr.* = payload_result; return ExpressionResult{ .literal_enum_value = .{ .label = label, .payload = payload_result_ptr } }; } else { return ExpressionResult{ .literal_enum_value = .{ .label = label, .payload = null } }; } } fn genUnArith(cs: *CodegenState, cms: *CodegenModuleState, sr: SourceRange, maybe_result_loc: ?BufferDest, op: UnArithOp, ea: *const Expression) !ExpressionResult { const cc: CodegenContext = .{ .module = cms }; const ra = try genExpression(cs, cc, ea, null); defer releaseExpressionResult(cms, ra); if (isResultFloat(cs, cc, ra)) { // float -> float const float_dest = try requestFloatDest(cms); try addInstruction(cms, .{ .arith_float = .{ .out = float_dest, .op = op, .a = ra } }); return commitFloatDest(float_dest); } if (isResultBuffer(cs, cc, ra)) { // buffer -> buffer const buffer_dest = try requestBufferDest(cms, maybe_result_loc); try addInstruction(cms, .{ .arith_buffer = .{ .out = buffer_dest, .op = op, .a = ra } }); return commitBufferDest(maybe_result_loc, buffer_dest); } return fail(cs.ctx, sr, "arithmetic can only be performed on numeric types", .{}); } fn genBinArith(cs: *CodegenState, cms: *CodegenModuleState, sr: SourceRange, maybe_result_loc: ?BufferDest, op: BinArithOp, ea: *const Expression, eb: *const Expression) !ExpressionResult { const cc: CodegenContext = .{ .module = cms }; const ra = try genExpression(cs, cc, ea, null); defer releaseExpressionResult(cms, ra); const rb = try genExpression(cs, cc, eb, null); defer releaseExpressionResult(cms, rb); if (isResultFloat(cs, cc, ra)) { if (isResultFloat(cs, cc, rb)) { // float * float -> float const float_dest = try requestFloatDest(cms); try addInstruction(cms, .{ .arith_float_float = .{ .out = float_dest, .op = op, .a = ra, .b = rb } }); return commitFloatDest(float_dest); } if (isResultBuffer(cs, cc, rb)) { // float * buffer -> buffer const buffer_dest = try requestBufferDest(cms, maybe_result_loc); try addInstruction(cms, .{ .arith_float_buffer = .{ .out = buffer_dest, .op = op, .a = ra, .b = rb } }); return commitBufferDest(maybe_result_loc, buffer_dest); } } if (isResultBuffer(cs, cc, ra)) { if (isResultFloat(cs, cc, rb)) { // buffer * float -> buffer const buffer_dest = try requestBufferDest(cms, maybe_result_loc); try addInstruction(cms, .{ .arith_buffer_float = .{ .out = buffer_dest, .op = op, .a = ra, .b = rb } }); return commitBufferDest(maybe_result_loc, buffer_dest); } if (isResultBuffer(cs, cc, rb)) { // buffer * buffer -> buffer const buffer_dest = try requestBufferDest(cms, maybe_result_loc); try addInstruction(cms, .{ .arith_buffer_buffer = .{ .out = buffer_dest, .op = op, .a = ra, .b = rb } }); return commitBufferDest(maybe_result_loc, buffer_dest); } } return fail(cs.ctx, sr, "arithmetic can only be performed on numeric types", .{}); } // typecheck (coercing if possible) and return a value that matches the callee param's type fn commitCalleeParam(cs: *const CodegenState, cc: CodegenContext, sr: SourceRange, result: ExpressionResult, callee_param_type: ParamType) !ExpressionResult { switch (callee_param_type) { .boolean => { if (isResultBoolean(cs, cc, result)) return result; return fail(cs.ctx, sr, "expected boolean value", .{}); }, .buffer => { if (isResultBuffer(cs, cc, result)) return result; if (isResultFloat(cs, cc, result)) { switch (cc) { .global => unreachable, .module => |cms| { const temp_buffer_index = try cms.temp_buffers.claim(); try addInstruction(cms, .{ .float_to_buffer = .{ .out = .{ .temp_buffer_index = temp_buffer_index }, .in = result } }); return ExpressionResult{ .temp_buffer = TempRef.strong(temp_buffer_index) }; }, } } return fail(cs.ctx, sr, "expected buffer value", .{}); }, .constant_or_buffer => { if (isResultBuffer(cs, cc, result)) return result; if (isResultFloat(cs, cc, result)) return result; return fail(cs.ctx, sr, "expected float or buffer value", .{}); }, .constant => { if (isResultFloat(cs, cc, result)) return result; return fail(cs.ctx, sr, "expected float value", .{}); }, .curve => { if (isResultCurve(cs, cc, result)) return result; return fail(cs.ctx, sr, "expected curve value", .{}); }, .one_of => |e| { if (isResultEnumValue(cs, cc, result, e.values)) return result; return fail(cs.ctx, sr, "expected one of |", .{e.values}); }, } } // remember to call releaseExpressionResult on the results afterward fn genArgs( cs: *CodegenState, cc: CodegenContext, sr: SourceRange, params: []const ModuleParam, args: []const CallArg, ) ![]const ExpressionResult { for (args) |a| { for (params) |param| { if (std.mem.eql(u8, a.param_name, param.name)) break; } else return fail(cs.ctx, a.param_name_token.source_range, "call target has no param called `<`", .{}); } var arg_results = try cs.arena_allocator.alloc(ExpressionResult, params.len); for (params) |param, i| { // find this arg in the call node var maybe_arg: ?CallArg = null; for (args) |a| { if (!std.mem.eql(u8, a.param_name, param.name)) continue; if (maybe_arg != null) return fail(cs.ctx, a.param_name_token.source_range, "param `<` provided more than once", .{}); maybe_arg = a; } switch (cc) { .global => {}, .module => |cms| { if (maybe_arg == null and std.mem.eql(u8, param.name, "sample_rate")) { // sample_rate is passed implicitly const self_param_index = for (cs.modules[cms.module_index].params) |self_param, j| { if (std.mem.eql(u8, self_param.name, "sample_rate")) break j; } else unreachable; arg_results[i] = .{ .self_param = self_param_index }; continue; } }, } const arg = maybe_arg orelse return fail(cs.ctx, sr, "argument list is missing param `#`", .{param.name}); const result = try genExpression(cs, cc, arg.value, null); arg_results[i] = try commitCalleeParam(cs, cc, arg.value.source_range, result, param.param_type); } return arg_results; } fn genCall( cs: *CodegenState, cms: *CodegenModuleState, sr: SourceRange, maybe_result_loc: ?BufferDest, call: Call, ) !ExpressionResult { // generate the expression that resolves to the module to be called const field_result = try genExpression(cs, .{ .module = cms }, call.field_expr, null); const callee_module_index = isResultModule(cs, .{ .module = cms }, field_result) orelse { return fail(cs.ctx, call.field_expr.source_range, "not a module", .{}); }; // add a "field" to the self module const field_index = cms.fields.items.len; try cms.fields.append(.{ .module_index = callee_module_index, }); // typecheck and codegen the args const callee_module = cs.modules[callee_module_index]; const arg_results = try genArgs(cs, .{ .module = cms }, sr, callee_module.params, call.args); defer for (callee_module.params) |param, i| releaseExpressionResult(cms, arg_results[i]); // the callee needs temps for its own internal use var temps = try cs.arena_allocator.alloc(usize, cs.module_results[callee_module_index].?.num_temps); for (temps) |*ptr| ptr.* = try cms.temp_buffers.claim(); defer for (temps) |temp_buffer_index| cms.temp_buffers.release(temp_buffer_index); const buffer_dest = try requestBufferDest(cms, maybe_result_loc); try addInstruction(cms, .{ .call = .{ .out = buffer_dest, .field_index = field_index, .temps = temps, .args = arg_results, }, }); return commitBufferDest(maybe_result_loc, buffer_dest); } fn genTrackCall( cs: *CodegenState, cms: *CodegenModuleState, sr: SourceRange, maybe_result_loc: ?BufferDest, track_call: TrackCall, ) !ExpressionResult { if (cms.current_track_call != null) { return fail(cs.ctx, sr, "you cannot nest track calls", .{}); } if (cms.current_delay != null) { return fail(cs.ctx, sr, "you cannot use a track call inside a delay", .{}); } const track_result = try genExpression(cs, .{ .module = cms }, track_call.track_expr, null); const track_index = isResultTrack(cs, .{ .module = cms }, track_result) orelse { return fail(cs.ctx, track_call.track_expr.source_range, "not a track", .{}); }; const speed_result = try genExpression(cs, .{ .module = cms }, track_call.speed, null); if (!isResultFloat(cs, .{ .module = cms }, speed_result)) { return fail(cs.ctx, track_call.speed.source_range, "speed must be a constant value", .{}); } const trigger_index = cms.triggers.items.len; try cms.triggers.append(.{ .track_index = track_index }); const note_tracker_index = cms.note_trackers.items.len; try cms.note_trackers.append(.{ .track_index = track_index }); const buffer_dest = try requestBufferDest(cms, maybe_result_loc); var current_track_call: CurrentTrackCall = .{ .track_index = track_index, .instructions = std.ArrayList(Instruction).init(cs.arena_allocator), }; cms.current_track_call = &current_track_call; for (track_call.scope.statements.items) |statement| { switch (statement) { .let_assignment => |x| { cms.local_results[x.local_index] = try genExpression(cs, .{ .module = cms }, x.expression, null); }, .output => |expr| { const result = try genExpression(cs, .{ .module = cms }, expr, buffer_dest); try commitOutput(cs, cms, expr.source_range, result, buffer_dest); releaseExpressionResult(cms, result); // this should do nothing (because we passed a result loc) }, .feedback => |expr| { return fail(cs.ctx, expr.source_range, "`feedback` can only be used within a `delay` operation", .{}); }, } } cms.current_track_call = null; try addInstruction(cms, .{ .track_call = .{ .out = buffer_dest, .track_index = track_index, .speed = speed_result, .trigger_index = trigger_index, .note_tracker_index = note_tracker_index, .instructions = current_track_call.instructions.toOwnedSlice(), }, }); releaseExpressionResult(cms, speed_result); return commitBufferDest(maybe_result_loc, buffer_dest); } fn genDelay(cs: *CodegenState, cms: *CodegenModuleState, sr: SourceRange, maybe_result_loc: ?BufferDest, delay: Delay) !ExpressionResult { if (cms.current_delay != null) { return fail(cs.ctx, sr, "you cannot nest delay operations", .{}); // i might be able to support this, but why? } if (cms.current_track_call != null) { return fail(cs.ctx, sr, "you cannot use a delay inside a track call", .{}); } const delay_index = cms.delays.items.len; try cms.delays.append(.{ .num_samples = delay.num_samples }); const feedback_temp_index = try cms.temp_buffers.claim(); defer cms.temp_buffers.release(feedback_temp_index); const buffer_dest = try requestBufferDest(cms, maybe_result_loc); const feedback_out_temp_index = try cms.temp_buffers.claim(); defer cms.temp_buffers.release(feedback_out_temp_index); var current_delay: CurrentDelay = .{ .feedback_temp_index = feedback_temp_index, .instructions = std.ArrayList(Instruction).init(cs.arena_allocator), }; cms.current_delay = &current_delay; for (delay.scope.statements.items) |statement| { switch (statement) { .let_assignment => |x| { cms.local_results[x.local_index] = try genExpression(cs, .{ .module = cms }, x.expression, null); }, .output => |expr| { const result = try genExpression(cs, .{ .module = cms }, expr, buffer_dest); try commitOutput(cs, cms, expr.source_range, result, buffer_dest); releaseExpressionResult(cms, result); // this should do nothing (because we passed a result loc) }, .feedback => |expr| { const result_loc: BufferDest = .{ .temp_buffer_index = feedback_out_temp_index }; const result = try genExpression(cs, .{ .module = cms }, expr, result_loc); try commitOutput(cs, cms, expr.source_range, result, result_loc); releaseExpressionResult(cms, result); // this should do nothing (because we passed a result loc) }, } } cms.current_delay = null; try addInstruction(cms, .{ .delay = .{ .out = buffer_dest, .delay_index = delay_index, .feedback_out_temp_buffer_index = feedback_out_temp_index, .feedback_temp_buffer_index = feedback_temp_index, // do i need this? .instructions = current_delay.instructions.toOwnedSlice(), }, }); return commitBufferDest(maybe_result_loc, buffer_dest); } fn genTrack(cs: *CodegenState, track_index: usize) !void { if (cs.track_results[track_index] != null) { return; // already generated } const track = cs.tracks[track_index]; var notes = try cs.arena_allocator.alloc([]const ExpressionResult, track.notes.len); for (track.notes) |note, note_index| { notes[note_index] = try genArgs(cs, .global, note.args_source_range, track.params, note.args); } // don't need to call releaseExpressionResult since we're at the global scope where // temporaries can't exist anyway cs.track_results[track_index] = .{ .note_values = notes }; } fn genModule(cs: *CodegenState, module_index: usize) !void { if (cs.module_results[module_index] != null) { return; // already generated } const module_info = cs.modules[module_index].info.?; var cms: CodegenModuleState = .{ .module_index = module_index, .locals = module_info.locals, .instructions = std.ArrayList(Instruction).init(cs.arena_allocator), .temp_buffers = TempManager.init(cs.inner_allocator, true), // pass false: don't reuse temp floats slots (they become `const` in zig) // TODO we could reuse them if we're targeting runtime, not codegen_zig .temp_floats = TempManager.init(cs.inner_allocator, false), .local_results = try cs.arena_allocator.alloc(?ExpressionResult, module_info.locals.len), .fields = std.ArrayList(Field).init(cs.arena_allocator), .delays = std.ArrayList(DelayDecl).init(cs.arena_allocator), .triggers = std.ArrayList(TriggerDecl).init(cs.arena_allocator), .note_trackers = std.ArrayList(NoteTrackerDecl).init(cs.arena_allocator), .current_delay = null, .current_track_call = null, }; defer cms.temp_buffers.deinit(); defer cms.temp_floats.deinit(); std.mem.set(?ExpressionResult, cms.local_results, null); for (module_info.scope.statements.items) |statement| { try genTopLevelStatement(cs, &cms, statement); } for (cms.local_results) |maybe_result| { const result = maybe_result orelse continue; releaseExpressionResult(&cms, result); } cms.temp_buffers.reportLeaks(); cms.temp_floats.reportLeaks(); if (cs.dump_codegen_out) |out| { printBytecode(out, cs, &cms) catch |err| std.debug.warn("printBytecode failed: {}\n", .{err}); } cs.module_results[module_index] = .{ .num_outputs = 1, .num_temps = cms.temp_buffers.finalCount(), .num_temp_floats = cms.temp_floats.finalCount(), .inner = .{ .custom = .{ .fields = cms.fields.toOwnedSlice(), .delays = cms.delays.toOwnedSlice(), .note_trackers = cms.note_trackers.toOwnedSlice(), .triggers = cms.triggers.toOwnedSlice(), .instructions = cms.instructions.toOwnedSlice(), }, }, }; } pub const GenError = error{ Failed, OutOfMemory, }; // generate bytecode instructions for an expression fn genExpression( cs: *CodegenState, cc: CodegenContext, expr: *const Expression, maybe_result_loc: ?BufferDest, ) GenError!ExpressionResult { switch (expr.inner) { .literal_boolean => |value| return ExpressionResult{ .literal_boolean = value }, .literal_number => |value| return ExpressionResult{ .literal_number = value }, .literal_enum_value => |v| return genLiteralEnum(cs, cc, v.label, v.payload), .literal_curve => |curve_index| return ExpressionResult{ .literal_curve = curve_index }, .literal_track => |track_index| { try genTrack(cs, track_index); return ExpressionResult{ .literal_track = track_index }; }, .literal_module => |module_index| { try genModule(cs, module_index); return ExpressionResult{ .literal_module = module_index }; }, .name => |token| { const name = cs.ctx.source.getString(token.source_range); switch (cc) { .global => {}, .module => |cms| { // is it a param from a track call? if (cms.current_track_call) |ctc| { for (cs.tracks[ctc.track_index].params) |param, param_index| { if (!std.mem.eql(u8, param.name, name)) continue; // note: tracks aren't allowed to use buffer or cob types. so we don't need the cob-to-buffer // instruction that self_param uses return ExpressionResult{ .track_param = .{ .track_index = ctc.track_index, .param_index = param_index } }; } } // is it a param of the current module? for (cs.modules[cms.module_index].params) |param, param_index| { if (!std.mem.eql(u8, param.name, name)) continue; // immediately turn constant_or_buffer into buffer (the rest of codegen isn't able to work with constant_or_buffer) if (param.param_type == .constant_or_buffer) { const buffer_dest = try requestBufferDest(cms, maybe_result_loc); try addInstruction(cms, .{ .cob_to_buffer = .{ .out = buffer_dest, .in_self_param = param_index } }); return try commitBufferDest(maybe_result_loc, buffer_dest); } else { return ExpressionResult{ .self_param = param_index }; } } }, } // is it a global? const global_index = for (cs.globals) |global, i| { if (std.mem.eql(u8, name, global.name)) break i; } else return fail(cs.ctx, token.source_range, "use of undeclared identifier `<`", .{}); if (cs.global_results[global_index] == null) { // globals defined out of order - generate recursively if (cs.global_visited[global_index]) { return fail(cs.ctx, token.source_range, "circular reference in global", .{}); } cs.global_visited[global_index] = true; cs.global_results[global_index] = try genExpression(cs, .global, cs.globals[global_index].value, null); } const result = cs.global_results[global_index].?; switch (result) { .temp_buffer => |temp_ref| return ExpressionResult{ .temp_buffer = TempRef.weak(temp_ref.index) }, .temp_float => |temp_ref| return ExpressionResult{ .temp_float = TempRef.weak(temp_ref.index) }, else => return result, } }, .local => |local_index| { switch (cc) { .global => unreachable, .module => |cms| { // a local is just a saved ExpressionResult. make a weak-reference version of it const result = cms.local_results[local_index].?; switch (result) { .temp_buffer => |temp_ref| return ExpressionResult{ .temp_buffer = TempRef.weak(temp_ref.index) }, .temp_float => |temp_ref| return ExpressionResult{ .temp_float = TempRef.weak(temp_ref.index) }, else => return result, } }, } }, .un_arith => |m| { switch (cc) { .global => return fail(cs.ctx, expr.source_range, "constant arithmetic is not supported", .{}), .module => |cms| return try genUnArith(cs, cms, expr.source_range, maybe_result_loc, m.op, m.a), } }, .bin_arith => |m| { switch (cc) { .global => return fail(cs.ctx, expr.source_range, "constant arithmetic is not supported", .{}), .module => |cms| return try genBinArith(cs, cms, expr.source_range, maybe_result_loc, m.op, m.a, m.b), } }, .call => |call| { switch (cc) { .global => unreachable, .module => |cms| return try genCall(cs, cms, expr.source_range, maybe_result_loc, call), } }, .track_call => |track_call| { switch (cc) { .global => unreachable, .module => |cms| return try genTrackCall(cs, cms, expr.source_range, maybe_result_loc, track_call), } }, .delay => |delay| { switch (cc) { .global => unreachable, .module => |cms| return try genDelay(cs, cms, expr.source_range, maybe_result_loc, delay), } }, .feedback => { switch (cc) { .global => unreachable, .module => |cms| { const feedback_temp_index = if (cms.current_delay) |current_delay| current_delay.feedback_temp_index else return fail(cs.ctx, expr.source_range, "`feedback` can only be used within a `delay` operation", .{}); return ExpressionResult{ .temp_buffer = TempRef.weak(feedback_temp_index) }; }, } }, } } // typecheck and make sure that the expression result is written into buffer_dest. fn commitOutput(cs: *const CodegenState, cms: *CodegenModuleState, sr: SourceRange, result: ExpressionResult, buffer_dest: BufferDest) !void { switch (result) { .nothing => { // value has already been written into the result location }, .temp_buffer => { try addInstruction(cms, .{ .copy_buffer = .{ .out = buffer_dest, .in = result } }); }, .temp_float, .literal_number => { try addInstruction(cms, .{ .float_to_buffer = .{ .out = buffer_dest, .in = result } }); }, .literal_boolean => return fail(cs.ctx, sr, "expected buffer value, found boolean", .{}), .literal_enum_value => return fail(cs.ctx, sr, "expected buffer value, found enum value", .{}), .literal_curve => return fail(cs.ctx, sr, "expected buffer value, found curve", .{}), .literal_track => return fail(cs.ctx, sr, "expected buffer value, found track", .{}), .literal_module => return fail(cs.ctx, sr, "expected buffer value, found module", .{}), .self_param => |param_index| { switch (cs.modules[cms.module_index].params[param_index].param_type) { .boolean => return fail(cs.ctx, sr, "expected buffer value, found boolean", .{}), .buffer, .constant_or_buffer => { // constant_or_buffer are immediately unwrapped to buffers in codegen (for now) try addInstruction(cms, .{ .copy_buffer = .{ .out = buffer_dest, .in = .{ .self_param = param_index } } }); }, .constant => { try addInstruction(cms, .{ .float_to_buffer = .{ .out = buffer_dest, .in = .{ .self_param = param_index } } }); }, .curve => return fail(cs.ctx, sr, "expected buffer value, found curve", .{}), .one_of => |e| return fail(cs.ctx, sr, "expected buffer value, found enum value", .{}), } }, .track_param => |x| { switch (cs.tracks[x.track_index].params[x.param_index].param_type) { .boolean => return fail(cs.ctx, sr, "expected buffer value, found boolean", .{}), .buffer, .constant_or_buffer => { // constant_or_buffer are immediately unwrapped to buffers in codegen (for now) try addInstruction(cms, .{ .copy_buffer = .{ .out = buffer_dest, .in = .{ .track_param = x } } }); }, .constant => { try addInstruction(cms, .{ .float_to_buffer = .{ .out = buffer_dest, .in = .{ .track_param = x } } }); }, .curve => return fail(cs.ctx, sr, "expected buffer value, found curve", .{}), .one_of => |e| return fail(cs.ctx, sr, "expected buffer value, found enum value", .{}), } }, } } fn genTopLevelStatement(cs: *CodegenState, cms: *CodegenModuleState, statement: Statement) !void { std.debug.assert(cms.current_delay == null); std.debug.assert(cms.current_track_call == null); switch (statement) { .let_assignment => |x| { cms.local_results[x.local_index] = try genExpression(cs, .{ .module = cms }, x.expression, null); }, .output => |expression| { const result_loc: BufferDest = .{ .output_index = 0 }; const result = try genExpression(cs, .{ .module = cms }, expression, result_loc); try commitOutput(cs, cms, expression.source_range, result, result_loc); releaseExpressionResult(cms, result); // this should do nothing (because we passed a result loc) }, .feedback => |expression| { return fail(cs.ctx, expression.source_range, "`feedback` can only be used within a `delay` operation", .{}); }, } } pub const CodeGenTrackResult = struct { note_values: []const []const ExpressionResult, // values in order of track params }; pub const CodeGenCustomModuleInner = struct { fields: []const Field, // owned slice delays: []const DelayDecl, // owned slice note_trackers: []const NoteTrackerDecl, // owned slice triggers: []const TriggerDecl, // owned slice instructions: []const Instruction, // owned slice }; pub const CodeGenModuleResult = struct { num_outputs: usize, num_temps: usize, num_temp_floats: usize, inner: union(enum) { builtin, custom: CodeGenCustomModuleInner, }, }; pub const ExportedModule = struct { name: []const u8, module_index: usize, }; pub const CodeGenResult = struct { arena: std.heap.ArenaAllocator, track_results: []const CodeGenTrackResult, module_results: []const CodeGenModuleResult, exported_modules: []const ExportedModule, pub fn deinit(self: *CodeGenResult) void { self.arena.deinit(); } }; // codegen entry point pub fn codegen( ctx: Context, parse_result: ParseResult, inner_allocator: *std.mem.Allocator, dump_codegen_out: ?std.io.StreamSource.OutStream, ) !CodeGenResult { var arena = std.heap.ArenaAllocator.init(inner_allocator); errdefer arena.deinit(); // globals var global_results = try arena.allocator.alloc(?ExpressionResult, parse_result.globals.len); var global_visited = try arena.allocator.alloc(bool, parse_result.globals.len); std.mem.set(?ExpressionResult, global_results, null); std.mem.set(bool, global_visited, false); var track_results = try arena.allocator.alloc(?CodeGenTrackResult, parse_result.tracks.len); std.mem.set(?CodeGenTrackResult, track_results, null); var module_results = try arena.allocator.alloc(?CodeGenModuleResult, parse_result.modules.len); std.mem.set(?CodeGenModuleResult, module_results, null); var cs: CodegenState = .{ .arena_allocator = &arena.allocator, .inner_allocator = inner_allocator, .ctx = ctx, .globals = parse_result.globals, .curves = parse_result.curves, .tracks = parse_result.tracks, .modules = parse_result.modules, .global_results = global_results, .global_visited = global_visited, .track_results = track_results, .module_results = module_results, .dump_codegen_out = dump_codegen_out, }; // generate builtin modules var builtin_index: usize = 0; for (ctx.builtin_packages) |pkg| { for (pkg.builtins) |builtin| { module_results[builtin_index] = .{ .num_outputs = builtin.num_outputs, .num_temps = builtin.num_temps, .num_temp_floats = 0, .inner = .builtin, }; builtin_index += 1; } } for (parse_result.globals) |global, global_index| { // note: genExpression has the ability to call this recursively, if a global refers // to another global that hasn't been generated yet. if (global_visited[global_index]) { continue; } global_visited[global_index] = true; global_results[global_index] = try genExpression(&cs, .global, global.value, null); } var exported_modules = std.ArrayList(ExportedModule).init(&arena.allocator); for (parse_result.globals) |global, i| { switch (global_results[i].?) { .literal_module => |module_index| { if (parse_result.modules[module_index].info == null) continue; try exported_modules.append(.{ .name = global.name, .module_index = module_index, }); }, else => {}, } } // convert []?T to []T var track_results2 = try arena.allocator.alloc(CodeGenTrackResult, track_results.len); for (track_results) |maybe_result, i| { track_results2[i] = maybe_result.?; } var module_results2 = try arena.allocator.alloc(CodeGenModuleResult, module_results.len); for (module_results) |maybe_result, i| { module_results2[i] = maybe_result.?; } return CodeGenResult{ .arena = arena, .track_results = track_results2, .module_results = module_results2, .exported_modules = exported_modules.toOwnedSlice(), }; }
src/zangscript/codegen.zig
const std = @import("std"); const ecs = @import("ecs"); // override the EntityTraits used by ecs pub const EntityTraits = ecs.EntityTraitsType(.medium); pub const Velocity = struct { x: f32, y: f32 }; pub const Position = struct { x: f32, y: f32 }; /// logs the timing for views vs non-owning groups vs owning groups with 1,000,000 entities pub fn main() !void { var reg = ecs.Registry.init(std.heap.c_allocator); defer reg.deinit(); // var timer = try std.time.Timer.start(); createEntities(&reg); iterateView(&reg); nonOwningGroup(&reg); owningGroup(&reg); } fn createEntities(reg: *ecs.Registry) void { var timer = std.time.Timer.start() catch unreachable; var i: usize = 0; while (i < 1000000) : (i += 1) { var e1 = reg.create(); reg.add(e1, Position{ .x = 1, .y = 1 }); reg.add(e1, Velocity{ .x = 1, .y = 1 }); } var end = timer.lap(); std.debug.print("create entities: \t{d}\n", .{@intToFloat(f64, end) / 1000000000}); } fn iterateView(reg: *ecs.Registry) void { std.debug.print("--- multi-view ---\n", .{}); var view = reg.view(.{ Velocity, Position }, .{}); var timer = std.time.Timer.start() catch unreachable; var iter = view.iterator(); while (iter.next()) |entity| { var pos = view.get(Position, entity); const vel = view.getConst(Velocity, entity); pos.*.x += vel.x; pos.*.y += vel.y; } var end = timer.lap(); std.debug.print("view (iter): \t{d}\n", .{@intToFloat(f64, end) / 1000000000}); } fn nonOwningGroup(reg: *ecs.Registry) void { std.debug.print("--- non-owning ---\n", .{}); var timer = std.time.Timer.start() catch unreachable; var group = reg.group(.{}, .{ Velocity, Position }, .{}); var end = timer.lap(); std.debug.print("group (create): {d}\n", .{@intToFloat(f64, end) / 1000000000}); timer.reset(); var group_iter = group.iterator(); while (group_iter.next()) |entity| { var pos = group.get(Position, entity); const vel = group.getConst(Velocity, entity); pos.*.x += vel.x; pos.*.y += vel.y; } end = timer.lap(); std.debug.print("group (iter): \t{d}\n", .{@intToFloat(f64, end) / 1000000000}); } fn owningGroup(reg: *ecs.Registry) void { std.debug.print("--- owning ---\n", .{}); var timer = std.time.Timer.start() catch unreachable; var group = reg.group(.{ Velocity, Position }, .{}, .{}); var end = timer.lap(); std.debug.print("group (create): {d}\n", .{@intToFloat(f64, end) / 1000000000}); timer.reset(); var group_iter = group.iterator(struct { vel: *Velocity, pos: *Position }); while (group_iter.next()) |e| { e.pos.*.x += e.vel.x; e.pos.*.y += e.vel.y; } end = timer.lap(); std.debug.print("group (iter): \t{d}\n", .{@intToFloat(f64, end) / 1000000000}); timer.reset(); group.each(each); end = timer.lap(); std.debug.print("group (each): \t{d}\n", .{@intToFloat(f64, end) / 1000000000}); timer.reset(); // var storage = reg.assure(Velocity); // var vel = storage.instances.items; var pos = reg.assure(Position).instances.items; var index: usize = group.group_data.current; while (true) { if (index == 0) break; index -= 1; pos[index].x += pos[index].x; pos[index].y += pos[index].y; } end = timer.lap(); std.debug.print("group (direct): {d}\n", .{@intToFloat(f64, end) / 1000000000}); } fn each(e: struct { vel: *Velocity, pos: *Position }) void { e.pos.*.x += e.vel.x; e.pos.*.y += e.vel.y; }
examples/view_vs_group.zig
const std = @import("std"); const math = std.math; const glfw = @import("glfw"); const zgpu = @import("zgpu"); const gpu = zgpu.gpu; const c = zgpu.cimgui; const zm = @import("zmath"); const zmesh = @import("zmesh"); const znoise = @import("znoise"); const wgsl = @import("procedural_mesh_wgsl.zig"); const content_dir = @import("build_options").content_dir; const window_title = "zig-gamedev: procedural mesh (wgpu)"; const Vertex = struct { position: [3]f32, normal: [3]f32, }; const FrameUniforms = struct { world_to_clip: zm.Mat, camera_position: [3]f32, }; const DrawUniforms = struct { object_to_world: zm.Mat, basecolor_roughness: [4]f32, }; const Mesh = struct { index_offset: u32, vertex_offset: i32, num_indices: u32, num_vertices: u32, }; const Drawable = struct { mesh_index: u32, position: [3]f32, basecolor_roughness: [4]f32, }; const DemoState = struct { gctx: *zgpu.GraphicsContext, pipeline: zgpu.RenderPipelineHandle, bind_group: zgpu.BindGroupHandle, vertex_buffer: zgpu.BufferHandle, index_buffer: zgpu.BufferHandle, depth_texture: zgpu.TextureHandle, depth_texture_view: zgpu.TextureViewHandle, meshes: std.ArrayList(Mesh), drawables: std.ArrayList(Drawable), camera: struct { position: [3]f32 = .{ 0.0, 4.0, -4.0 }, forward: [3]f32 = .{ 0.0, 0.0, 1.0 }, pitch: f32 = 0.15 * math.pi, yaw: f32 = 0.0, } = .{}, mouse: struct { cursor: glfw.Window.CursorPos = .{ .xpos = 0.0, .ypos = 0.0 }, } = .{}, }; fn appendMesh( mesh: zmesh.Shape, meshes: *std.ArrayList(Mesh), meshes_indices: *std.ArrayList(u16), meshes_positions: *std.ArrayList([3]f32), meshes_normals: *std.ArrayList([3]f32), ) void { meshes.append(.{ .index_offset = @intCast(u32, meshes_indices.items.len), .vertex_offset = @intCast(i32, meshes_positions.items.len), .num_indices = @intCast(u32, mesh.indices.len), .num_vertices = @intCast(u32, mesh.positions.len), }) catch unreachable; meshes_indices.appendSlice(mesh.indices) catch unreachable; meshes_positions.appendSlice(mesh.positions) catch unreachable; meshes_normals.appendSlice(mesh.normals.?) catch unreachable; } fn initScene( allocator: std.mem.Allocator, drawables: *std.ArrayList(Drawable), meshes: *std.ArrayList(Mesh), meshes_indices: *std.ArrayList(u16), meshes_positions: *std.ArrayList([3]f32), meshes_normals: *std.ArrayList([3]f32), ) void { var arena_state = std.heap.ArenaAllocator.init(allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); zmesh.init(arena); defer zmesh.deinit(); // Trefoil knot. { var mesh = zmesh.Shape.initTrefoilKnot(10, 128, 0.8); defer mesh.deinit(); mesh.rotate(math.pi * 0.5, 1.0, 0.0, 0.0); mesh.unweld(); mesh.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ 0, 1, 0 }, .basecolor_roughness = .{ 0.0, 0.7, 0.0, 0.6 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Parametric sphere. { var mesh = zmesh.Shape.initParametricSphere(20, 20); defer mesh.deinit(); mesh.rotate(math.pi * 0.5, 1.0, 0.0, 0.0); mesh.unweld(); mesh.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ 3, 1, 0 }, .basecolor_roughness = .{ 0.7, 0.0, 0.0, 0.2 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Icosahedron. { var mesh = zmesh.Shape.initIcosahedron(); defer mesh.deinit(); mesh.unweld(); mesh.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ -3, 1, 0 }, .basecolor_roughness = .{ 0.7, 0.6, 0.0, 0.4 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Dodecahedron. { var mesh = zmesh.Shape.initDodecahedron(); defer mesh.deinit(); mesh.unweld(); mesh.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ 0, 1, 3 }, .basecolor_roughness = .{ 0.0, 0.1, 1.0, 0.2 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Cylinder with top and bottom caps. { var disk = zmesh.Shape.initParametricDisk(10, 2); defer disk.deinit(); disk.invert(0, 0); var cylinder = zmesh.Shape.initCylinder(10, 4); defer cylinder.deinit(); cylinder.merge(disk); cylinder.translate(0, 0, -1); disk.invert(0, 0); cylinder.merge(disk); cylinder.scale(0.5, 0.5, 2); cylinder.rotate(math.pi * 0.5, 1.0, 0.0, 0.0); cylinder.unweld(); cylinder.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ -3, 0, 3 }, .basecolor_roughness = .{ 1.0, 0.0, 0.0, 0.3 }, }) catch unreachable; appendMesh(cylinder, meshes, meshes_indices, meshes_positions, meshes_normals); } // Torus. { var mesh = zmesh.Shape.initTorus(10, 20, 0.2); defer mesh.deinit(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ 3, 1.5, 3 }, .basecolor_roughness = .{ 1.0, 0.5, 0.0, 0.2 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Subdivided sphere. { var mesh = zmesh.Shape.initSubdividedSphere(3); defer mesh.deinit(); mesh.unweld(); mesh.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ 3, 1, 6 }, .basecolor_roughness = .{ 0.0, 1.0, 0.0, 0.2 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Tetrahedron. { var mesh = zmesh.Shape.initTetrahedron(); defer mesh.deinit(); mesh.unweld(); mesh.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ 0, 0.5, 6 }, .basecolor_roughness = .{ 1.0, 0.0, 1.0, 0.2 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Octahedron. { var mesh = zmesh.Shape.initOctahedron(); defer mesh.deinit(); mesh.unweld(); mesh.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ -3, 1, 6 }, .basecolor_roughness = .{ 0.2, 0.0, 1.0, 0.2 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Rock. { var rock = zmesh.Shape.initRock(123, 4); defer rock.deinit(); rock.unweld(); rock.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ -6, 0, 3 }, .basecolor_roughness = .{ 1.0, 1.0, 1.0, 1.0 }, }) catch unreachable; appendMesh(rock, meshes, meshes_indices, meshes_positions, meshes_normals); } // Custom parametric (simple terrain). { const gen = znoise.FnlGenerator{ .fractal_type = .fbm, .frequency = 2.0, .octaves = 5, .lacunarity = 2.02, }; const local = struct { fn terrain(uv: *const [2]f32, position: *[3]f32, userdata: ?*anyopaque) callconv(.C) void { _ = userdata; position[0] = uv[0]; position[1] = 0.025 * gen.noise2(uv[0], uv[1]); position[2] = uv[1]; } }; var ground = zmesh.Shape.initParametric(local.terrain, 40, 40, null); defer ground.deinit(); ground.translate(-0.5, -0.0, -0.5); ground.invert(0, 0); ground.scale(20, 20, 20); ground.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ 0, 0, 0 }, .basecolor_roughness = .{ 0.1, 0.1, 0.1, 1.0 }, }) catch unreachable; appendMesh(ground, meshes, meshes_indices, meshes_positions, meshes_normals); } } fn init(allocator: std.mem.Allocator, window: glfw.Window) !DemoState { const gctx = try zgpu.GraphicsContext.init(allocator, window); var arena_state = std.heap.ArenaAllocator.init(allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const bind_group_layout = gctx.createBindGroupLayout(&.{ zgpu.bglBuffer(0, .{ .vertex = true, .fragment = true }, .uniform, true, 0), }); defer gctx.destroyResource(bind_group_layout); const pipeline_layout = gctx.createPipelineLayout(&.{ bind_group_layout, bind_group_layout, }); defer gctx.destroyResource(pipeline_layout); const pipeline = pipeline: { const vs_module = gctx.device.createShaderModule(&.{ .label = "vs", .code = .{ .wgsl = wgsl.vs } }); defer vs_module.release(); const fs_module = gctx.device.createShaderModule(&.{ .label = "fs", .code = .{ .wgsl = wgsl.fs } }); defer fs_module.release(); const color_target = gpu.ColorTargetState{ .format = zgpu.GraphicsContext.swapchain_format, .blend = &.{ .color = .{}, .alpha = .{} }, }; const vertex_attributes = [_]gpu.VertexAttribute{ .{ .format = .float32x3, .offset = 0, .shader_location = 0 }, .{ .format = .float32x3, .offset = @offsetOf(Vertex, "normal"), .shader_location = 1 }, }; const vertex_buffer_layout = gpu.VertexBufferLayout{ .array_stride = @sizeOf(Vertex), .attribute_count = vertex_attributes.len, .attributes = &vertex_attributes, }; // Create a render pipeline. const pipeline_descriptor = gpu.RenderPipeline.Descriptor{ .vertex = gpu.VertexState{ .module = vs_module, .entry_point = "main", .buffers = &.{vertex_buffer_layout}, }, .primitive = gpu.PrimitiveState{ .front_face = .cw, .cull_mode = .back, .topology = .triangle_list, }, .depth_stencil = &gpu.DepthStencilState{ .format = .depth32_float, .depth_write_enabled = true, .depth_compare = .less, }, .fragment = &gpu.FragmentState{ .module = fs_module, .entry_point = "main", .targets = &.{color_target}, }, }; break :pipeline gctx.createRenderPipeline(pipeline_layout, pipeline_descriptor); }; const bind_group = gctx.createBindGroup(bind_group_layout, &[_]zgpu.BindGroupEntryInfo{ .{ .binding = 0, .buffer_handle = gctx.uniforms.buffer, .offset = 0, .size = 256 }, }); var drawables = std.ArrayList(Drawable).init(allocator); var meshes = std.ArrayList(Mesh).init(allocator); var meshes_indices = std.ArrayList(u16).init(arena); var meshes_positions = std.ArrayList([3]f32).init(arena); var meshes_normals = std.ArrayList([3]f32).init(arena); initScene(allocator, &drawables, &meshes, &meshes_indices, &meshes_positions, &meshes_normals); const total_num_vertices = @intCast(u32, meshes_positions.items.len); const total_num_indices = @intCast(u32, meshes_indices.items.len); // Create a vertex buffer. const vertex_buffer = gctx.createBuffer(.{ .usage = .{ .copy_dst = true, .vertex = true }, .size = total_num_vertices * @sizeOf(Vertex), }); { var vertex_data = std.ArrayList(Vertex).init(arena); defer vertex_data.deinit(); vertex_data.resize(total_num_vertices) catch unreachable; for (meshes_positions.items) |_, i| { vertex_data.items[i].position = meshes_positions.items[i]; vertex_data.items[i].normal = meshes_normals.items[i]; } gctx.queue.writeBuffer(gctx.lookupResource(vertex_buffer).?, 0, Vertex, vertex_data.items); } // Create an index buffer. const index_buffer = gctx.createBuffer(.{ .usage = .{ .copy_dst = true, .index = true }, .size = total_num_indices * @sizeOf(u16), }); gctx.queue.writeBuffer(gctx.lookupResource(index_buffer).?, 0, u16, meshes_indices.items); // Create a depth texture and its 'view'. const depth = createDepthTexture(gctx); return DemoState{ .gctx = gctx, .pipeline = pipeline, .bind_group = bind_group, .vertex_buffer = vertex_buffer, .index_buffer = index_buffer, .depth_texture = depth.texture, .depth_texture_view = depth.view, .meshes = meshes, .drawables = drawables, }; } fn deinit(allocator: std.mem.Allocator, demo: *DemoState) void { demo.meshes.deinit(); demo.drawables.deinit(); demo.gctx.deinit(allocator); demo.* = undefined; } fn update(demo: *DemoState) void { zgpu.gui.newFrame(demo.gctx.swapchain_descriptor.width, demo.gctx.swapchain_descriptor.height); if (c.igBegin("Demo Settings", null, c.ImGuiWindowFlags_NoMove | c.ImGuiWindowFlags_NoResize)) { c.igBulletText("Right Mouse Button + drag : rotate camera"); c.igBulletText("W, A, S, D : move camera"); c.igBulletText( "Average : %.3f ms/frame (%.1f fps)", demo.gctx.stats.average_cpu_time, demo.gctx.stats.fps, ); c.igBulletText( "CPU is ahead of GPU by : %d frame(s)", demo.gctx.stats.cpu_frame_number - demo.gctx.stats.gpu_frame_number, ); } c.igEnd(); const window = demo.gctx.window; // Handle camera rotation with mouse. { const cursor = window.getCursorPos() catch unreachable; const delta_x = @floatCast(f32, cursor.xpos - demo.mouse.cursor.xpos); const delta_y = @floatCast(f32, cursor.ypos - demo.mouse.cursor.ypos); demo.mouse.cursor.xpos = cursor.xpos; demo.mouse.cursor.ypos = cursor.ypos; if (window.getMouseButton(.right) == .press) { demo.camera.pitch += 0.0025 * delta_y; demo.camera.yaw += 0.0025 * delta_x; demo.camera.pitch = math.min(demo.camera.pitch, 0.48 * math.pi); demo.camera.pitch = math.max(demo.camera.pitch, -0.48 * math.pi); demo.camera.yaw = zm.modAngle(demo.camera.yaw); } } // Handle camera movement with 'WASD' keys. { const speed = zm.f32x4s(2.0); const delta_time = zm.f32x4s(demo.gctx.stats.delta_time); const transform = zm.mul(zm.rotationX(demo.camera.pitch), zm.rotationY(demo.camera.yaw)); var forward = zm.normalize3(zm.mul(zm.f32x4(0.0, 0.0, 1.0, 0.0), transform)); zm.store(demo.camera.forward[0..], forward, 3); const right = speed * delta_time * zm.normalize3(zm.cross3(zm.f32x4(0.0, 1.0, 0.0, 0.0), forward)); forward = speed * delta_time * forward; var cpos = zm.load(demo.camera.position[0..], zm.Vec, 3); if (window.getKey(.w) == .press) { cpos += forward; } else if (window.getKey(.s) == .press) { cpos -= forward; } if (window.getKey(.d) == .press) { cpos += right; } else if (window.getKey(.a) == .press) { cpos -= right; } zm.store(demo.camera.position[0..], cpos, 3); } } fn draw(demo: *DemoState) void { const gctx = demo.gctx; const fb_width = gctx.swapchain_descriptor.width; const fb_height = gctx.swapchain_descriptor.height; const cam_world_to_view = zm.lookToLh( zm.load(demo.camera.position[0..], zm.Vec, 3), zm.load(demo.camera.forward[0..], zm.Vec, 3), zm.f32x4(0.0, 1.0, 0.0, 0.0), ); const cam_view_to_clip = zm.perspectiveFovLh( 0.25 * math.pi, @intToFloat(f32, fb_width) / @intToFloat(f32, fb_height), 0.01, 200.0, ); const cam_world_to_clip = zm.mul(cam_world_to_view, cam_view_to_clip); const back_buffer_view = gctx.swapchain.getCurrentTextureView(); defer back_buffer_view.release(); const commands = commands: { const encoder = gctx.device.createCommandEncoder(null); defer encoder.release(); // Main pass. pass: { const vb_info = gctx.lookupResourceInfo(demo.vertex_buffer) orelse break :pass; const ib_info = gctx.lookupResourceInfo(demo.index_buffer) orelse break :pass; const pipeline = gctx.lookupResource(demo.pipeline) orelse break :pass; const bind_group = gctx.lookupResource(demo.bind_group) orelse break :pass; const depth_view = gctx.lookupResource(demo.depth_texture_view) orelse break :pass; const color_attachment = gpu.RenderPassColorAttachment{ .view = back_buffer_view, .load_op = .clear, .store_op = .store, }; const depth_attachment = gpu.RenderPassDepthStencilAttachment{ .view = depth_view, .depth_load_op = .clear, .depth_store_op = .store, .depth_clear_value = 1.0, }; const render_pass_info = gpu.RenderPassEncoder.Descriptor{ .color_attachments = &.{color_attachment}, .depth_stencil_attachment = &depth_attachment, }; const pass = encoder.beginRenderPass(&render_pass_info); defer { pass.end(); pass.release(); } pass.setVertexBuffer(0, vb_info.gpuobj.?, 0, vb_info.size); pass.setIndexBuffer(ib_info.gpuobj.?, .uint16, 0, ib_info.size); pass.setPipeline(pipeline); // Update "world to clip" (camera) xform. { const mem = gctx.uniformsAllocate(FrameUniforms, 1); mem.slice[0].world_to_clip = zm.transpose(cam_world_to_clip); mem.slice[0].camera_position = demo.camera.position; pass.setBindGroup(0, bind_group, &.{mem.offset}); } for (demo.drawables.items) |drawable| { // Update "object to world" xform. const object_to_world = zm.translationV(zm.load(drawable.position[0..], zm.Vec, 3)); const mem = gctx.uniformsAllocate(DrawUniforms, 1); mem.slice[0].object_to_world = zm.transpose(object_to_world); mem.slice[0].basecolor_roughness = drawable.basecolor_roughness; pass.setBindGroup(1, bind_group, &.{mem.offset}); // Draw. pass.drawIndexed( demo.meshes.items[drawable.mesh_index].num_indices, 1, demo.meshes.items[drawable.mesh_index].index_offset, demo.meshes.items[drawable.mesh_index].vertex_offset, 0, ); } } // Gui pass. { const color_attachment = gpu.RenderPassColorAttachment{ .view = back_buffer_view, .load_op = .load, .store_op = .store, }; const render_pass_info = gpu.RenderPassEncoder.Descriptor{ .color_attachments = &.{color_attachment}, }; const pass = encoder.beginRenderPass(&render_pass_info); defer { pass.end(); pass.release(); } zgpu.gui.draw(pass); } break :commands encoder.finish(null); }; defer commands.release(); gctx.submit(&.{commands}); if (gctx.present() == .swap_chain_resized) { // Release old depth texture. gctx.destroyResource(demo.depth_texture_view); gctx.destroyResource(demo.depth_texture); // Create a new depth texture to match the new window size. const depth = createDepthTexture(gctx); demo.depth_texture = depth.texture; demo.depth_texture_view = depth.view; } } fn createDepthTexture(gctx: *zgpu.GraphicsContext) struct { texture: zgpu.TextureHandle, view: zgpu.TextureViewHandle, } { const texture = gctx.createTexture(.{ .usage = .{ .render_attachment = true }, .dimension = .dimension_2d, .size = .{ .width = gctx.swapchain_descriptor.width, .height = gctx.swapchain_descriptor.height, .depth_or_array_layers = 1, }, .format = .depth32_float, .mip_level_count = 1, .sample_count = 1, }); const view = gctx.createTextureView(texture, .{}); return .{ .texture = texture, .view = view }; } pub fn main() !void { zgpu.checkContent(content_dir) catch { // In case of error zgpu.checkContent() will print error message. return; }; try glfw.init(.{}); defer glfw.terminate(); const window = try glfw.Window.create(1280, 960, window_title, null, null, .{ .client_api = .no_api, .cocoa_retina_framebuffer = true, }); defer window.destroy(); try window.setSizeLimits(.{ .width = 400, .height = 400 }, .{ .width = null, .height = null }); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var demo = try init(allocator, window); defer deinit(allocator, &demo); zgpu.gui.init(window, demo.gctx.device, content_dir, "Roboto-Medium.ttf", 25.0); defer zgpu.gui.deinit(); while (!window.shouldClose()) { try glfw.pollEvents(); update(&demo); draw(&demo); } }
samples/procedural_mesh_wgpu/src/procedural_mesh_wgpu.zig
const std = @import("std"); const generate = @import("vulkan/generator.zig").generate; const usage = "Usage: {s} [-h|--help] <spec xml path> <output zig source>\n"; pub fn main() !void { const stderr = std.io.getStdErr(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); var args = try std.process.argsWithAllocator(allocator); const prog_name = args.next() orelse return error.ExecutableNameMissing; var maybe_xml_path: ?[]const u8 = null; var maybe_out_path: ?[]const u8 = null; while (args.next()) |arg| { if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) { @setEvalBranchQuota(2000); try stderr.writer().print( \\Utility to generate a Zig binding from the Vulkan XML API registry. \\ \\The most recent Vulkan XML API registry can be obtained from \\https://github.com/KhronosGroup/Vulkan-Docs/blob/master/xml/vk.xml, \\and the most recent LunarG Vulkan SDK version can be found at \\$VULKAN_SDK/x86_64/share/vulkan/registry/vk.xml. \\ \\ ++ usage, .{prog_name}, ); return; } else if (maybe_xml_path == null) { maybe_xml_path = arg; } else if (maybe_out_path == null) { maybe_out_path = arg; } else { try stderr.writer().print("Error: Superficial argument '{s}'\n", .{arg}); } } const xml_path = maybe_xml_path orelse { try stderr.writer().print("Error: Missing required argument <spec xml path>\n" ++ usage, .{prog_name}); return; }; const out_path = maybe_out_path orelse { try stderr.writer().print("Error: Missing required argument <output zig source>\n" ++ usage, .{prog_name}); return; }; const cwd = std.fs.cwd(); const xml_src = cwd.readFileAlloc(allocator, xml_path, std.math.maxInt(usize)) catch |err| { try stderr.writer().print("Error: Failed to open input file '{s}' ({s})\n", .{ xml_path, @errorName(err) }); return; }; var out_buffer = std.ArrayList(u8).init(allocator); try generate(allocator, xml_src, out_buffer.writer()); try out_buffer.append(0); const src = out_buffer.items[0 .. out_buffer.items.len - 1 :0]; const tree = try std.zig.parse(allocator, src); const formatted = try tree.render(allocator); defer allocator.free(formatted); if (std.fs.path.dirname(out_path)) |dir| { cwd.makePath(dir) catch |err| { try stderr.writer().print("Error: Failed to create output directory '{s}' ({s})\n", .{ dir, @errorName(err) }); return; }; } cwd.writeFile(out_path, formatted) catch |err| { try stderr.writer().print("Error: Failed to write to output file '{s}' ({s})\n", .{ out_path, @errorName(err) }); return; }; }
generator/main.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day01.txt"); pub fn main() !void { var counterPart1: u64 = 0; var counterPart2: u64 = 0; var tempOrFirst:u64 = 0; const test_allocator = std.testing.allocator; var list = List(u64).init(test_allocator); var lines = tokenize(u8,data, "\r\n"); while(lines.next()) |line| { var currentLine = parseInt(u64, line, 10) catch unreachable; list.append(currentLine) catch unreachable; if(tempOrFirst < currentLine){ counterPart1 +=1; } tempOrFirst = currentLine; } var index: u32 = 0; while(index < list.items.len -3) :(index +=1){ var a1Num : u64 = list.items[index]; var a2b1Num :u64 = list.items[index+1]; var a3b2Num:u64 = list.items[index+2]; var b3Num: u64 = list.items[index+3]; var partA :u64 = a1Num + a2b1Num + a3b2Num; var partB :u64 = a2b1Num + a3b2Num + b3Num; if(partA < partB){ counterPart2 += 1; } } std.debug.print("Day 1 Part 1: {}\n", .{counterPart1-1}); std.debug.print("Day 1 Part 2: {}\n", .{counterPart2}); } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc;
src/day01.zig
const std = @import("std"); const builtin = @import("builtin"); const is_test = builtin.is_test; const native_arch = builtin.cpu.arch; // AArch64 is the only ABI (at the moment) to support f16 arguments without the // need for extending them to wider fp types. pub const F16T = if (native_arch.isAARCH64()) f16 else u16; pub fn __extendhfxf2(a: F16T) callconv(.C) f80 { return extendF80(f16, @bitCast(u16, a)); } pub fn __extendsfxf2(a: f32) callconv(.C) f80 { return extendF80(f32, @bitCast(u32, a)); } pub fn __extenddfxf2(a: f64) callconv(.C) f80 { return extendF80(f64, @bitCast(u64, a)); } inline fn extendF80(comptime src_t: type, a: std.meta.Int(.unsigned, @typeInfo(src_t).Float.bits)) f80 { @setRuntimeSafety(builtin.is_test); const src_rep_t = std.meta.Int(.unsigned, @typeInfo(src_t).Float.bits); const src_sig_bits = std.math.floatMantissaBits(src_t); const dst_int_bit = 0x8000000000000000; const dst_sig_bits = std.math.floatMantissaBits(f80) - 1; // -1 for the integer bit const dst_exp_bias = 16383; const src_bits = @bitSizeOf(src_t); const src_exp_bits = src_bits - src_sig_bits - 1; const src_inf_exp = (1 << src_exp_bits) - 1; const src_exp_bias = src_inf_exp >> 1; const src_min_normal = 1 << src_sig_bits; const src_inf = src_inf_exp << src_sig_bits; const src_sign_mask = 1 << (src_sig_bits + src_exp_bits); const src_abs_mask = src_sign_mask - 1; const src_qnan = 1 << (src_sig_bits - 1); const src_nan_code = src_qnan - 1; var dst: std.math.F80 = undefined; // Break a into a sign and representation of the absolute value const a_abs = a & src_abs_mask; const sign: u16 = if (a & src_sign_mask != 0) 0x8000 else 0; if (a_abs -% src_min_normal < src_inf - src_min_normal) { // a is a normal number. // Extend to the destination type by shifting the significand and // exponent into the proper position and rebiasing the exponent. dst.exp = @intCast(u16, a_abs >> src_sig_bits); dst.exp += dst_exp_bias - src_exp_bias; dst.fraction = @as(u64, a_abs) << (dst_sig_bits - src_sig_bits); dst.fraction |= dst_int_bit; // bit 64 is always set for normal numbers } else if (a_abs >= src_inf) { // a is NaN or infinity. // Conjure the result by beginning with infinity, then setting the qNaN // bit (if needed) and right-aligning the rest of the trailing NaN // payload field. dst.exp = 0x7fff; dst.fraction = dst_int_bit; dst.fraction |= @as(u64, a_abs & src_qnan) << (dst_sig_bits - src_sig_bits); dst.fraction |= @as(u64, a_abs & src_nan_code) << (dst_sig_bits - src_sig_bits); } else if (a_abs != 0) { // a is denormal. // renormalize the significand and clear the leading bit, then insert // the correct adjusted exponent in the destination type. const scale: u16 = @clz(src_rep_t, a_abs) - @clz(src_rep_t, @as(src_rep_t, src_min_normal)); dst.fraction = @as(u64, a_abs) << @intCast(u6, dst_sig_bits - src_sig_bits + scale); dst.fraction |= dst_int_bit; // bit 64 is always set for normal numbers dst.exp = @truncate(u16, a_abs >> @intCast(u4, src_sig_bits - scale)); dst.exp ^= 1; dst.exp |= dst_exp_bias - src_exp_bias - scale + 1; } else { // a is zero. dst.exp = 0; dst.fraction = 0; } dst.exp |= sign; return std.math.make_f80(dst); } pub fn __extendxftf2(a: f80) callconv(.C) f128 { @setRuntimeSafety(builtin.is_test); const src_int_bit: u64 = 0x8000000000000000; const src_sig_mask = ~src_int_bit; const src_sig_bits = std.math.floatMantissaBits(f80) - 1; // -1 for the integer bit const dst_sig_bits = std.math.floatMantissaBits(f128); const dst_bits = @bitSizeOf(f128); const dst_min_normal = @as(u128, 1) << dst_sig_bits; // Break a into a sign and representation of the absolute value var a_rep = std.math.break_f80(a); const sign = a_rep.exp & 0x8000; a_rep.exp &= 0x7FFF; var abs_result: u128 = undefined; if (a_rep.exp == 0 and a_rep.fraction == 0) { // zero abs_result = 0; } else if (a_rep.exp == 0x7FFF) { // a is nan or infinite abs_result = @as(u128, a_rep.fraction) << (dst_sig_bits - src_sig_bits); abs_result |= @as(u128, a_rep.exp) << dst_sig_bits; } else if (a_rep.fraction & src_int_bit != 0) { // a is a normal value abs_result = @as(u128, a_rep.fraction & src_sig_mask) << (dst_sig_bits - src_sig_bits); abs_result |= @as(u128, a_rep.exp) << dst_sig_bits; } else { // a is denormal // renormalize the significand and clear the leading bit and integer part, // then insert the correct adjusted exponent in the destination type. const scale: u32 = @clz(u64, a_rep.fraction); abs_result = @as(u128, a_rep.fraction) << @intCast(u7, dst_sig_bits - src_sig_bits + scale + 1); abs_result ^= dst_min_normal; abs_result |= @as(u128, scale + 1) << dst_sig_bits; } // Apply the signbit to (dst_t)abs(a). const result: u128 align(@alignOf(f128)) = abs_result | @as(u128, sign) << (dst_bits - 16); return @bitCast(f128, result); }
lib/std/special/compiler_rt/extend_f80.zig
const std = @import("../../std.zig"); const builtin = @import("builtin"); const mem = std.mem; const assert = std.debug.assert; const fs = std.fs; const elf = std.elf; const native_endian = builtin.cpu.arch.endian(); const NativeTargetInfo = @This(); const Target = std.Target; const Allocator = std.mem.Allocator; const CrossTarget = std.zig.CrossTarget; const windows = std.zig.system.windows; const darwin = std.zig.system.darwin; const linux = std.zig.system.linux; target: Target, dynamic_linker: DynamicLinker = DynamicLinker{}, pub const DynamicLinker = Target.DynamicLinker; pub const DetectError = error{ OutOfMemory, FileSystem, SystemResources, SymLinkLoop, ProcessFdQuotaExceeded, SystemFdQuotaExceeded, DeviceBusy, OSVersionDetectionFail, }; /// Given a `CrossTarget`, which specifies in detail which parts of the target should be detected /// natively, which should be standard or default, and which are provided explicitly, this function /// resolves the native components by detecting the native system, and then resolves standard/default parts /// relative to that. /// Any resources this function allocates are released before returning, and so there is no /// deinitialization method. /// TODO Remove the Allocator requirement from this function. pub fn detect(allocator: Allocator, cross_target: CrossTarget) DetectError!NativeTargetInfo { var os = cross_target.getOsTag().defaultVersionRange(cross_target.getCpuArch()); if (cross_target.os_tag == null) { switch (builtin.target.os.tag) { .linux => { const uts = std.os.uname(); const release = mem.sliceTo(&uts.release, 0); // The release field sometimes has a weird format, // `Version.parse` will attempt to find some meaningful interpretation. if (std.builtin.Version.parse(release)) |ver| { os.version_range.linux.range.min = ver; os.version_range.linux.range.max = ver; } else |err| switch (err) { error.Overflow => {}, error.InvalidCharacter => {}, error.InvalidVersion => {}, } }, .solaris => { const uts = std.os.uname(); const release = mem.sliceTo(&uts.release, 0); if (std.builtin.Version.parse(release)) |ver| { os.version_range.semver.min = ver; os.version_range.semver.max = ver; } else |err| switch (err) { error.Overflow => {}, error.InvalidCharacter => {}, error.InvalidVersion => {}, } }, .windows => { const detected_version = windows.detectRuntimeVersion(); os.version_range.windows.min = detected_version; os.version_range.windows.max = detected_version; }, .macos => try darwin.macos.detect(&os), .freebsd, .netbsd, .dragonfly => { const key = switch (builtin.target.os.tag) { .freebsd => "kern.osreldate", .netbsd, .dragonfly => "kern.osrevision", else => unreachable, }; var value: u32 = undefined; var len: usize = @sizeOf(@TypeOf(value)); std.os.sysctlbynameZ(key, &value, &len, null, 0) catch |err| switch (err) { error.NameTooLong => unreachable, // constant, known good value error.PermissionDenied => unreachable, // only when setting values, error.SystemResources => unreachable, // memory already on the stack error.UnknownName => unreachable, // constant, known good value error.Unexpected => return error.OSVersionDetectionFail, }; switch (builtin.target.os.tag) { .freebsd => { // https://www.freebsd.org/doc/en_US.ISO8859-1/books/porters-handbook/versions.html // Major * 100,000 has been convention since FreeBSD 2.2 (1997) // Minor * 1(0),000 summed has been convention since FreeBSD 2.2 (1997) // e.g. 492101 = 4.11-STABLE = 4.(9+2) const major = value / 100_000; const minor1 = value % 100_000 / 10_000; // usually 0 since 5.1 const minor2 = value % 10_000 / 1_000; // 0 before 5.1, minor version since const patch = value % 1_000; os.version_range.semver.min = .{ .major = major, .minor = minor1 + minor2, .patch = patch }; os.version_range.semver.max = os.version_range.semver.min; }, .netbsd => { // #define __NetBSD_Version__ MMmmrrpp00 // // M = major version // m = minor version; a minor number of 99 indicates current. // r = 0 (*) // p = patchlevel const major = value / 100_000_000; const minor = value % 100_000_000 / 1_000_000; const patch = value % 10_000 / 100; os.version_range.semver.min = .{ .major = major, .minor = minor, .patch = patch }; os.version_range.semver.max = os.version_range.semver.min; }, .dragonfly => { // https://github.com/DragonFlyBSD/DragonFlyBSD/blob/cb2cde83771754aeef9bb3251ee48959138dec87/Makefile.inc1#L15-L17 // flat base10 format: Mmmmpp // M = major // m = minor; odd-numbers indicate current dev branch // p = patch const major = value / 100_000; const minor = value % 100_000 / 100; const patch = value % 100; os.version_range.semver.min = .{ .major = major, .minor = minor, .patch = patch }; os.version_range.semver.max = os.version_range.semver.min; }, else => unreachable, } }, .openbsd => { const mib: [2]c_int = [_]c_int{ std.os.CTL.KERN, std.os.KERN.OSRELEASE, }; var buf: [64]u8 = undefined; var len: usize = buf.len; std.os.sysctl(&mib, &buf, &len, null, 0) catch |err| switch (err) { error.NameTooLong => unreachable, // constant, known good value error.PermissionDenied => unreachable, // only when setting values, error.SystemResources => unreachable, // memory already on the stack error.UnknownName => unreachable, // constant, known good value error.Unexpected => return error.OSVersionDetectionFail, }; if (std.builtin.Version.parse(buf[0 .. len - 1])) |ver| { os.version_range.semver.min = ver; os.version_range.semver.max = ver; } else |_| { return error.OSVersionDetectionFail; } }, else => { // Unimplemented, fall back to default version range. }, } } if (cross_target.os_version_min) |min| switch (min) { .none => {}, .semver => |semver| switch (cross_target.getOsTag()) { .linux => os.version_range.linux.range.min = semver, else => os.version_range.semver.min = semver, }, .windows => |win_ver| os.version_range.windows.min = win_ver, }; if (cross_target.os_version_max) |max| switch (max) { .none => {}, .semver => |semver| switch (cross_target.getOsTag()) { .linux => os.version_range.linux.range.max = semver, else => os.version_range.semver.max = semver, }, .windows => |win_ver| os.version_range.windows.max = win_ver, }; if (cross_target.glibc_version) |glibc| { assert(cross_target.isGnuLibC()); os.version_range.linux.glibc = glibc; } // Until https://github.com/ziglang/zig/issues/4592 is implemented (support detecting the // native CPU architecture as being different than the current target), we use this: const cpu_arch = cross_target.getCpuArch(); var cpu = switch (cross_target.cpu_model) { .native => detectNativeCpuAndFeatures(cpu_arch, os, cross_target), .baseline => Target.Cpu.baseline(cpu_arch), .determined_by_cpu_arch => if (cross_target.cpu_arch == null) detectNativeCpuAndFeatures(cpu_arch, os, cross_target) else Target.Cpu.baseline(cpu_arch), .explicit => |model| model.toCpu(cpu_arch), } orelse backup_cpu_detection: { break :backup_cpu_detection Target.Cpu.baseline(cpu_arch); }; var result = try detectAbiAndDynamicLinker(allocator, cpu, os, cross_target); // For x86, we need to populate some CPU feature flags depending on architecture // and mode: // * 16bit_mode => if the abi is code16 // * 32bit_mode => if the arch is i386 // However, the "mode" flags can be used as overrides, so if the user explicitly // sets one of them, that takes precedence. switch (cpu_arch) { .i386 => { if (!std.Target.x86.featureSetHasAny(cross_target.cpu_features_add, .{ .@"16bit_mode", .@"32bit_mode", })) { switch (result.target.abi) { .code16 => result.target.cpu.features.addFeature( @enumToInt(std.Target.x86.Feature.@"16bit_mode"), ), else => result.target.cpu.features.addFeature( @enumToInt(std.Target.x86.Feature.@"32bit_mode"), ), } } }, .arm, .armeb => { // XXX What do we do if the target has the noarm feature? // What do we do if the user specifies +thumb_mode? }, .thumb, .thumbeb => { result.target.cpu.features.addFeature( @enumToInt(std.Target.arm.Feature.thumb_mode), ); }, else => {}, } cross_target.updateCpuFeatures(&result.target.cpu.features); return result; } /// First we attempt to use the executable's own binary. If it is dynamically /// linked, then it should answer both the C ABI question and the dynamic linker question. /// If it is statically linked, then we try /usr/bin/env. If that does not provide the answer, then /// we fall back to the defaults. /// TODO Remove the Allocator requirement from this function. fn detectAbiAndDynamicLinker( allocator: Allocator, cpu: Target.Cpu, os: Target.Os, cross_target: CrossTarget, ) DetectError!NativeTargetInfo { const native_target_has_ld = comptime builtin.target.hasDynamicLinker(); const is_linux = builtin.target.os.tag == .linux; const have_all_info = cross_target.dynamic_linker.get() != null and cross_target.abi != null and (!is_linux or cross_target.abi.?.isGnu()); const os_is_non_native = cross_target.os_tag != null; if (!native_target_has_ld or have_all_info or os_is_non_native) { return defaultAbiAndDynamicLinker(cpu, os, cross_target); } if (cross_target.abi) |abi| { if (abi.isMusl()) { // musl implies static linking. return defaultAbiAndDynamicLinker(cpu, os, cross_target); } } // The current target's ABI cannot be relied on for this. For example, we may build the zig // compiler for target riscv64-linux-musl and provide a tarball for users to download. // A user could then run that zig compiler on riscv64-linux-gnu. This use case is well-defined // and supported by Zig. But that means that we must detect the system ABI here rather than // relying on `builtin.target`. const all_abis = comptime blk: { assert(@enumToInt(Target.Abi.none) == 0); const fields = std.meta.fields(Target.Abi)[1..]; var array: [fields.len]Target.Abi = undefined; inline for (fields) |field, i| { array[i] = @field(Target.Abi, field.name); } break :blk array; }; var ld_info_list_buffer: [all_abis.len]LdInfo = undefined; var ld_info_list_len: usize = 0; for (all_abis) |abi| { // This may be a nonsensical parameter. We detect this with error.UnknownDynamicLinkerPath and // skip adding it to `ld_info_list`. const target: Target = .{ .cpu = cpu, .os = os, .abi = abi, }; const ld = target.standardDynamicLinkerPath(); if (ld.get() == null) continue; ld_info_list_buffer[ld_info_list_len] = .{ .ld = ld, .abi = abi, }; ld_info_list_len += 1; } const ld_info_list = ld_info_list_buffer[0..ld_info_list_len]; // Best case scenario: the executable is dynamically linked, and we can iterate // over our own shared objects and find a dynamic linker. self_exe: { const lib_paths = try std.process.getSelfExeSharedLibPaths(allocator); defer { for (lib_paths) |lib_path| { allocator.free(lib_path); } allocator.free(lib_paths); } var found_ld_info: LdInfo = undefined; var found_ld_path: [:0]const u8 = undefined; // Look for dynamic linker. // This is O(N^M) but typical case here is N=2 and M=10. find_ld: for (lib_paths) |lib_path| { for (ld_info_list) |ld_info| { const standard_ld_basename = fs.path.basename(ld_info.ld.get().?); if (std.mem.endsWith(u8, lib_path, standard_ld_basename)) { found_ld_info = ld_info; found_ld_path = lib_path; break :find_ld; } } } else break :self_exe; // Look for glibc version. var os_adjusted = os; if (builtin.target.os.tag == .linux and found_ld_info.abi.isGnu() and cross_target.glibc_version == null) { for (lib_paths) |lib_path| { if (std.mem.endsWith(u8, lib_path, glibc_so_basename)) { os_adjusted.version_range.linux.glibc = glibcVerFromSO(lib_path) catch |err| switch (err) { error.UnrecognizedGnuLibCFileName => continue, error.InvalidGnuLibCVersion => continue, error.GnuLibCVersionUnavailable => continue, else => |e| return e, }; break; } } } var result: NativeTargetInfo = .{ .target = .{ .cpu = cpu, .os = os_adjusted, .abi = cross_target.abi orelse found_ld_info.abi, }, .dynamic_linker = if (cross_target.dynamic_linker.get() == null) DynamicLinker.init(found_ld_path) else cross_target.dynamic_linker, }; return result; } const env_file = std.fs.openFileAbsoluteZ("/usr/bin/env", .{}) catch |err| switch (err) { error.NoSpaceLeft => unreachable, error.NameTooLong => unreachable, error.PathAlreadyExists => unreachable, error.SharingViolation => unreachable, error.InvalidUtf8 => unreachable, error.BadPathName => unreachable, error.PipeBusy => unreachable, error.FileLocksNotSupported => unreachable, error.WouldBlock => unreachable, error.FileBusy => unreachable, // opened without write permissions error.IsDir, error.NotDir, error.InvalidHandle, error.AccessDenied, error.NoDevice, error.FileNotFound, error.FileTooBig, error.Unexpected, => return defaultAbiAndDynamicLinker(cpu, os, cross_target), else => |e| return e, }; defer env_file.close(); // If Zig is statically linked, such as via distributed binary static builds, the above // trick won't work. The next thing we fall back to is the same thing, but for /usr/bin/env. // Since that path is hard-coded into the shebang line of many portable scripts, it's a // reasonably reliable path to check for. return abiAndDynamicLinkerFromFile(env_file, cpu, os, ld_info_list, cross_target) catch |err| switch (err) { error.FileSystem, error.SystemResources, error.SymLinkLoop, error.ProcessFdQuotaExceeded, error.SystemFdQuotaExceeded, => |e| return e, error.UnableToReadElfFile, error.InvalidElfClass, error.InvalidElfVersion, error.InvalidElfEndian, error.InvalidElfFile, error.InvalidElfMagic, error.Unexpected, error.UnexpectedEndOfFile, error.NameTooLong, // Finally, we fall back on the standard path. => defaultAbiAndDynamicLinker(cpu, os, cross_target), }; } const glibc_so_basename = "libc.so.6"; fn glibcVerFromSO(so_path: [:0]const u8) !std.builtin.Version { var link_buf: [std.os.PATH_MAX]u8 = undefined; const link_name = std.os.readlinkZ(so_path.ptr, &link_buf) catch |err| switch (err) { error.AccessDenied => return error.GnuLibCVersionUnavailable, error.FileSystem => return error.FileSystem, error.SymLinkLoop => return error.SymLinkLoop, error.NameTooLong => unreachable, error.NotLink => return error.GnuLibCVersionUnavailable, error.FileNotFound => return error.GnuLibCVersionUnavailable, error.SystemResources => return error.SystemResources, error.NotDir => return error.GnuLibCVersionUnavailable, error.Unexpected => return error.GnuLibCVersionUnavailable, error.InvalidUtf8 => unreachable, // Windows only error.BadPathName => unreachable, // Windows only error.UnsupportedReparsePointType => unreachable, // Windows only }; return glibcVerFromLinkName(link_name, "libc-"); } fn glibcVerFromLinkName(link_name: []const u8, prefix: []const u8) !std.builtin.Version { // example: "libc-2.3.4.so" // example: "libc-2.27.so" // example: "ld-2.33.so" const suffix = ".so"; if (!mem.startsWith(u8, link_name, prefix) or !mem.endsWith(u8, link_name, suffix)) { return error.UnrecognizedGnuLibCFileName; } // chop off "libc-" and ".so" const link_name_chopped = link_name[prefix.len .. link_name.len - suffix.len]; return std.builtin.Version.parse(link_name_chopped) catch |err| switch (err) { error.Overflow => return error.InvalidGnuLibCVersion, error.InvalidCharacter => return error.InvalidGnuLibCVersion, error.InvalidVersion => return error.InvalidGnuLibCVersion, }; } pub const AbiAndDynamicLinkerFromFileError = error{ FileSystem, SystemResources, SymLinkLoop, ProcessFdQuotaExceeded, SystemFdQuotaExceeded, UnableToReadElfFile, InvalidElfClass, InvalidElfVersion, InvalidElfEndian, InvalidElfFile, InvalidElfMagic, Unexpected, UnexpectedEndOfFile, NameTooLong, }; pub fn abiAndDynamicLinkerFromFile( file: fs.File, cpu: Target.Cpu, os: Target.Os, ld_info_list: []const LdInfo, cross_target: CrossTarget, ) AbiAndDynamicLinkerFromFileError!NativeTargetInfo { var hdr_buf: [@sizeOf(elf.Elf64_Ehdr)]u8 align(@alignOf(elf.Elf64_Ehdr)) = undefined; _ = try preadMin(file, &hdr_buf, 0, hdr_buf.len); const hdr32 = @ptrCast(*elf.Elf32_Ehdr, &hdr_buf); const hdr64 = @ptrCast(*elf.Elf64_Ehdr, &hdr_buf); if (!mem.eql(u8, hdr32.e_ident[0..4], elf.MAGIC)) return error.InvalidElfMagic; const elf_endian: std.builtin.Endian = switch (hdr32.e_ident[elf.EI_DATA]) { elf.ELFDATA2LSB => .Little, elf.ELFDATA2MSB => .Big, else => return error.InvalidElfEndian, }; const need_bswap = elf_endian != native_endian; if (hdr32.e_ident[elf.EI_VERSION] != 1) return error.InvalidElfVersion; const is_64 = switch (hdr32.e_ident[elf.EI_CLASS]) { elf.ELFCLASS32 => false, elf.ELFCLASS64 => true, else => return error.InvalidElfClass, }; var phoff = elfInt(is_64, need_bswap, hdr32.e_phoff, hdr64.e_phoff); const phentsize = elfInt(is_64, need_bswap, hdr32.e_phentsize, hdr64.e_phentsize); const phnum = elfInt(is_64, need_bswap, hdr32.e_phnum, hdr64.e_phnum); var result: NativeTargetInfo = .{ .target = .{ .cpu = cpu, .os = os, .abi = cross_target.abi orelse Target.Abi.default(cpu.arch, os), }, .dynamic_linker = cross_target.dynamic_linker, }; var rpath_offset: ?u64 = null; // Found inside PT_DYNAMIC const look_for_ld = cross_target.dynamic_linker.get() == null; var ph_buf: [16 * @sizeOf(elf.Elf64_Phdr)]u8 align(@alignOf(elf.Elf64_Phdr)) = undefined; if (phentsize > @sizeOf(elf.Elf64_Phdr)) return error.InvalidElfFile; var ph_i: u16 = 0; while (ph_i < phnum) { // Reserve some bytes so that we can deref the 64-bit struct fields // even when the ELF file is 32-bits. const ph_reserve: usize = @sizeOf(elf.Elf64_Phdr) - @sizeOf(elf.Elf32_Phdr); const ph_read_byte_len = try preadMin(file, ph_buf[0 .. ph_buf.len - ph_reserve], phoff, phentsize); var ph_buf_i: usize = 0; while (ph_buf_i < ph_read_byte_len and ph_i < phnum) : ({ ph_i += 1; phoff += phentsize; ph_buf_i += phentsize; }) { const ph32 = @ptrCast(*elf.Elf32_Phdr, @alignCast(@alignOf(elf.Elf32_Phdr), &ph_buf[ph_buf_i])); const ph64 = @ptrCast(*elf.Elf64_Phdr, @alignCast(@alignOf(elf.Elf64_Phdr), &ph_buf[ph_buf_i])); const p_type = elfInt(is_64, need_bswap, ph32.p_type, ph64.p_type); switch (p_type) { elf.PT_INTERP => if (look_for_ld) { const p_offset = elfInt(is_64, need_bswap, ph32.p_offset, ph64.p_offset); const p_filesz = elfInt(is_64, need_bswap, ph32.p_filesz, ph64.p_filesz); if (p_filesz > result.dynamic_linker.buffer.len) return error.NameTooLong; const filesz = @intCast(usize, p_filesz); _ = try preadMin(file, result.dynamic_linker.buffer[0..filesz], p_offset, filesz); // PT_INTERP includes a null byte in filesz. const len = filesz - 1; // dynamic_linker.max_byte is "max", not "len". // We know it will fit in u8 because we check against dynamic_linker.buffer.len above. result.dynamic_linker.max_byte = @intCast(u8, len - 1); // Use it to determine ABI. const full_ld_path = result.dynamic_linker.buffer[0..len]; for (ld_info_list) |ld_info| { const standard_ld_basename = fs.path.basename(ld_info.ld.get().?); if (std.mem.endsWith(u8, full_ld_path, standard_ld_basename)) { result.target.abi = ld_info.abi; break; } } }, // We only need this for detecting glibc version. elf.PT_DYNAMIC => if (builtin.target.os.tag == .linux and result.target.isGnuLibC() and cross_target.glibc_version == null) { var dyn_off = elfInt(is_64, need_bswap, ph32.p_offset, ph64.p_offset); const p_filesz = elfInt(is_64, need_bswap, ph32.p_filesz, ph64.p_filesz); const dyn_size: usize = if (is_64) @sizeOf(elf.Elf64_Dyn) else @sizeOf(elf.Elf32_Dyn); const dyn_num = p_filesz / dyn_size; var dyn_buf: [16 * @sizeOf(elf.Elf64_Dyn)]u8 align(@alignOf(elf.Elf64_Dyn)) = undefined; var dyn_i: usize = 0; dyn: while (dyn_i < dyn_num) { // Reserve some bytes so that we can deref the 64-bit struct fields // even when the ELF file is 32-bits. const dyn_reserve: usize = @sizeOf(elf.Elf64_Dyn) - @sizeOf(elf.Elf32_Dyn); const dyn_read_byte_len = try preadMin( file, dyn_buf[0 .. dyn_buf.len - dyn_reserve], dyn_off, dyn_size, ); var dyn_buf_i: usize = 0; while (dyn_buf_i < dyn_read_byte_len and dyn_i < dyn_num) : ({ dyn_i += 1; dyn_off += dyn_size; dyn_buf_i += dyn_size; }) { const dyn32 = @ptrCast( *elf.Elf32_Dyn, @alignCast(@alignOf(elf.Elf32_Dyn), &dyn_buf[dyn_buf_i]), ); const dyn64 = @ptrCast( *elf.Elf64_Dyn, @alignCast(@alignOf(elf.Elf64_Dyn), &dyn_buf[dyn_buf_i]), ); const tag = elfInt(is_64, need_bswap, dyn32.d_tag, dyn64.d_tag); const val = elfInt(is_64, need_bswap, dyn32.d_val, dyn64.d_val); if (tag == elf.DT_RUNPATH) { rpath_offset = val; break :dyn; } } } }, else => continue, } } } if (builtin.target.os.tag == .linux and result.target.isGnuLibC() and cross_target.glibc_version == null) { if (rpath_offset) |rpoff| { const shstrndx = elfInt(is_64, need_bswap, hdr32.e_shstrndx, hdr64.e_shstrndx); var shoff = elfInt(is_64, need_bswap, hdr32.e_shoff, hdr64.e_shoff); const shentsize = elfInt(is_64, need_bswap, hdr32.e_shentsize, hdr64.e_shentsize); const str_section_off = shoff + @as(u64, shentsize) * @as(u64, shstrndx); var sh_buf: [16 * @sizeOf(elf.Elf64_Shdr)]u8 align(@alignOf(elf.Elf64_Shdr)) = undefined; if (sh_buf.len < shentsize) return error.InvalidElfFile; _ = try preadMin(file, &sh_buf, str_section_off, shentsize); const shstr32 = @ptrCast(*elf.Elf32_Shdr, @alignCast(@alignOf(elf.Elf32_Shdr), &sh_buf)); const shstr64 = @ptrCast(*elf.Elf64_Shdr, @alignCast(@alignOf(elf.Elf64_Shdr), &sh_buf)); const shstrtab_off = elfInt(is_64, need_bswap, shstr32.sh_offset, shstr64.sh_offset); const shstrtab_size = elfInt(is_64, need_bswap, shstr32.sh_size, shstr64.sh_size); var strtab_buf: [4096:0]u8 = undefined; const shstrtab_len = std.math.min(shstrtab_size, strtab_buf.len); const shstrtab_read_len = try preadMin(file, &strtab_buf, shstrtab_off, shstrtab_len); const shstrtab = strtab_buf[0..shstrtab_read_len]; const shnum = elfInt(is_64, need_bswap, hdr32.e_shnum, hdr64.e_shnum); var sh_i: u16 = 0; const dynstr: ?struct { offset: u64, size: u64 } = find_dyn_str: while (sh_i < shnum) { // Reserve some bytes so that we can deref the 64-bit struct fields // even when the ELF file is 32-bits. const sh_reserve: usize = @sizeOf(elf.Elf64_Shdr) - @sizeOf(elf.Elf32_Shdr); const sh_read_byte_len = try preadMin( file, sh_buf[0 .. sh_buf.len - sh_reserve], shoff, shentsize, ); var sh_buf_i: usize = 0; while (sh_buf_i < sh_read_byte_len and sh_i < shnum) : ({ sh_i += 1; shoff += shentsize; sh_buf_i += shentsize; }) { const sh32 = @ptrCast( *elf.Elf32_Shdr, @alignCast(@alignOf(elf.Elf32_Shdr), &sh_buf[sh_buf_i]), ); const sh64 = @ptrCast( *elf.Elf64_Shdr, @alignCast(@alignOf(elf.Elf64_Shdr), &sh_buf[sh_buf_i]), ); const sh_name_off = elfInt(is_64, need_bswap, sh32.sh_name, sh64.sh_name); // TODO this pointer cast should not be necessary const sh_name = mem.sliceTo(std.meta.assumeSentinel(shstrtab[sh_name_off..].ptr, 0), 0); if (mem.eql(u8, sh_name, ".dynstr")) { break :find_dyn_str .{ .offset = elfInt(is_64, need_bswap, sh32.sh_offset, sh64.sh_offset), .size = elfInt(is_64, need_bswap, sh32.sh_size, sh64.sh_size), }; } } } else null; if (dynstr) |ds| { const strtab_len = std.math.min(ds.size, strtab_buf.len); const strtab_read_len = try preadMin(file, &strtab_buf, ds.offset, strtab_len); const strtab = strtab_buf[0..strtab_read_len]; // TODO this pointer cast should not be necessary const rpoff_usize = std.math.cast(usize, rpoff) orelse return error.InvalidElfFile; const rpath_list = mem.sliceTo(std.meta.assumeSentinel(strtab[rpoff_usize..].ptr, 0), 0); var it = mem.tokenize(u8, rpath_list, ":"); while (it.next()) |rpath| { var dir = fs.cwd().openDir(rpath, .{}) catch |err| switch (err) { error.NameTooLong => unreachable, error.InvalidUtf8 => unreachable, error.BadPathName => unreachable, error.DeviceBusy => unreachable, error.FileNotFound, error.NotDir, error.InvalidHandle, error.AccessDenied, error.NoDevice, => continue, error.ProcessFdQuotaExceeded, error.SystemFdQuotaExceeded, error.SystemResources, error.SymLinkLoop, error.Unexpected, => |e| return e, }; defer dir.close(); var link_buf: [std.os.PATH_MAX]u8 = undefined; const link_name = std.os.readlinkatZ( dir.fd, glibc_so_basename, &link_buf, ) catch |err| switch (err) { error.NameTooLong => unreachable, error.InvalidUtf8 => unreachable, // Windows only error.BadPathName => unreachable, // Windows only error.UnsupportedReparsePointType => unreachable, // Windows only error.AccessDenied, error.FileNotFound, error.NotLink, error.NotDir, => continue, error.SystemResources, error.FileSystem, error.SymLinkLoop, error.Unexpected, => |e| return e, }; result.target.os.version_range.linux.glibc = glibcVerFromLinkName( link_name, "libc-", ) catch |err| switch (err) { error.UnrecognizedGnuLibCFileName, error.InvalidGnuLibCVersion, => continue, }; break; } } } else if (result.dynamic_linker.get()) |dl_path| glibc_ver: { // There is no DT_RUNPATH but we can try to see if the information is // present in the symlink data for the dynamic linker path. var link_buf: [std.os.PATH_MAX]u8 = undefined; const link_name = std.os.readlink(dl_path, &link_buf) catch |err| switch (err) { error.NameTooLong => unreachable, error.InvalidUtf8 => unreachable, // Windows only error.BadPathName => unreachable, // Windows only error.UnsupportedReparsePointType => unreachable, // Windows only error.AccessDenied, error.FileNotFound, error.NotLink, error.NotDir, => break :glibc_ver, error.SystemResources, error.FileSystem, error.SymLinkLoop, error.Unexpected, => |e| return e, }; result.target.os.version_range.linux.glibc = glibcVerFromLinkName( fs.path.basename(link_name), "ld-", ) catch |err| switch (err) { error.UnrecognizedGnuLibCFileName, error.InvalidGnuLibCVersion, => break :glibc_ver, }; } } return result; } fn preadMin(file: fs.File, buf: []u8, offset: u64, min_read_len: usize) !usize { var i: usize = 0; while (i < min_read_len) { const len = file.pread(buf[i..], offset + i) catch |err| switch (err) { error.OperationAborted => unreachable, // Windows-only error.WouldBlock => unreachable, // Did not request blocking mode error.NotOpenForReading => unreachable, error.SystemResources => return error.SystemResources, error.IsDir => return error.UnableToReadElfFile, error.BrokenPipe => return error.UnableToReadElfFile, error.Unseekable => return error.UnableToReadElfFile, error.ConnectionResetByPeer => return error.UnableToReadElfFile, error.ConnectionTimedOut => return error.UnableToReadElfFile, error.Unexpected => return error.Unexpected, error.InputOutput => return error.FileSystem, error.AccessDenied => return error.Unexpected, }; if (len == 0) return error.UnexpectedEndOfFile; i += len; } return i; } fn defaultAbiAndDynamicLinker(cpu: Target.Cpu, os: Target.Os, cross_target: CrossTarget) !NativeTargetInfo { const target: Target = .{ .cpu = cpu, .os = os, .abi = cross_target.abi orelse Target.Abi.default(cpu.arch, os), }; return NativeTargetInfo{ .target = target, .dynamic_linker = if (cross_target.dynamic_linker.get() == null) target.standardDynamicLinkerPath() else cross_target.dynamic_linker, }; } pub const LdInfo = struct { ld: DynamicLinker, abi: Target.Abi, }; pub fn elfInt(is_64: bool, need_bswap: bool, int_32: anytype, int_64: anytype) @TypeOf(int_64) { if (is_64) { if (need_bswap) { return @byteSwap(@TypeOf(int_64), int_64); } else { return int_64; } } else { if (need_bswap) { return @byteSwap(@TypeOf(int_32), int_32); } else { return int_32; } } } fn detectNativeCpuAndFeatures(cpu_arch: Target.Cpu.Arch, os: Target.Os, cross_target: CrossTarget) ?Target.Cpu { // Here we switch on a comptime value rather than `cpu_arch`. This is valid because `cpu_arch`, // although it is a runtime value, is guaranteed to be one of the architectures in the set // of the respective switch prong. switch (builtin.cpu.arch) { .x86_64, .i386 => { return @import("x86.zig").detectNativeCpuAndFeatures(cpu_arch, os, cross_target); }, else => {}, } switch (builtin.os.tag) { .linux => return linux.detectNativeCpuAndFeatures(), .macos => return darwin.macos.detectNativeCpuAndFeatures(), else => {}, } // This architecture does not have CPU model & feature detection yet. // See https://github.com/ziglang/zig/issues/4591 return null; } pub const Executor = union(enum) { native, rosetta, qemu: []const u8, wine: []const u8, wasmtime: []const u8, darling: []const u8, bad_dl: []const u8, bad_os_or_cpu, }; pub const GetExternalExecutorOptions = struct { allow_darling: bool = true, allow_qemu: bool = true, allow_rosetta: bool = true, allow_wasmtime: bool = true, allow_wine: bool = true, qemu_fixes_dl: bool = false, link_libc: bool = false, }; /// Return whether or not the given host target is capable of executing natively executables /// of the other target. pub fn getExternalExecutor( host: NativeTargetInfo, candidate: NativeTargetInfo, options: GetExternalExecutorOptions, ) Executor { const os_match = host.target.os.tag == candidate.target.os.tag; const cpu_ok = cpu_ok: { if (host.target.cpu.arch == candidate.target.cpu.arch) break :cpu_ok true; if (host.target.cpu.arch == .x86_64 and candidate.target.cpu.arch == .i386) break :cpu_ok true; if (host.target.cpu.arch == .aarch64 and candidate.target.cpu.arch == .arm) break :cpu_ok true; if (host.target.cpu.arch == .aarch64_be and candidate.target.cpu.arch == .armeb) break :cpu_ok true; // TODO additionally detect incompatible CPU features. // Note that in some cases the OS kernel will emulate missing CPU features // when an illegal instruction is encountered. break :cpu_ok false; }; var bad_result: Executor = .bad_os_or_cpu; if (os_match and cpu_ok) native: { if (options.link_libc) { if (candidate.dynamic_linker.get()) |candidate_dl| { fs.cwd().access(candidate_dl, .{}) catch { bad_result = .{ .bad_dl = candidate_dl }; break :native; }; } } return .native; } // If the OS match and OS is macOS and CPU is arm64, we can use Rosetta 2 // to emulate the foreign architecture. if (options.allow_rosetta and os_match and host.target.os.tag == .macos and host.target.cpu.arch == .aarch64) { switch (candidate.target.cpu.arch) { .x86_64 => return .rosetta, else => return bad_result, } } // If the OS matches, we can use QEMU to emulate a foreign architecture. if (options.allow_qemu and os_match and (!cpu_ok or options.qemu_fixes_dl)) { return switch (candidate.target.cpu.arch) { .aarch64 => Executor{ .qemu = "qemu-aarch64" }, .aarch64_be => Executor{ .qemu = "qemu-aarch64_be" }, .arm => Executor{ .qemu = "qemu-arm" }, .armeb => Executor{ .qemu = "qemu-armeb" }, .hexagon => Executor{ .qemu = "qemu-hexagon" }, .i386 => Executor{ .qemu = "qemu-i386" }, .m68k => Executor{ .qemu = "qemu-m68k" }, .mips => Executor{ .qemu = "qemu-mips" }, .mipsel => Executor{ .qemu = "qemu-mipsel" }, .mips64 => Executor{ .qemu = "qemu-mips64" }, .mips64el => Executor{ .qemu = "qemu-mips64el" }, .powerpc => Executor{ .qemu = "qemu-ppc" }, .powerpc64 => Executor{ .qemu = "qemu-ppc64" }, .powerpc64le => Executor{ .qemu = "qemu-ppc64le" }, .riscv32 => Executor{ .qemu = "qemu-riscv32" }, .riscv64 => Executor{ .qemu = "qemu-riscv64" }, .s390x => Executor{ .qemu = "qemu-s390x" }, .sparc => Executor{ .qemu = "qemu-sparc" }, .sparc64 => Executor{ .qemu = "qemu-sparc64" }, .x86_64 => Executor{ .qemu = "qemu-x86_64" }, else => return bad_result, }; } switch (candidate.target.os.tag) { .windows => { if (options.allow_wine) { switch (candidate.target.cpu.arch.ptrBitWidth()) { 32 => return Executor{ .wine = "wine" }, 64 => return Executor{ .wine = "wine64" }, else => return bad_result, } } return bad_result; }, .wasi => { if (options.allow_wasmtime) { switch (candidate.target.cpu.arch.ptrBitWidth()) { 32 => return Executor{ .wasmtime = "wasmtime" }, else => return bad_result, } } return bad_result; }, .macos => { if (options.allow_darling) { // This check can be loosened once darling adds a QEMU-based emulation // layer for non-host architectures: // https://github.com/darlinghq/darling/issues/863 if (candidate.target.cpu.arch != builtin.cpu.arch) { return bad_result; } return Executor{ .darling = "darling" }; } return bad_result; }, else => return bad_result, } }
lib/std/zig/system/NativeTargetInfo.zig
const std = @import("std"); const Type = @import("typeset.zig").Type; const TypeSet = @import("typeset.zig").TypeSet; /// A scope structure that can be used to manage variable /// allocation with different scopes (global, local). pub const Scope = struct { const Self = @This(); const Variable = struct { /// This is the offset of the variables name: []const u8, storage_slot: u16, type: enum { local, global }, possible_types: TypeSet = TypeSet.any, is_const: bool, }; arena: std.heap.ArenaAllocator, local_variables: std.ArrayList(Variable), global_variables: std.ArrayList(Variable), return_point: std.ArrayList(usize), /// When this is true, the scope will declare /// top-level variables as `global`, otherwise as `local`. is_global: bool, /// When this is non-null, the scope will use this as a fallback /// in `get` and will pass the query to this value. /// Note: It is not allowed that `global_scope` will return a `local` variable then! global_scope: ?*Self, /// The highest number of local variables that were declared at a point in this scope. max_locals: usize = 0, /// Creates a new scope. /// `global_scope` is a reference towards a scope that will provide references to a encasing scope. /// This scope must only provide `global` variables. pub fn init(allocator: std.mem.Allocator, global_scope: ?*Self, is_global: bool) Self { return Self{ .arena = std.heap.ArenaAllocator.init(allocator), .local_variables = std.ArrayList(Variable).init(allocator), .global_variables = std.ArrayList(Variable).init(allocator), .return_point = std.ArrayList(usize).init(allocator), .is_global = is_global, .global_scope = global_scope, }; } pub fn deinit(self: *Self) void { self.local_variables.deinit(); self.global_variables.deinit(); self.return_point.deinit(); self.arena.deinit(); self.* = undefined; } /// Enters a sub-scope. This is usually called at the start of a block. /// Sub-scopes are a set of variables that are only valid in a smaller /// portion of the code. /// This will push a return point to which later must be returned by /// calling `leave`. pub fn enter(self: *Self) !void { try self.return_point.append(self.local_variables.items.len); } /// Leaves a sub-scope. This is usually called at the end of a block. pub fn leave(self: *Self) !void { self.local_variables.shrinkRetainingCapacity(self.return_point.pop()); } /// Declares are new variable. pub fn declare(self: *Self, name: []const u8, is_const: bool) !void { if (self.is_global and (self.return_point.items.len == 0)) { // a variable is only global when the scope is a global scope and // we don't have any sub-scopes open (which would create temporary variables) for (self.global_variables.items) |variable| { if (std.mem.eql(u8, variable.name, name)) { // Global variables are not allowed to return error.AlreadyDeclared; } } if (self.global_variables.items.len == std.math.maxInt(u16)) return error.TooManyVariables; try self.global_variables.append(Variable{ .storage_slot = @intCast(u16, self.global_variables.items.len), .name = try self.arena.allocator().dupe(u8, name), .type = .global, .is_const = is_const, }); } else { if (self.local_variables.items.len == std.math.maxInt(u16)) return error.TooManyVariables; try self.local_variables.append(Variable{ .storage_slot = @intCast(u16, self.local_variables.items.len), .name = try self.arena.allocator().dupe(u8, name), .type = .local, .is_const = is_const, }); self.max_locals = std.math.max(self.max_locals, self.local_variables.items.len); } } /// Tries to return a variable named `name`. This will first search in the /// local variables, then in the global ones. /// Will return `null` when a variable is not found. pub fn get(self: Self, name: []const u8) ?*Variable { var i: usize = undefined; // First, search all local variables back-to-front: // This allows trivial shadowing as variables will be searched // in reverse declaration order. i = self.local_variables.items.len; while (i > 0) { i -= 1; const variable = &self.local_variables.items[i]; if (std.mem.eql(u8, variable.name, name)) return variable; } if (self.is_global) { // The same goes for global variables i = self.global_variables.items.len; while (i > 0) { i -= 1; const variable = &self.global_variables.items[i]; if (std.mem.eql(u8, variable.name, name)) return variable; } } if (self.global_scope) |globals| { const global = globals.get(name); // The global scope is not allowed to supply local variables to us. If this happens, // a programming error was done. std.debug.assert(global == null or global.?.type != .local); return global; } return null; } }; test "scope init/deinit" { var scope = Scope.init(std.testing.allocator, null, false); defer scope.deinit(); } test "scope declare/get" { var scope = Scope.init(std.testing.allocator, null, true); defer scope.deinit(); try scope.declare("foo", true); try std.testing.expectError(error.AlreadyDeclared, scope.declare("foo", true)); try scope.enter(); try scope.declare("bar", true); try std.testing.expect(scope.get("foo").?.type == .global); try std.testing.expect(scope.get("bar").?.type == .local); try std.testing.expect(scope.get("bam") == null); try scope.leave(); try std.testing.expect(scope.get("foo").?.type == .global); try std.testing.expect(scope.get("bar") == null); try std.testing.expect(scope.get("bam") == null); } test "variable allocation" { var scope = Scope.init(std.testing.allocator, null, true); defer scope.deinit(); try scope.declare("foo", true); try scope.declare("bar", true); try scope.declare("bam", true); try std.testing.expect(scope.get("foo").?.storage_slot == 0); try std.testing.expect(scope.get("bar").?.storage_slot == 1); try std.testing.expect(scope.get("bam").?.storage_slot == 2); try scope.enter(); try scope.declare("foo", true); try scope.enter(); try scope.declare("bar", true); try scope.declare("bam", true); try std.testing.expect(scope.get("foo").?.storage_slot == 0); try std.testing.expect(scope.get("bar").?.storage_slot == 1); try std.testing.expect(scope.get("bam").?.storage_slot == 2); try std.testing.expect(scope.get("foo").?.type == .local); try std.testing.expect(scope.get("bar").?.type == .local); try std.testing.expect(scope.get("bam").?.type == .local); try scope.leave(); try std.testing.expect(scope.get("foo").?.type == .local); try std.testing.expect(scope.get("bar").?.type == .global); try std.testing.expect(scope.get("bam").?.type == .global); try scope.leave(); try std.testing.expect(scope.get("foo").?.type == .global); try std.testing.expect(scope.get("bar").?.type == .global); try std.testing.expect(scope.get("bam").?.type == .global); }
src/library/compiler/scope.zig
const std = @import("std"); const assert = std.debug.assert; const mem = std.mem; const server = &@import("../main.zig").server; const util = @import("../util.zig"); const View = @import("../View.zig"); const ViewStack = @import("view_stack.zig").ViewStack; const Error = @import("../command.zig").Error; const Seat = @import("../Seat.zig"); const FilterKind = enum { @"app-id", title, }; pub fn floatFilterAdd( allocator: *mem.Allocator, seat: *Seat, args: []const [:0]const u8, out: *?[]const u8, ) Error!void { if (args.len < 3) return Error.NotEnoughArguments; if (args.len > 3) return Error.TooManyArguments; const kind = std.meta.stringToEnum(FilterKind, args[1]) orelse return Error.UnknownOption; const map = switch (kind) { .@"app-id" => &server.config.float_filter_app_ids, .title => &server.config.float_filter_titles, }; const key = args[2]; const gop = try map.getOrPut(util.gpa, key); if (gop.found_existing) return; errdefer assert(map.remove(key)); gop.key_ptr.* = try std.mem.dupe(util.gpa, u8, key); } pub fn floatFilterRemove( allocator: *mem.Allocator, seat: *Seat, args: []const [:0]const u8, out: *?[]const u8, ) Error!void { if (args.len < 3) return Error.NotEnoughArguments; if (args.len > 3) return Error.TooManyArguments; const kind = std.meta.stringToEnum(FilterKind, args[1]) orelse return Error.UnknownOption; const map = switch (kind) { .@"app-id" => &server.config.float_filter_app_ids, .title => &server.config.float_filter_titles, }; const key = args[2]; if (map.fetchRemove(key)) |kv| util.gpa.free(kv.key); } pub fn csdFilterAdd( allocator: *mem.Allocator, seat: *Seat, args: []const [:0]const u8, out: *?[]const u8, ) Error!void { if (args.len < 3) return Error.NotEnoughArguments; if (args.len > 3) return Error.TooManyArguments; const kind = std.meta.stringToEnum(FilterKind, args[1]) orelse return Error.UnknownOption; const map = switch (kind) { .@"app-id" => &server.config.csd_filter_app_ids, .title => &server.config.csd_filter_titles, }; const key = args[2]; const gop = try map.getOrPut(util.gpa, key); if (gop.found_existing) return; errdefer assert(map.remove(key)); gop.key_ptr.* = try std.mem.dupe(util.gpa, u8, key); csdFilterUpdateViews(kind, key, .add); } pub fn csdFilterRemove( allocator: *mem.Allocator, seat: *Seat, args: []const [:0]const u8, out: *?[]const u8, ) Error!void { if (args.len < 3) return Error.NotEnoughArguments; if (args.len > 3) return Error.TooManyArguments; const kind = std.meta.stringToEnum(FilterKind, args[1]) orelse return Error.UnknownOption; const map = switch (kind) { .@"app-id" => &server.config.csd_filter_app_ids, .title => &server.config.csd_filter_titles, }; const key = args[2]; if (map.fetchRemove(key)) |kv| { util.gpa.free(kv.key); csdFilterUpdateViews(kind, key, .remove); } } fn csdFilterUpdateViews(kind: FilterKind, pattern: []const u8, operation: enum { add, remove }) void { var decoration_it = server.decoration_manager.decorations.first; while (decoration_it) |decoration_node| : (decoration_it = decoration_node.next) { const xdg_toplevel_decoration = decoration_node.data.xdg_toplevel_decoration; const view = @intToPtr(*View, xdg_toplevel_decoration.surface.data); if (viewMatchesPattern(kind, pattern, view)) { const toplevel = view.impl.xdg_toplevel.xdg_surface.role_data.toplevel; switch (operation) { .add => { _ = xdg_toplevel_decoration.setMode(.client_side); view.draw_borders = false; _ = toplevel.setTiled(.{ .top = false, .bottom = false, .left = false, .right = false }); }, .remove => { _ = xdg_toplevel_decoration.setMode(.server_side); view.draw_borders = true; _ = toplevel.setTiled(.{ .top = true, .bottom = true, .left = true, .right = true }); }, } } } } fn viewMatchesPattern(kind: FilterKind, pattern: []const u8, view: *View) bool { const p = switch (kind) { .@"app-id" => mem.span(view.getAppId()), .title => mem.span(view.getTitle()), } orelse return false; return mem.eql(u8, pattern, p); }
source/river-0.1.0/river/command/filter.zig
const x86_64 = @import("../../index.zig"); const bitjuggle = @import("bitjuggle"); const std = @import("std"); const formatWithoutFields = @import("../../common.zig").formatWithoutFields; const PageSize = x86_64.structures.paging.PageSize; /// The number of entries in a page table. pub const PAGE_TABLE_ENTRY_COUNT: usize = 512; /// The error returned by the `PageTableEntry::frame` method. pub const FrameError = error{ /// The entry does not have the `present` flag set, so it isn't currently mapped to a frame. FrameNotPresent, /// The entry does have the `huge_page` flag set. The `frame` method has a standard 4KiB frame /// as return type, so a huge frame can't be returned. HugeFrame, }; /// A 64-bit page table entry. pub const PageTableEntry = packed struct { entry: u64, /// Creates an unused page table entry. pub fn init() PageTableEntry { return .{ .entry = 0 }; } /// Returns whether this entry is zero. pub fn isUnused(self: PageTableEntry) bool { return self.entry == 0; } /// Sets this entry to zero. pub fn setUnused(self: *PageTableEntry) void { self.entry = 0; } /// Returns the flags of this entry. pub fn getFlags(self: PageTableEntry) PageTableFlags { return PageTableFlags.fromU64(self.entry); } /// Returns the physical address mapped by this entry, might be zero. pub fn getAddr(self: PageTableEntry) x86_64.PhysAddr { // Unchecked is used as the mask ensures validity return x86_64.PhysAddr.initUnchecked(self.entry & 0x000f_ffff_ffff_f000); } /// Returns the physical frame mapped by this entry. /// /// Returns the following errors: /// /// - `FrameError::FrameNotPresent` if the entry doesn't have the `present` flag set. /// - `FrameError::HugeFrame` if the entry has the `huge_page` flag set (for huge pages the /// `addr` function must be used) pub fn getFrame(self: PageTableEntry) FrameError!x86_64.structures.paging.PhysFrame { const flags = self.getFlags(); if (!flags.present) { return FrameError.FrameNotPresent; } if (flags.huge) { return FrameError.HugeFrame; } return x86_64.structures.paging.PhysFrame.containingAddress(self.getAddr()); } /// Map the entry to the specified physical address pub fn setAddr(self: *PageTableEntry, addr: x86_64.PhysAddr) void { std.debug.assert(addr.isAligned(PageSize.Size4KiB.bytes())); self.entry = addr.value | self.getFlags().toU64(); } /// Map the entry to the specified physical frame with the specified flags. pub fn setFrame(self: *PageTableEntry, frame: x86_64.structures.paging.PhysFrame, flags: PageTableFlags) void { std.debug.assert(!self.getFlags().huge); self.setAddr(frame.start_address); self.setFlags(flags); } /// Sets the flags of this entry. pub fn setFlags(self: *PageTableEntry, flags: PageTableFlags) void { self.entry = self.getAddr().value | flags.toU64(); } pub fn format(value: PageTableEntry, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; _ = options; try writer.print("PageTableEntry({}, Flags = 0b{b})", .{ value.getAddr(), value.getFlags().value }); } test { std.testing.refAllDecls(@This()); try std.testing.expectEqual(@bitSizeOf(u64), @bitSizeOf(PageTableEntry)); try std.testing.expectEqual(@sizeOf(u64), @sizeOf(PageTableEntry)); } }; pub const PageTableFlags = packed struct { /// Specifies whether the mapped frame or page table is loaded in memory. present: bool = false, /// Controls whether writes to the mapped frames are allowed. /// /// If this bit is unset in a level 1 page table entry, the mapped frame is read-only. /// If this bit is unset in a higher level page table entry the complete range of mapped /// pages is read-only. writeable: bool = false, /// Controls whether accesses from userspace (i.e. ring 3) are permitted. user_accessible: bool = false, /// If this bit is set, a “write-through” policy is used for the cache, else a “write-back” /// policy is used. write_through: bool = false, /// Disables caching for the pointed entry is cacheable. no_cache: bool = false, /// Set by the CPU when the mapped frame or page table is accessed. accessed: bool = false, /// Set by the CPU on a write to the mapped frame. dirty: bool = false, /// Specifies that the entry maps a huge frame instead of a page table. Only allowed in /// P2 or P3 tables. huge: bool = false, /// Indicates that the mapping is present in all address spaces, so it isn't flushed from /// the TLB on an address space switch. global: bool = false, /// Available to the OS, can be used to store additional data, e.g. custom flags. bit_9_11: u3 = 0, z_reserved12_15: u4 = 0, z_reserved16_47: u32 = 0, z_reserved48_51: u4 = 0, /// Available to the OS, can be used to store additional data, e.g. custom flags. bit_52_62: u11 = 0, /// Forbid code execution from the mapped frames. /// /// Can be only used when the no-execute page protection feature is enabled in the EFER /// register. no_execute: bool = false, pub fn sanitizeForParent(self: PageTableFlags) PageTableFlags { var parent_flags = PageTableFlags{}; if (self.present) parent_flags.present = true; if (self.writeable) parent_flags.writeable = true; if (self.user_accessible) parent_flags.user_accessible = true; return parent_flags; } pub fn fromU64(value: u64) PageTableFlags { return @bitCast(PageTableFlags, value & ALL_NOT_RESERVED); } pub fn toU64(self: PageTableFlags) u64 { return @bitCast(u64, self) & ALL_NOT_RESERVED; } const ALL_RESERVED: u64 = blk: { var flags = std.mem.zeroes(PageTableFlags); flags.z_reserved12_15 = std.math.maxInt(u4); flags.z_reserved16_47 = std.math.maxInt(u32); flags.z_reserved48_51 = std.math.maxInt(u4); break :blk @bitCast(u64, flags); }; const ALL_NOT_RESERVED: u64 = ~ALL_RESERVED; pub fn format(value: PageTableFlags, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; return formatWithoutFields( value, options, writer, &.{ "z_reserved12_15", "z_reserved16_47", "z_reserved48_51" }, ); } test { try std.testing.expectEqual(@bitSizeOf(u64), @bitSizeOf(PageTableFlags)); try std.testing.expectEqual(@sizeOf(u64), @sizeOf(PageTableFlags)); } comptime { std.testing.refAllDecls(@This()); } }; /// Represents a page table. /// Always page-sized. /// **IMPORTANT** Must be align(4096) pub const PageTable = extern struct { entries: [PAGE_TABLE_ENTRY_COUNT]PageTableEntry = [_]PageTableEntry{PageTableEntry.init()} ** PAGE_TABLE_ENTRY_COUNT, /// Clears all entries. pub fn zero(self: *PageTable) void { for (self.entries) |*entry| { entry.setUnused(); } } pub fn getAtIndex(self: *PageTable, index: PageTableIndex) *PageTableEntry { return &self.entries[index.value]; } comptime { std.testing.refAllDecls(@This()); } }; /// A 9-bit index into a page table. pub const PageTableIndex = struct { value: u9, /// Creates a new index from the given `u16`. pub fn init(index: u9) PageTableIndex { return .{ .value = index }; } pub fn format(value: PageTableIndex, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = options; _ = fmt; try writer.print("PageTableIndex({})", .{value.value}); } comptime { std.testing.refAllDecls(@This()); } }; /// A 12-bit offset into a 4KiB Page. pub const PageOffset = struct { value: u12, /// Creates a new offset from the given `u12`. pub fn init(offset: u12) PageOffset { return .{ .value = offset }; } pub fn format(value: PageOffset, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = options; _ = fmt; try writer.print("PageOffset({})", .{value.value}); } comptime { std.testing.refAllDecls(@This()); } }; comptime { std.testing.refAllDecls(@This()); }
src/structures/paging/page_table.zig
const std = @import("std"); const fmt = std.fmt; const mem = std.mem; const testing = std.testing; pub const HistogramResult = struct { pub const Bucket = struct { vmrange: []const u8, count: u64, }; pub const SumValue = struct { value: f64 = 0, pub fn format(self: @This(), comptime format_string: []const u8, options: fmt.FormatOptions, writer: anytype) !void { _ = format_string; const as_int = @floatToInt(u64, self.value); if (@intToFloat(f64, as_int) == self.value) { try fmt.formatInt(as_int, 10, .lower, options, writer); } else { try fmt.formatFloatDecimal(self.value, options, writer); } } }; buckets: []Bucket, sum: SumValue, count: u64, }; pub const Metric = struct { pub const Error = error{ OutOfMemory, } || std.os.WriteError; pub const Result = union(enum) { const Self = @This(); counter: u64, gauge: f64, histogram: HistogramResult, pub fn deinit(self: Self, allocator: mem.Allocator) void { switch (self) { .histogram => |v| { allocator.free(v.buckets); }, else => {}, } } }; getResultFn: fn (self: *Metric, allocator: mem.Allocator) Error!Result, pub fn write(self: *Metric, allocator: mem.Allocator, writer: anytype, name: []const u8) Error!void { const result = try self.getResultFn(self, allocator); defer result.deinit(allocator); switch (result) { .counter => |v| { return try writer.print("{s} {d}\n", .{ name, v }); }, .gauge => |v| { return try writer.print("{s} {d:.6}\n", .{ name, v }); }, .histogram => |v| { if (v.buckets.len <= 0) return; const name_and_labels = splitName(name); if (name_and_labels.labels.len > 0) { for (v.buckets) |bucket| { try writer.print("{s}_bucket{{{s},vmrange=\"{s}\"}} {d:.6}\n", .{ name_and_labels.name, name_and_labels.labels, bucket.vmrange, bucket.count, }); } try writer.print("{s}_sum{{{s}}} {:.6}\n", .{ name_and_labels.name, name_and_labels.labels, v.sum, }); try writer.print("{s}_count{{{s}}} {d}\n", .{ name_and_labels.name, name_and_labels.labels, v.count, }); } else { for (v.buckets) |bucket| { try writer.print("{s}_bucket{{vmrange=\"{s}\"}} {d:.6}\n", .{ name_and_labels.name, bucket.vmrange, bucket.count, }); } try writer.print("{s}_sum {:.6}\n", .{ name_and_labels.name, v.sum, }); try writer.print("{s}_count {d}\n", .{ name_and_labels.name, v.count, }); } }, } } }; const NameAndLabels = struct { name: []const u8, labels: []const u8 = "", }; fn splitName(name: []const u8) NameAndLabels { const bracket_pos = mem.indexOfScalar(u8, name, '{'); if (bracket_pos) |pos| { return NameAndLabels{ .name = name[0..pos], .labels = name[pos + 1 .. name.len - 1], }; } else { return NameAndLabels{ .name = name, }; } } test "splitName" { const TestCase = struct { input: []const u8, exp: NameAndLabels, }; const test_cases = &[_]TestCase{ .{ .input = "foobar", .exp = .{ .name = "foobar", }, }, .{ .input = "foobar{route=\"/home\"}", .exp = .{ .name = "foobar", .labels = "route=\"/home\"", }, }, .{ .input = "foobar{route=\"/home\",status=\"500\"}", .exp = .{ .name = "foobar", .labels = "route=\"/home\",status=\"500\"", }, }, }; inline for (test_cases) |tc| { const res = splitName(tc.input); try testing.expectEqualStrings(tc.exp.name, res.name); try testing.expectEqualStrings(tc.exp.labels, res.labels); } }
src/metric.zig
const std = @import("std"); const tls = @import("tls"); const use_gpa = @import("build_options").use_gpa; pub const log_level = .debug; const RecordingAllocator = struct { const Stats = struct { peak_allocated: usize = 0, total_allocated: usize = 0, total_deallocated: usize = 0, total_allocations: usize = 0, }; allocator: std.mem.Allocator = .{ .allocFn = allocFn, .resizeFn = resizeFn, }, base_allocator: *std.mem.Allocator, stats: Stats = .{}, fn allocFn( a: *std.mem.Allocator, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize, ) ![]u8 { const self = @fieldParentPtr(RecordingAllocator, "allocator", a); const mem = try self.base_allocator.allocFn( self.base_allocator, len, ptr_align, len_align, ret_addr, ); self.stats.total_allocations += 1; self.stats.total_allocated += mem.len; self.stats.peak_allocated = std.math.max( self.stats.peak_allocated, self.stats.total_allocated - self.stats.total_deallocated, ); return mem; } fn resizeFn(a: *std.mem.Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) !usize { const self = @fieldParentPtr(RecordingAllocator, "allocator", a); const actual_len = try self.base_allocator.resizeFn( self.base_allocator, buf, buf_align, new_len, len_align, ret_addr, ); if (actual_len == 0) { std.debug.assert(new_len == 0); self.stats.total_deallocated += buf.len; } else if (actual_len > buf.len) { self.stats.total_allocated += actual_len - buf.len; self.stats.peak_allocated = std.math.max( self.stats.peak_allocated, self.stats.total_allocated - self.stats.total_deallocated, ); } else { self.stats.total_deallocated += buf.len - actual_len; } return actual_len; } }; const SinkWriter = blk: { const S = struct {}; break :blk std.io.Writer(S, error{}, struct { fn f(_: S, buffer: []const u8) !usize { return buffer.len; } }.f); }; const ReplayingReaderState = struct { data: []const u8, }; const ReplayingReader = std.io.Reader(*ReplayingReaderState, error{}, struct { fn f(self: *ReplayingReaderState, buffer: []u8) !usize { if (self.data.len < buffer.len) @panic("Not enoguh reader data!"); std.mem.copy(u8, buffer, self.data[0..buffer.len]); self.data = self.data[buffer.len..]; return buffer.len; } }.f); const ReplayingRandom = struct { rand: std.rand.Random = .{ .fillFn = fillFn }, data: []const u8, fn fillFn(r: *std.rand.Random, buf: []u8) void { const self = @fieldParentPtr(ReplayingRandom, "rand", r); if (self.data.len < buf.len) @panic("Not enough random data!"); std.mem.copy(u8, buf, self.data[0..buf.len]); self.data = self.data[buf.len..]; } }; fn benchmark_run( comptime ciphersuites: anytype, comptime curves: anytype, gpa: *std.mem.Allocator, allocator: *std.mem.Allocator, running_time: f32, hostname: []const u8, port: u16, trust_anchors: tls.x509.TrustAnchorChain, reader_recording: []const u8, random_recording: []const u8, ) !void { { const warmup_time_secs = std.math.max(0.5, running_time / 20); std.debug.print("Warming up for {d:.2} seconds...\n", .{warmup_time_secs}); const warmup_time_ns = @floatToInt(i128, warmup_time_secs * std.time.ns_per_s); var warmup_time_passed: i128 = 0; var timer = try std.time.Timer.start(); while (warmup_time_passed < warmup_time_ns) { var rand = ReplayingRandom{ .data = random_recording, }; var reader_state = ReplayingReaderState{ .data = reader_recording, }; const reader = ReplayingReader{ .context = &reader_state }; const writer = SinkWriter{ .context = .{} }; timer.reset(); _ = try tls.client_connect(.{ .rand = rand.rand, .reader = reader, .writer = writer, .ciphersuites = ciphersuites, .curves = curves, .cert_verifier = .default, .temp_allocator = allocator, .trusted_certificates = trust_anchors.data.items, }, hostname); warmup_time_passed += timer.read(); } } { std.debug.print("Benchmarking for {d:.2} seconds...\n", .{running_time}); const RunRecording = struct { time: i128, mem_stats: RecordingAllocator.Stats, }; var run_recordings = std.ArrayList(RunRecording).init(gpa); defer run_recordings.deinit(); const bench_time_ns = @floatToInt(i128, running_time * std.time.ns_per_s); var total_time_passed: i128 = 0; var iterations: usize = 0; var timer = try std.time.Timer.start(); while (total_time_passed < bench_time_ns) : (iterations += 1) { var rand = ReplayingRandom{ .data = random_recording, }; var reader_state = ReplayingReaderState{ .data = reader_recording, }; const reader = ReplayingReader{ .context = &reader_state }; const writer = SinkWriter{ .context = .{} }; var recording_allocator = RecordingAllocator{ .base_allocator = allocator }; timer.reset(); _ = try tls.client_connect(.{ .rand = rand.rand, .reader = reader, .writer = writer, .ciphersuites = ciphersuites, .curves = curves, .cert_verifier = .default, .temp_allocator = &recording_allocator.allocator, .trusted_certificates = trust_anchors.data.items, }, hostname); const runtime = timer.read(); total_time_passed += runtime; (try run_recordings.addOne()).* = .{ .mem_stats = recording_allocator.stats, .time = runtime, }; } const total_time_secs = @intToFloat(f64, total_time_passed) / std.time.ns_per_s; const mean_time_ns = @divTrunc(total_time_passed, iterations); const mean_time_ms = @intToFloat(f64, mean_time_ns) * std.time.ms_per_s / std.time.ns_per_s; const std_dev_ns = blk: { var acc: i128 = 0; for (run_recordings.items) |rec| { const dt = rec.time - mean_time_ns; acc += dt * dt; } break :blk std.math.sqrt(@divTrunc(acc, iterations)); }; const std_dev_ms = @intToFloat(f64, std_dev_ns) * std.time.ms_per_s / std.time.ns_per_s; std.debug.print( \\Finished benchmarking. \\Total runtime: {d:.2} sec \\Iterations: {} ({d:.2} iterations/sec) \\Mean iteration time: {d:.2} ms \\Standard deviation: {d:.2} ms \\ , .{ total_time_secs, iterations, @intToFloat(f64, iterations) / total_time_secs, mean_time_ms, std_dev_ms, }); // (percentile/100) * (total number n + 1) std.sort.sort(RunRecording, run_recordings.items, {}, struct { fn f(_: void, lhs: RunRecording, rhs: RunRecording) bool { return lhs.time < rhs.time; } }.f); const percentiles = .{ 99.0, 90.0, 75.0, 50.0 }; inline for (percentiles) |percentile| { if (percentile < iterations) { const idx = @floatToInt(usize, @intToFloat(f64, iterations + 1) * percentile / 100.0); std.debug.print( "{d:.0}th percentile value: {d:.2} ms\n", .{ percentile, @intToFloat(f64, run_recordings.items[idx].time) * std.time.ms_per_s / std.time.ns_per_s, }, ); } } const first_mem_stats = run_recordings.items[0].mem_stats; for (run_recordings.items[1..]) |rec| { std.debug.assert(std.meta.eql(first_mem_stats, rec.mem_stats)); } std.debug.print( \\Peak allocated memory: {Bi:.2}, \\Total allocated memory: {Bi:.2}, \\Number of allocations: {d}, \\ , .{ first_mem_stats.peak_allocated, first_mem_stats.total_allocated, first_mem_stats.total_allocations, }); } } fn benchmark_run_with_ciphersuite( comptime ciphersuites: anytype, curve_str: []const u8, gpa: *std.mem.Allocator, allocator: *std.mem.Allocator, running_time: f32, hostname: []const u8, port: u16, trust_anchors: tls.x509.TrustAnchorChain, reader_recording: []const u8, random_recording: []const u8, ) !void { if (std.mem.eql(u8, curve_str, "all")) { return try benchmark_run( ciphersuites, tls.curves.all, gpa, allocator, running_time, hostname, port, trust_anchors, reader_recording, random_recording, ); } inline for (tls.curves.all) |curve| { if (std.mem.eql(u8, curve_str, curve.name)) { return try benchmark_run( ciphersuites, .{curve}, gpa, allocator, running_time, hostname, port, trust_anchors, reader_recording, random_recording, ); } } return error.InvalidCurve; } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = &gpa.allocator; var args = std.process.args(); std.debug.assert(args.skip()); const running_time = blk: { const maybe_arg = args.next(allocator) orelse return error.NoArguments; const arg = try maybe_arg; break :blk std.fmt.parseFloat(f32, arg) catch { std.log.crit("Running time is not a floating point number...", .{}); return error.InvalidArg; }; }; // Loop over all files, swap gpa with a fixed buffer allocator for the handhsake arg_loop: while (args.next(allocator)) |recorded_file_path_or_err| { const recorded_file_path = try recorded_file_path_or_err; defer allocator.free(recorded_file_path); std.debug.print( \\============================================================ \\{s} \\============================================================ \\ , .{std.fs.path.basename(recorded_file_path)}); const recorded_file = try std.fs.cwd().openFile(recorded_file_path, .{}); defer recorded_file.close(); const ciphersuite_str_len = try recorded_file.reader().readByte(); const ciphersuite_str = try allocator.alloc(u8, ciphersuite_str_len); defer allocator.free(ciphersuite_str); try recorded_file.reader().readNoEof(ciphersuite_str); const curve_str_len = try recorded_file.reader().readByte(); const curve_str = try allocator.alloc(u8, curve_str_len); defer allocator.free(curve_str); try recorded_file.reader().readNoEof(curve_str); const hostname_len = try recorded_file.reader().readIntLittle(usize); const hostname = try allocator.alloc(u8, hostname_len); defer allocator.free(hostname); try recorded_file.reader().readNoEof(hostname); const port = try recorded_file.reader().readIntLittle(u16); const trust_anchors = blk: { const pem_file_path_len = try recorded_file.reader().readIntLittle(usize); const pem_file_path = try allocator.alloc(u8, pem_file_path_len); defer allocator.free(pem_file_path); try recorded_file.reader().readNoEof(pem_file_path); const pem_file = try std.fs.cwd().openFile(pem_file_path, .{}); defer pem_file.close(); const tas = try tls.x509.TrustAnchorChain.from_pem(allocator, pem_file.reader()); std.debug.print("Read {} certificates.\n", .{tas.data.items.len}); break :blk tas; }; defer trust_anchors.deinit(); const reader_recording_len = try recorded_file.reader().readIntLittle(usize); const reader_recording = try allocator.alloc(u8, reader_recording_len); defer allocator.free(reader_recording); try recorded_file.reader().readNoEof(reader_recording); const random_recording_len = try recorded_file.reader().readIntLittle(usize); const random_recording = try allocator.alloc(u8, random_recording_len); defer allocator.free(random_recording); try recorded_file.reader().readNoEof(random_recording); const handshake_allocator = if (use_gpa) &gpa.allocator else &std.heap.ArenaAllocator.init(std.heap.page_allocator).allocator; defer if (!use_gpa) @fieldParentPtr(std.heap.ArenaAllocator, "allocator", handshake_allocator).deinit(); if (std.mem.eql(u8, ciphersuite_str, "all")) { try benchmark_run_with_ciphersuite( tls.ciphersuites.all, curve_str, allocator, handshake_allocator, running_time, hostname, port, trust_anchors, reader_recording, random_recording, ); continue :arg_loop; } inline for (tls.ciphersuites.all) |ciphersuite| { if (std.mem.eql(u8, ciphersuite_str, ciphersuite.name)) { try benchmark_run_with_ciphersuite( .{ciphersuite}, curve_str, allocator, handshake_allocator, running_time, hostname, port, trust_anchors, reader_recording, random_recording, ); continue :arg_loop; } } return error.InvalidCiphersuite; } }
bench/bench.zig
const std = @import("std"); const pike = @import("pike.zig"); const os = std.os; const mem = std.mem; const net = std.net; const log = std.log; const heap = std.heap; const atomic = std.atomic; pub const ClientQueue = atomic.Queue(*Client); pub const Client = struct { socket: pike.Socket, address: net.Address, frame: @Frame(Client.run), fn run(self: *Client, server: *Server, notifier: *const pike.Notifier) !void { var node = ClientQueue.Node{ .data = self }; server.clients.put(&node); defer if (server.clients.remove(&node)) { suspend { self.socket.deinit(); server.allocator.destroy(self); } }; try self.socket.registerTo(notifier); log.info("New peer {} has connected.", .{self.address}); defer log.info("Peer {} has disconnected.", .{self.address}); var reader = self.socket.reader(); var writer = self.socket.writer(); try writer.writeAll("Hello from the server!\n"); var buf: [1024]u8 = undefined; while (true) { const num_bytes = try reader.read(&buf); if (num_bytes == 0) return; const message = mem.trim(u8, buf[0..num_bytes], " \t\r\n"); log.info("Peer {} said: {s}", .{ self.address, message }); } } }; pub const Server = struct { socket: pike.Socket, clients: ClientQueue, allocator: *mem.Allocator, frame: @Frame(Server.run), pub fn init(allocator: *mem.Allocator) !Server { var socket = try pike.Socket.init(os.AF.INET, os.SOCK.STREAM, os.IPPROTO.TCP, 0); errdefer socket.deinit(); try socket.set(.reuse_address, true); return Server{ .socket = socket, .clients = ClientQueue.init(), .frame = undefined, .allocator = allocator, }; } pub fn deinit(self: *Server) void { self.socket.deinit(); await self.frame; while (self.clients.get()) |node| { node.data.socket.writer().writeAll("Server is shutting down! Good bye...\n") catch {}; node.data.socket.deinit(); await node.data.frame catch {}; self.allocator.destroy(node.data); } } pub fn start(self: *Server, notifier: *const pike.Notifier, address: net.Address) !void { try self.socket.bind(address); try self.socket.listen(128); try self.socket.registerTo(notifier); self.frame = async self.run(notifier); log.info("Listening for peers on: {}", .{try self.socket.getBindAddress()}); } fn run(self: *Server, notifier: *const pike.Notifier) callconv(.Async) void { defer log.debug("TCP server has shut down.", .{}); while (true) { var conn = self.socket.accept() catch |err| switch (err) { error.SocketNotListening, error.OperationCancelled, => return, else => { log.err("Server - socket.accept(): {s}", .{@errorName(err)}); continue; }, }; const client = self.allocator.create(Client) catch |err| { log.err("Server - allocator.create(Client): {s}", .{@errorName(err)}); conn.socket.deinit(); continue; }; client.socket = conn.socket; client.address = conn.address; client.frame = async client.run(self, notifier); } } }; pub fn run(notifier: *const pike.Notifier, stopped: *bool) !void { // Setup allocator. var gpa: heap.GeneralPurposeAllocator(.{}) = .{}; defer _ = gpa.deinit(); // Setup signal handler. var event = try pike.Event.init(); defer event.deinit(); try event.registerTo(notifier); var signal = try pike.Signal.init(.{ .interrupt = true }); defer signal.deinit(); defer { stopped.* = true; event.post() catch unreachable; } // Setup TCP server. var server = try Server.init(&gpa.allocator); defer server.deinit(); // Start the server, and await for an interrupt signal to gracefully shutdown // the server. try server.start(notifier, net.Address.initIp4(.{ 0, 0, 0, 0 }, 0)); try signal.wait(); } pub fn main() !void { try pike.init(); defer pike.deinit(); const notifier = try pike.Notifier.init(); defer notifier.deinit(); var stopped = false; var frame = async run(&notifier, &stopped); while (!stopped) { try notifier.poll(1_000_000); } try nosuspend await frame; log.debug("Successfully shut down.", .{}); }
example_tcp_server.zig
const builtin = @import("builtin"); const std = @import("../index.zig"); const math = std.math; const assert = std.debug.assert; pub fn sin(x: var) @typeOf(x) { const T = @typeOf(x); return switch (T) { f32 => sin32(x), f64 => sin64(x), else => @compileError("sin not implemented for " ++ @typeName(T)), }; } // sin polynomial coefficients const S0 = 1.58962301576546568060E-10; const S1 = -2.50507477628578072866E-8; const S2 = 2.75573136213857245213E-6; const S3 = -1.98412698295895385996E-4; const S4 = 8.33333333332211858878E-3; const S5 = -1.66666666666666307295E-1; // cos polynomial coeffiecients const C0 = -1.13585365213876817300E-11; const C1 = 2.08757008419747316778E-9; const C2 = -2.75573141792967388112E-7; const C3 = 2.48015872888517045348E-5; const C4 = -1.38888888888730564116E-3; const C5 = 4.16666666666665929218E-2; // NOTE: This is taken from the go stdlib. The musl implementation is much more complex. // // This may have slight differences on some edge cases and may need to replaced if so. fn sin32(x_: f32) f32 { @setFloatMode(this, @import("builtin").FloatMode.Strict); const pi4a = 7.85398125648498535156e-1; const pi4b = 3.77489470793079817668E-8; const pi4c = 2.69515142907905952645E-15; const m4pi = 1.273239544735162542821171882678754627704620361328125; var x = x_; if (x == 0 or math.isNan(x)) { return x; } if (math.isInf(x)) { return math.nan(f32); } var sign = false; if (x < 0) { x = -x; sign = true; } var y = math.floor(x * m4pi); var j = i64(y); if (j & 1 == 1) { j += 1; y += 1; } j &= 7; if (j > 3) { j -= 4; sign = !sign; } const z = ((x - y * pi4a) - y * pi4b) - y * pi4c; const w = z * z; const r = r: { if (j == 1 or j == 2) { break :r 1.0 - 0.5 * w + w * w * (C5 + w * (C4 + w * (C3 + w * (C2 + w * (C1 + w * C0))))); } else { break :r z + z * w * (S5 + w * (S4 + w * (S3 + w * (S2 + w * (S1 + w * S0))))); } }; if (sign) { return -r; } else { return r; } } fn sin64(x_: f64) f64 { const pi4a = 7.85398125648498535156e-1; const pi4b = 3.77489470793079817668E-8; const pi4c = 2.69515142907905952645E-15; const m4pi = 1.273239544735162542821171882678754627704620361328125; var x = x_; if (x == 0 or math.isNan(x)) { return x; } if (math.isInf(x)) { return math.nan(f64); } var sign = false; if (x < 0) { x = -x; sign = true; } var y = math.floor(x * m4pi); var j = i64(y); if (j & 1 == 1) { j += 1; y += 1; } j &= 7; if (j > 3) { j -= 4; sign = !sign; } const z = ((x - y * pi4a) - y * pi4b) - y * pi4c; const w = z * z; const r = r: { if (j == 1 or j == 2) { break :r 1.0 - 0.5 * w + w * w * (C5 + w * (C4 + w * (C3 + w * (C2 + w * (C1 + w * C0))))); } else { break :r z + z * w * (S5 + w * (S4 + w * (S3 + w * (S2 + w * (S1 + w * S0))))); } }; if (sign) { return -r; } else { return r; } } test "math.sin" { assert(sin(f32(0.0)) == sin32(0.0)); assert(sin(f64(0.0)) == sin64(0.0)); assert(comptime (math.sin(f64(2))) == math.sin(f64(2))); } test "math.sin32" { const epsilon = 0.000001; assert(math.approxEq(f32, sin32(0.0), 0.0, epsilon)); assert(math.approxEq(f32, sin32(0.2), 0.198669, epsilon)); assert(math.approxEq(f32, sin32(0.8923), 0.778517, epsilon)); assert(math.approxEq(f32, sin32(1.5), 0.997495, epsilon)); assert(math.approxEq(f32, sin32(37.45), -0.246544, epsilon)); assert(math.approxEq(f32, sin32(89.123), 0.916166, epsilon)); } test "math.sin64" { const epsilon = 0.000001; assert(math.approxEq(f64, sin64(0.0), 0.0, epsilon)); assert(math.approxEq(f64, sin64(0.2), 0.198669, epsilon)); assert(math.approxEq(f64, sin64(0.8923), 0.778517, epsilon)); assert(math.approxEq(f64, sin64(1.5), 0.997495, epsilon)); assert(math.approxEq(f64, sin64(37.45), -0.246543, epsilon)); assert(math.approxEq(f64, sin64(89.123), 0.916166, epsilon)); } test "math.sin32.special" { assert(sin32(0.0) == 0.0); assert(sin32(-0.0) == -0.0); assert(math.isNan(sin32(math.inf(f32)))); assert(math.isNan(sin32(-math.inf(f32)))); assert(math.isNan(sin32(math.nan(f32)))); } test "math.sin64.special" { assert(sin64(0.0) == 0.0); assert(sin64(-0.0) == -0.0); assert(math.isNan(sin64(math.inf(f64)))); assert(math.isNan(sin64(-math.inf(f64)))); assert(math.isNan(sin64(math.nan(f64)))); }
std/math/sin.zig
const std = @import("std"); const Value = @import("value.zig").Value; /// Parses a list of values from the provided code slice. Destructively modifies code. /// No allocations are performed other than to create the returned values. pub fn parse(allocator: std.mem.Allocator, code: []u8) ParseError!*Value { var parser = Parser{ .allocator = allocator, .toks = Tokenizer.init(code), }; return parser.list(.eof); } pub const ParseError = error{ EndOfStream, InvalidToken, UnexpectedToken, Overflow, OutOfMemory, }; const Parser = struct { allocator: std.mem.Allocator, toks: Tokenizer, fn list(self: *Parser, end: Token.Tag) ParseError!*Value { var val = Value.nil; var tail: ?*Value = null; while (true) { const tok = self.toks.next(); if (tok.tag == end) break; const parsed = try self.value(tok); const v = if (tail) |t| &t.cons[1] else &val; std.debug.assert(v.* == Value.nil); v.* = try Value.cons(self.allocator, parsed, Value.nil); tail = v.*; } return val; } fn value(self: *Parser, tok: Token) ParseError!*Value { return switch (tok.tag) { .eof => error.EndOfStream, .invalid => error.InvalidToken, .@")" => error.UnexpectedToken, .@"(" => try self.list(.@")"), .@"'" => try Value.cons( self.allocator, try Value.sym(self.allocator, "quote"), try Value.cons( self.allocator, try self.value(self.toks.next()), Value.nil, ), ), .integer => try Value.int(self.allocator, std.fmt.parseInt(i64, tok.text, 0) catch |err| switch (err) { error.InvalidCharacter => unreachable, else => |e| return e, }), .string => try Value.str(self.allocator, tok.text[1 .. tok.text.len - 1]), .symbol => try Value.sym(self.allocator, tok.text), }; } }; const Token = struct { tag: Tag, text: []const u8, const Tag = enum { eof, invalid, @"(", @")", @"'", integer, string, symbol, }; }; const Tokenizer = struct { code: []u8, pub fn init(code: []u8) Tokenizer { var self = Tokenizer{ .code = code }; self.skipSpace(); return self; } fn skipSpace(self: *Tokenizer) void { while (self.code.len > 0 and std.ascii.isSpace(self.code[0])) { self.code = self.code[1..]; } } pub fn next(self: *Tokenizer) Token { if (self.code.len == 0) { return .{ .tag = .eof, .text = "" }; } var end: usize = 1; const tag: Token.Tag = switch (self.code[0]) { 0x00...0x20, 0x7f...0xff => .invalid, // non-printing chars '(' => .@"(", ')' => .@")", '\'' => .@"'", '-', '0'...'9' => while (end < self.code.len and isDigit(self.code[end])) { end += 1; } else .integer, '"' => while (end < self.code.len) { const c = self.code[end]; end += 1; switch (c) { '"' => break Token.Tag.string, '\\' => end += 1, else => {}, } } else .invalid, else => while (end < self.code.len and isSymbol(self.code[end])) { end += 1; } else .symbol, }; const tok: Token = .{ .tag = tag, .text = self.code[0..end], }; self.code = self.code[end..]; self.skipSpace(); return tok; } inline fn isSymbol(c: u8) bool { return switch (c) { 0x00...0x20, 0x7f...0xff => false, // non-printing chars '(', ')', '"' => false, // Reserved else => true, }; } inline fn isDigit(c: u8) bool { return switch (c) { '0'...'9' => true, else => false, }; } }; test "Parse simple s-expr" { var code = \\"Hello, world!" \\(foo '(bar baz) 'quux) \\0 1 2 3 4 -1 -2 -3 .*; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const v = try parse(arena.allocator(), &code); try std.testing.expectEqualStrings( \\("Hello, world!" (foo (quote (bar baz)) (quote quux)) 0 1 2 3 4 -1 -2 -3) , try std.fmt.allocPrint(arena.allocator(), "{}", .{v})); } test "String escapes" { var code = \\"a\"b" \\"a\nb" \\"a\tb" \\"a\x00b" .*; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const v = try parse(arena.allocator(), &code); try std.testing.expectEqualStrings( \\("a\"b" "a\nb" "a\tb" "a\x00b") , try std.fmt.allocPrint(arena.allocator(), "{}", .{v})); }
parse.zig
const util = @import("../sdf_util.zig"); pub const info: util.SdfInfo = .{ .name = "Quad", .data_size = @sizeOf(Data), .function_definition = function_definition, .enter_command_fn = util.surfaceEnterCommand(Data), .exit_command_fn = util.surfaceExitCommand(Data, exitCommand), .append_mat_check_fn = util.surfaceMatCheckCommand(Data), .sphere_bound_fn = sphereBound, }; pub const Data = struct { point_a: util.math.vec3, point_b: util.math.vec3, point_c: util.math.vec3, point_d: util.math.vec3, mat: usize, }; const function_definition: []const u8 = \\float sdQuad(vec3 p, vec3 a, vec3 b, vec3 c, vec3 d){ \\ vec3 ba = b - a; vec3 pa = p - a; \\ vec3 cb = c - b; vec3 pb = p - b; \\ vec3 dc = d - c; vec3 pc = p - c; \\ vec3 ad = a - d; vec3 pd = p - d; \\ vec3 nor = cross(ba, ad); \\ return sqrt( \\ (sign(dot(cross(ba,nor),pa)) + \\ sign(dot(cross(cb,nor),pb)) + \\ sign(dot(cross(dc,nor),pc)) + \\ sign(dot(cross(ad,nor),pd))<3.) \\ ? \\ min(min(min( \\ dot2(ba*clamp(dot(ba,pa)/dot2(ba),0.,1.)-pa), \\ dot2(cb*clamp(dot(cb,pb)/dot2(cb),0.,1.)-pb)), \\ dot2(dc*clamp(dot(dc,pc)/dot2(dc),0.,1.)-pc)), \\ dot2(ad*clamp(dot(ad,pd)/dot2(ad),0.,1.)-pd)) \\ : \\ dot(nor,pa)*dot(nor,pa)/dot2(nor)); \\} \\ ; fn exitCommand(data: *Data, enter_index: usize, cur_point_name: []const u8, allocator: util.std.mem.Allocator) []const u8 { const format: []const u8 = "float d{d} = sdQuad({s},vec3({d:.5},{d:.5},{d:.5}),vec3({d:.5},{d:.5},{d:.5}),vec3({d:.5},{d:.5},{d:.5}),vec3({d:.5},{d:.5},{d:.5}));"; return util.std.fmt.allocPrint(allocator, format, .{ enter_index, cur_point_name, data.point_a[0], data.point_a[1], data.point_a[2], data.point_b[0], data.point_b[1], data.point_b[2], data.point_c[0], data.point_c[1], data.point_c[2], data.point_d[0], data.point_d[1], data.point_d[2], }) catch unreachable; } fn sphereBound(buffer: *[]u8, bound: *util.math.sphereBound, children: []util.math.sphereBound) void { _ = children; const data: *Data = @ptrCast(*Data, @alignCast(@alignOf(Data), buffer.ptr)); bound.* = util.math.SphereBound.merge( util.math.SphereBound.from3Points(data.point_a, data.point_b, data.point_c), util.math.SphereBound.from3Points(data.point_b, data.point_c, data.point_d), ); }
src/sdf/surfaces/quad.zig
const std = @import("std"); const hapi = @cImport({ @cInclude("HAPI/HAPI.h"); @cInclude("raylib.h"); @cInclude("rlgl.h"); }); const ray = hapi; fn initMesh() ray.Mesh { return ray.Mesh{ .vertexCount = 0, .triangleCount = 0, .vertices = null, .texcoords = null, .texcoords2 = null, .normals = null, .tangents = null, .colors = null, .indices = null, .animVertices = null, .animNormals = null, .boneIds = null, .boneWeights = null, .vaoId = 0, .vboId = null, }; } const LightLocs = struct { enable: i32, ltype: i32, pos: i32, target: i32, color: i32, }; const Light = struct { enable: i32 = 1, ltype: i32 = 1, // 0 = directional, 1 = point pos: [3]f32 = .{ 0, 0, 0 }, target: [3]f32 = .{ 0, 0, 0 }, color: [4]f32 = .{ 1, 1, 1, 1 }, locs: LightLocs, fn updateShader(self: @This(), shader: *ray.Shader) void { ray.SetShaderValue(shader.*, self.locs.enable, &self.enable, ray.SHADER_UNIFORM_INT); ray.SetShaderValue(shader.*, self.locs.ltype, &self.ltype, ray.SHADER_UNIFORM_INT); ray.SetShaderValue(shader.*, self.locs.pos, &self.pos, ray.SHADER_UNIFORM_VEC3); ray.SetShaderValue(shader.*, self.locs.target, &self.target, ray.SHADER_UNIFORM_VEC3); ray.SetShaderValue(shader.*, self.locs.color, &self.color, ray.SHADER_UNIFORM_VEC4); } }; pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var session: hapi.HAPI_Session = undefined; var result: hapi.HAPI_Result = undefined; var cook_status: c_int = undefined; var cook_result: hapi.HAPI_Result = undefined; if (false) { result = hapi.HAPI_CreateInProcessSession(&session); } else { var hapi_thrift_server_opts = hapi.HAPI_ThriftServerOptions{ .autoClose = 1, .timeoutMs = 3000.0 }; result = hapi.HAPI_StartThriftNamedPipeServer(&hapi_thrift_server_opts, "hapi", null); result = hapi.HAPI_CreateThriftNamedPipeSession(&session, "hapi"); } var cook_options = hapi.HAPI_CookOptions_Create(); cook_options.maxVerticesPerPrimitive = 3; cook_options.checkPartChanges = 0; cook_options.cacheMeshTopology = 1; result = hapi.HAPI_Initialize(&session, &cook_options, 1, -1, null, null, null, null, null); defer result = hapi.HAPI_CloseSession(&session); defer result = hapi.HAPI_Cleanup(&session); var grid_id: hapi.HAPI_NodeId = undefined; var mountain_id: hapi.HAPI_NodeId = undefined; var color_id: hapi.HAPI_NodeId = undefined; var normal_id: hapi.HAPI_NodeId = undefined; var reverse_id: hapi.HAPI_NodeId = undefined; result = hapi.HAPI_CreateNode(&session, -1, "Sop/grid", "grid", 0, &grid_id); result = hapi.HAPI_CreateNode(&session, -1, "Sop/reverse", "reverse", 0, &reverse_id); result = hapi.HAPI_CreateNode(&session, -1, "Sop/normal", "normal", 0, &normal_id); result = hapi.HAPI_CreateNode(&session, -1, "Sop/color", "color", 0, &color_id); result = hapi.HAPI_CreateNode(&session, -1, "Sop/mountain", "mountain", 0, &mountain_id); result = hapi.HAPI_ConnectNodeInput(&session, reverse_id, 0, grid_id, 0); result = hapi.HAPI_ConnectNodeInput(&session, normal_id, 0, reverse_id, 0); result = hapi.HAPI_ConnectNodeInput(&session, color_id, 0, normal_id, 0); result = hapi.HAPI_ConnectNodeInput(&session, mountain_id, 0, color_id, 0); result = hapi.HAPI_SetParmIntValue(&session, grid_id, "surftype", 0, 4); result = hapi.HAPI_SetParmIntValue(&session, grid_id, "rows", 0, 255); result = hapi.HAPI_SetParmIntValue(&session, grid_id, "cols", 0, 255); result = hapi.HAPI_SetParmIntValue(&session, normal_id, "type", 0, 0); result = hapi.HAPI_SetParmIntValue(&session, normal_id, "reverse", 0, 1); result = hapi.HAPI_SetParmIntValue(&session, color_id, "colortype", 0, 1); result = hapi.HAPI_SetParmFloatValue(&session, mountain_id, "height", 0, 10); result = hapi.HAPI_SetParmFloatValue(&session, mountain_id, "elementsize", 0, 6); result = hapi.HAPI_SetParmFloatValue(&session, mountain_id, "roughness", 0, 0.4); result = hapi.HAPI_SetParmFloatValue(&session, mountain_id, "lacunarity", 0, 2.01); result = hapi.HAPI_CookNode(&session, mountain_id, &cook_options); cook_result = hapi.HAPI_Result.HAPI_RESULT_SUCCESS; cook_status = hapi.HAPI_STATE_MAX; while (cook_status > hapi.HAPI_STATE_MAX_READY_STATE and cook_result == hapi.HAPI_Result.HAPI_RESULT_SUCCESS) { cook_result = hapi.HAPI_GetStatus( &session, hapi.HAPI_StatusType.HAPI_STATUS_COOK_STATE, &cook_status, ); } var part_id: hapi.HAPI_PartId = 0; var geo_info: hapi.HAPI_GeoInfo = undefined; result = hapi.HAPI_GetDisplayGeoInfo(&session, mountain_id, &geo_info); // std.debug.print("Part count: {}\n", .{geo_info.partCount}); var part_info: hapi.HAPI_PartInfo = undefined; result = hapi.HAPI_GetPartInfo(&session, mountain_id, part_id, &part_info); // std.debug.print("Point count: {}\n", .{part_info.pointCount}); var p_attrib_info: hapi.HAPI_AttributeInfo = undefined; result = hapi.HAPI_GetAttributeInfo( &session, mountain_id, part_id, "P", hapi.HAPI_AttributeOwner.HAPI_ATTROWNER_POINT, &p_attrib_info, ); var P_data = try arena.allocator.alloc(f32, @intCast(usize, p_attrib_info.count * p_attrib_info.tupleSize)); defer arena.allocator.free(P_data); result = hapi.HAPI_GetAttributeFloatData( &session, mountain_id, part_id, "P", &p_attrib_info, -1, @ptrCast([*c]f32, P_data), 0, p_attrib_info.count, ); var n_attrib_info: hapi.HAPI_AttributeInfo = undefined; result = hapi.HAPI_GetAttributeInfo( &session, mountain_id, part_id, "N", hapi.HAPI_AttributeOwner.HAPI_ATTROWNER_POINT, &n_attrib_info, ); var N_data = try arena.allocator.alloc(f32, @intCast(usize, n_attrib_info.count * n_attrib_info.tupleSize)); defer arena.allocator.free(N_data); result = hapi.HAPI_GetAttributeFloatData( &session, mountain_id, part_id, "N", &n_attrib_info, -1, @ptrCast([*c]f32, N_data), 0, n_attrib_info.count, ); var cd_attrib_info: hapi.HAPI_AttributeInfo = undefined; result = hapi.HAPI_GetAttributeInfo( &session, mountain_id, part_id, "Cd", hapi.HAPI_AttributeOwner.HAPI_ATTROWNER_POINT, &cd_attrib_info, ); var clr_uchar_data = try arena.allocator.alloc(u8, @intCast(usize, cd_attrib_info.count * 4)); defer arena.allocator.free(clr_uchar_data); { var clr_float_data = try arena.allocator.alloc(f32, @intCast(usize, cd_attrib_info.count * cd_attrib_info.tupleSize)); defer arena.allocator.free(clr_float_data); result = hapi.HAPI_GetAttributeFloatData( &session, mountain_id, part_id, "Cd", &cd_attrib_info, -1, @ptrCast([*c]f32, clr_float_data), 0, cd_attrib_info.count, ); var i: usize = 0; while (i < cd_attrib_info.count) : (i += 1) { clr_uchar_data[i * 4] = @floatToInt(u8, @round(clr_float_data[i * 3] * 255.0)); clr_uchar_data[i * 4 + 1] = @floatToInt(u8, @round(clr_float_data[i * 3 + 1] * 255.0)); clr_uchar_data[i * 4 + 2] = @floatToInt(u8, @round(clr_float_data[i * 3 + 2] * 255.0)); clr_uchar_data[i * 4 + 3] = 255; } } var vtx_list = try arena.allocator.alloc(i32, @intCast(usize, part_info.vertexCount)); defer arena.allocator.free(vtx_list); result = hapi.HAPI_GetVertexList( &session, mountain_id, part_id, @ptrCast([*c]i32, vtx_list), 0, part_info.vertexCount, ); //for (N_data) |p,i| { // if (i % 3 == 0 and i>0 ) { // std.debug.print("\n", .{}); // } // std.debug.print("{d:0.4}", .{p}); // if ( i%3 <2) { // std.debug.print(", ", .{}); // } //} //std.debug.print("\n", .{}); //for (clr_uchar_data) |p,i| { // if (i % 4 == 0 and i>0 ) { // std.debug.print("\n", .{}); // } // std.debug.print("{}", .{p}); // if ( i%4 <3) { // std.debug.print(", ", .{}); // } //} //std.debug.print("\n", .{}); ray.InitWindow(640, 480, "ZigEngine"); defer ray.CloseWindow(); ray.SetExitKey(0); ray.SetTargetFPS(60); var camera: ray.Camera = .{ .position = .{ .x = 0, .y = 20, .z = 10 }, .target = .{ .x = 0, .y = 0, .z = 0 }, .up = .{ .x = 0, .y = 1, .z = 0 }, .fovy = 35, .projection = ray.CAMERA_PERSPECTIVE, }; var shader = ray.LoadShader("resources/base_lighting.vs", "resources/lighting.fs"); //var shader = ray.LoadShader("resources/base.vs", "resources/base.fs"); shader.locs[ray.SHADER_LOC_VECTOR_VIEW] = ray.GetShaderLocation(shader, "viewPos"); shader.locs[ray.SHADER_LOC_MATRIX_MODEL] = ray.GetShaderLocation(shader, "matModel"); var light_loc = LightLocs{ .enable = ray.GetShaderLocation(shader, "lights[0].enabled"), .ltype = ray.GetShaderLocation(shader, "lights[0].type"), .pos = ray.GetShaderLocation(shader, "lights[0].position"), .target = ray.GetShaderLocation(shader, "lights[0].target"), .color = ray.GetShaderLocation(shader, "lights[0].color"), }; var light: Light = .{ .locs = light_loc, .pos = .{ -20, -20, -15 }, .color = .{1,1,1,1}, }; light.updateShader(&shader); var ambient: [4]f32 = .{0.05, 0.05, 0.05, 1.0}; ray.SetShaderValue(shader, ray.GetShaderLocation(shader, "ambient"), &ambient, ray.SHADER_UNIFORM_VEC4); var view_pos: [3]f32 = .{ camera.position.x, camera.position.y, camera.position.z }; ray.SetShaderValue(shader, shader.locs[ray.SHADER_LOC_VECTOR_VIEW], &view_pos, ray.SHADER_UNIFORM_VEC3); var mesh = initMesh(); mesh.vertexCount = part_info.pointCount; mesh.triangleCount = part_info.faceCount; mesh.vertices = @ptrCast([*c]f32, P_data); mesh.colors = @ptrCast([*c]u8, clr_uchar_data); mesh.normals = @ptrCast([*c]f32, N_data); mesh.indices = @ptrCast([*c]c_ushort, try arena.allocator.alloc(c_ushort, @intCast(usize, part_info.vertexCount))); for (vtx_list) |vtx, i| { mesh.indices[i] = @intCast(u16, vtx); } ray.UploadMesh(&mesh, true); var model = ray.LoadModelFromMesh(mesh); defer ray.UnloadModelKeepMeshes(model); var material = ray.LoadMaterialDefault(); material.shader = shader; material.maps[ray.MATERIAL_MAP_DIFFUSE].color = ray.WHITE; model.materials[0] = material; ray.SetCameraMode(camera, ray.CAMERA_ORBITAL); while (!ray.WindowShouldClose()) { { result = hapi.HAPI_SetParmFloatValue(&session, mountain_id, "time", 0, @floatCast(f32, ray.GetTime() / 4.0)); result = hapi.HAPI_CookNode(&session, mountain_id, &cook_options); cook_result = hapi.HAPI_Result.HAPI_RESULT_SUCCESS; cook_status = hapi.HAPI_STATE_MAX; while (cook_status > hapi.HAPI_STATE_MAX_READY_STATE and cook_result == hapi.HAPI_Result.HAPI_RESULT_SUCCESS) { cook_result = hapi.HAPI_GetStatus( &session, hapi.HAPI_StatusType.HAPI_STATUS_COOK_STATE, &cook_status, ); } result = hapi.HAPI_GetAttributeFloatData( &session, mountain_id, part_id, "P", &p_attrib_info, -1, @ptrCast([*c]f32, P_data), 0, p_attrib_info.count, ); result = hapi.HAPI_GetAttributeFloatData( &session, mountain_id, part_id, "N", &n_attrib_info, -1, @ptrCast([*c]f32, N_data), 0, n_attrib_info.count, ); } ray.UpdateMeshBuffer(mesh, 0, @ptrCast([*c]f32, P_data), 4 * 3 * mesh.vertexCount, 0); // size in bytes, offset in bytes ray.UpdateMeshBuffer(mesh, 2, @ptrCast([*c]f32, N_data), 4 * 3 * mesh.vertexCount, 0); // size in bytes, offset in bytes ray.ClearBackground(ray.BLACK); ray.UpdateCamera(&camera); view_pos = .{ camera.position.x, camera.position.y, camera.position.z }; ray.SetShaderValue(shader, shader.locs[ray.SHADER_LOC_VECTOR_VIEW], &view_pos, ray.SHADER_UNIFORM_VEC3); ray.BeginDrawing(); ray.DrawFPS(50, 50); ray.BeginMode3D(camera); ray.rlDisableBackfaceCulling(); ray.DrawModel(model, .{ .x = 0, .y = 0, .z = 0 }, 1.0, ray.WHITE); ray.EndMode3D(); ray.EndDrawing(); } }
src/main.zig
const std = @import("std"); pub const StreamFns = enum { XADD, XREAD, XREADGROUP, XRANGE, XREVRANGE, }; pub const SpecialIDs = struct { pub const NEW_MESSAGES = "$"; pub const ASSIGN_NEW_MESSAGES = "<"; pub const MIN = "-"; pub const MAX = "+"; pub const AUTO_ID = "*"; pub const BEGINNING = "0-0"; }; pub fn isValidStreamID(cmd: StreamFns, id: []const u8) bool { return switch (cmd) { .XREAD => isNumericStreamID(id) or isAny(id, .{SpecialIDs.NEW_MESSAGES}), .XREADGROUP => isNumericStreamID(id) or isAny(id, .{ SpecialIDs.NEW_MESSAGES, SpecialIDs.ASSIGN_NEW_MESSAGES }), .XADD => !std.mem.eql(u8, id, SpecialIDs.BEGINNING) and (isNumericStreamID(id) or isAny(id, .{SpecialIDs.AUTO_ID})), .XRANGE, .XREVRANGE => isNumericStreamID(id) or isAny(id, .{ SpecialIDs.MIN, SpecialIDs.MAX }), }; } fn isAny(arg: []const u8, strings: anytype) bool { inline for (std.meta.fields(@TypeOf(strings))) |field| { const str = @field(strings, field.name); if (std.mem.eql(u8, arg, str)) return true; } return false; } pub fn isNumericStreamID(id: []const u8) bool { if (id.len > 41) return false; var hyphenPosition: isize = -1; var i: usize = 0; while (i < id.len) : (i += 1) { switch (id[i]) { '0'...'9' => {}, '-' => { if (hyphenPosition != -1) return false; hyphenPosition = @bitCast(isize, i); const first_part = id[0..i]; if (first_part.len == 0) return false; _ = std.fmt.parseInt(u64, first_part, 10) catch return false; }, else => return false, } } const second_part = id[@bitCast(usize, hyphenPosition + 1)..]; if (second_part.len == 0) return false; _ = std.fmt.parseInt(u64, second_part, 10) catch return false; return true; } test "numeric stream ids" { std.testing.expectEqual(false, isNumericStreamID("")); std.testing.expectEqual(false, isNumericStreamID(" ")); std.testing.expectEqual(false, isNumericStreamID("-")); std.testing.expectEqual(false, isNumericStreamID("-0")); std.testing.expectEqual(false, isNumericStreamID("-1234")); std.testing.expectEqual(false, isNumericStreamID("0-")); std.testing.expectEqual(false, isNumericStreamID("123-")); std.testing.expectEqual(true, isNumericStreamID("0")); std.testing.expectEqual(true, isNumericStreamID("123")); std.testing.expectEqual(true, isNumericStreamID("0-0")); std.testing.expectEqual(true, isNumericStreamID("0-123")); std.testing.expectEqual(true, isNumericStreamID("123123123-123123123")); std.testing.expectEqual(true, isNumericStreamID("18446744073709551615-18446744073709551615")); std.testing.expectEqual(false, isNumericStreamID("18446744073709551616-18446744073709551615")); std.testing.expectEqual(false, isNumericStreamID("18446744073709551615-18446744073709551616")); std.testing.expectEqual(false, isNumericStreamID("922337203685412312377580123123112317-922337212312312312312036854775808")); }
src/commands/streams/_utils.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 Tree = opaque { pub fn deinit(self: *Tree) void { log.debug("Tree.deinit called", .{}); c.git_tree_free(@ptrCast(*c.git_tree, self)); log.debug("tree freed successfully", .{}); } /// Get the id of a tree. pub fn getId(self: *const Tree) *const git.Oid { log.debug("Tree.id called", .{}); const ret = @ptrCast( *const git.Oid, c.git_tree_id(@ptrCast(*const c.git_tree, self)), ); 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("tree id: {s}", .{slice}); } else |_| {} } return ret; } /// Get the repository that contains the tree. pub fn owner(self: *const Tree) *git.Repository { log.debug("Tree.owner called", .{}); const ret = @ptrCast( *git.Repository, c.git_tree_owner(@ptrCast(*const c.git_tree, self)), ); log.debug("tree owner: {*}", .{ret}); return ret; } /// Get the number of entries listed in a tree pub fn entryCount(self: *const Tree) usize { log.debug("Tree.entryCount called", .{}); const ret = c.git_tree_entrycount(@ptrCast(*const c.git_tree, self)); log.debug("tree entry count: {}", .{ret}); return ret; } /// Lookup a tree entry by its filename /// /// This returns a `git.Tree.Entry` that is owned by the `git.Tree`. /// You don't have to free it, but you must not use it after the `git.Tree` is `deinit`ed. pub fn entryByName(self: *const Tree, name: [:0]const u8) ?*const Tree.Entry { log.debug("Tree.entryByName called, name={s}", .{name}); const opt_ret = @ptrCast(?*const Tree.Entry, c.git_tree_entry_byname( @ptrCast(*const c.git_tree, self), name.ptr, )); if (opt_ret) |ret| { log.debug("found entry: {*}", .{ret}); } else { log.debug("could not find entry", .{}); } return opt_ret; } /// Lookup a tree entry by its position in the tree /// /// This returns a `git.Tree.Entry` that is owned by the `git.Tree`. /// You don't have to free it, but you must not use it after the `git.Tree` is `deinit`ed. pub fn entryByIndex(self: *const Tree, index: usize) ?*const Tree.Entry { log.debug("Tree.entryByIndex called, index={}", .{index}); const opt_ret = @ptrCast(?*const Tree.Entry, c.git_tree_entry_byindex( @ptrCast(*const c.git_tree, self), index, )); if (opt_ret) |ret| { log.debug("found entry: {*}", .{ret}); } else { log.debug("could not find entry", .{}); } return opt_ret; } /// Duplicate a tree /// /// The returned tree is owned by the user and must be freed explicitly with `Tree.deinit`. pub fn duplicate(self: *Tree) !*Tree { log.debug("Tree.duplicate called", .{}); var ret: *Tree = undefined; try internal.wrapCall("git_tree_dup", .{ @ptrCast(*?*c.git_tree, &ret), @ptrCast(*c.git_tree, self), }); log.debug("successfully duplicated tree", .{}); return ret; } /// * Lookup a tree entry by SHA value. /// /// This returns a `git.Tree.Entry` that is owned by the `git.Tree`. /// You don't have to free it, but you must not use it after the `git.Tree` is `deinit`ed. /// /// Warning: this must examine every entry in the tree, so it is not fast. pub fn entryById(self: *const Tree, id: *const git.Oid) ?*const Tree.Entry { if (@enumToInt(std.log.Level.debug) <= @enumToInt(std.log.level)) { var buf: [git.Oid.HEX_BUFFER_SIZE]u8 = undefined; if (id.formatHex(&buf)) |slice| { log.debug("Tree.entryById called, id={s}", .{slice}); } else |_| {} } const opt_ret = @ptrCast(?*const Tree.Entry, c.git_tree_entry_byid( @ptrCast(*const c.git_tree, self), @ptrCast(*const c.git_oid, id), )); if (opt_ret) |ret| { log.debug("found entry: {*}", .{ret}); } else { log.debug("could not find entry", .{}); } return opt_ret; } /// Retrieve a tree entry contained in a tree or in any of its subtrees, given its relative path. /// /// Unlike the other lookup functions, the returned tree entry is owned by the user and must be freed explicitly with /// `Entry.deinit`. pub fn entryByPath(root: *const Tree, path: [:0]const u8) !*Tree.Entry { log.debug("Tree.entryByPath called, path={s}", .{path}); var ret: *Entry = undefined; try internal.wrapCall("git_tree_entry_bypath", .{ @ptrCast(*?*c.git_tree_entry, &ret), @ptrCast(*const c.git_tree, root), path.ptr, }); log.debug("found entry: {*}", .{ret}); return ret; } /// Tree traversal modes pub const WalkMode = enum(c_uint) { pre = 0, post = 1, }; /// Traverse the entries in a tree and its subtrees in post or pre order. /// /// The entries will be traversed in the specified order, children subtrees will be automatically loaded as required, /// and the `callback` will be called once per entry with the current (relative) root for the entry and the entry data itself. /// /// If the callback returns a positive value, the passed entry will be skipped on the traversal (in pre mode). /// A negative value stops the walk. /// /// ## Parameters /// * `mode` - Traversal mode (pre or post-order) /// * `user_data` - pointer to user data to be passed to the callback /// * `callback_fn` - the callback function /// /// ## Callback Parameters /// * `root` - The current (relative) root /// * `entry` - The entry /// * `user_data_ptr` - pointer to user data pub fn walk( self: *const Tree, mode: WalkMode, comptime callback_fn: fn ( root: [:0]const u8, entry: *const Tree.Entry, ) c_int, ) !void { const cb = struct { pub fn cb( root: [:0]const u8, entry: *const Tree.Entry, _: *u8, ) bool { return callback_fn(root, entry); } }.cb; var dummy_data: u8 = undefined; return self.walkWithUserData(&dummy_data, mode, cb); } /// Traverse the entries in a tree and its subtrees in post or pre order. /// /// The entries will be traversed in the specified order, children subtrees will be automatically loaded as required, /// and the `callback` will be called once per entry with the current (relative) root for the entry and the entry data itself. /// /// If the callback returns a positive value, the passed entry will be skipped on the traversal (in pre mode). /// A negative value stops the walk. /// /// ## Parameters /// * `mode` - Traversal mode (pre or post-order) /// * `user_data` - pointer to user data to be passed to the callback /// * `callback_fn` - the callback function /// /// ## Callback Parameters /// * `root` - The current (relative) root /// * `entry` - The entry /// * `user_data_ptr` - pointer to user data pub fn walkWithUserData( self: *const Tree, mode: WalkMode, user_data: anytype, comptime callback_fn: fn ( root: [:0]const u8, entry: *const Tree.Entry, user_data_ptr: @TypeOf(user_data), ) c_int, ) !void { const UserDataType = @TypeOf(user_data); const cb = struct { pub fn cb( root: [*:0]const u8, entry: *const c.git_tree_entry, payload: ?*anyopaque, ) callconv(.C) c_int { return callback_fn( std.mem.sliceTo(root, 0), @ptrCast(*const Tree.Entry, entry), @ptrCast(UserDataType, payload), ); } }.cb; log.debug("Tree.walkWithUserData called, mode={}", .{mode}); _ = try internal.wrapCallWithReturn("git_tree_walk", .{ @ptrCast(*c.git_tree, self), @enumToInt(mode), cb, user_data, }); } pub const Entry = opaque { pub fn deinit(self: *Entry) void { log.debug("Entry.deinit called", .{}); c.git_tree_entry_free(@ptrCast(*c.git_tree_entry, self)); log.debug("tree entry freed successfully", .{}); } /// Get the filename of a tree entry pub fn filename(self: *const Entry) [:0]const u8 { log.debug("Entry.filename called", .{}); const ret = c.git_tree_entry_name(@ptrCast(*const c.git_tree_entry, self)); const slice = std.mem.sliceTo(ret, 0); log.debug("entry filename: {s}", .{slice}); return slice; } /// Get the id of the object pointed by the entry pub fn getId(self: *const Entry) *const git.Oid { log.debug("Entry.getId called", .{}); const ret = @ptrCast( *const git.Oid, c.git_tree_entry_id(@ptrCast(*const c.git_tree_entry, self)), ); 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("entry id: {s}", .{slice}); } else |_| {} } return ret; } /// Get the type of the object pointed by the entry pub fn getType(self: *const Entry) git.ObjectType { log.debug("Entry.getType called", .{}); const ret = @intToEnum(git.ObjectType, c.git_tree_entry_type(@ptrCast(*const c.git_tree_entry, self))); log.debug("entry type: {}", .{ret}); return ret; } /// Get the UNIX file attributes of a tree entry pub fn filemode(self: *const Entry) git.FileMode { log.debug("Entry.filemode called", .{}); const ret = @intToEnum(git.FileMode, c.git_tree_entry_filemode(@ptrCast(*const c.git_tree_entry, self))); log.debug("entry file mode: {}", .{ret}); return ret; } /// Get the raw UNIX file attributes of a tree entry /// /// This function does not perform any normalization and is only useful if you need to be able to recreate the /// original tree object. pub fn filemodeRaw(self: *const Entry) c_uint { log.debug("Entry.filemodeRaw called", .{}); const ret = c.git_tree_entry_filemode_raw(@ptrCast(*const c.git_tree_entry, self)); log.debug("entry raw file mode: {}", .{ret}); return ret; } /// Compare two tree entries /// /// Returns <0 if `self` is before `other`, 0 if `self` == `other`, >0 if `self` is after `other` pub fn compare(self: *const Entry, other: *const Entry) c_int { log.debug("Entry.compare called", .{}); const ret = c.git_tree_entry_cmp( @ptrCast(*const c.git_tree_entry, self), @ptrCast(*const c.git_tree_entry, other), ); log.debug("compare result: {}", .{ret}); return ret; } /// Duplicate a tree entry /// /// The returned tree entry is owned by the user and must be freed explicitly with `Entry.deinit`. pub fn duplicate(self: *Entry) !*Entry { log.debug("Tree.duplicate called", .{}); var ret: *Entry = undefined; try internal.wrapCall("git_tree_entry_dup", .{ @ptrCast(*?*c.git_tree_entry, &ret), @ptrCast(*c.git_tree_entry, self), }); log.debug("successfully duplicated tree entry", .{}); return ret; } comptime { std.testing.refAllDecls(@This()); } }; comptime { std.testing.refAllDecls(@This()); } }; pub const TreeBuilder = opaque { /// Free a tree builder /// /// This will clear all the entries and free to builder. /// Failing to free the builder after you're done using it will result in a memory leak pub fn deinit(self: *TreeBuilder) void { log.debug("TreeBuilder.deinit called", .{}); c.git_treebuilder_free(@ptrCast(*c.git_treebuilder, self)); log.debug("treebuilder freed successfully", .{}); } /// Clear all the entires in the builder pub fn clear(self: *TreeBuilder) !void { log.debug("Tree.clear called", .{}); try internal.wrapCall("git_treebuilder_clear", .{ @ptrCast(*c.git_treebuilder, self), }); log.debug("successfully cleared treebuilder", .{}); } /// Get the number of entries listed in a treebuilder pub fn entryCount(self: *TreeBuilder) usize { log.debug("TreeBuilder.entryCount called", .{}); const ret = c.git_treebuilder_entrycount(@ptrCast(*c.git_treebuilder, self)); log.debug("treebuilder entry count: {}", .{ret}); return ret; } /// Get an entry from the builder from its filename /// /// The returned entry is owned by the builder and should not be freed manually. pub fn get(self: *TreeBuilder, filename: [:0]const u8) ?*const git.Tree.Entry { log.debug("TreeBuilder.get called, filename={s}", .{filename}); const opt_ret = @ptrCast( ?*const git.Tree.Entry, c.git_treebuilder_get( @ptrCast(*c.git_treebuilder, self), filename.ptr, ), ); if (opt_ret) |ret| { log.debug("found entry: {*}", .{ret}); } else { log.debug("could not find entry", .{}); } return opt_ret; } /// Add or update an entry to the builder /// /// Insert a new entry for `filename` in the builder with the given attributes. /// /// If an entry named `filename` already exists, its attributes will be updated with the given ones. /// /// The returned pointer may not be valid past the next operation in this builder. Duplicate the entry if you want to keep it. /// /// By default the entry that you are inserting will be checked for validity; that it exists in the object database and /// is of the correct type. If you do not want this behavior, set `Handle.optionSetStrictObjectCreation` to false. pub fn insert(self: *TreeBuilder, filename: [:0]const u8, id: *const git.Oid, filemode: git.FileMode) !*const Tree.Entry { if (@enumToInt(std.log.Level.debug) <= @enumToInt(std.log.level)) { var buf: [git.Oid.HEX_BUFFER_SIZE]u8 = undefined; if (id.formatHex(&buf)) |slice| { log.debug("TreeBuilder.insert called, filename={s}, id={s}, filemode={}", .{ filename, slice, filemode }); } else |_| {} } var ret: *const Tree.Entry = undefined; try internal.wrapCall("git_treebuilder_insert", .{ @ptrCast(*?*const c.git_tree_entry, &ret), @ptrCast(*c.git_treebuilder, self), filename.ptr, @ptrCast(*const c.git_oid, id), @enumToInt(filemode), }); log.debug("inserted entry: {*}", .{ret}); return ret; } /// Remove an entry from the builder by its filename pub fn remove(self: *TreeBuilder, filename: [:0]const u8) !void { log.debug("TreeBuilder.remove called, filename={s}", .{filename}); try internal.wrapCall("git_treebuilder_remove", .{ @ptrCast(*c.git_treebuilder, self), filename.ptr, }); log.debug("successfully removed entry", .{}); } /// Invoke `callback_fn` to selectively remove entries in the tree /// /// The `filter` callback will be called for each entry in the tree with a pointer to the entry; /// if the callback returns `true`, the entry will be filtered (removed from the builder). /// /// ## Parameters /// * `callback_fn` - the callback function /// /// ## Callback Parameters /// * `entry` - The entry pub fn filter( self: *TreeBuilder, comptime callback_fn: fn (entry: *const Tree.Entry) bool, ) !void { const cb = struct { pub fn cb( entry: *const Tree.Entry, _: *u8, ) bool { return callback_fn(entry); } }.cb; var dummy_data: u8 = undefined; return self.filterWithUserData(&dummy_data, cb); } /// Invoke `callback_fn` to selectively remove entries in the tree /// /// The `filter` callback will be called for each entry in the tree with a pointer to the entry and the provided `payload`; /// if the callback returns `true`, the entry will be filtered (removed from the builder). /// /// ## Parameters /// * `user_data` - pointer to user data to be passed to the callback /// * `callback_fn` - the callback function /// /// ## Callback Parameters /// * `entry` - The entry /// * `user_data_ptr` - pointer to user data pub fn filterWithUserData( self: *TreeBuilder, user_data: anytype, comptime callback_fn: fn ( entry: *const Tree.Entry, user_data_ptr: @TypeOf(user_data), ) bool, ) !void { const UserDataType = @TypeOf(user_data); const cb = struct { pub fn cb( entry: *const c.git_tree_entry, payload: ?*anyopaque, ) callconv(.C) c_int { return callback_fn( @ptrCast(*const Tree.Entry, entry), @ptrCast(UserDataType, payload), ) != 0; } }.cb; log.debug("Repository.filterWithUserData called", .{}); _ = try internal.wrapCallWithReturn("git_treebuilder_filter", .{ @ptrCast(*c.git_treebuilder, self), cb, user_data, }); } /// Write the contents of the tree builder as a tree object /// /// The tree builder will be written to the given `repo`, and its identifying SHA1 hash will be returned. pub fn write(self: *TreeBuilder) !git.Oid { log.debug("TreeBuilder.write called", .{}); var ret: git.Oid = undefined; try internal.wrapCall("git_treebuilder_write", .{ @ptrCast(*c.git_oid, &ret), @ptrCast(*c.git_treebuilder, self), }); log.debug("successfully written treebuilder", .{}); return ret; } comptime { std.testing.refAllDecls(@This()); } }; comptime { std.testing.refAllDecls(@This()); }
src/tree.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const log = std.log.scoped(.vr); const config = @import("config.zig"); /// TODO Use IO and callbacks: pub const Storage = struct { allocator: *Allocator, memory: []u8 align(config.sector_size), size: u64, pub fn init(allocator: *Allocator, size: u64) !Storage { var memory = try allocator.allocAdvanced(u8, config.sector_size, size, .exact); errdefer allocator.free(memory); std.mem.set(u8, memory, 0); return Storage{ .allocator = allocator, .memory = memory, .size = size, }; } pub fn deinit() void { self.allocator.free(self.memory); } /// Detects whether the underlying file system for a given directory fd supports Direct I/O. /// Not all Linux file systems support `O_DIRECT`, e.g. a shared macOS volume. pub fn fs_supports_direct_io(dir_fd: std.os.fd_t) !bool { if (!@hasDecl(std.os, "O_DIRECT")) return false; const os = std.os; const path = "fs_supports_direct_io"; const dir = fs.Dir{ .fd = dir_fd }; const fd = try os.openatZ(dir_fd, path, os.O_CLOEXEC | os.O_CREAT | os.O_TRUNC, 0o666); defer os.close(fd); defer dir.deleteFile(path) catch {}; while (true) { const res = os.system.openat(dir_fd, path, os.O_CLOEXEC | os.O_RDONLY | os.O_DIRECT, 0); switch (linux.getErrno(res)) { 0 => { os.close(@intCast(os.fd_t, res)); return true; }, linux.EINTR => continue, linux.EINVAL => return false, else => |err| return os.unexpectedErrno(err), } } } pub fn read(self: *Storage, buffer: []u8, offset: u64) void { self.assert_bounds_and_alignment(buffer, offset); if (self.read_all(buffer, offset)) |bytes_read| { if (bytes_read != buffer.len) { assert(bytes_read < buffer.len); log.emerg("short read: bytes_read={} buffer_len={} offset={}", .{ bytes_read, buffer.len, offset, }); @panic("fs corruption: file inode size truncated"); } } else |err| switch (err) { error.InputOutput => { // The disk was unable to read some sectors (an internal CRC or hardware failure): if (buffer.len > config.sector_size) { log.err("latent sector error: offset={}, subdividing read...", .{offset}); // Subdivide the read into sectors to read around the faulty sector(s): // This is considerably slower than doing a bulk read. // By now we might have also experienced the disk's read timeout (in seconds). // TODO Docs should instruct on why and how to reduce disk firmware timeouts. var buffer_offset = 0; while (buffer_offset < buffer.len) : (buffer_offset += config.sector_size) { self.read( buffer[buffer_offset..][0..config.sector_size], offset + buffer_offset, ); } assert(buffer_offset == buffer.len); } else { // Zero any remaining sectors that cannot be read: // We treat these EIO errors the same as a checksum failure. log.err("latent sector error: offset={}, zeroing buffer sector...", .{offset}); assert(buffer.len == config.sector_size); mem.set(u8, buffer, 0); } }, else => { log.emerg("impossible read: buffer_len={} offset={} error={}", .{ buffer_len, offset, err, }); @panic("impossible read"); }, } } pub fn write(self: *Storage, buffer: []const u8, offset: u64) void { self.assert_bounds_and_alignment(buffer, offset); self.write_all(buffer, offset) catch |err| switch (err) { // We assume that the disk will attempt to reallocate a spare sector for any LSE. // TODO What if we receive an EIO error because of a faulty cable? error.InputOutput => @panic("latent sector error: no spare sectors to reallocate"), else => { log.emerg("write: buffer.len={} offset={} error={}", .{ buffer.len, offset, err }); @panic("unrecoverable disk error"); }, }; } fn assert_bounds_and_alignment(self: *Storage, buffer: []const u8, offset: u64) void { assert(buffer.len > 0); assert(offset + buffer.len <= self.size); // Ensure that the read or write is aligned correctly for Direct I/O: // If this is not the case, the underlying syscall will return EINVAL. assert(@mod(@ptrToInt(buffer.ptr), config.sector_size) == 0); assert(@mod(buffer.len, config.sector_size) == 0); assert(@mod(offset, config.sector_size) == 0); } fn read_all(self: *Storage, buffer: []u8, offset: u64) !u64 { std.mem.copy(u8, buffer, self.memory[offset .. offset + buffer.len]); return buffer.len; } fn write_all(self: *Storage, buffer: []const u8, offset: u64) !void { std.mem.copy(u8, self.memory[offset .. offset + buffer.len], buffer); } };
src/storage.zig
const std = @import("std"); const ArrayList = std.ArrayList; const Allocator = std.mem.Allocator; const testing = std.testing; const expect = testing.expect; const expectEqual = testing.expectEqual; const Encoding = @import("encoding.zig").Encoding; const getEncoding = @import("encoding.zig").getEncoding; const getEncoderHandler = @import("encoding.zig").getEncoderHandler; const ErrorMode = @import("error.zig").ErrorMode; const WebEncError = @import("error.zig").WebEncError; const IoQueue = @import("io_queue.zig").IoQueue; pub const TextEncodeOptions = struct { encoding: []const u8 = "utf-8", fatal: bool = false, }; pub const HandlerResult = union(enum) { Finished, Items: []u8, Continue, }; pub const EncoderHandler = struct { handleFn: fn (self: *EncoderHandler, item: IoQueue(u21).Item) anyerror!HandlerResult, deinitFn: fn (self: *EncoderHandler) void, pub fn handle(self: *EncoderHandler, item: IoQueue(u21).Item) anyerror!HandlerResult { return self.handleFn(self, item); } pub fn deinit(self: *EncoderHandler) void { self.deinitFn(self); } }; // https://encoding.spec.whatwg.org/#interface-textencoder pub const TextEncoder = struct { allocator: *Allocator, options: TextEncodeOptions, encoding: Encoding, error_mode: ErrorMode, handler: *EncoderHandler, pub fn init(allocator: *Allocator, options: TextEncodeOptions) !TextEncoder { var encoding = try getEncoding(options.encoding); if (encoding == Encoding.Replacement) { return WebEncError.RangeError; } var handler: *EncoderHandler = try getEncoderHandler(allocator, encoding); return TextEncoder{ .allocator = allocator, .options = options, .encoding = encoding, .handler = handler, .error_mode = if (options.fatal) .Fatal else .Replacement, }; } pub fn deinit(self: *TextEncoder) void { self.handler.deinit(); } /// The caller owns the returned text pub fn encode(self: *TextEncoder, input: []const u21) ![]u8 { var text = ArrayList(u8).init(self.allocator); defer text.deinit(); var input_queue: IoQueue(u21) = IoQueue(u21).init(self.allocator, input); defer input_queue.deinit(); var output_queue: IoQueue(u8) = IoQueue(u8).init(self.allocator, ""); defer output_queue.deinit(); outer: while (true) { const item = input_queue.read(); const result = try self.handler.handle(item); switch (result) { .Finished => { break :outer; }, .Items => |items| { for (items) |output_item| { try output_queue.push(IoQueue(u8).Item{ .Regular = output_item }); } self.allocator.free(items); }, .Continue => {}, } } return try output_queue.serialize(); } }; // https://encoding.spec.whatwg.org/#interface-textencoderstream pub const TextEncoderStream = struct {}; test "Encode 'Hello, World!' to UTF-8" { var encoder = try TextEncoder.init(testing.allocator, .{}); defer encoder.deinit(); try expectEqual(Encoding.Utf8, encoder.encoding); var hello_world_str = [_]u21{ 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!' }; const hello_world_slice: []u21 = &hello_world_str; const encoded = try encoder.encode(hello_world_slice); defer testing.allocator.free(encoded); try expect(std.mem.eql(u8, "Hello, World!", encoded)); } test "Encode 'ə⚡𝅘𝅥𝅮'" { // U+0259 2 UTF-8 characters LATIN SMALL LETTER SCHWA // U+26A1 3 UTF-8 characters HIGH VOLTAGE SIGN // U+1D160 4 UTF-8 characters MUSICAL SYMBOL EIGHTH NOTE var encoder = try TextEncoder.init(testing.allocator, .{}); defer encoder.deinit(); try expectEqual(Encoding.Utf8, encoder.encoding); var schwa_lightning_note_str = [_]u21{ 0x0259, 0x26A1, 0x1D160 }; const schwa_lightning_note_slice: []u21 = &schwa_lightning_note_str; const encoded = try encoder.encode(schwa_lightning_note_slice); defer testing.allocator.free(encoded); try expect(std.mem.eql(u8, "ə⚡𝅘𝅥𝅮", encoded)); }
src/encode.zig
const std = @import("std"); const za = @import("zalgebra"); const Vec2 = za.vec2; // dross-zig // ----------------------------------------- // ----------------------------------------- // - Vector2 - // ----------------------------------------- pub const Vector2 = struct { data: Vec2, const Self = @This(); /// Builds and returns a new Vector2 with the compoents /// set to their respective passed values. pub fn new(x_value: f32, y_value: f32) Self { return Self{ .data = Vec2.new(x_value, y_value), }; } /// Returns the value of the x component pub fn x(self: Self) f32 { return self.data.x; } /// Returns the value of the y component pub fn y(self: Self) f32 { return self.data.y; } /// Builds and returns a Vector2 with all components /// set to `value`. pub fn setAll(value: f32) Self { return Self{ .data = Vec2.set(value), }; } /// Shorthand for a zeroed out Vector2 pub fn zero() Self { return Self{ .data = Vec2.zero(), }; } /// Shorthand for (0.0, 1.0) pub fn up() Self { return Self{ .data = Vec2.up(), }; } /// Shorthand for (1.0, 0.0) pub fn right() Self { return Self{ .data = Vec2.new(1.0, 0.0), }; } /// Transform vector to an array pub fn toArray(self: Self) [2]f32 { return self.data.to_array(); } /// Returns the angle (in degrees) between two vectors. pub fn angle(lhs: Self, rhs: Self) f32 { return lhs.data.get_angle(rhs.data); } /// Returns the length (magnitude) of the calling vector |a|. pub fn length(self: Self) f32 { return self.data.length(); } /// Returns a normalized copy of the calling vector. pub fn normalize(self: Self) Self { return Self{ .data = self.data.norm(), }; } /// Returns whether two vectors are equal or not pub fn isEqual(lhs: Self, rhs: Self) bool { return lsh.data.is_eq(rhs.data); } /// Subtraction between two vectors. pub fn subtract(lhs: Self, rhs: Self) Self { return Self{ .data = Vec2.sub(lhs.data, rhs.data), }; } /// Addition between two vectors. pub fn add(lhs: Self, rhs: Self) Self { return Self{ .data = Vec2.add(lhs.data, rhs.data), }; } /// Returns a new Vector2 multiplied by a scalar value pub fn scale(self: Self, scalar: f32) Self { return Self{ .data = self.data.scale(scalar), }; } /// Returns the dot product between two given vectors. pub fn dot(lhs: Self, rhs: Self) f32 { return lhs.data.dot(rhs.data); } /// Returns a linear interpolated Vector3 of the given vectors. /// t: [0.0 - 1.0] - How much should lhs move towards rhs /// Formula for a single value: /// start * (1 - t) + end * t pub fn lerp(lhs: Self, rhs: Self, t: f32) Self { return Self{ .data = lhs.data.lerp(rhs.data, t), }; } };
src/core/vector2.zig
const std = @import("std"); const Answer = struct { @"0": u64, @"1": u64 }; const Counts = std.AutoHashMap(u8, u64); fn applyRulesAndCount(template: std.ArrayList(u8), iterated_rules: std.StringHashMap(Counts), counts: *Counts) !void { var i: usize = 0; while (i < template.items.len - 1) : (i += 1) { try addCounts(iterated_rules.get(template.items[i .. i + 2]).?, counts); if (i == 0 or i == template.items.len - 2) { if (counts.get(template.items[i])) |count| { try counts.put(template.items[i], count - 1); } } } } fn most_extreme(counts: Counts, max_not_min: bool) ?u64 { var it = counts.valueIterator(); var extremum: ?u64 = null; while (it.next()) |count| { extremum = if (max_not_min) @maximum(extremum orelse count.*, count.*) else @minimum(extremum orelse count.*, count.*); } return extremum; } fn addCounts(x: Counts, y: *Counts) !void { var it = x.iterator(); while (it.next()) |entry| { if (y.get(entry.key_ptr.*)) |value| { try y.put(entry.key_ptr.*, entry.value_ptr.* + value); } else { try y.put(entry.key_ptr.*, entry.value_ptr.*); } } } fn step(iterated_rules: std.StringHashMap(Counts), iterated_rules_next: *std.StringHashMap(Counts), rules: std.StringHashMap(u8), arena: *std.heap.ArenaAllocator) !void { var it = rules.iterator(); while (it.next()) |entry| { const production: u8 = entry.value_ptr.*; const left = [2]u8{ (entry.key_ptr.*)[0], production }; const right = [2]u8{ production, (entry.key_ptr.*)[1] }; var counts = Counts.init(&arena.allocator); try addCounts(iterated_rules.get(left[0..2]).?, &counts); try addCounts(iterated_rules.get(right[0..2]).?, &counts); if (counts.get(production)) |count| { try counts.put(production, count - 1); } try iterated_rules_next.put(entry.key_ptr.*, counts); } } fn run(filename: []const u8) !Answer { const file = try std.fs.cwd().openFile(filename, .{ .read = true }); defer file.close(); var reader = std.io.bufferedReader(file.reader()).reader(); var buffer: [1024]u8 = undefined; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var arena = std.heap.ArenaAllocator.init(&gpa.allocator); defer arena.deinit(); var template = std.ArrayList(u8).init(&gpa.allocator); defer template.deinit(); var rules = std.StringHashMap(u8).init(&arena.allocator); var iterated_rules = std.StringHashMap(Counts).init(&arena.allocator); var iterated_rules_next = std.StringHashMap(Counts).init(&arena.allocator); if (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| { try template.resize(line.len); std.mem.copy(u8, template.items, line); } while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| { if (line.len == 0) { continue; } var tokens = std.mem.tokenize(u8, line, " >-"); const lhs = try arena.allocator.dupe(u8, tokens.next().?); const rhs = tokens.next().?[0]; try rules.put(lhs, rhs); var counts = Counts.init(&arena.allocator); if (lhs[0] == lhs[1]) { try counts.put(lhs[0], 2); } else { try counts.put(lhs[0], 1); try counts.put(lhs[1], 1); } try iterated_rules.put(lhs, counts); } var i: usize = 0; while (i < 10) : (i += 1) { try step(iterated_rules, &iterated_rules_next, rules, &arena); std.mem.swap(std.StringHashMap(Counts), &iterated_rules, &iterated_rules_next); iterated_rules_next.clearRetainingCapacity(); } var counts = Counts.init(&arena.allocator); try applyRulesAndCount(template, iterated_rules, &counts); const answer1 = most_extreme(counts, true).? - most_extreme(counts, false).?; while (i < 40) : (i += 1) { try step(iterated_rules, &iterated_rules_next, rules, &arena); std.mem.swap(std.StringHashMap(Counts), &iterated_rules, &iterated_rules_next); iterated_rules_next.clearRetainingCapacity(); } counts.clearRetainingCapacity(); try applyRulesAndCount(template, iterated_rules, &counts); const answer2 = most_extreme(counts, true).? - most_extreme(counts, false).?; return Answer{ .@"0" = answer1, .@"1" = answer2 }; } pub fn main() !void { const answer = try run("inputs/" ++ @typeName(@This()) ++ ".txt"); std.debug.print("{d}\n", .{answer.@"0"}); std.debug.print("{d}\n", .{answer.@"1"}); } test { const answer = try run("test-inputs/" ++ @typeName(@This()) ++ ".txt"); try std.testing.expectEqual(answer.@"0", 1588); try std.testing.expectEqual(answer.@"1", 2188189693529); }
src/day14.zig
const std = @import("std"); const georgios = @import("georgios"); const utils = @import("utils"); const Guid = utils.Guid; const ext2 = @import("ext2.zig"); const gpt = @import("gpt.zig"); const io = @import("io.zig"); const memory = @import("memory.zig"); const print = @import("print.zig"); const MappedList = @import("mapped_list.zig").MappedList; const List = @import("list.zig").List; pub const Error = georgios.fs.Error; pub const InitError = ext2.Error || gpt.Error || Guid.Error; const FileId = io.File.Id; fn file_id_eql(a: FileId, b: FileId) bool { return a == b; } fn file_id_cmp(a: FileId, b: FileId) bool { return a > b; } /// TODO: Make Abstract pub const File = ext2.File; /// TODO: Make Abstract pub const Filesystem = struct { const OpenFiles = MappedList(FileId, *File, file_id_eql, file_id_cmp); impl: ext2.Ext2 = ext2.Ext2{}, open_files: OpenFiles = undefined, next_file_id: FileId = 0, pub fn init(self: *Filesystem, alloc: *memory.Allocator, block_store: *io.BlockStore) InitError!void { var found = false; if (gpt.Disk.new(block_store)) |disk| { var disk_guid: [Guid.string_size]u8 = undefined; try disk.guid.to_string(disk_guid[0..]); print.format( \\ - Disk GUID is {} \\ - Disk partitions entries at LBA {} \\ - Disk partitions entries are {}B each \\ - Partitions: \\ , .{ disk_guid, disk.partition_entries_lba, disk.partition_entry_size, }); var part_it = try disk.partitions(); defer (part_it.done() catch unreachable); while (try part_it.next()) |part| { var type_guid: [Guid.string_size]u8 = undefined; try part.type_guid.to_string(type_guid[0..]); print.format( \\ - Part \\ - {} \\ - {} - {} \\ , .{ type_guid, part.start, part.end, }); if (part.is_linux()) { // TODO: Acutally see if this the right partition print.string(" - Is Linux!\n"); self.impl.offset = part.start * block_store.block_size; found = true; } } } else |e| { if (e != gpt.Error.InvalidMbr) { return e; } else { print.string(" - Disk doesn't have a MBR, going to try to use whole " ++ "disk as a ext2 filesystem.\n"); // Else try to use whole disk found = true; } } if (found) { print.string(" - Filesystem\n"); try self.impl.init(alloc, block_store); } else { print.string(" - No Filesystem\n"); } self.open_files = OpenFiles{.alloc = alloc}; } pub fn open(self: *Filesystem, path: []const u8) Error!*File { const file = try self.impl.open(path); file.io_file.id = self.next_file_id; self.next_file_id += 1; try self.open_files.push_front(file.io_file.id.?, file); return file; } pub fn file_id_read(self: *Filesystem, id: FileId, to: []u8) io.FileError!usize { if (self.open_files.find(id)) |file| { return file.io_file.read(to); } else { return io.FileError.InvalidFileId; } } pub fn file_id_write(self: *Filesystem, id: FileId, from: []const u8) io.FileError!usize { _ = from; if (self.open_files.find(id)) |file| { // TODO _ = file; @panic("Filesystem.file_id_write called"); } else { return io.FileError.InvalidFileId; } } // TODO: file_id_seek pub fn file_id_close(self: *Filesystem, id: FileId) io.FileError!void { if (try self.open_files.find_remove(id)) |file| { try self.impl.close(file); } else { return io.FileError.InvalidFileId; } } pub fn resolve_directory_path(self: *Filesystem, path: []const u8) Error![]const u8 { return self.impl.resolve_directory_path(path); } }; pub const Manager = struct { root: *Filesystem, }; /// TODO pub const Directory = struct { mount: ?*Filesystem = null, }; // File System Implementation Management / Mounting // Root of File System // On Disk File Structure? // Directory Structure // Directory Contents Iterator pub const PathIterator = struct { path: []const u8, pos: usize = 0, absolute: bool, trailing_slash: bool, pub fn new(path: []const u8) PathIterator { var trimmed_path = path; var absolute = false; var trailing_slash = false; if (trimmed_path.len > 0 and trimmed_path[0] == '/') { absolute = true; trimmed_path = trimmed_path[1..]; } if (trimmed_path.len > 0 and trimmed_path[trimmed_path.len - 1] == '/') { trailing_slash = true; trimmed_path = trimmed_path[0..trimmed_path.len - 1]; } return PathIterator{ .path = trimmed_path, .absolute = absolute, .trailing_slash = trailing_slash, }; } fn next_slash(self: *PathIterator) ?usize { var i: usize = self.pos; while (self.path[i] != '/') { i += 1; if (i >= self.path.len) return null; } return i; } pub fn done(self: *PathIterator) bool { return self.pos >= self.path.len; } pub fn next(self: *PathIterator) ?[]const u8 { var component: ?[]const u8 = null; while (component == null) { if (self.done()) { return null; } if (self.next_slash()) |slash| { component = self.path[self.pos..slash]; self.pos = slash + 1; } else { component = self.path[self.pos..]; self.pos = self.path.len; } if (component.?.len == 0 or utils.memory_compare(component.?, ".")) { component = null; } } return component; } }; fn assert_path_iterator( path: []const u8, expected: []const []const u8, absolute: bool, trailing_slash: bool) !void { var i: usize = 0; var it = PathIterator.new(path); try std.testing.expectEqual(absolute, it.absolute); try std.testing.expectEqual(trailing_slash, it.trailing_slash); while (it.next()) |component| { try std.testing.expect(i < expected.len); try std.testing.expectEqualStrings(expected[i], component); i += 1; } try std.testing.expect(it.done()); try std.testing.expectEqual(expected.len, i); } test "PathIterator" { try assert_path_iterator( "", &[_][]const u8{}, false, false); try assert_path_iterator( ".", &[_][]const u8{}, false, false); try assert_path_iterator( "./", &[_][]const u8{}, false, true); try assert_path_iterator( ".///////", &[_][]const u8{}, false, true); try assert_path_iterator( ".//.///.", &[_][]const u8{}, false, false); try assert_path_iterator( "/", &[_][]const u8{}, true, false); try assert_path_iterator( "/.", &[_][]const u8{}, true, false); try assert_path_iterator( "/./", &[_][]const u8{}, true, true); try assert_path_iterator( "/.///////", &[_][]const u8{}, true, true); try assert_path_iterator( "/.//.///.", &[_][]const u8{}, true, false); try assert_path_iterator( "alice", &[_][]const u8{"alice"}, false, false); try assert_path_iterator( "alice/bob", &[_][]const u8{"alice", "bob"}, false, false); try assert_path_iterator( "alice/bob/carol", &[_][]const u8{"alice", "bob", "carol"}, false, false); try assert_path_iterator( "alice/", &[_][]const u8{"alice"}, false, true); try assert_path_iterator( "alice/bob/", &[_][]const u8{"alice", "bob"}, false, true); try assert_path_iterator( "alice/bob/carol/", &[_][]const u8{"alice", "bob", "carol"}, false, true); try assert_path_iterator( "alice/bob/./carol/", &[_][]const u8{"alice", "bob", "carol"}, false, true); try assert_path_iterator( "alice/bob/../carol/.//./", &[_][]const u8{"alice", "bob", "..", "carol"}, false, true); try assert_path_iterator( "/alice", &[_][]const u8{"alice"}, true, false); try assert_path_iterator( "/alice/bob", &[_][]const u8{"alice", "bob"}, true, false); try assert_path_iterator( "/alice/bob/carol", &[_][]const u8{"alice", "bob", "carol"}, true, false); try assert_path_iterator( "/alice/", &[_][]const u8{"alice"}, true, true); try assert_path_iterator( "/alice/bob/", &[_][]const u8{"alice", "bob"}, true, true); try assert_path_iterator( "/alice/bob/carol/", &[_][]const u8{"alice", "bob", "carol"}, true, true); try assert_path_iterator( "/alice/bob/./carol/", &[_][]const u8{"alice", "bob", "carol"}, true, true); try assert_path_iterator( "/alice/bob/../carol/.//./", &[_][]const u8{"alice", "bob", "..", "carol"}, true, true); } pub const Path = struct { const StrList = List([]const u8); alloc: *memory.Allocator, absolute: bool = false, list: StrList = undefined, fn copy_string(self: *const Path, str: []const u8) Error![]u8 { const copy = try self.alloc.alloc_array(u8, str.len); _ = utils.memory_copy_truncate(copy, str); return copy; } fn push_to_list(self: *Path, list: *StrList, str: []const u8) Error!void { try list.push_back(try self.copy_string(str)); } pub fn push_component(self: *Path, str: []const u8) Error!void { try self.push_to_list(&self.list, str); } pub fn pop_component(self: *Path) Error!void { if (try self.list.pop_back()) |component| { try self.alloc.free_array(component); } } fn path_to_list(self: *Path, list: *StrList, path: []const u8) Error!bool { var it = PathIterator.new(path); while (it.next()) |component| { // Parent of root is root if (utils.memory_compare(component, "..") and it.absolute and list.len == 0) { continue; } try self.push_to_list(list, component); } return it.absolute; } pub fn set(self: *Path, path: []const u8) Error!void { self.absolute = try self.path_to_list(&self.list, path); } pub fn prepend(self: *Path, path: []const u8) Error!void { if (self.absolute) { @panic("Can not prepend to an absolute path"); } var new_list = StrList{.alloc = self.alloc}; self.absolute = try self.path_to_list(&new_list, path); new_list.push_back_list(&self.list); self.list = new_list; } pub fn init(self: *Path, path: ?[]const u8) Error!void { self.list = .{.alloc = self.alloc}; if (path) |p| { try self.set(p); } } pub fn done(self: *Path) Error!void { while (self.list.len > 0) { try self.pop_component(); } } fn value_if_empty(self: *const Path) []const u8 { return if (self.absolute) "/" else "."; } pub fn get(self: *const Path) Error![]u8 { // Calculate size of path string var size: usize = 0; var iter = self.list.const_iterator(); while (iter.next()) |component| { if (size > 0 or self.absolute) { size += 1; // For '/' } size += component.len; } if (size == 0) { size = 1; // For '.' or '/' } // Build path string iter = self.list.const_iterator(); var buffer: []u8 = try self.alloc.alloc_array(u8, size); var build = utils.ToString{.buffer = buffer}; while (iter.next()) |component| { if (build.got > 0 or self.absolute) { try build.string("/"); } try build.string(component); } if (build.got == 0) { try build.string(self.value_if_empty()); } return build.get(); } pub fn filename(self: *const Path) Error![]u8 { return try self.copy_string(if (self.list.tail) |tail_node| tail_node.value else self.value_if_empty()); } }; fn assert_path(alloc: *memory.Allocator, prepend: ?[]const u8, path_str: []const u8, expected: []const u8, expected_filename: []const u8) !void { var path = Path{.alloc = alloc}; try path.init(path_str); defer (path.done() catch unreachable); if (prepend) |pre| { try path.prepend(pre); } const result_path_str = try path.get(); try std.testing.expectEqualStrings(expected, result_path_str); try alloc.free_array(result_path_str); const filename = try path.filename(); try std.testing.expectEqualStrings(expected_filename, filename); try alloc.free_array(filename); } test "Path" { var alloc = memory.UnitTestAllocator{}; alloc.init(); defer alloc.done(); const galloc = &alloc.allocator; try assert_path(galloc, null, "", ".", "."); try assert_path(galloc, null, "./", ".", "."); try assert_path(galloc, null, "./.", ".", "."); try assert_path(galloc, null, "./a/b/c", "a/b/c", "c"); try assert_path(galloc, null, "./a/b/../c", "a/b/../c", "c"); try assert_path(galloc, null, "/", "/", "/"); try assert_path(galloc, null, "/a/b/c", "/a/b/c", "c"); try assert_path(galloc, null, "/a/b/../c", "/a/b/../c", "c"); try assert_path(galloc, null, "/a/../a/b/..//c///./.", "/a/../a/b/../c", "c"); try assert_path(galloc, null, "..", "..", ".."); try assert_path(galloc, null, "a/../../b", "a/../../b", "b"); try assert_path(galloc, null, "/..", "/", "/"); try assert_path(galloc, null, "/../file", "/file", "file"); try assert_path(galloc, ".", ".", ".", "."); try assert_path(galloc, "", "goodbye", "goodbye", "goodbye"); try assert_path(galloc, "hello", "goodbye", "hello/goodbye", "goodbye"); try assert_path(galloc, "/", "a", "/a", "a"); }
kernel/fs.zig
const std = @import("std"); const testing = std.testing; const Opaque = @OpaqueType(); pub const Dynamic = struct { v: *const Opaque, Type: type, pub fn init(comptime Type: type, v: *const Type) Dynamic { return Dynamic{ .v = @ptrCast(*const Opaque, v), .Type = Type, }; } // TODO: Change to pass-by-value pub fn value(comptime dyn: *const Dynamic) dyn.Type { return @ptrCast(*const dyn.Type, dyn.v).*; } // TODO: Change to pass-by-value pub fn field(comptime dyn: *const Dynamic, comptime field_name: []const u8) (@TypeOf(@field(dyn.Type{}, field_name))) { return @field(dyn.value(), field_name); } // TODO: Change to pass-by-value pub fn call(comptime dyn: *const Dynamic, args: ...) dyn.Type.ReturnType { return switch (args.len) { 0 => dyn.value()(), 1 => dyn.value()(args[0]), 2 => dyn.value()(args[0], args[1]), 3 => dyn.value()(args[0], args[1], args[2]), 4 => dyn.value()(args[0], args[1], args[2], args[3]), 5 => dyn.value()(args[0], args[1], args[2], args[3], args[4]), 6 => dyn.value()(args[0], args[1], args[2], args[3], args[4], args[5]), 7 => dyn.value()(args[0], args[1], args[2], args[3], args[4], args[5], args[6]), 8 => dyn.value()(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]), 9 => dyn.value()(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]), else => comptime unreachable, }; } }; test "Dynamic.value" { comptime { var a: u8 = 0; var b: f32 = 1.0; var c: []const u8 = "Hello World!"; const dyn_int = Dynamic.init(u8, &a); const dyn_float = Dynamic.init(f32, &b); const dyn_string = Dynamic.init([]const u8, &c); // They are all the same static type, just like in dynamic typed languages testing.expectEqual(@TypeOf(dyn_int), @TypeOf(dyn_float)); testing.expectEqual(@TypeOf(dyn_int), @TypeOf(dyn_string)); testing.expectEqual(@TypeOf(dyn_float), @TypeOf(dyn_string)); // Their values, are not the same dynamic type though. testing.expect(@TypeOf(dyn_int.value()) != @TypeOf(dyn_float.value())); testing.expect(@TypeOf(dyn_int.value()) != @TypeOf(dyn_string.value())); testing.expect(@TypeOf(dyn_float.value()) != @TypeOf(dyn_string.value())); testing.expectEqual(dyn_int.value(), 0); testing.expectEqual(dyn_float.value(), 1.0); testing.expectEqualSlices(u8, "Hello World!", dyn_string.value()); } }
fun/comptime_dynamic_typing.zig
const std = @import("std"); const nvg = @import("nanovg"); title: []const u8, artist: []const u8, album_art: []const u8, video: []const u8, image: ?nvg.Image = null, const Self = @This(); const Song = Self; pub fn loadSongs(allocator: std.mem.Allocator, pref_path: []const u8) ![]Song { var arr = std.ArrayList(Song).init(allocator); defer arr.deinit(); const buf = try allocator.alloc(u8, 0x1000); // json can't be larger than 64k defer allocator.free(buf); const user_songs_path = try std.fs.path.join(allocator, &.{ pref_path, "songs" }); defer allocator.free(user_songs_path); for ([_][]const u8{ "songs", user_songs_path }) |songs_path| { const songs_dir = std.fs.cwd().openDir(songs_path, .{ .iterate = true }) catch |err| { switch (err) { error.FileNotFound => continue, // skip dir else => return err, } }; var dir_it = songs_dir.iterate(); while (try dir_it.next()) |entry| { if (entry.kind != .File) continue; const file_ext = std.fs.path.extension(entry.name); if (std.ascii.eqlIgnoreCase(".json", file_ext)) { const file = try songs_dir.openFile(entry.name, .{}); defer file.close(); const len = try file.readAll(buf); var stream = std.json.TokenStream.init(buf[0..len]); var song = try std.json.parse(Song, &stream, .{ .allocator = allocator, .ignore_unknown_fields = true }); try song.resolvePaths(allocator, songs_path); try arr.append(song); } } } // sort songs by artist, title asc std.sort.sort(Song, arr.items, {}, struct { fn lessThan(ctx: void, lhs: Song, rhs: Song) bool { _ = ctx; const artist_order = std.ascii.orderIgnoreCase(lhs.artist, rhs.artist); if (artist_order == .eq) { const title_order = std.ascii.orderIgnoreCase(lhs.title, rhs.title); return title_order == .lt; } else { return artist_order == .lt; } } }.lessThan); return arr.toOwnedSlice(); } pub fn resolvePaths(self: *Self, allocator: std.mem.Allocator, path_prefix: []const u8) !void { if (!std.fs.path.isAbsolute(self.album_art)) { const old_path = self.album_art; self.album_art = try std.fs.path.join(allocator, &.{ path_prefix, self.album_art }); allocator.free(old_path); } if (!std.fs.path.isAbsolute(self.video)) { const old_path = self.video; self.video = try std.fs.path.join(allocator, &.{ path_prefix, self.video }); allocator.free(old_path); } } pub fn free(self: Self, allocator: std.mem.Allocator) void { allocator.free(self.title); allocator.free(self.artist); allocator.free(self.album_art); allocator.free(self.video); }
src/Song.zig
const std = @import("std"); const builtin = @import("builtin"); const root = @import("main.zig"); const req = @import("request.zig"); const Request = req.Request; const Response = req.Response; const libressl = root.libressl; const zuri = root.zuri; const hzzp = root.hzzp; fn initWindows() void { if (@import("builtin").os.tag == .windows) { _ = std.os.windows.WSAStartup(2, 2) catch { @panic("Failed to initialize on windows"); }; } } var windowsInit = std.once(initWindows); const CurlConnectionPoolMaxAgeSecs = 118; const CurlConnectionPoolMaxClients = 5; // things to check when matching connections // host & port match // protocols match // TODO(haze/for the future): stuff that i saw curl doing (ConnectionExists in lib/url.c) // ssl upgraded connections? // authentication? // Doubly linked list, protected by a parent rwlock to ensure thread safety const StoredConnection = struct { const Self = @This(); const Criteria = struct { allocator: std.mem.Allocator, host: union(enum) { provided: []const u8, allocated: []u8, }, port: u16, is_tls: bool, fn getHost(self: Criteria) []const u8 { return switch (self.host) { .allocated => |data| data, .provided => |data| data, }; } pub fn eql(self: Criteria, other: Criteria) bool { const are_both_tls = self.is_tls == other.is_tls; const do_ports_match = self.port == other.port; const do_hosts_match = std.mem.eql(u8, self.getHost(), other.getHost()); return are_both_tls and do_ports_match and do_hosts_match; } pub fn deinit(self: *Criteria) void { switch (self.host) { .provided => {}, .allocated => |buf| self.allocator.free(buf), } self.* = undefined; } }; allocator: std.mem.Allocator, clientState: union(enum) { Ssl: libressl.SslStream, Normal: std.net.Stream, }, criteria: Criteria, pub fn deinit(self: *Self) void { self.criteria.deinit(); self.allocator.destroy(self); } }; const ConnectionCache = struct { const Self = @This(); // TODO(haze): remove mutex in single threaded mode const Queue = std.TailQueue(*StoredConnection); const Node = Queue.Node; items: Queue = Queue{}, fn findSuitableConnection(self: *Self, criteria: StoredConnection.Criteria) ?*Node { var ptr: ?*Node = self.items.last; while (ptr) |node| { root.logger.debug("Checking Connection {*} {}", .{ node, node.data }); if (node.data.criteria.eql(criteria)) return node; ptr = node.prev; } return null; } fn removeFromCache(self: *Self, stored_connection_node: *Node) void { self.items.remove(stored_connection_node); } pub fn deinit(self: *Self) void { while (self.items.pop()) |node| { var allocator = node.data.allocator; node.data.deinit(); allocator.destroy(node); } } fn addNewConnection(self: *Self, stored_connection_node: *Node) void { // var lock = self.mutex.acquire(); // defer lock.release(); self.items.append(stored_connection_node); } }; pub var globalConnectionCache = ConnectionCache{}; pub const Client = struct { const Self = @This(); const HzzpSslResponseParser = hzzp.parser.response.ResponseParser(libressl.SslStream.Reader); const HzzpResponseParser = hzzp.parser.response.ResponseParser(std.net.Stream.Reader); pub const HzzpSslClient = hzzp.base.client.BaseClient(libressl.SslStream.Reader, libressl.SslStream.Writer); pub const HzzpClient = hzzp.base.client.BaseClient(std.net.Stream.Reader, std.net.Stream.Writer); pub const State = union(enum) { Created, ConnectedSsl: struct { tunnel: libressl.SslStream, client: HzzpSslClient, }, Connected: struct { tcpConnection: std.net.Stream, client: HzzpClient, }, Shutdown, const NextError = HzzpSslResponseParser.NextError || HzzpResponseParser.NextError; const PayloadReader = union(enum) { SslReader: HzzpSslClient.PayloadReader, Reader: HzzpClient.PayloadReader, }; pub fn payloadReader(self: *State) PayloadReader { return switch (self.*) { .ConnectedSsl => |*state| .{ .SslReader = state.client.reader() }, .Connected => |*state| .{ .Reader = state.client.reader() }, else => unreachable, }; } pub fn next(self: *State) NextError!?hzzp.parser.response.Event { return switch (self.*) { .ConnectedSsl => |*state| state.client.next(), .Connected => |*state| state.client.next(), else => unreachable, }; } pub fn writePayload(self: *State, maybeData: ?[]const u8) !void { if (maybeData) |data| root.logger.debug("Attempting to write {} byte payload", .{data.len}) else root.logger.debug("Attempting to write null payload", .{}); return switch (self.*) { .ConnectedSsl => |*state| state.client.writePayload(maybeData), .Connected => |*state| state.client.writePayload(maybeData), else => unreachable, }; } pub fn finishHeaders(self: *State) !void { root.logger.debug("Attempting to finish headers", .{}); return switch (self.*) { .ConnectedSsl => |*state| state.client.finishHeaders(), .Connected => |*state| state.client.finishHeaders(), else => unreachable, }; } pub fn writeHeaderValue(self: *State, name: []const u8, value: []const u8) !void { root.logger.debug("Attempting to set header: \"{s}\" = \"{s}\"", .{ name, value }); return switch (self.*) { .ConnectedSsl => |*state| state.client.writeHeaderValue(name, value), .Connected => |*state| state.client.writeHeaderValue(name, value), else => unreachable, }; } pub fn writeStatusLine(self: *State, method: []const u8, path: []const u8) !void { root.logger.debug("Attempting to write status line (method={s}, path={s})", .{ method, path }); return switch (self.*) { .ConnectedSsl => |*state| state.client.writeStatusLine(method, path), .Connected => |*state| state.client.writeStatusLine(method, path), else => unreachable, }; } }; allocator: std.mem.Allocator, state: State, clientReadBuffer: []u8, userAgent: ?[]u8, pub fn deinit(self: *Self) void { if (self.userAgent) |userAgent| self.allocator.free(userAgent); self.allocator.free(self.clientReadBuffer); self.allocator.destroy(self); } /// if a user agent is provided, it will be copied into the client and free'd once deinit is called pub fn init(allocator: std.mem.Allocator, options: struct { userAgent: ?[]const u8 = null, }) !*Self { var client: *Self = try allocator.create(Self); errdefer allocator.destroy(client); client.allocator = allocator; client.state = .Created; client.clientReadBuffer = try allocator.alloc(u8, 1 << 13); errdefer allocator.free(client.clientReadBuffer); if (options.userAgent) |userAgent| { client.userAgent = try allocator.alloc(u8, userAgent.len); std.mem.copy(u8, client.userAgent.?, userAgent); } else { client.userAgent = null; } windowsInit.call(); return client; } pub fn perform(self: *Self, request: Request) !Response { var uri = try zuri.Uri.parse(request.url, false); if (!std.ascii.eqlIgnoreCase(uri.scheme, "http") and !std.ascii.eqlIgnoreCase(uri.scheme, "https")) return error.InvalidHttpScheme; const port: u16 = if (uri.port == null) if (std.mem.startsWith(u8, uri.scheme, "https")) @as(u16, 443) else @as(u16, 80) else uri.port.?; var tunnelHostBuf: [1 << 8]u8 = undefined; var tunnelHost: []const u8 = undefined; var isSsl = port == 443; var reused_connection: ?*ConnectionCache.Node = null; switch (uri.host) { .name => |host| { if (host.len == 0) return error.MissingHost; std.mem.copy(u8, &tunnelHostBuf, host); tunnelHost = tunnelHostBuf[0..host.len]; }, .ip => |addr| { // if we have an ip, print it as the host for the iguanaTLS client tunnelHost = try std.fmt.bufPrint(&tunnelHostBuf, "{}", .{addr}); }, } // we need to set this null byte for tls connections (because before tunnelHost would be a // slice pointing to the url, and that would include the path) tunnelHostBuf[tunnelHost.len] = '\x00'; if (request.use_global_connection_pool) { root.logger.info("Searching connection cache...", .{}); if (globalConnectionCache.findSuitableConnection(StoredConnection.Criteria{ .allocator = self.allocator, .host = .{ .provided = tunnelHost }, .port = port, .is_tls = isSsl, })) |stored_connection_node| { reused_connection = stored_connection_node; self.state = switch (stored_connection_node.data.clientState) { .Ssl => |*sslTunnel| .{ .ConnectedSsl = .{ .tunnel = sslTunnel.*, .client = hzzp.base.client.create(self.clientReadBuffer, sslTunnel.reader(), sslTunnel.writer()), }, }, .Normal => |tcpConnection| .{ .Connected = .{ .tcpConnection = tcpConnection, .client = hzzp.base.client.create(self.clientReadBuffer, tcpConnection.reader(), tcpConnection.writer()), } }, }; globalConnectionCache.removeFromCache(stored_connection_node); root.logger.info("Found a connection to reuse! {}", .{stored_connection_node.data.criteria}); } else { root.logger.info("No reusable connection found", .{}); } } var created_new_connection = false; root.logger.debug("req={}", .{request}); if (reused_connection == null) { var tcpConnection = switch (uri.host) { .name => |host| blk: { root.logger.debug("Opening tcp connection to {s}:{}...", .{ host, port }); break :blk try std.net.tcpConnectToHost(self.allocator, host, port); }, .ip => |addr| blk: { root.logger.debug("Opening tcp connection to {s}:{}...", .{ tunnelHost, port }); break :blk try std.net.tcpConnectToAddress(addr); }, }; if (isSsl) { var tls_configuration = request.tls_configuration orelse try (libressl.TlsConfigurationParams{}).build(); root.logger.debug("Opening TLS tunnel... (host='{s}') {}", .{ tunnelHost, tls_configuration.params }); var tunnel = try libressl.SslStream.wrapClientStream(tls_configuration, tcpConnection, tunnelHost); root.logger.debug("Tunnel open, creating client now", .{}); var client = hzzp.base.client.create(self.clientReadBuffer, tunnel.reader(), tunnel.writer()); created_new_connection = true; self.state = .{ .ConnectedSsl = .{ .tunnel = tunnel, .client = client, }, }; } else { var client = hzzp.base.client.create(self.clientReadBuffer, tcpConnection.reader(), tcpConnection.writer()); created_new_connection = true; self.state = .{ .Connected = .{ .client = client, .tcpConnection = tcpConnection, }, }; } root.logger.debug("Client created...", .{}); } var added_connection_to_global_cache = false; root.logger.debug("path={s} query={s} fragment={s}", .{ uri.path, uri.query, uri.fragment }); var path = if (std.mem.trim(u8, uri.path, " ").len == 0) "/" else uri.path; if (std.mem.trim(u8, uri.query, " ").len == 0) { try self.state.writeStatusLine(@tagName(request.method), path); } else { var status = try std.fmt.allocPrint(self.allocator, "{s}?{s}", .{ path, uri.query }); try self.state.writeStatusLine(@tagName(request.method), status); self.allocator.free(status); } try self.state.writeHeaderValue("Host", tunnelHost); try self.state.writeHeaderValue("Connection", "Keep-Alive"); if (self.userAgent) |userAgent| try self.state.writeHeaderValue("User-Agent", userAgent) else try self.state.writeHeaderValue("User-Agent", root.ZeldaDefaultUserAgent); // write headers now that we are connected if (request.headers) |headerMap| { var headerMapIter = headerMap.iterator(); while (headerMapIter.next()) |kv| { var value = try kv.value_ptr.value(self.allocator); defer self.allocator.free(value); try self.state.writeHeaderValue(kv.key_ptr.*, value); } } // write body if (request.body) |body| { switch (body.kind) { .JSON => try self.state.writeHeaderValue("Content-Type", "application/json"), .URLEncodedForm => try self.state.writeHeaderValue("Content-Type", "application/x-www-form-urlencoded"), else => {}, } var contentLengthBuffer: [64]u8 = undefined; const contentLength = try std.fmt.bufPrint(&contentLengthBuffer, "{}", .{body.bytes.len}); try self.state.writeHeaderValue("Content-Length", contentLength); try self.state.finishHeaders(); try self.state.writePayload(body.bytes); } else { try self.state.finishHeaders(); try self.state.writePayload(null); } root.logger.debug("Finished sending request...", .{}); var event = try self.state.next(); if (event == null) { return error.MissingStatus; } else while (event.? == .skip) : (event = try self.state.next()) {} if (event == null or event.? != .status) { return error.MissingStatus; } const rawCode = try std.math.cast(u10, event.?.status.code); const responseCode = @intToEnum(hzzp.StatusCode, rawCode); // read response headers var response = Response.init(self.allocator, responseCode); event = try self.state.next(); while (event != null and event.? != .head_done) : (event = try self.state.next()) { switch (event.?) { .header => |header| { const value = try self.allocator.alloc(u8, header.value.len); std.mem.copy(u8, value, header.value); if (response.headers.getEntry(header.name)) |entry| { try entry.value_ptr.parts.append(value); } else { var list = req.HeaderValue.init(self.allocator); try list.parts.append(value); const name = try self.allocator.alloc(u8, header.name.len); std.mem.copy(u8, name, header.name); try response.headers.put(name, list); } }, else => return error.ExpectedHeaders, } } // read response body (if any) var bodyReader = self.state.payloadReader(); response.body = switch (bodyReader) { .SslReader => |reader| try reader.readAllAlloc(self.allocator, std.math.maxInt(u64)), .Reader => |reader| try reader.readAllAlloc(self.allocator, std.math.maxInt(u64)), }; if (created_new_connection and request.use_global_connection_pool) { var stored_connection = try self.allocator.create(StoredConnection); stored_connection.allocator = self.allocator; stored_connection.clientState = switch (self.state) { .ConnectedSsl => |sslState| .{ .Ssl = sslState.tunnel }, .Connected => |normalState| .{ .Normal = normalState.tcpConnection }, else => unreachable, }; stored_connection.criteria = StoredConnection.Criteria{ .allocator = self.allocator, .host = .{ .allocated = try self.allocator.dupe(u8, tunnelHost) }, .port = port, .is_tls = isSsl, }; var node = try self.allocator.create(@TypeOf(globalConnectionCache).Node); node.next = null; node.prev = null; node.data = stored_connection; globalConnectionCache.addNewConnection(node); added_connection_to_global_cache = true; } else if (reused_connection) |stored_connection| { // we're done with the one we used, we can put it back globalConnectionCache.addNewConnection(stored_connection); } return response; } };
src/client.zig
const Assertion = @import("parse.zig").Assertion; pub const Input = struct { bytes: []const u8, byte_pos: usize, currentFn: fn (input: Input) ?u8, advanceFn: fn (input: *Input) void, isNextWordCharFn: fn (input: Input) bool, isPrevWordCharFn: fn (input: Input) bool, pub fn advance(self: *Input) void { self.advanceFn(self); } pub fn current(self: Input) ?u8 { return self.currentFn(self); } // Note: We extend the range here to one past the end of the input. This is done in order to // handle complete matches correctly. pub fn isConsumed(self: Input) bool { return self.byte_pos > self.bytes.len; } pub fn isEmptyMatch(self: Input, match: Assertion) bool { switch (match) { Assertion.None => { return true; }, Assertion.BeginLine => { return self.byte_pos == 0; }, Assertion.EndLine => { return self.byte_pos >= self.bytes.len - 1; }, Assertion.BeginText => { // TODO: Handle different modes. return self.byte_pos == 0; }, Assertion.EndText => { return self.byte_pos >= self.bytes.len - 1; }, Assertion.WordBoundaryAscii => { return self.isPrevWordCharFn(self) != self.isNextWordCharFn(self); }, Assertion.NotWordBoundaryAscii => { return self.isPrevWordCharFn(self) == self.isNextWordCharFn(self); }, } } // Create a new instance using the same interface functions. pub fn clone(self: Input) Input { return Input{ .bytes = self.bytes, .byte_pos = self.byte_pos, .currentFn = self.currentFn, .advanceFn = self.advanceFn, .isNextWordCharFn = self.isNextWordCharFn, .isPrevWordCharFn = self.isPrevWordCharFn, }; } }; pub const InputBytes = struct { input: Input, pub fn init(bytes: []const u8) InputBytes { return InputBytes{ .input = Input{ .bytes = bytes, .byte_pos = 0, .currentFn = current, .advanceFn = advance, .isNextWordCharFn = isNextWordChar, .isPrevWordCharFn = isPrevWordChar, }, }; } // TODO: When we can compare ?usize == usize this will be a bit nicer. fn current(self: Input) ?u8 { if (self.byte_pos < self.bytes.len) { return self.bytes[self.byte_pos]; } else { return null; } } fn advance(self: *Input) void { if (self.byte_pos <= self.bytes.len) { self.byte_pos += 1; } } fn isWordChar(c: u8) bool { return switch (c) { '0'...'9', 'a'...'z', 'A'...'Z' => true, else => false, }; } fn isNextWordChar(self: Input) bool { return (self.byte_pos == 0) or isWordChar(self.bytes[self.byte_pos - 1]); } fn isPrevWordChar(self: Input) bool { return (self.byte_pos >= self.bytes.len - 1) or isWordChar(self.bytes[self.byte_pos + 1]); } };
src/input.zig
const DaisyChain = @import("DaisyChain.zig"); const PIO = @This(); ports: [NumPorts]Port = [_]Port{.{}} ** NumPorts, reset_active: bool = true, // reset state sticks until first control word received in_func: PortInput, // port-input callback out_func: PortOutput, // port-output callback // reset the PIO chip pub fn reset(self: *PIO) void { for (self.ports) |*p| { p.mode = Mode.INPUT; p.output = 0; p.io_select = 0; p.int_control &= ~IntCtrl.EI; p.int_mask = 0xFF; p.int_enabled = false; p.expect_int_mask = false; p.expect_io_select = false; p.bctrl_match = false; p.intrp.reset(); } self.reset_active = true; } // perform an IO request pub fn iorq(self: *PIO, in_pins: u64) u64 { var pins = in_pins; if ((pins & (CE|IORQ|M1)) == (CE|IORQ)) { const port_index = @truncate(u1, (pins & BASEL) >> BASELPinShift); if (0 != (pins & RD)) { // an IO read request const data = if (0 != (pins & CDSEL)) self.readCtrl() else self.readData(port_index); pins = setData(pins, data); } else { // an IO write request const data = getData(pins); if (0 != (pins & CDSEL)) { self.writeCtrl(port_index, data); } else { self.writeData(port_index, data); } } pins = setPAB(pins, self.ports[PA].port, self.ports[PB].port); } return pins; } // write value to PIO port, this may trigger an interrupt pub fn writePort(self: *PIO, port_index: u1, data: u8) void { var p = &self.ports[port_index]; if (Mode.BITCONTROL == p.mode) { p.input = data; const val = (p.input & p.io_select) | (p.output & ~p.io_select); p.port = val; const mask = ~p.int_mask; var match = false; val &= mask; const ictrl = p.int_control & 0x60; if ((ictrl == 0) and (val != mask)) { match = true; } else if ((ictrl == 0x20) and (val != 0)) { match = true; } else if ((ictrl == 0x40) and (val == 0)) { match = true; } else if ((ictrl == 0x60) and (val == mask)) { match = true; } if (!p.bctrl_match and match and (0 != (p.int_control & 0x80))) { // request interrupt p.intr.irq(); } p.bctrl_match = match; } } // call once per CPU machine cycle for interrupt handling pub fn int(self: *PIO, in_pins: u64) u64 { var pins = in_pins; for (self.ports) |*p| { pins = p.intr.tick(pins); } return pins; } // set data pins in pin mask pub fn setData(pins: u64, data: u8) u64 { return (pins & ~DataPinMask) | (@as(u64, data) << DataPinShift); } // get data pins in pin mask pub fn getData(pins: u64) u8 { return @truncate(u8, pins >> DataPinShift); } // set port A pins pub fn setPA(pins: u64, data: u8) u64 { return (pins & ~PAPinMask) | ((@as(u64, data)<<PAPinShift) & PAPinMask); } // set port B pins pub fn setPB(pins: u64, data: u8) u64 { return (pins & ~PBPinMask) | ((@as(u64, data)<<PBPinShift) & PBPinMask); } // set both port A and B pins pub fn setPAB(pins: u64, pa_data: u8, pb_data: u8) u64 { return setPB(setPA(pins, pa_data), pb_data); } // data bus pins shared with CPU pub const D0: u64 = 1<<16; pub const D1: u64 = 1<<17; pub const D2: u64 = 1<<18; pub const D3: u64 = 1<<19; pub const D4: u64 = 1<<20; pub const D5: u64 = 1<<21; pub const D6: u64 = 1<<22; pub const D7: u64 = 1<<23; pub const DataPinShift = 16; pub const DataPinMask: u64 = 0xFF0000; // control pins shared with CPU pub const M1: u64 = 1<<24; // machine cycle 1 pub const IORQ: u64 = 1<<26; // IO request pub const RD: u64 = 1<<27; // read request // PIO specific pins starting at bit 40 pub const CE: u64 = 1<<40; // chip enable pub const BASEL: u64 = 1<<41; // port A/B select (0: A, 1: B) pub const CDSEL: u64 = 1<<42; // control/data select (0: data, 1: control) pub const ARDY: u64 = 1<<43; // port A ready pub const BRDY: u64 = 1<<44; // port B ready pub const ASTB: u64 = 1<<45; // port A strobe pub const BSTB: u64 = 1<<46; // port B strobe pub const BASELPinShift = 41; // port pins pub const PA0: u64 = 1<<48; pub const PA1: u64 = 1<<49; pub const PA2: u64 = 1<<50; pub const PA3: u64 = 1<<51; pub const PA4: u64 = 1<<52; pub const PA5: u64 = 1<<53; pub const PA6: u64 = 1<<54; pub const PA7: u64 = 1<<55; pub const PB0: u64 = 1<<56; pub const PB1: u64 = 1<<57; pub const PB2: u64 = 1<<58; pub const PB3: u64 = 1<<59; pub const PB4: u64 = 1<<60; pub const PB5: u64 = 1<<61; pub const PB6: u64 = 1<<62; pub const PB7: u64 = 1<<63; pub const PAPinMask: u64 = 0x00FF_0000_0000_0000; pub const PBPinMask: u64 = 0xFF00_0000_0000_0000; pub const PAPinShift = 48; pub const PBPinShift = 56; // port indices pub const PA: u1 = 0; pub const PB: u1 = 1; pub const NumPorts: usize = 2; // Operating Modes // // The operating mode of a port is established by writing a control word // to the PIO in the following format: // // D7 D6 D5 D4 D3 D2 D1 D0 // |M1|M0| x| x| 1| 1| 1| 1| // // D7,D6 are the mode word bits // D3..D0 set to 1111 to indicate 'Set Mode' // pub const Mode = struct { pub const OUTPUT: u2 = 0; pub const INPUT: u2 = 1; pub const BIDIRECTIONAL: u2 = 2; pub const BITCONTROL: u2 = 3; }; // Interrupt control word bits. // // D7 D6 D5 D4 D3 D2 D1 D0 // |EI|AO|HL|MF| 0| 1| 1| 1| // // D7 (EI) interrupt enabled (1=enabled, 0=disabled) // D6 (AND/OR) logical operation during port monitoring (only Mode 3, AND=1, OR=0) // D5 (HIGH/LOW) port data polarity during port monitoring (only Mode 3) // D4 (MASK FOLLOWS) if set, the next control word are the port monitoring mask (only Mode 3) // // (*) if an interrupt is pending when the enable flag is set, it will then be // enabled on the onto the CPU interrupt request line // (*) setting bit D4 during any mode of operation will cause any pending // interrupt to be reset // // The interrupt enable flip-flop of a port may be set or reset // without modifying the rest of the interrupt control word // by the following command: // // D7 D6 D5 D4 D3 D2 D1 D0 // |EI| x| x| x| 0| 0| 1| 1| // pub const IntCtrl = struct { pub const EI: u8 = 1<<7; pub const ANDOR: u8 = 1<<6; pub const HILO: u8 = 1<<5; pub const MASK_FOLLOWS: u8 = 1<<4; }; // // IO port registers // pub const Port = struct { input: u8 = 0, // data input register output: u8 = 0, // data output register port: u8 = 0, // current state of the port I/O pins mode: u2 = Mode.INPUT, // mode control register (Mode.*) io_select: u8 = 0, // input/output select register int_control: u8 = 0, // interrupt control word (IntCtrl.*) int_mask: u8 = 0xFF, // interrupt control mask int_enabled: bool = false, // definitive interrupt enabled flag expect_io_select: bool = false, // next control word will be io_select expect_int_mask: bool = false, // next control word will be int_mask bctrl_match: bool = false, // bitcontrol logic equation result intr: DaisyChain = .{}, // interrupt daisychain state }; // Port IO callbacks and userdata const PortInput = struct { func: fn(port: u1, userdata: usize) u8, userdata: usize = 0, }; const PortOutput = struct { func: fn(port: u1, data: u8, userdata: usize) void, userdata: usize = 0, }; // new control word received from CPU fn writeCtrl(self: *PIO, port_index: u1, data: u8) void { self.reset_active = false; var p = &self.ports[port_index]; if (p.expect_io_select) { // followup io select mask p.expect_io_select = false; p.io_select = data; p.int_enabled = 0 != (p.int_control & IntCtrl.EI); } else if (p.expect_int_mask) { // followup interrupt mask p.expect_int_mask = false; p.int_mask = data; p.int_enabled = 0 != (p.int_control & IntCtrl.EI); } else switch (data & 0x0F) { 0x0F => { // set operating mode (Mode.*) p.mode = @truncate(u2, data >> 6); switch (p.mode) { Mode.OUTPUT => { // make output visible on port pins p.port = p.output; self.out_func.func(port_index, p.port, self.out_func.userdata); }, Mode.BITCONTROL => { // next control word is the io_select mask p.expect_io_select = true; // temporarily disable interrupts until io_select mask written p.int_enabled = false; p.bctrl_match = false; }, else => { }, } }, 0x07 => { // set interrupt control word (IntCtrl.*) p.int_control = data & 0xF0; if (0 != (data & IntCtrl.MASK_FOLLOWS)) { // next control word is the interrupt control mask p.expect_int_mask = true; // temporarily disable interrupts until mask written p.int_enabled = false; // reset pending interrupt p.intr.state = 0; p.bctrl_match = false; } else { p.int_enabled = 0 != (p.int_control & IntCtrl.EI); } }, 0x03 => { // only set interrupt enable bit p.int_control = (data & IntCtrl.EI) | (p.int_control & ~IntCtrl.EI); p.int_enabled = 0 != (p.int_control & IntCtrl.EI); }, else => if (0 == (data & 1)) { // set interrupt vector p.intr.vector = data; // according to MAME setting the interrupt vector // also enables interrupts, but this doesn't seem to // be mentioned in the spec p.int_control |= IntCtrl.EI; p.int_enabled = true; } } } // read control word back to CPU fn readCtrl(self: *PIO) u8 { // I haven't found definitive documentation about what is // returned when reading the control word, this // is what MAME does return (self.ports[PA].int_control & 0xC0) | (self.ports[PB].int_control >> 4); } // new data word received from CPU fn writeData(self: *PIO, port_index: u1, data: u8) void { var p = &self.ports[port_index]; switch (p.mode) { Mode.OUTPUT => { p.output = data; p.port = data; self.out_func.func(port_index, p.port, self.out_func.userdata); }, Mode.INPUT => { p.output = data; }, Mode.BIDIRECTIONAL => { // FIXME: not implemented }, Mode.BITCONTROL => { p.output = data; p.port = p.io_select | (p.output & ~p.io_select); self.out_func.func(port_index, p.port, self.out_func.userdata); } } } // read port data back to CPU fn readData(self: *PIO, port_index: u1) u8 { var p = &self.ports[port_index]; switch (p.mode) { Mode.OUTPUT => { return p.output; }, Mode.INPUT => { p.input = self.in_func.func(port_index, self.in_func.userdata); p.port = p.input; return p.port; }, Mode.BIDIRECTIONAL => { p.input = self.in_func.func(port_index, self.in_func.userdata); p.port = (p.input & p.io_select) | (p.output & ~p.io_select); return p.port; }, else => { return 0xFF; } } } //=== TEST ===================================================================== const expect = @import("std").testing.expect; var pa_val: u8 = 0; var pb_val: u8 = 0; fn in_func(port: u1, userdata: usize) u8 { _ = userdata; return switch (port) { PA => 0, PB => 1, }; } fn out_func(port: u1, data: u8, userdata: usize) void { _ = userdata; switch (port) { PA => { pa_val = data; }, PB => { pb_val = data; }, } } test "read_write_control" { var pio = PIO{ .in_func = .{ .func = in_func }, .out_func = .{ .func = out_func }, }; // write interrupt vector 0xEE to port A try expect(pio.reset_active); pio.writeCtrl(PA, 0xEE); try expect(!pio.reset_active); try expect(pio.ports[PA].intr.vector == 0xEE); try expect(0 != (pio.ports[PA].int_control & IntCtrl.EI)); // write interrupt vector 0xCC for port B pio.writeCtrl(PB, 0xCC); try expect(pio.ports[PB].intr.vector == 0xCC); try expect(0 != (pio.ports[PB].int_control & IntCtrl.EI)); // set port A to output pio.writeCtrl(PA, (@as(u8, Mode.OUTPUT)<<6)|0x0F); try expect(pio.ports[PA].mode == Mode.OUTPUT); // set port B to input pio.writeCtrl(PB, (@as(u8, Mode.INPUT)<<6)|0x0F); try expect(pio.ports[PB].mode == Mode.INPUT); // set port A to bidirectional pio.writeCtrl(PA, (@as(u8, Mode.BIDIRECTIONAL)<<6)|0x0F); try expect(pio.ports[PA].mode == Mode.BIDIRECTIONAL); // set port A to mode control (plus followup io_select mask) pio.writeCtrl(PA, (@as(u8, Mode.BITCONTROL)<<6)|0x0F); try expect(!pio.ports[PA].int_enabled); try expect(pio.ports[PA].mode == Mode.BITCONTROL); pio.writeCtrl(PA, 0xAA); try expect(pio.ports[PA].int_enabled); try expect(pio.ports[PA].io_select == 0xAA); // set port B interrupt control word (with interrupt control mask following) pio.writeCtrl(PB, (IntCtrl.ANDOR|IntCtrl.HILO|IntCtrl.MASK_FOLLOWS)|0x07); try expect(!pio.ports[PB].int_enabled); try expect(pio.ports[PB].int_control == (IntCtrl.ANDOR|IntCtrl.HILO|IntCtrl.MASK_FOLLOWS)); pio.writeCtrl(PB, 0x23); try expect(!pio.ports[PB].int_enabled); try expect(pio.ports[PB].int_mask == 0x23); // enable interrupts on port B pio.writeCtrl(PB, IntCtrl.EI|0x03); try expect(pio.ports[PB].int_enabled); try expect(pio.ports[PB].int_control == (IntCtrl.EI|IntCtrl.ANDOR|IntCtrl.HILO|IntCtrl.MASK_FOLLOWS)); // write interrupt control word to A and B, // and read the control word back, this does not // seem to be documented anywhere, so we're doing // the same thing that MAME does. pio.writeCtrl(PA, IntCtrl.ANDOR|IntCtrl.HILO|0x07); pio.writeCtrl(PB, IntCtrl.EI|IntCtrl.ANDOR|0x07); const data = pio.readCtrl(); try expect(data == 0x4C); }
src/emu/PIO.zig
const std = @import("std"); usingnamespace @import("common.zig"); const base64 = std.base64; const ascii = std.ascii; const math = std.math; const time = std.time; const rand = std.rand; const mem = std.mem; const assert = std.debug.assert; pub fn extractMaskByte(mask: u32, index: usize) u8 { return @truncate(u8, mask >> @truncate(u5, (index % 4) * 8)); } pub fn create(buffer: []u8, reader: anytype) Client(@TypeOf(reader)) { assert(buffer.len >= 16); return ClientParser(@TypeOf(reader)).init(buffer, reader); } pub fn ClientParser(comptime Reader: type) type { return struct { const Self = @This(); read_buffer: []u8, reader: Reader, current_mask: ?u32 = null, mask_index: usize = 0, chunk_need: usize = 0, chunk_read: usize = 0, chunk_mask: ?u32 = null, state: ParserState = .header, pub fn init(buffer: []u8, reader: Reader) Self { return .{ .read_buffer = buffer, .reader = reader, }; } pub fn reset(self: *Self) void { self.current_mask = null; self.mask_index = 0; self.chunk_need = 0; self.chunk_read = 0; self.chunk_mask = null; self.state = .header; } pub const NextError = error{EndOfStream} || Reader.Error; pub fn next(self: *Self) NextError!?Event { switch (self.state) { .header => { const read_head_len = try self.reader.readAll(self.read_buffer[0..2]); if (read_head_len != 2) return error.EndOfStream; const fin = self.read_buffer[0] & 0x80 == 0x80; const rsv1 = self.read_buffer[0] & 0x40 == 0x40; const rsv2 = self.read_buffer[0] & 0x20 == 0x20; const rsv3 = self.read_buffer[0] & 0x10 == 0x10; const opcode = @truncate(u4, self.read_buffer[0]); const masked = self.read_buffer[1] & 0x80 == 0x80; const check_len = @truncate(u7, self.read_buffer[1]); var len: u64 = check_len; var mask_index: u4 = 2; self.chunk_read = 0; if (check_len == 127) { const read_len_len = try self.reader.readAll(self.read_buffer[2..10]); if (read_len_len != 8) return error.EndOfStream; mask_index = 10; len = mem.readIntBig(u64, self.read_buffer[2..10]); self.chunk_need = len; } else if (check_len == 126) { const read_len_len = try self.reader.readAll(self.read_buffer[2..4]); if (read_len_len != 2) return error.EndOfStream; mask_index = 4; len = mem.readIntBig(u16, self.read_buffer[2..4]); self.chunk_need = len; } else { self.chunk_need = check_len; } if (masked) { const read_mask_len = try self.reader.readAll(self.read_buffer[mask_index .. mask_index + 4]); if (read_mask_len != 4) return error.EndOfStream; self.chunk_mask = mem.readIntSliceBig(u32, self.read_buffer[mask_index .. mask_index + 4]); } else { self.chunk_mask = null; } self.state = .chunk; return Event{ .header = .{ .fin = fin, .rsv1 = rsv1, .rsv2 = rsv2, .rsv3 = rsv3, .opcode = @intToEnum(Opcode, opcode), .length = len, .mask = self.chunk_mask, }, }; }, .chunk => { const left = math.min(self.chunk_need - self.chunk_read, self.read_buffer.len); const read = try self.reader.read(self.read_buffer[0..left]); self.chunk_read += read; if (self.chunk_mask) |mask| { for (self.read_buffer[0..read]) |*c, i| { c.* = c.* ^ extractMaskByte(mask, i + self.chunk_read); } } assert(self.chunk_read <= self.chunk_need); if (self.chunk_read == self.chunk_need) { self.state = .header; } return Event{ .chunk = .{ .data = self.read_buffer[0..read], .final = self.chunk_read == self.chunk_need, }, }; }, } } }; }
src/parser/client.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day03.txt"); const width = indexOf(u8, data, '\n').?; const uint = std.meta.Int(.unsigned, width); const UintList = List(uint); const UBitSet = std.bit_set.IntegerBitSet(width); fn get_gamma(nums: UintList, eql: u1) uint { var digits: [2][width]u32 = .{ .{0} ** width, .{0} ** width }; var bs: UBitSet = UBitSet.initEmpty(); // count for (nums.items) |n| { bs.mask = @as(UBitSet.MaskInt, n); var i: usize = 0; while (i < width) : (i += 1) { var d: u1 = if (bs.isSet(i)) 1 else 0; digits[d][i] += 1; } } var gamma: uint = 0; var i: usize = 0; while (i < width) : (i += 1) { gamma = gamma << 1; if (digits[1][i] > digits[0][i]) { gamma += 1; } else if (digits[1][i] == digits[0][i]) { gamma += eql; } } return gamma; } fn load_data() !UintList { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); var nums: UintList = UintList.init(&arena.allocator); var lines = util.strtok(data, "\n"); while (lines.next()) |line| { var n: uint = try parseInt(uint, line, 2); try nums.append(n); } return nums; } pub fn main() !void { { // part 1 var nums: UintList = try load_data(); var gamma: uint = get_gamma(nums, 0); print("gamma: {d}\n", .{gamma}); print("epsilon: {d}\n", .{~gamma}); var rate: u128 = @intCast(u128, gamma) * @intCast(u128, ~gamma); print("rate: {d}\n", .{rate}); } var oxygen = find_oxygen: { // part 2.1 var bs: UBitSet = UBitSet.initEmpty(); var nums: UintList = try load_data(); var mask: uint = 0; var masked: u4 = width; //var pos = 1; while (nums.items.len > 1) { var gamma: uint = get_gamma(nums, 1); bs.mask = @as(UBitSet.MaskInt, gamma); mask <<= 1; masked -= 1; if (bs.isSet(masked)) { mask += 1; } removing: for (nums.items) |n, i| { if (n >> masked == mask) continue; var cur: uint = n; while (cur >> masked != mask) { if (i >= nums.items.len) break :removing; _ = nums.swapRemove(i); if (i >= nums.items.len) break :removing; cur = nums.items[i]; } } print("masked: {d} mask: {b} items: {d}\n", .{ masked, mask, nums.items.len }); } break :find_oxygen nums.items[0]; }; var co2 = find_co2: { // part 2.1 var bs: UBitSet = UBitSet.initEmpty(); var nums: UintList = try load_data(); var mask: uint = 0; var masked: u4 = width; //var pos = 1; while (nums.items.len > 1) { var gamma: uint = get_gamma(nums, 0); bs.mask = @as(UBitSet.MaskInt, ~gamma); mask <<= 1; masked -= 1; if (bs.isSet(masked)) { mask += 1; } removing: for (nums.items) |n, i| { if (n >> masked == mask) continue; var cur: uint = n; while (cur >> masked != mask) { if (i >= nums.items.len) break :removing; _ = nums.swapRemove(i); if (i >= nums.items.len) break :removing; cur = nums.items[i]; } } print("masked: {d} mask: {b} items: {d}\n", .{ masked, mask, nums.items.len }); } break :find_co2 nums.items[0]; }; var rating: u128 = @intCast(u128, oxygen) * @intCast(u128, co2); print("oxygen: {d} co2: {d} rating: {d}\n", .{ oxygen, co2, rating }); } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc;
src/day03.zig
const std = @import("std"); pub fn copy(comptime T: type, dest: []T, source: []const T) void { const n = 32; // TODO: Adjust based on bitSizeOf T const V = @Vector(n, T); if (source.len < n) return std.mem.copy(T, dest, source); var end: usize = n; while (end < source.len) { const start = end - n; const source_chunk: V = source[start..end][0..n].*; const dest_chunk: *V = &@as(V, dest[start..end][0..n].*); dest_chunk.* = source_chunk; end = std.math.min(end + n, source.len); } } pub fn eql(comptime T: type, a: []const T, b: []const T) bool { const n = 32; const V8x32 = @Vector(n, T); if (a.len != b.len) return false; if (a.ptr == b.ptr) return true; if (a.len < n) { // Too small to fit, fallback to standard eql for (a) |item, index| { if (b[index] != item) return false; } } else { var end: usize = n; while (end < a.len) { const start = end - n; const a_chunk: V8x32 = a[start..end][0..n].*; const b_chunk: V8x32 = b[start..end][0..n].*; if (!@reduce(.And, a_chunk == b_chunk)) { return false; } end = std.math.min(end + n, a.len); } } return true; } pub fn lastIndexOf(comptime T: type, buf: []const u8, delimiter: []const u8) ?usize { const n = 32; const k = delimiter.len; const V8x32 = @Vector(n, T); const V1x32 = @Vector(n, u1); // const Vbx32 = @Vector(n, bool); const first = @splat(n, delimiter[0]); const last = @splat(n, delimiter[k - 1]); if (buf.len < n) { return std.mem.lastIndexOfPos(T, buf, 0, delimiter); } var start: usize = buf.len - n; while (start > 0) { const end = start + n; const last_end = std.math.min(end + k - 1, buf.len); const last_start = last_end - n; // Look for the first character in the delimter const first_chunk: V8x32 = buf[start..end][0..n].*; const last_chunk: V8x32 = buf[last_start..last_end][0..n].*; const mask = @bitCast(V1x32, first == first_chunk) & @bitCast(V1x32, last == last_chunk); if (@reduce(.Or, mask) != 0) { // TODO: Use __builtin_ctz??? var i: usize = n; while (i > 0) { i -= 1; if (mask[i] == 1 and eql(T, buf[start + i .. start + i + k], delimiter)) { return start + i; } } } start = std.math.max(start - n, 0); } return null; // Not found } pub fn indexOf(comptime T: type, buf: []const u8, delimiter: []const u8) ?usize { return indexOfPos(T, buf, 0, delimiter); } pub fn indexOfPos(comptime T: type, buf: []const u8, start_index: usize, delimiter: []const u8) ?usize { const n = 32; const k = delimiter.len; const V8x32 = @Vector(n, T); const V1x32 = @Vector(n, u1); const Vbx32 = @Vector(n, bool); const first = @splat(n, delimiter[0]); const last = @splat(n, delimiter[k - 1]); var end: usize = start_index + n; var start: usize = end - n; while (end < buf.len) { start = end - n; const last_end = std.math.min(end + k - 1, buf.len); const last_start = last_end - n; // Look for the first character in the delimter const first_chunk: V8x32 = buf[start..end][0..n].*; const last_chunk: V8x32 = buf[last_start..last_end][0..n].*; const mask = @bitCast(V1x32, first == first_chunk) & @bitCast(V1x32, last == last_chunk); if (@reduce(.Or, mask) != 0) { // TODO: Use __builtin_clz??? for (@as([n]bool, @bitCast(Vbx32, mask))) |match, i| { if (match and eql(T, buf[start + i .. start + i + k], delimiter)) { return start + i; } } } end = std.math.min(end + n, buf.len); } if (start < buf.len) return std.mem.indexOfPos(T, buf, start_index, delimiter); return null; // Not found } pub fn split(buffer: []const u8, delimiter: []const u8) SplitIterator { return SplitIterator{ .buffer = buffer, .delimiter = delimiter }; } pub const SplitIterator = struct { index: ?usize = 0, buffer: []const u8, delimiter: []const u8, /// Returns a slice of the next field, or null if splitting is complete. pub fn next(self: *SplitIterator) ?[]const u8 { const start = self.index orelse return null; const end = if (indexOfPos(u8, self.buffer, start, self.delimiter)) |delim_start| blk: { self.index = delim_start + self.delimiter.len; break :blk delim_start; } else blk: { self.index = null; break :blk self.buffer.len; }; return self.buffer[start..end]; } /// Returns a slice of the remaining bytes. Does not affect iterator state. pub fn rest(self: SplitIterator) []const u8 { const end = self.buffer.len; const start = self.index orelse end; return self.buffer[start..end]; } };
src/simd.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ines = @import("../ines.zig"); const console_ = @import("../console.zig"); const Config = console_.Config; const Console = console_.Console; const GenericMapper = @import("../mapper.zig").GenericMapper; const common = @import("common.zig"); pub fn Mapper(comptime config: Config) type { const G = GenericMapper(config); return struct { const Self = @This(); prgs: common.Prgs, chrs: common.Chrs, mirroring: ines.Mirroring, pub fn initMem( self: *Self, allocator: *Allocator, _: *Console(config), info: *ines.RomInfo, ) Allocator.Error!void { self.* = Self{ .prgs = try common.Prgs.init(allocator, info.prg_rom), .chrs = try common.Chrs.init(allocator, info.chr_rom), .mirroring = info.mirroring, }; } pub fn deinitMem(generic: G, allocator: *Allocator) void { const self = common.fromGeneric(Self, config, generic); self.prgs.deinit(allocator); self.chrs.deinit(allocator); allocator.destroy(self); } pub fn mirrorNametable(generic: G, addr: u16) u12 { const self = common.fromGeneric(Self, config, generic); return common.mirrorNametable(self.mirroring, addr); } pub fn readPrg(generic: G, addr: u16) ?u8 { const self = common.fromGeneric(Self, config, generic); if (addr >= 0x8000) { return self.prgs.read(addr); } else { return null; } } pub fn readChr(generic: G, addr: u16) u8 { const self = common.fromGeneric(Self, config, generic); return self.chrs.read(addr); } pub fn writePrg(_: *G, _: u16, _: u8) void {} pub fn writeChr(generic: *G, addr: u16, val: u8) void { const self = common.fromGeneric(Self, config, generic.*); self.chrs.write(addr, val); } }; }
src/mapper/nrom.zig
const std = @import("std"); const ray = @import("translate-c/raylib.zig"); const PostProcessShader = enum { bloom, blur, cross_hatching, cross_stitching, dream_vision, fisheye, grayscale, pixelizer, posterization, predator_view, scanlines, sobel, }; pub fn loadShader(shader_type: PostProcessShader) ray.Shader { return switch (shader_type) { .bloom => return ray.LoadShader(null, "3rd/raylib/examples/shaders/resources/shaders/glsl330/bloom.fs"), .blur => return ray.LoadShader(null, "3rd/raylib/examples/shaders/resources/shaders/glsl330/blur.fs"), .cross_hatching => return ray.LoadShader(null, "3rd/raylib/examples/shaders/resources/shaders/glsl330/cross_hatching.fs"), .cross_stitching => return ray.LoadShader(null, "3rd/raylib/examples/shaders/resources/shaders/glsl330/cross_stitching.fs"), .dream_vision => return ray.LoadShader(null, "3rd/raylib/examples/shaders/resources/shaders/glsl330/dream_vision.fs"), .fisheye => return ray.LoadShader(null, "3rd/raylib/examples/shaders/resources/shaders/glsl330/fisheye.fs"), .grayscale => return ray.LoadShader(null, "3rd/raylib/examples/shaders/resources/shaders/glsl330/grayscale.fs"), .pixelizer => return ray.LoadShader(null, "3rd/raylib/examples/shaders/resources/shaders/glsl330/pixelizer.fs"), .posterization => return ray.LoadShader(null, "3rd/raylib/examples/shaders/resources/shaders/glsl330/posterization.fs"), .predator_view => return ray.LoadShader(null, "3rd/raylib/examples/shaders/resources/shaders/glsl330/predator.fs"), .scanlines => return ray.LoadShader(null, "3rd/raylib/examples/shaders/resources/shaders/glsl330/scanlines.fs"), .sobel => return ray.LoadShader(null, "3rd/raylib/examples/shaders/resources/shaders/glsl330/sobel.fs"), }; } pub fn unloadShader() void {} pub fn main() anyerror!void { // Initialization //-------------------------------------------------------------------------------------- const screenWidth = 800; const screenHeight = 450; const total_shader = @intCast(std.meta.Tag(PostProcessShader), std.meta.fields(PostProcessShader).len); ray.SetConfigFlags(ray.FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available) ray.InitWindow(screenWidth, screenHeight, "raylib [shaders] example - postprocessing shader"); defer ray.CloseWindow(); // Define the camera to look into our 3d world var camera = ray.Camera{ .position = ray.Vector3{ .x = 2, .y = 3, .z = 2 }, .target = ray.Vector3{ .x = 0, .y = 1, .z = 0 }, .up = ray.Vector3{ .x = 0, .y = 1, .z = 0 }, .fovy = 45, .projection = ray.CAMERA_PERSPECTIVE, }; var model = ray.LoadModel("3rd/raylib/examples/shaders/resources/models/church.obj"); // Load OBJ model defer ray.UnloadModel(model); // Unload model var texture = ray.LoadTexture("3rd/raylib/examples/shaders/resources/models/church_diffuse.png"); // Load model texture defer ray.UnloadTexture(texture); // Unload texture // (diffuse map) model.materials[0].maps[ray.MATERIAL_MAP_DIFFUSE].texture = texture; // Set model diffuse texture var position = ray.Vector3{ .x = 0, .y = 0, .z = 0 }; // Set model position // Load all postpro shaders // NOTE 1: All postpro shader use the base vertex shader // (DEFAULT_VERTEX_SHADER) NOTE 2: We load the correct shader depending on // GLSL version var shaders: [total_shader]ray.Shader = undefined; for (shaders) |*sh, i| { sh.* = loadShader(@intToEnum(PostProcessShader, @intCast(std.meta.Tag(PostProcessShader), i))); } //TODO: find a way to deffer clean shader // comptime for (shaders) |sh| { // defer ray.UnloadShader(sh); // }; var current_shader = PostProcessShader.bloom; // Create a RenderTexture2D to be used for render to texture var target = ray.LoadRenderTexture(screenWidth, screenHeight); defer ray.UnloadRenderTexture(target); // Unload render texture // Setup orbital camera ray.SetCameraMode(camera, ray.CAMERA_ORBITAL); // Set an orbital camera mode ray.SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop while (!ray.WindowShouldClose()) { // Update //---------------------------------------------------------------------------------- ray.UpdateCamera(&camera); // Update camera if (ray.IsKeyPressed(ray.KEY_RIGHT)) { current_shader = @intToEnum(PostProcessShader, (@enumToInt(current_shader) +% 1) % total_shader); } else if (ray.IsKeyPressed(ray.KEY_LEFT)) { current_shader = @intToEnum(PostProcessShader, (@enumToInt(current_shader) -% 1) % total_shader); } //---------------------------------------------------------------------------------- // Draw //---------------------------------------------------------------------------------- ray.BeginTextureMode(target); // Enable drawing to texture ray.ClearBackground(ray.RAYWHITE); // Clear texture background ray.BeginMode3D(camera); // Begin 3d mode drawing ray.DrawModel(model, position, 0.1, ray.WHITE); // Draw 3d model with texture ray.DrawGrid(10, 1); // Draw a grid ray.EndMode3D(); // End 3d mode drawing, returns to orthographic 2d mode ray.EndTextureMode(); // End drawing to texture (now we have a texture available // for next passes) ray.BeginDrawing(); ray.ClearBackground(ray.RAYWHITE); // Clear screen background // Render generated texture using selected postprocessing shader { ray.BeginShaderMode(shaders[@enumToInt(current_shader)]); // NOTE: Render texture must be y-flipped due to default OpenGL coordinates // (left-bottom) ray.DrawTextureRec(target.texture, ray.Rectangle{ .x = 0, .y = 0, .width = @intToFloat(f32, target.texture.width), .height = @intToFloat(f32, -target.texture.height), }, ray.Vector2{ .x = 0, .y = 0 }, ray.WHITE); ray.EndShaderMode(); } // Draw 2d shapes and text over drawn texture ray.DrawRectangle(0, 9, 580, 30, ray.Fade(ray.LIGHTGRAY, 0.7)); ray.DrawText("(c) Church 3D model by <NAME>", screenWidth - 200, screenHeight - 20, 10, ray.GRAY); ray.DrawText("CURRENT POSTPRO SHADER:", 10, 15, 20, ray.BLACK); ray.DrawText(std.meta.tagName(current_shader).ptr, 330, 15, 20, ray.RED); ray.DrawText("< >", 540, 10, 30, ray.DARKBLUE); ray.DrawFPS(700, 15); ray.EndDrawing(); } }
src/examples/postprocess.zig
const std = @import("std"); const expect = std.testing.expect; const test_allocator = std.testing.allocator; const Allocator = std.mem.Allocator; const Cell = struct { rowIdx: u64 = 0, colIdx: u64 = 0, value: u64, seen: bool = false, }; const Board = struct { const Self = @This(); allocator: Allocator, cells: []Cell, map: std.AutoHashMap(u64, *Cell), hasWon: bool = false, pub fn load(allocator: Allocator, rows: [][]const u8) !Self { var cells = std.ArrayList(Cell).init(allocator); defer cells.deinit(); for (rows) |r, rowIdx| { var numIter = std.mem.tokenize(u8, r, " "); var colIdx: u64 = 0; while (numIter.next()) |n| { if (n.len != 0) { const val = try std.fmt.parseInt(u64, n, 10); colIdx += 1; try cells.append(Cell{ .value = val, .rowIdx = rowIdx, .colIdx = colIdx }); } } } var map = std.AutoHashMap(u64, *Cell).init(allocator); var ownedCells = cells.toOwnedSlice(); for (ownedCells) |*c| { try map.put(c.value, c); } return Self{ .allocator = allocator, .cells = ownedCells, .map = map }; } pub fn deinit(self: *Self) void { self.allocator.free(self.cells); self.map.deinit(); } fn offset(colIdx: u64, rowIdx: u64) u64 { return ((rowIdx * 5) + colIdx); } pub fn addNumber(self: *Self, num: u64) bool { var c = self.map.get(num); if (c != null) { var cPtr = c.?; cPtr.seen = true; return self.checkWin(); } return false; } fn checkWin(self: *Self) bool { var row: u64 = 0; var col: u64 = 0; var seenCount: u64 = 0; while (row < 5) : (row += 1) { col = 0; seenCount = 0; while (col < 5) : (col += 1) { var off = offset(col, row); if (self.cells[off].seen) { seenCount += 1; } } if (seenCount == 5) { return true; } } col = 0; while (col < 5) : (col += 1) { row = 0; seenCount = 0; while (row < 5) : (row += 1) { var off = offset(col, row); if (self.cells[off].seen) { seenCount += 1; } } if (seenCount == 5) { return true; } } return false; } pub fn unseenSum(self: *Self) u64 { var sum: u64 = 0; for (self.cells) |c| { if (!c.seen) { sum += c.value; } } return sum; } }; const Game = struct { const Self = @This(); numbers: []const u64, boards: []Board, allocator: Allocator, pub fn load(allocator: Allocator, str: []const u8) !Self { var nums = std.ArrayList(u64).init(allocator); defer nums.deinit(); var iter = std.mem.split(u8, str, "\n"); var numStr = iter.next().?; var numIter = std.mem.tokenize(u8, numStr, ","); while (numIter.next()) |n| { const val = try std.fmt.parseInt(u64, n, 10); try nums.append(val); } // skip empty line _ = iter.next().?; var boards = std.ArrayList(Board).init(allocator); defer boards.deinit(); var currRows = std.ArrayList([]const u8).init(allocator); defer currRows.deinit(); while (iter.next()) |line| { if (line.len == 0) { if (currRows.items.len == 0) { continue; } var b = try Board.load(allocator, currRows.items); try boards.append(b); currRows.resize(0) catch unreachable; continue; } try currRows.append(line); } return Self{ .allocator = allocator, .numbers = nums.toOwnedSlice(), .boards = boards.toOwnedSlice() }; } pub fn deinit(self: Self) void { self.allocator.free(self.numbers); for (self.boards) |*b| { b.deinit(); } self.allocator.free(self.boards); } pub fn winningScore(self: *Self) !u64 { for (self.numbers) |n| { for (self.boards) |*b| { if (b.addNumber(n)) { const sum = b.unseenSum(); return (n * sum); } } } std.debug.print("\nNo board won!\n", .{}); return 0; } pub fn worstBoard(self: *Self) !u64 { const boardCount = self.boards.len; var winCount: u64 = 0; for (self.numbers) |n| { for (self.boards) |*b| { if (!b.hasWon) { if (b.addNumber(n)) { if (winCount == (boardCount - 1)) { const sum = b.unseenSum(); return (n * sum); } else { b.hasWon = true; winCount += 1; } } } } } std.debug.print("\nNo board won!\n", .{}); return 0; } }; pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const str = @embedFile("../input.txt"); var g = try Game.load(allocator, str); defer g.deinit(); const stdout = std.io.getStdOut().writer(); const part1 = try g.winningScore(); try stdout.print("Part 1: {d}\n", .{part1}); const part2 = try g.worstBoard(); try stdout.print("Part 2: {d}\n", .{part2}); } test "part1 test" { const str = @embedFile("../test.txt"); var g = try Game.load(test_allocator, str); defer g.deinit(); const score = try g.winningScore(); try expect(4512 == score); } test "part2 test" { const str = @embedFile("../test.txt"); var g = try Game.load(test_allocator, str); defer g.deinit(); const score = try g.worstBoard(); try expect(1924 == score); }
day04/src/main.zig
const std = @import("std"); fn root() []const u8 { return std.fs.path.dirname(@src().file) orelse unreachable; } const root_path = root() ++ "/"; pub const include_dir = root_path ++ "libgit2/include"; pub const Library = struct { step: *std.build.LibExeObjStep, pub fn link(self: Library, other: *std.build.LibExeObjStep) void { other.addIncludeDir(include_dir); other.linkLibrary(self.step); } }; pub fn create( b: *std.build.Builder, target: std.zig.CrossTarget, mode: std.builtin.Mode, ) !Library { const ret = b.addStaticLibrary("git2", null); ret.setTarget(target); ret.setBuildMode(mode); var flags = std.ArrayList([]const u8).init(b.allocator); defer flags.deinit(); try flags.appendSlice(&.{ "-DLIBGIT2_NO_FEATURES_H", "-DGIT_TRACE=1", "-DGIT_THREADS=1", "-DGIT_USE_FUTIMENS=1", "-DGIT_REGEX_PCRE", "-DGIT_SSH=1", "-DGIT_SSH_MEMORY_CREDENTIALS=1", "-DGIT_HTTPS=1", "-DGIT_MBEDTLS=1", "-DGIT_SHA1_MBEDTLS=1", "-fno-sanitize=all", }); if (64 == target.getCpuArch().ptrBitWidth()) try flags.append("-DGIT_ARCH_64=1"); ret.addCSourceFiles(srcs, flags.items); if (target.isWindows()) { try flags.appendSlice(&.{ "-DGIT_WIN32", "-DGIT_WINHTTP", }); ret.addCSourceFiles(win32_srcs, flags.items); if (target.getAbi().isGnu()) { ret.addCSourceFiles(posix_srcs, flags.items); ret.addCSourceFiles(unix_srcs, flags.items); } } else { ret.addCSourceFiles(posix_srcs, flags.items); ret.addCSourceFiles(unix_srcs, flags.items); } if (target.isLinux()) try flags.appendSlice(&.{ "-DGIT_USE_NSEC=1", "-DGIT_USE_STAT_MTIM=1", }); ret.addCSourceFiles(pcre_srcs, &.{ "-DLINK_SIZE=2", "-DNEWLINE=10", "-DPOSIX_MALLOC_THRESHOLD=10", "-DMATCH_LIMIT_RECURSION=MATCH_LIMIT", "-DPARENS_NEST_LIMIT=250", "-DMATCH_LIMIT=10000000", "-DMAX_NAME_SIZE=32", "-DMAX_NAME_COUNT=10000", }); ret.addIncludeDir(include_dir); ret.addIncludeDir(root_path ++ "libgit2/src"); ret.addIncludeDir(root_path ++ "libgit2/deps/pcre"); ret.addIncludeDir(root_path ++ "libgit2/deps/http-parser"); ret.linkLibC(); return Library{ .step = ret }; } const srcs = &.{ root_path ++ "libgit2/deps/http-parser/http_parser.c", root_path ++ "libgit2/src/allocators/failalloc.c", root_path ++ "libgit2/src/allocators/stdalloc.c", root_path ++ "libgit2/src/streams/openssl.c", root_path ++ "libgit2/src/streams/registry.c", root_path ++ "libgit2/src/streams/socket.c", root_path ++ "libgit2/src/streams/tls.c", root_path ++ "mbedtls.c", root_path ++ "libgit2/src/transports/auth.c", root_path ++ "libgit2/src/transports/credential.c", root_path ++ "libgit2/src/transports/http.c", root_path ++ "libgit2/src/transports/httpclient.c", root_path ++ "libgit2/src/transports/smart_protocol.c", root_path ++ "libgit2/src/transports/ssh.c", root_path ++ "libgit2/src/transports/git.c", root_path ++ "libgit2/src/transports/smart.c", root_path ++ "libgit2/src/transports/smart_pkt.c", root_path ++ "libgit2/src/transports/local.c", root_path ++ "libgit2/src/xdiff/xdiffi.c", root_path ++ "libgit2/src/xdiff/xemit.c", root_path ++ "libgit2/src/xdiff/xhistogram.c", root_path ++ "libgit2/src/xdiff/xmerge.c", root_path ++ "libgit2/src/xdiff/xpatience.c", root_path ++ "libgit2/src/xdiff/xprepare.c", root_path ++ "libgit2/src/xdiff/xutils.c", root_path ++ "libgit2/src/hash/sha1/mbedtls.c", root_path ++ "libgit2/src/alloc.c", root_path ++ "libgit2/src/annotated_commit.c", root_path ++ "libgit2/src/apply.c", root_path ++ "libgit2/src/attr.c", root_path ++ "libgit2/src/attrcache.c", root_path ++ "libgit2/src/attr_file.c", root_path ++ "libgit2/src/blame.c", root_path ++ "libgit2/src/blame_git.c", root_path ++ "libgit2/src/blob.c", root_path ++ "libgit2/src/branch.c", root_path ++ "libgit2/src/buffer.c", root_path ++ "libgit2/src/cache.c", root_path ++ "libgit2/src/checkout.c", root_path ++ "libgit2/src/cherrypick.c", root_path ++ "libgit2/src/clone.c", root_path ++ "libgit2/src/commit.c", root_path ++ "libgit2/src/commit_graph.c", root_path ++ "libgit2/src/commit_list.c", root_path ++ "libgit2/src/config.c", root_path ++ "libgit2/src/config_cache.c", root_path ++ "libgit2/src/config_entries.c", root_path ++ "libgit2/src/config_file.c", root_path ++ "libgit2/src/config_mem.c", root_path ++ "libgit2/src/config_parse.c", root_path ++ "libgit2/src/config_snapshot.c", root_path ++ "libgit2/src/crlf.c", root_path ++ "libgit2/src/date.c", root_path ++ "libgit2/src/delta.c", root_path ++ "libgit2/src/describe.c", root_path ++ "libgit2/src/diff.c", root_path ++ "libgit2/src/diff_driver.c", root_path ++ "libgit2/src/diff_file.c", root_path ++ "libgit2/src/diff_generate.c", root_path ++ "libgit2/src/diff_parse.c", root_path ++ "libgit2/src/diff_print.c", root_path ++ "libgit2/src/diff_stats.c", root_path ++ "libgit2/src/diff_tform.c", root_path ++ "libgit2/src/diff_xdiff.c", root_path ++ "libgit2/src/errors.c", root_path ++ "libgit2/src/email.c", root_path ++ "libgit2/src/fetch.c", root_path ++ "libgit2/src/fetchhead.c", root_path ++ "libgit2/src/filebuf.c", root_path ++ "libgit2/src/filter.c", root_path ++ "libgit2/src/futils.c", root_path ++ "libgit2/src/graph.c", root_path ++ "libgit2/src/hash.c", root_path ++ "libgit2/src/hashsig.c", root_path ++ "libgit2/src/ident.c", root_path ++ "libgit2/src/idxmap.c", root_path ++ "libgit2/src/ignore.c", root_path ++ "libgit2/src/index.c", root_path ++ "libgit2/src/indexer.c", root_path ++ "libgit2/src/iterator.c", root_path ++ "libgit2/src/libgit2.c", root_path ++ "libgit2/src/mailmap.c", root_path ++ "libgit2/src/merge.c", root_path ++ "libgit2/src/merge_driver.c", root_path ++ "libgit2/src/merge_file.c", root_path ++ "libgit2/src/message.c", root_path ++ "libgit2/src/midx.c", root_path ++ "libgit2/src/mwindow.c", root_path ++ "libgit2/src/net.c", root_path ++ "libgit2/src/netops.c", root_path ++ "libgit2/src/notes.c", root_path ++ "libgit2/src/object_api.c", root_path ++ "libgit2/src/object.c", root_path ++ "libgit2/src/odb.c", root_path ++ "libgit2/src/odb_loose.c", root_path ++ "libgit2/src/odb_mempack.c", root_path ++ "libgit2/src/odb_pack.c", root_path ++ "libgit2/src/offmap.c", root_path ++ "libgit2/src/oidarray.c", root_path ++ "libgit2/src/oid.c", root_path ++ "libgit2/src/oidmap.c", root_path ++ "libgit2/src/pack.c", root_path ++ "libgit2/src/pack-objects.c", root_path ++ "libgit2/src/parse.c", root_path ++ "libgit2/src/patch.c", root_path ++ "libgit2/src/patch_generate.c", root_path ++ "libgit2/src/patch_parse.c", root_path ++ "libgit2/src/path.c", root_path ++ "libgit2/src/pathspec.c", root_path ++ "libgit2/src/pool.c", root_path ++ "libgit2/src/pqueue.c", root_path ++ "libgit2/src/proxy.c", root_path ++ "libgit2/src/push.c", root_path ++ "libgit2/src/reader.c", root_path ++ "libgit2/src/rebase.c", root_path ++ "libgit2/src/refdb.c", root_path ++ "libgit2/src/refdb_fs.c", root_path ++ "libgit2/src/reflog.c", root_path ++ "libgit2/src/refs.c", root_path ++ "libgit2/src/refspec.c", root_path ++ "libgit2/src/regexp.c", root_path ++ "libgit2/src/remote.c", root_path ++ "libgit2/src/repository.c", root_path ++ "libgit2/src/reset.c", root_path ++ "libgit2/src/revert.c", root_path ++ "libgit2/src/revparse.c", root_path ++ "libgit2/src/revwalk.c", root_path ++ "libgit2/src/runtime.c", root_path ++ "libgit2/src/signature.c", root_path ++ "libgit2/src/sortedcache.c", root_path ++ "libgit2/src/stash.c", root_path ++ "libgit2/src/status.c", root_path ++ "libgit2/src/strarray.c", root_path ++ "libgit2/src/strmap.c", root_path ++ "libgit2/src/submodule.c", root_path ++ "libgit2/src/sysdir.c", root_path ++ "libgit2/src/tag.c", root_path ++ "libgit2/src/thread.c", root_path ++ "libgit2/src/threadstate.c", root_path ++ "libgit2/src/trace.c", root_path ++ "libgit2/src/trailer.c", root_path ++ "libgit2/src/transaction.c", root_path ++ "libgit2/src/transport.c", root_path ++ "libgit2/src/tree.c", root_path ++ "libgit2/src/tree-cache.c", root_path ++ "libgit2/src/tsort.c", root_path ++ "libgit2/src/utf8.c", root_path ++ "libgit2/src/util.c", root_path ++ "libgit2/src/varint.c", root_path ++ "libgit2/src/vector.c", root_path ++ "libgit2/src/wildmatch.c", root_path ++ "libgit2/src/worktree.c", root_path ++ "libgit2/src/zstream.c", }; const pcre_srcs = &.{ root_path ++ "libgit2/deps/pcre/pcre_byte_order.c", root_path ++ "libgit2/deps/pcre/pcre_chartables.c", root_path ++ "libgit2/deps/pcre/pcre_compile.c", root_path ++ "libgit2/deps/pcre/pcre_config.c", root_path ++ "libgit2/deps/pcre/pcre_dfa_exec.c", root_path ++ "libgit2/deps/pcre/pcre_exec.c", root_path ++ "libgit2/deps/pcre/pcre_fullinfo.c", root_path ++ "libgit2/deps/pcre/pcre_get.c", root_path ++ "libgit2/deps/pcre/pcre_globals.c", root_path ++ "libgit2/deps/pcre/pcre_jit_compile.c", root_path ++ "libgit2/deps/pcre/pcre_maketables.c", root_path ++ "libgit2/deps/pcre/pcre_newline.c", root_path ++ "libgit2/deps/pcre/pcre_ord2utf8.c", root_path ++ "libgit2/deps/pcre/pcreposix.c", root_path ++ "libgit2/deps/pcre/pcre_printint.c", root_path ++ "libgit2/deps/pcre/pcre_refcount.c", root_path ++ "libgit2/deps/pcre/pcre_string_utils.c", root_path ++ "libgit2/deps/pcre/pcre_study.c", root_path ++ "libgit2/deps/pcre/pcre_tables.c", root_path ++ "libgit2/deps/pcre/pcre_ucd.c", root_path ++ "libgit2/deps/pcre/pcre_valid_utf8.c", root_path ++ "libgit2/deps/pcre/pcre_version.c", root_path ++ "libgit2/deps/pcre/pcre_xclass.c", }; const posix_srcs = &.{ root_path ++ "libgit2/src/posix.c", }; const unix_srcs = &.{ root_path ++ "libgit2/src/unix/map.c", root_path ++ "libgit2/src/unix/realpath.c", }; const win32_srcs = &.{ root_path ++ "libgit2/src/win32/dir.c", root_path ++ "libgit2/src/win32/error.c", root_path ++ "libgit2/src/win32/findfile.c", root_path ++ "libgit2/src/win32/map.c", root_path ++ "libgit2/src/win32/path_w32.c", root_path ++ "libgit2/src/win32/posix_w32.c", root_path ++ "libgit2/src/win32/precompiled.c", root_path ++ "libgit2/src/win32/thread.c", root_path ++ "libgit2/src/win32/utf-conv.c", root_path ++ "libgit2/src/win32/w32_buffer.c", root_path ++ "libgit2/src/win32/w32_leakcheck.c", root_path ++ "libgit2/src/win32/w32_util.c", };
.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2.zig
const std = @import("std"); const testing = std.testing; const zero_width_cf = @import("manual.zig").zero_width_cf; const wide_eastasian = @import("table_wide.zig").wide_eastasian; const zero_width = @import("table_zero.zig").zero_width; /// A simple binary search in a list containing lower and upper bounds fn tableBisearch(ucs: u21, table: []const [2]u21) bool { var lbound: usize = 0; var ubound: usize = table.len - 1; // Out of entire table bounds if (ucs < table[lbound][0] or ucs > table[ubound][1]) { return false; } // Search table while (ubound >= lbound) { const mid = (lbound + ubound) / 2; if (ucs > table[mid][1]) { lbound = mid + 1; } else if (ucs < table[mid][0]) { ubound = mid - 1; } else { return true; } } return false; } /// A simple binary search for a simple ordered list fn listBisearch(ucs: u21, list: []const u21) bool { var lbound: usize = 0; var ubound: usize = list.len - 1; // Out of entire table bounds if (ucs < list[lbound] or ucs > list[ubound]) { return false; } // Search table while (ubound >= lbound) { const mid = (lbound + ubound) / 2; if (ucs > list[mid]) { lbound = mid + 1; } else if (ucs < list[mid]) { ubound = mid - 1; } else { return true; } } return false; } /// Given one unicode character, return its printable length on a terminal. /// /// The wcwidth() function returns 0 if the wc argument has no printable effect /// on a terminal (such as NUL '\0'), -1 if wc is not printable, or has an /// indeterminate effect on the terminal, such as a control character. /// Otherwise, the number of column positions the character occupies on a /// graphic terminal (1 or 2) is returned. /// /// The following have a column width of -1: /// /// - C0 control characters (U+001 through U+01F). /// /// - C1 control characters and DEL (U+07F through U+0A0). /// /// The following have a column width of 0: /// /// - Non-spacing and enclosing combining characters (general /// category code Mn or Me in the Unicode database). /// /// - NULL (U+0000, 0). /// /// - COMBINING GRAPHEME JOINER (U+034F). /// /// - ZERO WIDTH SPACE (U+200B) through /// RIGHT-TO-LEFT MARK (U+200F). /// /// - LINE SEPERATOR (U+2028) and /// PARAGRAPH SEPERATOR (U+2029). /// /// - LEFT-TO-RIGHT EMBEDDING (U+202A) through /// RIGHT-TO-LEFT OVERRIDE (U+202E). /// /// - WORD JOINER (U+2060) through /// INVISIBLE SEPARATOR (U+2063). /// /// The following have a column width of 1: /// /// - SOFT HYPHEN (U+00AD) has a column width of 1. /// /// - All remaining characters (including all printable /// ISO 8859-1 and WGL4 characters, Unicode control characters, /// etc.) have a column width of 1. /// /// The following have a column width of 2: /// /// - Spacing characters in the East Asian Wide (W) or East Asian /// Full-width (F) category as defined in Unicode Technical /// Report #11 have a column width of 2. pub fn wcwidth(wc: u21) isize { // Manual list if (listBisearch(wc, &zero_width_cf)) { return 0; } // C0/C1 control characters if (wc < 32 or 0x07F <= wc and wc < 0x0A0) { return -1; } // combining characters with zero width if (tableBisearch(wc, &zero_width)) { return 0; } // double width if (tableBisearch(wc, &wide_eastasian)) { return 2; } else { return 1; } } /// Given a unicode string, return its printable length on a terminal. /// /// Returns ``-1`` if a non-printable character is encountered. pub fn wcswidth(wcs: []const u21) isize { var width: isize = 0; for (wcs) |char| { const wcw = wcwidth(char); if (wcw < 0) return -1; width += wcw; } return width; } /// Given a byte slice, return its printable length on a terminal. Returns /// error.InvalidUtf8 when the byte slice does not contain valid UTF-8. /// /// Returns ``-1`` if a non-printable character is encountered. pub fn sliceWidth(s: []const u8) !isize { var width: isize = 0; var utf8 = (try std.unicode.Utf8View.init(s)).iterator(); while (utf8.nextCodepoint()) |codepoint| { const wcw = wcwidth(codepoint); if (wcw < 0) return -1; width += wcw; } return width; }
src/main.zig
const std = @import("std"); const Allocator = std.mem.Allocator; pub const TypeId = @TagType(TypeInfo); const TypeInfoSingleton = struct { resolved: bool = false, info: TypeInfo = .{ .Void = {} }, }; pub const TypeInfo = union(enum) { Type: void, Void: void, Bool: void, NoReturn: void, Int: Int, Float: Float, Pointer: Pointer, Array: Array, Struct: Struct, ComptimeFloat: void, ComptimeInt: void, Undefined: void, Null: void, Optional: Optional, ErrorUnion: ErrorUnion, ErrorSet: ErrorSet, Enum: Enum, Union: Union, Fn: Fn, BoundFn: Fn, Opaque: void, // TODO Opaque Frame: Frame, AnyFrame: AnyFrame, Vector: Vector, EnumLiteral: void, /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const Int = struct { signedness: Signedness, bits: i32, pub fn init(comptime m: std.builtin.TypeInfo.Int) Int { return comptime .{ .signedness = @intToEnum(Signedness, @enumToInt(m.signedness)), .bits = m.bits, }; } }; comptime { validateSymbolInSync(Int, std.builtin.TypeInfo.Int, .{}); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const Float = struct { bits: i32, pub fn init(comptime m: std.builtin.TypeInfo.Float) Float { return comptime .{ .bits = m.bits, }; } }; comptime { validateSymbolInSync(Float, std.builtin.TypeInfo.Float, .{}); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const Pointer = struct { size: Size, is_const: bool, is_volatile: bool, alignment: i32, child: *const TypeInfo, is_allowzero: bool, /// This field is an optional type. /// The type of the sentinel is the element type of the pointer, which is /// the value of the `child` field in this struct. However there is no way /// to refer to that type here, so we use `var`. // sentinel: anytype, /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const Size = enum { One, Many, Slice, C, }; pub fn init(comptime m: std.builtin.TypeInfo.Pointer) Pointer { return comptime .{ .size = @intToEnum(TypeInfo.Pointer.Size, @enumToInt(m.size)), .is_const = m.is_const, .is_volatile = m.is_volatile, .alignment = m.alignment, .child = &TypeInfo.init(m.child), .is_allowzero = m.is_allowzero, }; } pub fn deinit(self: *const Pointer, allocator: *Allocator) void { self.child.deinit(allocator); allocator.destroy(self.child); } }; comptime { validateSymbolInSync(Pointer, std.builtin.TypeInfo.Pointer, .{ .ignore_fields = .{"sentinel"}, }); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const Array = struct { len: i32, child: *const TypeInfo, /// This field is an optional type. /// The type of the sentinel is the element type of the array, which is /// the value of the `child` field in this struct. However there is no way /// to refer to that type here, so we use `var`. // sentinel: anytype, pub fn init(comptime m: std.builtin.TypeInfo.Array) Array { return comptime .{ .len = m.len, .child = &TypeInfo.init(m.child), }; } pub fn deinit(self: *const Array, allocator: *Allocator) void { self.child.deinit(allocator); allocator.destroy(self.child); } }; comptime { validateSymbolInSync(Array, std.builtin.TypeInfo.Array, .{ .ignore_fields = .{"sentinel"}, }); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const ContainerLayout = enum { Auto, Extern, Packed, }; comptime { validateSymbolInSync(ContainerLayout, std.builtin.TypeInfo.ContainerLayout, .{}); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const StructField = struct { name: []const u8, field_type: *const TypeInfo, // default_value: anytype, is_comptime: bool, alignment: i32, pub fn init(comptime f: std.builtin.TypeInfo.StructField) StructField { return comptime .{ .name = f.name, .field_type = &TypeInfo.init(f.field_type), .is_comptime = f.is_comptime, .alignment = f.alignment, }; } pub fn deinit(self: *const StructField, allocator: *Allocator) void { allocator.free(self.name); self.field_type.deinit(allocator); allocator.destroy(self.field_type); } }; comptime { validateSymbolInSync(StructField, std.builtin.TypeInfo.StructField, .{ .ignore_fields = .{"default_value"}, }); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const Struct = struct { // Additional Field name: ?[]const u8, layout: ContainerLayout, fields: []const StructField, decls: []const Declaration, is_tuple: bool, pub fn init(comptime m: std.builtin.TypeInfo.Struct, comptime name: []const u8) Struct { return comptime .{ .name = name, .layout = @intToEnum(TypeInfo.ContainerLayout, @enumToInt(m.layout)), .fields = fields: { comptime var arr: [m.fields.len]StructField = undefined; inline for (m.fields) |f, i| { arr[i] = StructField.init(f); } break :fields &arr; }, .decls = decls: { comptime var arr: [m.decls.len]Declaration = undefined; inline for (m.decls) |f, i| { arr[i] = Declaration.init(f); } break :decls &arr; }, .is_tuple = m.is_tuple, }; } comptime { validateSymbolInSync(Struct, std.builtin.TypeInfo.Struct, .{}); } pub fn deinit(self: *const Struct, allocator: *Allocator) void { for (self.fields) |f| f.deinit(allocator); for (self.decls) |f| f.deinit(allocator); allocator.free(self.fields); allocator.free(self.decls); } }; /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const Optional = struct { child: *const TypeInfo, pub fn init(comptime m: std.builtin.TypeInfo.Optional) Optional { return comptime .{ .child = &TypeInfo.init(m.child), }; } pub fn deinit(self: *const Optional, allocator: *Allocator) void { self.child.deinit(allocator); allocator.destroy(self.child); } }; comptime { validateSymbolInSync(Optional, std.builtin.TypeInfo.Optional, .{}); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const ErrorUnion = struct { error_set: *const TypeInfo, payload: *const TypeInfo, pub fn init(comptime m: std.builtin.TypeInfo.ErrorUnion) ErrorUnion { return comptime .{ .error_set = &TypeInfo.init(m.error_set), .payload = &TypeInfo.init(m.payload), }; } pub fn deinit(self: *const ErrorUnion, allocator: *Allocator) void { self.error_set.deinit(allocator); allocator.destroy(self.error_set); self.payload.deinit(allocator); allocator.destroy(self.payload); } }; comptime { validateSymbolInSync(ErrorUnion, std.builtin.TypeInfo.ErrorUnion, .{}); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const Error = struct { name: []const u8, pub fn deinit(self: *const Error, allocator: *Allocator) void { allocator.free(self.name); } }; comptime { validateSymbolInSync(Error, std.builtin.TypeInfo.Error, .{}); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const ErrorSet = ?[]const Error; /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const EnumField = struct { name: []const u8, value: i32, pub fn init(comptime f: std.builtin.TypeInfo.EnumField) EnumField { return comptime .{ .name = f.name, .value = f.value, }; } pub fn deinit(self: *const EnumField, allocator: *Allocator) void { allocator.free(self.name); } }; comptime { validateSymbolInSync(EnumField, std.builtin.TypeInfo.EnumField, .{}); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const Enum = struct { // Additional Field name: ?[]const u8, layout: ContainerLayout, tag_type: *const TypeInfo, fields: []const EnumField, decls: []const Declaration, is_exhaustive: bool, pub fn init(comptime m: std.builtin.TypeInfo.Enum, comptime name: []const u8) Enum { return comptime .{ .name = name, .layout = @intToEnum(TypeInfo.ContainerLayout, @enumToInt(m.layout)), .tag_type = &TypeInfo.init(m.tag_type), .fields = fields: { comptime var arr: [m.fields.len]EnumField = undefined; inline for (m.fields) |f, i| { arr[i] = EnumField.init(f); } break :fields &arr; }, .decls = decls: { comptime var arr: [m.decls.len]Declaration = undefined; inline for (m.decls) |f, i| { arr[i] = Declaration.init(f); } break :decls &arr; }, .is_exhaustive = m.is_exhaustive, }; } pub fn deinit(self: *const Enum, allocator: *Allocator) void { for (self.fields) |f| f.deinit(allocator); for (self.decls) |f| f.deinit(allocator); allocator.free(self.fields); allocator.free(self.decls); self.tag_type.deinit(allocator); allocator.destroy(self.tag_type); } }; comptime { validateSymbolInSync(Enum, std.builtin.TypeInfo.Enum, .{}); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const UnionField = struct { // Additional Field name: []const u8, field_type: *const TypeInfo, alignment: i32, pub fn init(comptime f: std.builtin.TypeInfo.UnionField) UnionField { return comptime .{ .name = f.name, .field_type = &TypeInfo.init(f.field_type), .alignment = f.alignment, }; } pub fn deinit(self: *const UnionField, allocator: *Allocator) void { allocator.free(self.name); self.field_type.deinit(allocator); allocator.destroy(self.field_type); if (self.enum_field) |ef| { ef.deinit(allocator); } } }; comptime { validateSymbolInSync(UnionField, std.builtin.TypeInfo.UnionField, .{}); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const Union = struct { // Additional Field name: ?[]const u8, layout: ContainerLayout, tag_type: ?*const TypeInfo, fields: []const UnionField, decls: []const Declaration, pub fn init(comptime m: std.builtin.TypeInfo.Union, comptime name: []const u8) Union { return comptime .{ .name = name, .layout = @intToEnum(TypeInfo.ContainerLayout, @enumToInt(m.layout)), .tag_type = if (m.tag_type) |t| &TypeInfo.init(t) else null, .fields = fields: { comptime var arr: [m.fields.len]UnionField = undefined; inline for (m.fields) |f, i| { arr[i] = UnionField.init(f); } break :fields &arr; }, .decls = decls: { comptime var arr: [m.decls.len]Declaration = undefined; inline for (m.decls) |f, i| { arr[i] = Declaration.init(f); } break :decls &arr; }, }; } pub fn deinit(self: *const Union, allocator: *Allocator) void { for (self.fields) |f| f.deinit(allocator); for (self.decls) |f| f.deinit(allocator); allocator.free(self.fields); allocator.free(self.decls); if (self.tag_type) |tag_type| { tag_type.deinit(allocator); allocator.destroy(tag_type); } } }; comptime { validateSymbolInSync(Union, std.builtin.TypeInfo.Union, .{}); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const FnArg = struct { is_generic: bool, is_noalias: bool, arg_type: ?*const TypeInfo, pub fn init(comptime f: std.builtin.TypeInfo.FnArg) FnArg { return comptime .{ .is_generic = f.is_generic, .is_noalias = f.is_noalias, .arg_type = if (f.arg_type) |t| &TypeInfo.init(t) else null, }; } pub fn deinit(self: *const FnArg, allocator: *Allocator) void { if (self.arg_type) |t| { t.deinit(allocator); allocator.destroy(self.arg_type); } } }; comptime { validateSymbolInSync(FnArg, std.builtin.TypeInfo.FnArg, .{}); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const Fn = struct { calling_convention: CallingConvention, alignment: i32, is_generic: bool, is_var_args: bool, return_type: ?*const TypeInfo, args: []const FnArg, pub fn init(comptime m: std.builtin.TypeInfo.Fn) Fn { return comptime .{ .calling_convention = @intToEnum(CallingConvention, @enumToInt(m.calling_convention)), .alignment = m.alignment, .is_generic = m.is_generic, .is_var_args = m.is_var_args, .return_type = if (m.return_type) |t| &TypeInfo.init(t) else null, .args = args: { comptime var arr: [m.args.len]FnArg = undefined; inline for (m.args) |f, i| { arr[i] = FnArg.init(f); } break :args &arr; }, }; } pub fn deinit(self: *const Fn, allocator: *Allocator) void { if (self.return_type) |r| { r.deinit(allocator); allocator.destroy(r); } for (self.args) |arg| arg.deinit(allocator); allocator.free(self.args); } }; comptime { validateSymbolInSync(Fn, std.builtin.TypeInfo.Fn, .{}); } pub const Opaque = struct { decls: []const Declaration, pub fn init(comptime m: std.builtin.TypeInfo.Opaque) Opaque { return comptime .{ .decls = decls: { comptime var arr: [m.decls.len]Declaration = undefined; inline for (m.decls) |f, i| { arr[i] = Declaration.init(f); } break :decls &arr; }, }; } }; comptime { validateSymbolInSync(Opaque, std.builtin.TypeInfo.Opaque, .{}); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const Frame = struct { // function: anytype, }; comptime { validateSymbolInSync(Frame, std.builtin.TypeInfo.Frame, .{ .ignore_fields = .{"function"}, }); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const AnyFrame = struct { child: ?*const TypeInfo, pub fn init(comptime m: std.builtin.TypeInfo.AnyFrame) AnyFrame { return comptime .{ .child = if (m.child) |t| &TypeInfo.init(t) else null, }; } pub fn deinit(self: *const AnyFrame, allocator: *Allocator) void { if (self.child) |child| { child.deinit(allocator); allocator.destroy(child); } } }; comptime { validateSymbolInSync(AnyFrame, std.builtin.TypeInfo.AnyFrame, .{}); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const Vector = struct { len: i32, child: *const TypeInfo, pub fn init(comptime m: std.builtin.TypeInfo.Vector) Vector { return comptime .{ .len = m.len, .child = &TypeInfo.init(m.child), }; } pub fn deinit(self: *const Vector, allocator: *Allocator) void { self.child.deinit(allocator); allocator.destroy(self.child); } }; comptime { validateSymbolInSync(Vector, std.builtin.TypeInfo.Vector, .{}); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const Declaration = struct { name: []const u8, is_pub: bool, data: Data, pub fn init(comptime f: std.builtin.TypeInfo.Declaration) Declaration { return comptime .{ .name = f.name, .is_pub = f.is_pub, .data = Data.init(f.data), }; } pub fn deinit(self: *const Declaration, allocator: *Allocator) void { self.data.deinit(allocator); allocator.free(self.name); } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const Data = union(enum) { Type: *const TypeInfo, Var: *const TypeInfo, Fn: FnDecl, pub fn init(comptime d: std.builtin.TypeInfo.Declaration.Data) Data { return comptime switch (d) { .Type => |t| .{ .Type = &TypeInfo.init(t) }, .Var => |t| .{ .Var = &TypeInfo.init(t), }, .Fn => |t| .{ .Fn = FnDecl.init(t) }, }; } /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const FnDecl = struct { fn_type: *const TypeInfo, is_noinline: bool, is_var_args: bool, is_extern: bool, is_export: bool, lib_name: ?[]const u8, return_type: *const TypeInfo, arg_names: []const []const u8, pub fn init(comptime t: std.builtin.TypeInfo.Declaration.Data.FnDecl) FnDecl { return comptime .{ .fn_type = &TypeInfo.init(t.fn_type), .is_noinline = t.is_noinline, .is_var_args = t.is_var_args, .is_extern = t.is_extern, .is_export = t.is_export, .lib_name = t.lib_name, .return_type = &TypeInfo.init(t.return_type), .arg_names = t.arg_names, }; } pub fn deinit(self: *const FnDecl, allocator: *Allocator) void { self.fn_type.deinit(allocator); self.return_type.deinit(allocator); allocator.destroy(self.fn_type); allocator.destroy(self.return_type); for (self.arg_names) |a| allocator.free(a); allocator.free(self.arg_names); if (self.lib_name) |lib_name| { allocator.free(lib_name); } } }; comptime { validateSymbolInSync(FnDecl, std.builtin.TypeInfo.Declaration.Data.FnDecl, .{}); } pub fn deinit(self: *const Data, allocator: *Allocator) void { switch (self.*) { .Type, .Var => |t| { t.deinit(allocator); allocator.destroy(t); }, .Fn => |f| f.deinit(allocator), } } }; comptime { validateSymbolInSync(Data, std.builtin.TypeInfo.Declaration.Data, .{}); } }; comptime { validateSymbolInSync(Declaration, std.builtin.TypeInfo.Declaration, .{}); } // Validate the whole TypeInfo sync comptime { @setEvalBranchQuota(2000); validateSymbolInSync(TypeInfo, std.builtin.TypeInfo, .{}); } usingnamespace comptime blk: { var uniqueIdCounter: usize = 0; break :blk struct { pub fn uniqueId(comptime T: type) usize { comptime { var id = uniqueIdCounter; uniqueIdCounter += 1; return id; } } }; }; pub fn alloc(comptime T: type) *TypeInfoSingleton { comptime var ptr = TypeInfoSingleton{}; return &ptr; } pub fn init(comptime T: type) TypeInfo { return TypeInfo.initPtr(T).*; } pub fn initPtr(comptime T: type) *const TypeInfo { comptime var ptr = TypeInfo.alloc(T); if (ptr.resolved) { return &ptr.info; } ptr.resolved = true; comptime const info = @typeInfo(T); ptr.info = comptime switch (info) { .Type => .{ .Type = {} }, .Void => .{ .Void = {} }, .Bool => .{ .Bool = {} }, .NoReturn => .{ .NoReturn = {} }, .Int => |m| .{ .Int = Int.init(m) }, .Float => |m| .{ .Float = Float.init(m) }, .Pointer => |m| .{ .Pointer = Pointer.init(m) }, .Array => |m| .{ .Array = Array.init(m) }, .Struct => |m| .{ .Struct = Struct.init(m, @typeName(T)) }, .ComptimeFloat => .{ .ComptimeFloat = {} }, .ComptimeInt => .{ .ComptimeInt = {} }, .Undefined => .{ .Undefined = {} }, .Null => .{ .Null = {} }, .Optional => |m| .{ .Optional = Optional.init(m) }, .ErrorUnion => |m| .{ .ErrorUnion = ErrorUnion.init(m) }, // TODO .ErrorSet => |m| .{ .ErrorSet = errorset: { if (m == null) return null; comptime var arr: [m.?.len]Error = undefined; inline for (m.?) |f, i| { arr[i] = .{ .name = f.name, }; } break :errorset &arr; }, }, .Enum => |m| .{ .Enum = Enum.init(m, @typeName(T)) }, .Union => |m| .{ .Union = Union.init(m, @typeName(T)) }, .Fn => |m| .{ .Fn = Fn.init(m) }, .BoundFn => |m| .{ .BoundedFn = Fn.init(m) }, .Opaque => .{ .Opaque = {} }, .Frame => .{ .Frame = {} }, // TODO .AnyFrame => |m| .{ .AnyFrame = AnyFrame.init(m) }, .Vector => |m| .{ .Vector = Vector.init(m) }, .EnumLiteral => .{ .EnumLiteral = {} }, }; return &ptr.info; } pub fn deinit(self: *TypeInfo, allocator: *Allocator) void { switch (self.*) { .Array => |a| a.deinit(allocator), .Pointer => |p| p.deinit(allocator), .Struct => |s| s.deinit(allocator), .Union => |u| u.deinit(allocator), .Enum => |e| e.deinit(allocator), .Optional => |o| o.deinit(allocator), .Fn => |f| f.deinit(allocator), .ErrorUnion => |e| e.deinit(allocator), .ErrorSet => |maybe_set| { if (maybe_set) |set| { for (set) |err| err.deinit(allocator); allocator.free(set); } }, .AnyFrame => |a| a.deinit(allocator), .Vector => |v| v.deinit(allocator), else => {}, } } }; pub const CallingConvention = enum { Unspecified, C, Naked, Async, Inline, Interrupt, Signal, Stdcall, Fastcall, Vectorcall, Thiscall, APCS, AAPCS, AAPCSVFP, SysV, }; pub const Signedness = enum { signed, unsigned, }; pub fn hasField(comptime T: type, comptime field_name: []const u8) bool { inline for (comptime std.meta.fields(T)) |field| { if (std.mem.eql(u8, field.name, field_name) == true) { return true; } } return false; } /// Function to be run in compile time, responsible for verifying if the /// structures/enums/unions defined in this file to represent the TypeInfo at /// runtime in sync with the current Zig version's comptime structures/enums/unions pub fn validateSymbolInSync(comptime runtime_type: type, comptime builtin_type: type, comptime options: anytype) void { const builtin_type_info = @typeInfo(builtin_type); const runtime_type_info = @typeInfo(runtime_type); // Make sure that the runtime type is a struct as well if (std.mem.eql(u8, @tagName(builtin_type_info), @tagName(runtime_type_info)) == false) { @compileError( "Type of " ++ @typeName(builtin_type) ++ " is " ++ @tagName(builtin_type_info) ++ " but runtime type is " ++ @tagName(runtime_type_info), ); } switch (builtin_type_info) { .Struct, .Enum, .Union => { // Compare the fields inline for (std.meta.fields(builtin_type)) |builtin_field| { var missing_field: bool = false; if (hasField(runtime_type, builtin_field.name) == false) { missing_field = true; if (@hasField(@TypeOf(options), "ignore_fields")) { inline for (options.ignore_fields) |ignore_field| { if (std.mem.eql(u8, ignore_field, builtin_field.name) == true) { missing_field = false; break; } } } if (missing_field == true) { @compileError( "Field " ++ builtin_field.name ++ " is missing in type " ++ @typeName(runtime_type), ); } } } }, else => @compileError( "Cannot validate symbol in sync " ++ @typeName(builtin_type) ++ " because type " ++ @tagName(builtin_type_info) ++ " is not supported", ), } } const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const expectEqualStrings = std.testing.expectEqualStrings; const talloc = std.testing.allocator; // TODO .Type test "Runtime TypeInfo.Void" { var info_void = TypeInfo.init(void); try expect(info_void == .Void); } test "Runtime TypeInfo.Bool" { var info_bool = TypeInfo.init(bool); try expect(info_bool == .Bool); } // TODO .NoReturn test "Runtime TypeInfo.Int" { var info_i32 = TypeInfo.init(i32); try expect(info_i32 == .Int); try expectEqual(@as(i32, 32), info_i32.Int.bits); try expectEqual(true, info_i32.Int.signedness == .signed); } test "Runtime TypeInfo.Float" { var info_f64 = TypeInfo.init(f64); try expect(info_f64 == .Float); try expectEqual(@as(i32, 64), info_f64.Float.bits); } test "Runtime TypeInfo.Pointer" { var info_pointer_f64 = TypeInfo.init(*f64); try expect(info_pointer_f64 == .Pointer); try expectEqual(TypeInfo.Pointer.Size.One, info_pointer_f64.Pointer.size); try expectEqual(false, info_pointer_f64.Pointer.is_const); try expectEqual(false, info_pointer_f64.Pointer.is_volatile); try expectEqual(@as(i32, 8), info_pointer_f64.Pointer.alignment); try expect(info_pointer_f64.Pointer.child.* == .Float); try expectEqual(false, info_pointer_f64.Pointer.is_allowzero); var info_pointer_many = TypeInfo.init([*]f64); try expect(info_pointer_many == .Pointer); try expectEqual(TypeInfo.Pointer.Size.Many, info_pointer_many.Pointer.size); try expectEqual(false, info_pointer_many.Pointer.is_const); try expectEqual(false, info_pointer_many.Pointer.is_volatile); try expectEqual(@as(i32, 8), info_pointer_many.Pointer.alignment); try expect(info_pointer_many.Pointer.child.* == .Float); try expectEqual(false, info_pointer_many.Pointer.is_allowzero); } test "Runtime TypeInfo.Array" { var info_array = TypeInfo.init([2]i32); try expect(info_array == .Array); try expectEqual(@as(i32, 2), info_array.Array.len); try expect(info_array.Array.child.* == .Int); } test "Runtime TypeInfo.Struct" { const FooStruct = struct { int: i32, pub fn bar() void {} }; var info_struct = TypeInfo.init(FooStruct); try expect(info_struct == .Struct); try expect(info_struct.Struct.layout == .Auto); try expectEqual(@as(usize, 1), info_struct.Struct.fields.len); try expectEqualStrings("int", info_struct.Struct.fields[0].name); try expect(info_struct.Struct.fields[0].field_type.* == .Int); } test "Runtime TypeInfo.ComptimeFloat" { var info_comptime_float = TypeInfo.init(comptime_float); try expect(info_comptime_float == .ComptimeFloat); } test "Runtime TypeInfo.ComptimeInt" { var info_comptime_int = TypeInfo.init(comptime_int); try expect(info_comptime_int == .ComptimeInt); } // // TODO .Undefined // // TODO .Null test "Runtime TypeInfo.Optional" { var info_optional = TypeInfo.init(?i32); try expect(info_optional == .Optional); try expect(info_optional.Optional.child.* == .Int); } // // TODO .ErrorUnion // // TODO .ErrorSet test "Runtime TypeInfo.Enum" { const FooEnum = enum { Foo, Bar }; var info_enum = TypeInfo.init(FooEnum); try expect(info_enum == .Enum); } test "Runtime TypeInfo.Union" { const FooUnion = union { Foo: void, Bar: i32 }; var info_union = TypeInfo.init(FooUnion); try expect(info_union == .Union); } test "Runtime TypeInfo.Fn" { // .Fn var info_fn = TypeInfo.init(fn () void); try expect(info_fn == .Fn); } test "Runtime TypeInfo.Struct declarations" { // .Fn var info_fn = TypeInfo.init(struct { const WackType = packed struct { mr_field: *LameType, ola: u8 }; const LameType = struct { blah: **WackType, }; pub fn thing(one: usize, two: *LameType, three: [*]u16) bool { return one == 1; } }); try expect(info_fn == .Struct); } // TODO .BoundFn // TODO .Opaque // TODO .Frame // TODO .AnyFrame // TODO .Vector // TODO .EnumLiteral
src/runtime.zig
const sdtx = @import("sokol").debugtext; pub const fontdesc = sdtx.FontDesc{ .data = sdtx.asRange([_]u8{ 0b00000000, // ! 0b00000000, 0b00011000, 0b00011000, 0b00011000, 0b00000000, 0b00011000, 0b00000000, 0b00000000, // " 0b01101100, 0b00100100, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, // # 0b00000000, 0b00101100, 0b01111110, 0b00101100, 0b01111110, 0b00101100, 0b00000000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // $ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // % 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // & 0b00000000, // ' 0b00011000, 0b00011000, 0b00010000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, // ( 0b00000000, 0b00011100, 0b00110000, 0b01100000, 0b00110000, 0b00011100, 0b00000000, 0b00000000, // ) 0b00000000, 0b01110000, 0b00011000, 0b00001100, 0b00011000, 0b01110000, 0b00000000, 0b00000000, // * 0b01101110, 0b00111100, 0b01101110, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, // + 0b00000000, 0b00011000, 0b00011000, 0b01111110, 0b00011000, 0b00011000, 0b00000000, 0b00000000, // , 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00011000, 0b00110000, 0b00000000, 0b00000000, // - 0b00000000, 0b00000000, 0b00000000, 0b01111110, 0b00000000, 0b00000000, 0b00000000, 0b00000000, // . 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00011000, 0b00011000, 0b00000000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 0 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0b00000000, // : 0b00000000, 0b00011000, 0b00011000, 0b00000000, 0b00011000, 0b00011000, 0b00000000, 0b00000000, // ; 0b00000000, 0b00011000, 0b00011000, 0b00000000, 0b00011000, 0b00110000, 0b00000000, 0b00000000, // < 0b00000000, 0b00000110, 0b00001100, 0b00011000, 0b00001100, 0b00000110, 0b00000000, 0b00000000, // = 0b00000000, 0b01111110, 0b00000000, 0b00000000, 0b01111110, 0b00000000, 0b00000000, 0b00000000, // > 0b00000000, 0b01100000, 0b00110000, 0b00011000, 0b00110000, 0b01100000, 0b00000000, 0b00000000, // ? 0b00011000, 0b00101100, 0b00001100, 0b00011000, 0b00000000, 0b00011000, 0b00000000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0b11111111, // A 0b11111111, 0b11000111, 0b10010011, 0b10010011, 0b10010011, 0b11001001, 0b11111111, 0b11111111, // B 0b10011111, 0b10011111, 0b10000011, 0b10011001, 0b10011001, 0b11000011, 0b11111111, 0b11111111, // C 0b11111111, 0b11000011, 0b10011001, 0b10011111, 0b10011001, 0b11000011, 0b11111111, 0b11111111, // D 0b11111001, 0b11111001, 0b11000001, 0b10011001, 0b10011001, 0b11000011, 0b11111111, 0b11111111, // E 0b11111111, 0b11000001, 0b10011111, 0b10000011, 0b10011111, 0b11000001, 0b11111111, 0b11111111, // F 0b11111111, 0b11000001, 0b10011111, 0b10000001, 0b10011111, 0b10011111, 0b11111111, 0b11111111, // G 0b11111111, 0b11000011, 0b10011001, 0b10011001, 0b11000001, 0b11111001, 0b11000011, 0b11111111, // H 0b11111111, 0b11011101, 0b10011101, 0b10000001, 0b10011101, 0b10011101, 0b11111111, 0b11111111, // I 0b11111111, 0b10000001, 0b11100111, 0b11100111, 0b11100111, 0b10000001, 0b11111111, 0b11111111, // J 0b11111111, 0b10000001, 0b11111001, 0b11111001, 0b10111001, 0b11000011, 0b11111111, 0b11111111, // K 0b11111111, 0b10011001, 0b10011001, 0b10000011, 0b10011001, 0b10011001, 0b11111111, 0b11111111, // L 0b11111111, 0b11001111, 0b10011111, 0b10011111, 0b10011111, 0b10000001, 0b11111111, 0b11111111, // M 0b11111111, 0b11001011, 0b10000001, 0b10010101, 0b10010101, 0b10010101, 0b11111111, 0b11111111, // N 0b11111111, 0b11001101, 0b10000101, 0b10000001, 0b10010001, 0b10011001, 0b11111111, 0b11111111, // O 0b11111111, 0b11000011, 0b10011001, 0b10011001, 0b10011001, 0b11000011, 0b11111111, 0b11111111, // P 0b11111111, 0b11000011, 0b10011001, 0b10011001, 0b10000011, 0b10011111, 0b11111111, 0b11111111, // Q 0b11111111, 0b11000011, 0b10011001, 0b10011001, 0b11000001, 0b11111001, 0b11111111, 0b11111111, // R 0b11111111, 0b11000011, 0b10011001, 0b10011001, 0b10000011, 0b10011001, 0b11111111, 0b11111111, // S 0b11111111, 0b11000001, 0b10011111, 0b10000011, 0b11111001, 0b10000011, 0b11111111, 0b11111111, // T 0b11111111, 0b11110001, 0b10000111, 0b11100111, 0b11100111, 0b11100111, 0b11111111, 0b11111111, // U 0b11111111, 0b10011001, 0b10011001, 0b10011001, 0b10011001, 0b11000011, 0b11111111, 0b11111111, // V 0b11111111, 0b10011001, 0b10011001, 0b11001001, 0b11001001, 0b11100011, 0b11111111, 0b11111111, // W 0b11111111, 0b10010101, 0b10010101, 0b10010101, 0b10000001, 0b11001011, 0b11111111, 0b11111111, // X 0b11111111, 0b10011001, 0b10011001, 0b11000011, 0b10011001, 0b10011001, 0b11111111, 0b11111111, // Y 0b11111111, 0b10011001, 0b10011001, 0b11100001, 0b10111001, 0b11000011, 0b11111111, 0b11111111, // Z 0b11111111, 0b10000001, 0b11111001, 0b11000001, 0b10011111, 0b10000001, 0b11111111, 0b00000000, // [ 0b01111110, 0b01100000, 0b01100000, 0b01100000, 0b01100000, 0b01111110, 0b00000000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // \ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ] 0b00000000, // ^ 0b00011000, 0b00111100, 0b01100110, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, // _ 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b01111110, 0b00000000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ´ 0b00000000, // a 0b00000000, 0b00111000, 0b01101100, 0b01101100, 0b01101100, 0b00110110, 0b00000000, 0b00000000, // b 0b01100000, 0b01100000, 0b01111100, 0b01100110, 0b01100110, 0b00111100, 0b00000000, 0b00000000, // c 0b00000000, 0b00111100, 0b01100110, 0b01100000, 0b01100110, 0b00111100, 0b00000000, 0b00000000, // d 0b00001100, 0b00000110, 0b00111110, 0b01100110, 0b01100110, 0b00111100, 0b00000000, 0b00000000, // e 0b00000000, 0b00111110, 0b01100000, 0b01111100, 0b01100000, 0b00111110, 0b00000000, 0b00000000, // f 0b00000000, 0b00111110, 0b01100000, 0b01111110, 0b01100000, 0b01100000, 0b00000000, 0b00000000, // g 0b00000000, 0b00111100, 0b01100110, 0b01100110, 0b00111110, 0b00000110, 0b00111100, 0b00000000, // h 0b00000000, 0b00100010, 0b01100010, 0b01111110, 0b01100010, 0b01100010, 0b00000000, 0b00000000, // i 0b00000000, 0b01111110, 0b00011000, 0b00011000, 0b00011000, 0b01111110, 0b00000000, 0b00000000, // j 0b00000000, 0b01111110, 0b00000110, 0b00000110, 0b01000110, 0b00111100, 0b00000000, 0b00000000, // k 0b00000000, 0b01100110, 0b01100110, 0b01111100, 0b01100110, 0b01100110, 0b00000000, 0b00000000, // l 0b00000000, 0b00110000, 0b01100000, 0b01100000, 0b01100000, 0b01111110, 0b00000000, 0b00000000, // m 0b00000000, 0b00110100, 0b01111110, 0b01101010, 0b01101010, 0b01101010, 0b00000000, 0b00000000, // n 0b00000000, 0b00110010, 0b01111010, 0b01111110, 0b01101110, 0b01100110, 0b00000000, 0b00000000, // o 0b00000000, 0b00111000, 0b01101100, 0b01100110, 0b01100110, 0b00111100, 0b00000000, 0b00000000, // p 0b00000000, 0b00111100, 0b01100110, 0b01100110, 0b01111100, 0b01100000, 0b00000000, 0b00000000, // q 0b00000000, 0b00111100, 0b01100110, 0b01100110, 0b00111110, 0b00000110, 0b00000000, 0b00000000, // r 0b00000000, 0b00111100, 0b01100110, 0b01100110, 0b01111100, 0b01100110, 0b00000000, 0b00000000, // s 0b00000000, 0b00111110, 0b01100000, 0b01111100, 0b00000110, 0b01111100, 0b00000000, 0b00000000, // t 0b00000000, 0b00001110, 0b01111000, 0b00011000, 0b00011000, 0b00011000, 0b00000000, 0b00000000, // u 0b00000000, 0b01100110, 0b01100110, 0b01100110, 0b01100110, 0b00111100, 0b00000000, 0b00000000, // v 0b00000000, 0b01100110, 0b01100110, 0b00110110, 0b00110110, 0b00011100, 0b00000000, 0b00000000, // w 0b00000000, 0b01101010, 0b01101010, 0b01101010, 0b01111110, 0b00110100, 0b00000000, 0b00000000, // x 0b00000000, 0b01100110, 0b01100110, 0b00111100, 0b01100110, 0b01100110, 0b00000000, 0b00000000, // y 0b00000000, 0b01100110, 0b01100110, 0b00011110, 0b01000110, 0b00111100, 0b00000000, 0b00000000, // z 0b00000000, 0b01111110, 0b00000110, 0b00111110, 0b01100000, 0b01111110, 0b00000000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // } 0b00000000, // ~ 0b00000000, 0b00000000, 0b00111010, 0b01101010, 0b01101100, 0b00000000, 0b00000000, }), .first_char = 33, // From ! .last_char = 126, // To z };
src/fontdata.zig
const std = @import("std"); // Command-line flags: // - part1 - output part 1 answer // - part2 - output part 2 answer // - jumps - print all possible jumps to stdout // - explain - run and print out operations to stderr // TODO: make an enum (see tagName) const ops = .{ "acc", "jmp", "nop" }; fn parseOp(candidate: []const u8) i16 { inline for (ops) |op, i| { if (std.mem.eql(u8, candidate, op)) { return @intCast(i16, i); } } return -1; } // TODO just use std.os.argv! fn argv(i: u8) []u8 { var args = std.process.args(); var j: u8 = 0; while (j <= i) : (j += 1) { _ = args.skip(); } return (args.next(std.heap.page_allocator) orelse "") catch ""; } pub fn load(operations: *[65536]i16, arguments: *[65536]i16, stderr: anytype) !void { const source = try std.fs.cwd().openFile("08.dat", .{}); defer source.close(); const source_size = try source.getEndPos(); var raw: [131072]u8 = undefined; _ = try source.read(raw[0..source_size]); var lines = std.mem.tokenize(&raw, "\n"); var line: usize = 0; while (lines.next()) |token| { if (lines.index > source_size) { break; } var segments = std.mem.tokenize(token, " "); const operation = segments.next() orelse ""; operations[line] = parseOp(operation); arguments[line] = try std.fmt.parseInt(i16, segments.next() orelse "0", 10); line += 1; if (operations[lines.index] == -1) { try stderr.print("unhandled operation: {}\n", .{operation}); break; } } } pub fn main() !void { var i: usize = 0; var opcode: i16 = 0; var argument: i16 = 0; var acc: i64 = 0; var operations: [65536]i16 = undefined; var arguments: [65536]i16 = undefined; var visited = [_]i16{0} ** 65536; const stdout = std.io.getStdOut().outStream(); const stderr = std.io.getStdErr().outStream(); const arg0 = argv(0); try load(&operations, &arguments, stderr); if (std.mem.eql(u8, "jumps", arg0)) { for (operations) |operation, j| { argument = arguments[j]; if (operation > 0) { try stdout.print("{}: {} {}: {}\n", .{ j, operation, argument, @intCast(usize, @intCast(i16, j) + argument) }); } } return; } while (true) { opcode = operations[i]; argument = arguments[i]; if (std.mem.eql(u8, "part1", arg0)) { if (visited[i] == 1) { try stdout.print("looping! {} {}\n", .{ i, acc }); break; } else { visited[i] = 1; } } else if (std.mem.eql(u8, "part2", arg0)) { if (i == 432) { opcode = 2; } } else if (std.mem.eql(u8, "explain", arg0)) { if (opcode > 0) { try stderr.print("{}: {} {} {}: {}\n", .{ i, opcode, argument, acc, @intCast(i16, i) + argument }); } } switch (opcode) { // acc 0 => { acc += argument; i += 1; }, // jmp 1 => { i = @intCast(usize, @intCast(i16, i) + argument); }, // nop 2 => { i += 1; }, else => { try stdout.print("terminated! {}\n", .{acc}); break; }, } } }
2020/08.zig
const std = @import("std"); const allocator = std.heap.page_allocator; const assert = std.debug.assert; const expect = std.testing.expect; const math = std.math; const mem = std.mem; const zip = @import("./zip.zig"); const time = @import("./time.zig"); const hamlet = @embedFile("../fixtures/hamlet.txt"); const UINT16_MAX = math.maxInt(u16); fn strlen(str: [*:0]const u8) usize { return mem.indexOfSentinel(u8, 0x00, str); } // Created by: // $ echo -n foo > foo // $ echo -n nanananana > bar // $ mkdir dir // $ echo -n baz > dir/baz // $ touch --date="2019-09-21 12:34:56" foo bar dir dir/baz // $ zip test.zip --entry-comments --archive-comment -r foo bar dir // adding: foo (stored 0%) // adding: bar (deflated 40%) // adding: dir/ (stored 0%) // adding: dir/baz (stored 0%) // Enter comment for foo: // foo // Enter comment for bar: // bar // Enter comment for dir/: // dir // Enter comment for dir/baz: // dirbaz // enter new zip file comment (end with .): // testzip // . // $ xxd -i < test.zip // const basic_zip = [_]u8{ 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5c, 0x64, 0x35, 0x4f, 0x21, 0x65, 0x73, 0x8c, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x1c, 0x00, 0x66, 0x6f, 0x6f, 0x55, 0x54, 0x09, 0x00, 0x03, 0xd0, 0xfc, 0x85, 0x5d, 0x5b, 0xca, 0x8b, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x66, 0x6f, 0x6f, 0x50, 0x4b, 0x03, 0x04, 0x14, 0x00, 0x00, 0x00, 0x08, 0x00, 0x5c, 0x64, 0x35, 0x4f, 0x9d, 0x3a, 0x97, 0x4a, 0x06, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x1c, 0x00, 0x62, 0x61, 0x72, 0x55, 0x54, 0x09, 0x00, 0x03, 0xd0, 0xfc, 0x85, 0x5d, 0x5b, 0xca, 0x8b, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0xcb, 0x4b, 0xcc, 0x83, 0x42, 0x00, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5c, 0x64, 0x35, 0x4f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x1c, 0x00, 0x64, 0x69, 0x72, 0x2f, 0x55, 0x54, 0x09, 0x00, 0x03, 0xd0, 0xfc, 0x85, 0x5d, 0x6e, 0xca, 0x8b, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5c, 0x64, 0x35, 0x4f, 0x98, 0x04, 0x24, 0x78, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x1c, 0x00, 0x64, 0x69, 0x72, 0x2f, 0x62, 0x61, 0x7a, 0x55, 0x54, 0x09, 0x00, 0x03, 0xd0, 0xfc, 0x85, 0x5d, 0xd0, 0xfc, 0x85, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x62, 0x61, 0x7a, 0x50, 0x4b, 0x01, 0x02, 0x1e, 0x03, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5c, 0x64, 0x35, 0x4f, 0x21, 0x65, 0x73, 0x8c, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x18, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xa4, 0x81, 0x00, 0x00, 0x00, 0x00, 0x66, 0x6f, 0x6f, 0x55, 0x54, 0x05, 0x00, 0x03, 0xd0, 0xfc, 0x85, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x66, 0x6f, 0x6f, 0x50, 0x4b, 0x01, 0x02, 0x1e, 0x03, 0x14, 0x00, 0x00, 0x00, 0x08, 0x00, 0x5c, 0x64, 0x35, 0x4f, 0x9d, 0x3a, 0x97, 0x4a, 0x06, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x18, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xa4, 0x81, 0x40, 0x00, 0x00, 0x00, 0x62, 0x61, 0x72, 0x55, 0x54, 0x05, 0x00, 0x03, 0xd0, 0xfc, 0x85, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x62, 0x61, 0x72, 0x50, 0x4b, 0x01, 0x02, 0x1e, 0x03, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5c, 0x64, 0x35, 0x4f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x18, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0xed, 0x41, 0x83, 0x00, 0x00, 0x00, 0x64, 0x69, 0x72, 0x2f, 0x55, 0x54, 0x05, 0x00, 0x03, 0xd0, 0xfc, 0x85, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x64, 0x69, 0x72, 0x50, 0x4b, 0x01, 0x02, 0x1e, 0x03, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5c, 0x64, 0x35, 0x4f, 0x98, 0x04, 0x24, 0x78, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x18, 0x00, 0x06, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xa4, 0x81, 0xc1, 0x00, 0x00, 0x00, 0x64, 0x69, 0x72, 0x2f, 0x62, 0x61, 0x7a, 0x55, 0x54, 0x05, 0x00, 0x03, 0xd0, 0xfc, 0x85, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x64, 0x69, 0x72, 0x62, 0x61, 0x7a, 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x04, 0x00, 0x38, 0x01, 0x00, 0x00, 0x05, 0x01, 0x00, 0x00, 0x07, 0x00, 0x74, 0x65, 0x73, 0x74, 0x7a, 0x69, 0x70, }; // Created by: // (After running the steps for basic_zip above) // $ curl -O https://www.hanshq.net/files/pkz204g.exe // $ unzip pkz204g.exe PKZIP.EXE // $ dosbox -c "mount c ." -c "c:" -c "pkzip pk.zip -P foo bar dir/baz" -c exit // $ xxd -i < PK.ZIP // const pk_zip = [_]u8{ 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5c, 0x64, 0x35, 0x4f, 0x21, 0x65, 0x73, 0x8c, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x46, 0x4f, 0x4f, 0x66, 0x6f, 0x6f, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5c, 0x64, 0x35, 0x4f, 0x9d, 0x3a, 0x97, 0x4a, 0x0a, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x42, 0x41, 0x52, 0x6e, 0x61, 0x6e, 0x61, 0x6e, 0x61, 0x6e, 0x61, 0x6e, 0x61, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5c, 0x64, 0x35, 0x4f, 0x98, 0x04, 0x24, 0x78, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x44, 0x49, 0x52, 0x2f, 0x42, 0x41, 0x5a, 0x62, 0x61, 0x7a, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5c, 0x64, 0x35, 0x4f, 0x21, 0x65, 0x73, 0x8c, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x4f, 0x4f, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5c, 0x64, 0x35, 0x4f, 0x9d, 0x3a, 0x97, 0x4a, 0x0a, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x42, 0x41, 0x52, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5c, 0x64, 0x35, 0x4f, 0x98, 0x04, 0x24, 0x78, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x4f, 0x00, 0x00, 0x00, 0x44, 0x49, 0x52, 0x2f, 0x42, 0x41, 0x5a, 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x97, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, }; // From https://en.wikipedia.org/wiki/Zip_(file_format)#Limits // const empty_zip = [_]u8{ 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; // Created by: // $ echo -n 1234567 > a // $ curl -O https://www.hanshq.net/files/pkz204g.exe // $ unzip pkz204g.exe PKZIP.EXE // $ dosbox -c "mount c ." -c "c:" -c "pkzip a.zip a" -c exit // $ xxd -i < A.ZIP | sed 's/0x07/0x4d/g' // // Why 0x4d? Because there is room for a 0x4c payload (if we allow it to // overlap with the cfh and eocdr): // "1234567" (7 bytes) + cfh (46 bytes) + filename (1 byte) + eocdr (22 bytes) // const out_of_bounds_member_zip = [_]u8{ 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x70, 0x88, 0x4f, 0x9f, 0x69, 0x03, 0x50, 0x4d, 0x00, 0x00, 0x00, 0x4d, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x41, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x70, 0x88, 0x4f, 0x9f, 0x69, 0x03, 0x50, 0x4d, 0x00, 0x00, 0x00, 0x4d, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x2f, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, }; // Created by: // $ for x in foo bar baz ; do echo $x > $x && zip $x.zip $x ; done // $ zip test.zip foo.zip bar.zip baz.zip // $ xxd -i < test.zip // const zip_in_zip = [_]u8{ 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0x4b, 0x8f, 0x4f, 0xfc, 0xe0, 0x94, 0x8d, 0xa0, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x07, 0x00, 0x1c, 0x00, 0x66, 0x6f, 0x6f, 0x2e, 0x7a, 0x69, 0x70, 0x55, 0x54, 0x09, 0x00, 0x03, 0x2c, 0xef, 0xf5, 0x5d, 0x2c, 0xef, 0xf5, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0x4b, 0x8f, 0x4f, 0xa8, 0x65, 0x32, 0x7e, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00, 0x1c, 0x00, 0x66, 0x6f, 0x6f, 0x55, 0x54, 0x09, 0x00, 0x03, 0x2c, 0xef, 0xf5, 0x5d, 0x0b, 0xef, 0xf5, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x66, 0x6f, 0x6f, 0x0a, 0x50, 0x4b, 0x01, 0x02, 0x1e, 0x03, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0x4b, 0x8f, 0x4f, 0xa8, 0x65, 0x32, 0x7e, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xa4, 0x81, 0x00, 0x00, 0x00, 0x00, 0x66, 0x6f, 0x6f, 0x55, 0x54, 0x05, 0x00, 0x03, 0x2c, 0xef, 0xf5, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x49, 0x00, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0x4b, 0x8f, 0x4f, 0x09, 0x2e, 0x40, 0x1a, 0xa0, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x07, 0x00, 0x1c, 0x00, 0x62, 0x61, 0x72, 0x2e, 0x7a, 0x69, 0x70, 0x55, 0x54, 0x09, 0x00, 0x03, 0x2c, 0xef, 0xf5, 0x5d, 0x2c, 0xef, 0xf5, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0x4b, 0x8f, 0x4f, 0xe9, 0xb3, 0xa2, 0x04, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00, 0x1c, 0x00, 0x62, 0x61, 0x72, 0x55, 0x54, 0x09, 0x00, 0x03, 0x2c, 0xef, 0xf5, 0x5d, 0x0b, 0xef, 0xf5, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x62, 0x61, 0x72, 0x0a, 0x50, 0x4b, 0x01, 0x02, 0x1e, 0x03, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0x4b, 0x8f, 0x4f, 0xe9, 0xb3, 0xa2, 0x04, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xa4, 0x81, 0x00, 0x00, 0x00, 0x00, 0x62, 0x61, 0x72, 0x55, 0x54, 0x05, 0x00, 0x03, 0x2c, 0xef, 0xf5, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x49, 0x00, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0x4b, 0x8f, 0x4f, 0x38, 0xcd, 0x36, 0x40, 0xa0, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x07, 0x00, 0x1c, 0x00, 0x62, 0x61, 0x7a, 0x2e, 0x7a, 0x69, 0x70, 0x55, 0x54, 0x09, 0x00, 0x03, 0x2c, 0xef, 0xf5, 0x5d, 0x2c, 0xef, 0xf5, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0x4b, 0x8f, 0x4f, 0xe1, 0x39, 0x7b, 0xcc, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00, 0x1c, 0x00, 0x62, 0x61, 0x7a, 0x55, 0x54, 0x09, 0x00, 0x03, 0x2c, 0xef, 0xf5, 0x5d, 0x0b, 0xef, 0xf5, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x62, 0x61, 0x7a, 0x0a, 0x50, 0x4b, 0x01, 0x02, 0x1e, 0x03, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0x4b, 0x8f, 0x4f, 0xe1, 0x39, 0x7b, 0xcc, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xa4, 0x81, 0x00, 0x00, 0x00, 0x00, 0x62, 0x61, 0x7a, 0x55, 0x54, 0x05, 0x00, 0x03, 0x2c, 0xef, 0xf5, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x49, 0x00, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x4b, 0x01, 0x02, 0x1e, 0x03, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0x4b, 0x8f, 0x4f, 0xfc, 0xe0, 0x94, 0x8d, 0xa0, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x07, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x81, 0x00, 0x00, 0x00, 0x00, 0x66, 0x6f, 0x6f, 0x2e, 0x7a, 0x69, 0x70, 0x55, 0x54, 0x05, 0x00, 0x03, 0x2c, 0xef, 0xf5, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x50, 0x4b, 0x01, 0x02, 0x1e, 0x03, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0x4b, 0x8f, 0x4f, 0x09, 0x2e, 0x40, 0x1a, 0xa0, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x07, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x81, 0xe1, 0x00, 0x00, 0x00, 0x62, 0x61, 0x72, 0x2e, 0x7a, 0x69, 0x70, 0x55, 0x54, 0x05, 0x00, 0x03, 0x2c, 0xef, 0xf5, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x50, 0x4b, 0x01, 0x02, 0x1e, 0x03, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd2, 0x4b, 0x8f, 0x4f, 0x38, 0xcd, 0x36, 0x40, 0xa0, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x07, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x81, 0xc2, 0x01, 0x00, 0x00, 0x62, 0x61, 0x7a, 0x2e, 0x7a, 0x69, 0x70, 0x55, 0x54, 0x05, 0x00, 0x03, 0x2c, 0xef, 0xf5, 0x5d, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0xe7, 0x00, 0x00, 0x00, 0xa3, 0x02, 0x00, 0x00, 0x00, 0x00, }; // Created by: // $ echo -n 1234567 > a // $ curl -O https://www.hanshq.net/files/pkz204g.exe // $ unzip pkz204g.exe PKZIP.EXE // $ dosbox -c "mount c ." -c "c:" -c "pkzip a.zip a" -c exit // $ xxd -i < A.ZIP // // Then hand modify the lowest byte in uncomp_size from 0x07 to 0x08. // This makes the uncompressed size not match the compressed size as it should. // const bad_stored_uncomp_size_zip = [_]u8{ 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x70, 0x88, 0x4f, 0x9f, 0x69, 0x03, 0x50, 0x07, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x41, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x70, 0x88, 0x4f, 0x9f, 0x69, 0x03, 0x50, 0x07, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x2f, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, }; fn magic_time() time.time_t { var tm: time.tm_t = time.tm_t{}; // 2019-09-21 12:34:56 tm.tm_year = 2019 - 1900; tm.tm_mon = 9 - 1; tm.tm_mday = 21; tm.tm_hour = 12; tm.tm_min = 34; tm.tm_sec = 56; tm.tm_isdst = -1; return time.mktime(&tm); } fn check_extract2(m: *const zip.zipmemb_t, expected: [*]const u8, n: usize) !void { var uncomp: [*]u8 = undefined; try expect(m.uncomp_size == n); var uncomp_mem = try allocator.alloc(u8, n); uncomp = uncomp_mem.ptr; try expect(try zip.zip_extract_member(m, uncomp)); try expect(mem.eql(u8, uncomp[0..n], expected[0..n])); allocator.free(uncomp_mem); } fn check_extract(m: *zip.zipmemb_t, expected: [*]const u8) !void { var expected_str = @ptrCast([*:0]const u8, expected); try check_extract2(m, expected, strlen(expected_str)); } test "zip_basic" { var z: zip.zip_t = undefined; var i: zip.zipiter_t = undefined; var m: zip.zipmemb_t = undefined; try expect(zip.zip_read(&z, basic_zip[0..], basic_zip.len)); try expect(z.num_members == 4); try expect(z.comment_len == 7); try expect(mem.eql(u8, z.comment[0..7], "testzip")); i = z.members_begin; m = zip.zip_member(&z, i); try expect(m.name_len == 3); try expect(mem.eql(u8, m.name[0..3], "foo")); try expect(m.mtime == magic_time()); try expect(m.comment_len == 3); try expect(mem.eql(u8, m.comment[0..3], "foo")); try expect(m.is_dir == false); try expect(m.crc32 == 0x8c73_6521); try check_extract(&m, "foo"); i = m.next; m = zip.zip_member(&z, i); try expect(m.name_len == 3); try expect(mem.eql(u8, m.name[0..3], "bar")); try expect(m.mtime == magic_time()); try expect(m.comment_len == 3); try expect(mem.eql(u8, m.comment[0..3], "bar")); try expect(m.is_dir == false); try expect(m.crc32 == 0x4a97_3a9d); try check_extract(&m, "nanananana"); i = m.next; m = zip.zip_member(&z, i); try expect(m.name_len == 4); try expect(mem.eql(u8, m.name[0..4], "dir/")); try expect(m.mtime == magic_time()); try expect(m.comment_len == 3); try expect(mem.eql(u8, m.comment[0..m.comment_len], "dir")); try expect(m.is_dir == true); i = m.next; m = zip.zip_member(&z, i); try expect(m.name_len == 7); try expect(mem.eql(u8, m.name[0..7], "dir/baz")); try expect(m.mtime == magic_time()); try expect(mem.eql(u8, m.comment[0..6], "dirbaz")); try expect(m.is_dir == false); try expect(m.crc32 == 0x7824_0498); try check_extract(&m, "baz"); i = m.next; try expect(i == z.members_end); } test "zip_pk" { var z: zip.zip_t = undefined; var i: zip.zipiter_t = undefined; var m: zip.zipmemb_t = undefined; try expect(zip.zip_read(&z, pk_zip[0..], pk_zip.len)); try expect(z.num_members == 3); try expect(z.comment_len == 0); i = z.members_begin; m = zip.zip_member(&z, i); try expect(m.name_len == 3); try expect(mem.eql(u8, m.name[0..3], "FOO")); try expect(m.mtime == magic_time()); try expect(m.comment_len == 0); try expect(m.is_dir == false); try expect(m.crc32 == 0x8c73_6521); try check_extract(&m, "foo"); i = m.next; m = zip.zip_member(&z, i); try expect(m.name_len == 3); try expect(mem.eql(u8, m.name[0..3], "BAR")); try expect(m.mtime == magic_time()); try expect(m.comment_len == 0); try expect(m.is_dir == false); try expect(m.crc32 == 0x4a97_3a9d); try check_extract(&m, "nanananana"); i = m.next; m = zip.zip_member(&z, i); try expect(m.name_len == 7); try expect(mem.eql(u8, m.name[0..7], "DIR/BAZ")); try expect(m.mtime == magic_time()); try expect(m.comment_len == 0); try expect(m.is_dir == false); try expect(m.crc32 == 0x7824_0498); try check_extract(&m, "baz"); i = m.next; try expect(i == z.members_end); } test "zip_out_of_bounds_member" { var z: zip.zip_t = undefined; try expect(!zip.zip_read(&z, out_of_bounds_member_zip[0..], out_of_bounds_member_zip.len)); } test "zip_empty" { var z: zip.zip_t = undefined; // Not enough bytes. try expect(!zip.zip_read(&z, empty_zip[0..], empty_zip.len - 1)); try expect(zip.zip_read(&z, empty_zip[0..], empty_zip.len)); try expect(z.comment_len == 0); try expect(z.num_members == 0); try expect(z.members_begin == z.members_end); } fn write_basic_callback(filename: [*]const u8, method: zip.method_t, size: u32, comp_size: u32) zip.CallbackError!void { const Static = struct { var n: u32 = 0; }; const err = zip.CallbackError.WriteCallbackError; switch (Static.n) { 0 => { expect(mem.eql(u8, filename[0..3], "one")) catch return err; expect(size == 3) catch return err; expect(comp_size <= 3) catch return err; expect(method == zip.method_t.ZIP_STORE) catch return err; }, 1 => { expect(mem.eql(u8, filename[0..3], "two")) catch return err; expect(size == 9) catch return err; expect(comp_size <= 9) catch return err; expect(method == zip.method_t.ZIP_DEFLATE) catch return err; }, else => { expect(false) catch return err; }, } Static.n += 1; } test "zip_write_basic" { const names = [_][*:0]const u8{ "one", "two" }; const data1 = "foo"; const data2 = "barbarbar"; const data: [2][*]const u8 = [_][*]const u8{ data1, data2 }; const sizes = [_]u32{ 3, 9 }; var mtimes: [2]time.time_t = undefined; const comment = "comment"; var max_size: usize = 0; var size: usize = 0; var out: [*]u8 = undefined; var in: [*]u8 = undefined; var z: zip.zip_t = undefined; var i: zip.zipiter_t = undefined; var m: zip.zipmemb_t = undefined; mtimes[0] = magic_time(); mtimes[1] = mtimes[0]; max_size = zip.zip_max_size(2, names[0..], sizes[0..], comment); var out_mem = try allocator.alloc(u8, max_size); out = out_mem.ptr; size = try zip.zip_write(out, 2, names[0..], &data, &sizes, &mtimes, comment, zip.method_t.ZIP_DEFLATE, write_basic_callback); var in_mem = try allocator.alloc(u8, size); in = in_mem.ptr; mem.copy(u8, in[0..size], out[0..size]); allocator.free(out_mem); try expect(zip.zip_read(&z, in, size)); try expect(z.num_members == 2); try expect(z.comment_len == comment.len); try expect(mem.eql(u8, z.comment[0..z.comment_len], comment[0..z.comment_len])); i = z.members_begin; m = zip.zip_member(&z, i); try expect(m.name_len == strlen(names[0])); try expect(mem.eql(u8, m.name[0..m.name_len], names[0][0..m.name_len])); try expect(m.mtime == mtimes[0]); try expect(m.crc32 == 0x8c73_6521); try check_extract(&m, data[0]); i = m.next; m = zip.zip_member(&z, i); try expect(m.name_len == strlen(names[1])); try expect(mem.eql(u8, m.name[0..m.name_len], names[1][0..m.name_len])); try expect(m.mtime == mtimes[1]); try expect(m.crc32 == 0x5acc_11a8); try check_extract(&m, data[1]); i = m.next; try expect(i == z.members_end); allocator.free(in_mem); } test "zip_write_empty" { var max_size: usize = 0; var size: usize = 0; var out: [*]u8 = undefined; max_size = zip.zip_max_size(0, null, null, null); var out_mem = try allocator.alloc(u8, max_size); out = out_mem.ptr; size = try zip.zip_write(out, 0, null, null, null, null, null, zip.method_t.ZIP_DEFLATE, null); try expect(size == empty_zip.len); try expect(mem.eql(u8, out[0..size], empty_zip[0..size])); allocator.free(out_mem); } test "zip_max_comment" { var comment: [UINT16_MAX + 1:0]u8 = undefined; var max_size: usize = 0; var size: usize = 0; var out: [*]u8 = undefined; var z: zip.zip_t = undefined; mem.set(u8, comment[0..], 'a'); comment[UINT16_MAX] = 0x00; max_size = zip.zip_max_size(0, null, null, &comment); var out_mem = try allocator.alloc(u8, max_size + 1000); out = out_mem.ptr; mem.set(u8, out[0 .. max_size + 1000], 0x00); size = try zip.zip_write(out, 0, null, null, null, null, &comment, zip.method_t.ZIP_DEFLATE, null); try expect(size <= max_size); try expect(size == empty_zip.len + UINT16_MAX); try expect(zip.zip_read(&z, out, size)); try expect(z.comment_len == UINT16_MAX); try expect(mem.eql(u8, z.comment[0..UINT16_MAX], comment[0..UINT16_MAX])); try expect(z.num_members == 0); try expect(z.members_begin == z.members_end); // The EOCDR + comment don't fit. try expect(!zip.zip_read(&z, out, size - 1)); // The EOCDR + comment should probably be at the end of the file as // per the spec, but neither Info-ZIP nor PKZIP are that picky. // There are files in the wild with some extra bytes at the end, // so we cannot be picky either. try expect(zip.zip_read(&z, out, size + 123)); allocator.free(out_mem); } test "zip_in_zip" { var z: zip.zip_t = undefined; var i: zip.zipiter_t = undefined; var m: zip.zipmemb_t = undefined; try expect(zip.zip_read(&z, zip_in_zip[0..], zip_in_zip.len)); try expect(z.num_members == 3); i = z.members_begin; m = zip.zip_member(&z, i); try expect(m.name_len == 7); try expect(mem.eql(u8, m.name[0..7], "foo.zip")); i = m.next; m = zip.zip_member(&z, i); try expect(m.name_len == 7); try expect(mem.eql(u8, m.name[0..7], "bar.zip")); i = m.next; m = zip.zip_member(&z, i); try expect(m.name_len == 7); try expect(mem.eql(u8, m.name[0..7], "baz.zip")); try expect(m.next == z.members_end); } test "zip_bad_stored_uncomp_size" { var z: zip.zip_t = undefined; try expect(!zip.zip_read( &z, &bad_stored_uncomp_size_zip, bad_stored_uncomp_size_zip.len, )); } // multizip - a zip file containing all the compression methods: // // for x in 092 110 250 ; do // dosbox -c "mount c ." -c "c:" -c "$(ls pk*$x*.exe) pkzip.exe" -c "exit" // mv PKZIP.EXE $x.exe // done // // # Store // echo -n foo > 0.txt // dosbox -c "mount c ." -c "c:" -c "110 x.zip 0.txt" -c exit // // # Shrink // echo -n ababcbababaaaaaaa > 1.txt // dosbox -c "mount c ." -c "c:" -c "110 -es x.zip 1.txt" -c exit // // # Reduce // for n in $(seq 2 5) ; do // rm -f $n.txt // for x in $(seq 1 42) ; do dd if=hamlet.txt bs=1 count=50 >> $n.txt ; done // done // dosbox -c "mount c ." -c "c:" -c "092 -ea1 x.zip 2.txt" -c "exit" // dosbox -c "mount c ." -c "c:" -c "092 -ea2 x.zip 3.txt" -c "exit" // dosbox -c "mount c ." -c "c:" -c "092 -ea3 x.zip 4.txt" -c "exit" // dosbox -c "mount c ." -c "c:" -c "092 -ea4 x.zip 5.txt" -c "exit" // // # Implode // # 4KB wnd, no lit tree; zipinfo "i4:2" // dd if=/dev/zero of=61.txt bs=1 count=256 // dosbox -c "mount c ." -c "c:" -c "110 -ei x.zip 61.txt" -c exit // # 8KB wnd, lit tree; zipinfo "i8:3" // rm -f 62.txt // for x in $(seq 1 200) ; do dd if=hamlet.txt bs=1 count=50 >> 62.txt ; done // dosbox -c "mount c ." -c "c:" -c "110 -ei x.zip 62.txt" -c exit // // # Deflate // dd if=hamlet.txt of=8.txt bs=1 count=128 // dosbox -c "mount c ." -c "c:" -c "250 -exx x.zip 8.txt" -c exit // const multizip = [_]u8{ 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x4a, 0x3b, 0x51, 0x21, 0x65, 0x73, 0x8c, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x30, 0x2e, 0x54, 0x58, 0x54, 0x66, 0x6f, 0x6f, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x62, 0x4a, 0x3b, 0x51, 0x02, 0x04, 0x12, 0x39, 0x0c, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x31, 0x2e, 0x54, 0x58, 0x54, 0x61, 0xc4, 0x04, 0x1c, 0x23, 0xb0, 0x60, 0x98, 0x83, 0x08, 0xc3, 0x00, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x02, 0x00, 0x63, 0x4a, 0x3b, 0x51, 0x6e, 0x4e, 0x6d, 0x9c, 0x0a, 0x01, 0x00, 0x00, 0x34, 0x08, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x32, 0x2e, 0x54, 0x58, 0x54, 0xc2, 0xff, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0xb4, 0x8d, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xef, 0xbb, 0xbf, 0x0d, 0x0a, 0x50, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x20, 0x47, 0x75, 0x74, 0x65, 0x6e, 0x62, 0x65, 0x72, 0x67, 0x20, 0x45, 0x42, 0x6f, 0x6f, 0x6b, 0x20, 0x6f, 0x66, 0x20, 0x48, 0x61, 0xb0, 0x95, 0xd1, 0xb1, 0x80, 0x88, 0xe5, 0x81, 0x5c, 0xa5, 0xb1, 0xb1, 0xa5, 0x85, 0x01, 0xf9, 0x25, 0x06, 0x72, 0x98, 0x90, 0x1a, 0x1d, 0x43, 0xc2, 0x47, 0x48, 0x10, 0x10, 0x10, 0x7a, 0xcc, 0x03, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x63, 0x4a, 0x3b, 0x51, 0x6e, 0x4e, 0x6d, 0x9c, 0x0f, 0x01, 0x00, 0x00, 0x34, 0x08, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x33, 0x2e, 0x54, 0x58, 0x54, 0xc2, 0xff, 0x39, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xb4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xef, 0xbb, 0xbf, 0x0d, 0x0a, 0x50, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x20, 0x47, 0x75, 0x74, 0x65, 0x6e, 0x62, 0x65, 0x72, 0x67, 0x20, 0x45, 0x42, 0x6f, 0x6f, 0x6b, 0x20, 0x6f, 0x66, 0x20, 0x48, 0x61, 0xb0, 0x95, 0xd1, 0xb1, 0x80, 0x88, 0xe5, 0x81, 0x5c, 0xa5, 0xb1, 0xb1, 0xa5, 0x85, 0x01, 0xf9, 0x25, 0x06, 0x52, 0x91, 0x31, 0x48, 0x0d, 0x8f, 0x21, 0xff, 0xfd, 0x7f, 0x84, 0xfc, 0xfb, 0x7f, 0x17, 0x12, 0x04, 0x04, 0x84, 0x1d, 0xe7, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x04, 0x00, 0x63, 0x4a, 0x3b, 0x51, 0x6e, 0x4e, 0x6d, 0x9c, 0x16, 0x01, 0x00, 0x00, 0x34, 0x08, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x34, 0x2e, 0x54, 0x58, 0x54, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x1f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xb4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xef, 0xbb, 0xbf, 0x0d, 0x0a, 0x50, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x20, 0x47, 0x75, 0x74, 0x65, 0x6e, 0x62, 0x65, 0x72, 0x67, 0x20, 0x45, 0x42, 0x6f, 0x6f, 0x6b, 0x20, 0x6f, 0x66, 0x20, 0x48, 0x61, 0xb0, 0x95, 0xd1, 0xb1, 0x80, 0x88, 0xe5, 0x81, 0x5c, 0xa5, 0xb1, 0xb1, 0xa5, 0x85, 0x01, 0x09, 0x44, 0x0c, 0x24, 0x42, 0x63, 0x90, 0x98, 0x1e, 0x43, 0xfe, 0xf9, 0x7f, 0x84, 0xfc, 0xf5, 0x9f, 0x08, 0xf9, 0xef, 0xbf, 0x16, 0xf2, 0xe7, 0x7f, 0x38, 0xe4, 0xef, 0xff, 0x06, 0x48, 0xbb, 0x0f, 0x00, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x05, 0x00, 0x63, 0x4a, 0x3b, 0x51, 0x6e, 0x4e, 0x6d, 0x9c, 0x1a, 0x01, 0x00, 0x00, 0x34, 0x08, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x35, 0x2e, 0x54, 0x58, 0x54, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x0f, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xb4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xef, 0xbb, 0xbf, 0x0d, 0x0a, 0x50, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x20, 0x47, 0x75, 0x74, 0x65, 0x6e, 0x62, 0x65, 0x72, 0x67, 0x20, 0x45, 0x42, 0x6f, 0x6f, 0x6b, 0x20, 0x6f, 0x66, 0x20, 0x48, 0x61, 0xb0, 0x95, 0xd1, 0xb1, 0x80, 0x88, 0xe5, 0x81, 0x5c, 0xa5, 0xb1, 0xb1, 0xa5, 0x85, 0x01, 0x09, 0x48, 0x0c, 0x24, 0x52, 0x63, 0x90, 0xd8, 0x1e, 0x43, 0xfe, 0xf8, 0x7f, 0x84, 0xfc, 0xf2, 0x9f, 0x08, 0xf9, 0xe7, 0x7f, 0x10, 0xf2, 0xd3, 0xff, 0x2b, 0xe4, 0xaf, 0xff, 0x54, 0xc8, 0x6f, 0xff, 0xd5, 0x90, 0xb2, 0x3c, 0x03, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x4a, 0x3b, 0x51, 0x58, 0x85, 0x96, 0x0d, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x36, 0x31, 0x2e, 0x54, 0x58, 0x54, 0x0f, 0x00, 0x12, 0x03, 0x24, 0x15, 0x36, 0x27, 0x38, 0x39, 0x6a, 0x7b, 0x4c, 0x9d, 0x6e, 0x1f, 0x09, 0x06, 0x01, 0x13, 0x34, 0xe5, 0xf6, 0x96, 0xf7, 0xfe, 0x04, 0xf8, 0x6f, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x06, 0x00, 0x06, 0x00, 0x65, 0x4a, 0x3b, 0x51, 0xf1, 0x0d, 0xc3, 0x06, 0x19, 0x01, 0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x36, 0x32, 0x2e, 0x54, 0x58, 0x54, 0x61, 0x0a, 0x7b, 0x07, 0x06, 0x1b, 0x06, 0xbb, 0x0c, 0x4b, 0x03, 0x09, 0x07, 0x0b, 0x09, 0x0b, 0x09, 0x07, 0x16, 0x07, 0x08, 0x06, 0x05, 0x06, 0x07, 0x06, 0x05, 0x36, 0x07, 0x16, 0x17, 0x0b, 0x0a, 0x06, 0x08, 0x0a, 0x0b, 0x05, 0x06, 0x15, 0x04, 0x06, 0x17, 0x05, 0x0a, 0x08, 0x05, 0x06, 0x15, 0x06, 0x0a, 0x25, 0x06, 0x08, 0x07, 0x18, 0x0a, 0x07, 0x0a, 0x08, 0x0b, 0x07, 0x0b, 0x04, 0x25, 0x04, 0x25, 0x04, 0x0a, 0x06, 0x04, 0x05, 0x14, 0x05, 0x09, 0x34, 0x07, 0x06, 0x17, 0x09, 0x1a, 0x2b, 0xfc, 0xfc, 0xfc, 0xfb, 0xfb, 0xfb, 0x0c, 0x0b, 0x2c, 0x0b, 0x2c, 0x0b, 0x3c, 0x0b, 0x2c, 0x2b, 0xac, 0x0c, 0x01, 0x22, 0x23, 0x14, 0x15, 0x36, 0x37, 0x68, 0x89, 0x9a, 0xdb, 0x3c, 0x05, 0x06, 0x12, 0x23, 0x14, 0xe5, 0xf6, 0x96, 0xf7, 0x01, 0x6c, 0x50, 0x08, 0x32, 0x45, 0xc5, 0x49, 0xdb, 0x1e, 0x42, 0x77, 0x63, 0xf9, 0x51, 0xe7, 0xe5, 0x3e, 0x9a, 0xf7, 0x56, 0xfd, 0x6f, 0xea, 0xbe, 0x27, 0xfc, 0xbd, 0xf6, 0xa3, 0x3c, 0xe5, 0xf3, 0x5e, 0xf2, 0x7f, 0x33, 0xdc, 0x8f, 0x7c, 0x9d, 0xe7, 0xf5, 0x94, 0xc5, 0x8e, 0xfa, 0xeb, 0x36, 0xea, 0x2f, 0x11, 0x51, 0x7f, 0x67, 0x1f, 0xf5, 0x37, 0x71, 0x50, 0x7f, 0x71, 0x0b, 0xf5, 0xd7, 0xd1, 0x51, 0x7f, 0x49, 0x15, 0xf5, 0x77, 0x92, 0x50, 0x7f, 0x53, 0x21, 0xea, 0x2f, 0xc6, 0x43, 0xfd, 0x75, 0x39, 0xa8, 0xbf, 0x04, 0x13, 0xf5, 0x77, 0xa6, 0xa3, 0xfe, 0x26, 0x14, 0xd4, 0x5f, 0x9c, 0x84, 0xfa, 0xeb, 0xe0, 0x51, 0x7f, 0x49, 0x2c, 0xea, 0xef, 0x84, 0x42, 0xfd, 0x4d, 0x11, 0xa8, 0xbf, 0x18, 0x2c, 0xea, 0xaf, 0x0b, 0x8d, 0xfa, 0x4b, 0x40, 0xa0, 0xfe, 0xce, 0x60, 0xa8, 0xbf, 0x09, 0x30, 0xea, 0x2f, 0x0e, 0x88, 0xfa, 0xab, 0x02, 0xa0, 0xfe, 0xaa, 0x00, 0xa8, 0xbf, 0x2a, 0x00, 0xea, 0xaf, 0x0a, 0x80, 0xfa, 0xab, 0x02, 0xa0, 0xfe, 0xaa, 0x00, 0x20, 0x04, 0x50, 0x4b, 0x03, 0x04, 0x14, 0x00, 0x02, 0x00, 0x08, 0x00, 0x66, 0x4a, 0x3b, 0x51, 0x9f, 0xf7, 0x53, 0x5a, 0x76, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x38, 0x2e, 0x54, 0x58, 0x54, 0x7b, 0xbf, 0x7b, 0x3f, 0x2f, 0x57, 0x40, 0x51, 0x7e, 0x56, 0x6a, 0x72, 0x89, 0x82, 0x7b, 0x69, 0x49, 0x6a, 0x5e, 0x52, 0x6a, 0x51, 0xba, 0x82, 0xab, 0x53, 0x7e, 0x7e, 0xb6, 0x42, 0x7e, 0x9a, 0x82, 0x47, 0x62, 0x6e, 0x4e, 0x6a, 0x89, 0x8e, 0x42, 0x52, 0xa5, 0x42, 0x78, 0x66, 0x4e, 0x4e, 0x66, 0x62, 0xae, 0x42, 0x70, 0x46, 0x62, 0x76, 0x6a, 0x71, 0x41, 0x6a, 0x62, 0x51, 0x2a, 0x2f, 0x17, 0x2f, 0x57, 0x48, 0x46, 0x66, 0xb1, 0x42, 0x2a, 0x58, 0x3d, 0x90, 0x91, 0x96, 0x5f, 0xa4, 0x50, 0x92, 0x91, 0xaa, 0x50, 0x5a, 0x9c, 0x0a, 0xd2, 0x9e, 0x98, 0x57, 0x99, 0x9f, 0x97, 0x0a, 0xa2, 0xca, 0x33, 0x52, 0x8b, 0x52, 0x15, 0x32, 0xf3, 0xc0, 0xb2, 0xa1, 0x79, 0x99, 0x25, 0xa9, 0x29, 0x0a, 0xc1, 0x25, 0x89, 0x00, 0x50, 0x4b, 0x01, 0x02, 0x0b, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x4a, 0x3b, 0x51, 0x21, 0x65, 0x73, 0x8c, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x2e, 0x54, 0x58, 0x54, 0x50, 0x4b, 0x01, 0x02, 0x0b, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x62, 0x4a, 0x3b, 0x51, 0x02, 0x04, 0x12, 0x39, 0x0c, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x31, 0x2e, 0x54, 0x58, 0x54, 0x50, 0x4b, 0x01, 0x02, 0x0a, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x02, 0x00, 0x63, 0x4a, 0x3b, 0x51, 0x6e, 0x4e, 0x6d, 0x9c, 0x0a, 0x01, 0x00, 0x00, 0x34, 0x08, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x32, 0x2e, 0x54, 0x58, 0x54, 0x50, 0x4b, 0x01, 0x02, 0x0a, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x63, 0x4a, 0x3b, 0x51, 0x6e, 0x4e, 0x6d, 0x9c, 0x0f, 0x01, 0x00, 0x00, 0x34, 0x08, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x82, 0x01, 0x00, 0x00, 0x33, 0x2e, 0x54, 0x58, 0x54, 0x50, 0x4b, 0x01, 0x02, 0x0a, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x04, 0x00, 0x63, 0x4a, 0x3b, 0x51, 0x6e, 0x4e, 0x6d, 0x9c, 0x16, 0x01, 0x00, 0x00, 0x34, 0x08, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0xb4, 0x02, 0x00, 0x00, 0x34, 0x2e, 0x54, 0x58, 0x54, 0x50, 0x4b, 0x01, 0x02, 0x0a, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x05, 0x00, 0x63, 0x4a, 0x3b, 0x51, 0x6e, 0x4e, 0x6d, 0x9c, 0x1a, 0x01, 0x00, 0x00, 0x34, 0x08, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0xed, 0x03, 0x00, 0x00, 0x35, 0x2e, 0x54, 0x58, 0x54, 0x50, 0x4b, 0x01, 0x02, 0x0b, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x4a, 0x3b, 0x51, 0x58, 0x85, 0x96, 0x0d, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x2a, 0x05, 0x00, 0x00, 0x36, 0x31, 0x2e, 0x54, 0x58, 0x54, 0x50, 0x4b, 0x01, 0x02, 0x0b, 0x00, 0x0a, 0x00, 0x06, 0x00, 0x06, 0x00, 0x65, 0x4a, 0x3b, 0x51, 0xf1, 0x0d, 0xc3, 0x06, 0x19, 0x01, 0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x6b, 0x05, 0x00, 0x00, 0x36, 0x32, 0x2e, 0x54, 0x58, 0x54, 0x50, 0x4b, 0x01, 0x02, 0x19, 0x00, 0x14, 0x00, 0x02, 0x00, 0x08, 0x00, 0x66, 0x4a, 0x3b, 0x51, 0x9f, 0xf7, 0x53, 0x5a, 0x76, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0xa8, 0x06, 0x00, 0x00, 0x38, 0x2e, 0x54, 0x58, 0x54, 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x09, 0x00, 0xcd, 0x01, 0x00, 0x00, 0x41, 0x07, 0x00, 0x00, 0x00, 0x00, }; test "zip_many_methods" { // Test reading a zip file with many different compression methods. var z: zip.zip_t = undefined; var it: zip.zipiter_t = undefined; var m: zip.zipmemb_t = undefined; var uncomp: [*]u8 = undefined; var i: usize = 0; var uncomp_mem = try allocator.alloc(u8, 100000); uncomp = uncomp_mem.ptr; try expect(zip.zip_read(&z, multizip[0..], multizip.len)); try expect(z.num_members == 9); it = z.members_begin; m = zip.zip_member(&z, it); try expect(mem.eql(u8, m.name[0..5], "0.TXT")); try expect(m.method == zip.method_t.ZIP_STORE); try expect(try zip.zip_extract_member(&m, uncomp)); try expect(mem.eql(u8, uncomp[0..3], "foo")); it = m.next; m = zip.zip_member(&z, it); try expect(mem.eql(u8, m.name[0..5], "1.TXT")); try expect(m.method == zip.method_t.ZIP_SHRINK); try expect(try zip.zip_extract_member(&m, uncomp)); try expect(mem.eql(u8, uncomp[0..17], "ababcbababaaaaaaa")); it = m.next; m = zip.zip_member(&z, it); try expect(mem.eql(u8, m.name[0..5], "2.TXT")); try expect(m.method == zip.method_t.ZIP_REDUCE1); try expect(try zip.zip_extract_member(&m, uncomp)); i = 0; while (i < 42 * 50) : (i += 1) { try expect(uncomp[i] == hamlet[i % 50]); } it = m.next; m = zip.zip_member(&z, it); try expect(mem.eql(u8, m.name[0..5], "3.TXT")); try expect(m.method == zip.method_t.ZIP_REDUCE2); try expect(try zip.zip_extract_member(&m, uncomp)); i = 0; while (i < 42 * 50) : (i += 1) { try expect(uncomp[i] == hamlet[i % 50]); } it = m.next; m = zip.zip_member(&z, it); try expect(mem.eql(u8, m.name[0..5], "4.TXT")); try expect(m.method == zip.method_t.ZIP_REDUCE3); try expect(try zip.zip_extract_member(&m, uncomp)); i = 0; while (i < 42 * 50) : (i += 1) { try expect(uncomp[i] == hamlet[i % 50]); } it = m.next; m = zip.zip_member(&z, it); try expect(mem.eql(u8, m.name[0..5], "5.TXT")); try expect(m.method == zip.method_t.ZIP_REDUCE4); try expect(try zip.zip_extract_member(&m, uncomp)); i = 0; while (i < 42 * 50) : (i += 1) { try expect(uncomp[i] == hamlet[i % 50]); } it = m.next; m = zip.zip_member(&z, it); try expect(mem.eql(u8, m.name[0..6], "61.TXT")); try expect(m.method == zip.method_t.ZIP_IMPLODE); try expect(m.imp_large_wnd == false); try expect(m.imp_lit_tree == false); try expect(try zip.zip_extract_member(&m, uncomp)); i = 0; while (i < 128) : (i += 1) { try expect(uncomp[i] == 0); } it = m.next; m = zip.zip_member(&z, it); try expect(mem.eql(u8, m.name[0..6], "62.TXT")); try expect(m.method == zip.method_t.ZIP_IMPLODE); try expect(m.imp_large_wnd == true); try expect(m.imp_lit_tree == true); try expect(try zip.zip_extract_member(&m, uncomp)); i = 0; while (i < 200 * 50) : (i += 1) { try expect(uncomp[i] == hamlet[i % 50]); } it = m.next; m = zip.zip_member(&z, it); try expect(mem.eql(u8, m.name[0..5], "8.TXT")); try expect(m.method == zip.method_t.ZIP_DEFLATE); try expect(try zip.zip_extract_member(&m, uncomp)); i = 0; while (i < 128) : (i += 1) { try expect(uncomp[i] == hamlet[i]); } it = m.next; try expect(it == z.members_end); allocator.free(uncomp_mem); } // Created by a hacked up version of hwzip. // It uses all combinations of the large_wnd and lit_tree flags, // in 1.01/1.02 and 1.10 compatible modes. // // In particular, pkzip 1.01/1.02 will not be able to decompress b & c, // and pkzip 1.1, info-zip etc. won't be able to decompress f & g. // // hwzip is aware of the problem and can to handle it. // // -rw-a-- 1.1 fat 19 b- i4:2 20-Sep-29 22:06 a // -rw-a-- 1.1 fat 19 b- i4:3 20-Sep-29 22:06 b // -rw-a-- 1.1 fat 19 b- i8:2 20-Sep-29 22:06 c // -rw-a-- 1.1 fat 19 b- i8:3 20-Sep-29 22:06 d // -rw-a-- 1.0 fat 19 b- i4:2 20-Sep-29 22:06 e // -rw-a-- 1.0 fat 19 b- i4:3 20-Sep-29 22:06 f // -rw-a-- 1.0 fat 19 b- i8:2 20-Sep-29 22:06 g // -rw-a-- 1.0 fat 19 b- i8:3 20-Sep-29 22:06 h // const legacy_implode_zip = [_]u8{ 0x50, 0x4b, 0x03, 0x04, 0x0b, 0x00, 0x00, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x21, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x61, 0x07, 0x16, 0x02, 0x16, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0x06, 0x02, 0x36, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0xc3, 0x86, 0x0d, 0x1b, 0x36, 0xa6, 0x58, 0xb1, 0x62, 0xc5, 0xca, 0x48, 0xfe, 0x33, 0x92, 0x1f, 0x50, 0x4b, 0x03, 0x04, 0x0b, 0x00, 0x04, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x34, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x62, 0x16, 0x38, 0xf7, 0xf7, 0x77, 0x48, 0x25, 0xf8, 0xf8, 0xc8, 0x13, 0xd8, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0x78, 0x37, 0x18, 0x07, 0x07, 0x06, 0x02, 0x26, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0x06, 0x02, 0x36, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0xff, 0xff, 0x7f, 0x7f, 0xef, 0xbd, 0x9b, 0xe4, 0xbf, 0x4a, 0x7e, 0x50, 0x4b, 0x03, 0x04, 0x0b, 0x00, 0x02, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x21, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x63, 0x07, 0x16, 0x02, 0x16, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0x06, 0x02, 0x36, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0xc3, 0x86, 0x0d, 0x1b, 0x36, 0xa6, 0x58, 0xb1, 0x62, 0xc5, 0xca, 0x48, 0xfc, 0x67, 0x24, 0x7e, 0x50, 0x4b, 0x03, 0x04, 0x0b, 0x00, 0x06, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x35, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0x16, 0x38, 0xf7, 0xf7, 0x77, 0x48, 0x25, 0xf8, 0xf8, 0xc8, 0x13, 0xd8, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0x78, 0x37, 0x18, 0x07, 0x07, 0x06, 0x02, 0x26, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0x06, 0x02, 0x36, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0xff, 0xff, 0x7f, 0x7f, 0xef, 0xbd, 0x9b, 0xc4, 0x7f, 0x95, 0xf8, 0x01, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x21, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x65, 0x07, 0x16, 0x02, 0x16, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0x06, 0x02, 0x36, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0xc3, 0x86, 0x0d, 0x1b, 0x36, 0xa6, 0x58, 0xb1, 0x62, 0xc5, 0xca, 0x48, 0xfe, 0x33, 0x92, 0x1f, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x04, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x34, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x66, 0x16, 0x38, 0xf7, 0xf7, 0x77, 0x48, 0x25, 0xf8, 0xf8, 0xc8, 0x13, 0xd8, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0x78, 0x37, 0x18, 0x07, 0x07, 0x16, 0x02, 0x16, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0x06, 0x02, 0x36, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0xff, 0xff, 0x7f, 0x7f, 0xef, 0xbd, 0x9b, 0xe4, 0xbf, 0x4a, 0x7e, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x02, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x21, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x67, 0x07, 0x06, 0x02, 0x26, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0x06, 0x02, 0x36, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0xc3, 0x86, 0x0d, 0x1b, 0x36, 0xa6, 0x58, 0xb1, 0x62, 0xc5, 0xca, 0x48, 0xfc, 0x67, 0x24, 0x7e, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x06, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x35, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x68, 0x16, 0x38, 0xf7, 0xf7, 0x77, 0x48, 0x25, 0xf8, 0xf8, 0xc8, 0x13, 0xd8, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0xf7, 0x78, 0x37, 0x18, 0x07, 0x07, 0x06, 0x02, 0x26, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0x06, 0x02, 0x36, 0xf5, 0xf5, 0xf5, 0x96, 0x05, 0xff, 0xff, 0x7f, 0x7f, 0xef, 0xbd, 0x9b, 0xc4, 0x7f, 0x95, 0xf8, 0x01, 0x50, 0x4b, 0x01, 0x02, 0x0b, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x21, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x50, 0x4b, 0x01, 0x02, 0x0b, 0x00, 0x0b, 0x00, 0x04, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x34, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x62, 0x50, 0x4b, 0x01, 0x02, 0x0b, 0x00, 0x0b, 0x00, 0x02, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x21, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x93, 0x00, 0x00, 0x00, 0x63, 0x50, 0x4b, 0x01, 0x02, 0x0b, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x35, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xd3, 0x00, 0x00, 0x00, 0x64, 0x50, 0x4b, 0x01, 0x02, 0x0a, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x21, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x27, 0x01, 0x00, 0x00, 0x65, 0x50, 0x4b, 0x01, 0x02, 0x0a, 0x00, 0x0a, 0x00, 0x04, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x34, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x67, 0x01, 0x00, 0x00, 0x66, 0x50, 0x4b, 0x01, 0x02, 0x0a, 0x00, 0x0a, 0x00, 0x02, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x21, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xba, 0x01, 0x00, 0x00, 0x67, 0x50, 0x4b, 0x01, 0x02, 0x0a, 0x00, 0x0a, 0x00, 0x06, 0x00, 0x06, 0x00, 0xdb, 0xb0, 0x3d, 0x51, 0x8f, 0xb9, 0xb8, 0xaa, 0x35, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xfa, 0x01, 0x00, 0x00, 0x68, 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x08, 0x00, 0x78, 0x01, 0x00, 0x00, 0x4e, 0x02, 0x00, 0x00, 0x00, 0x00, }; test "zip_legacy_implode" { var z: zip.zip_t = undefined; var it: zip.zipiter_t = undefined; var m: zip.zipmemb_t = undefined; var uncomp: [*]u8 = undefined; var i: usize = 0; var uncomp_mem = try allocator.alloc(u8, 100); uncomp = uncomp_mem.ptr; try expect(zip.zip_read(&z, legacy_implode_zip[0..], legacy_implode_zip.len)); try expect(z.num_members == 8); it = z.members_begin; i = 0; while (i < 8) : (i += 1) { m = zip.zip_member(&z, it); try expect(m.name[0] == "abcdefgh"[i]); try expect(m.method == zip.method_t.ZIP_IMPLODE); try expect(try zip.zip_extract_member(&m, uncomp)); try expect(mem.eql(u8, uncomp[0..19], "aaaa1bbbb2aaaa3bbbb")); it = m.next; } try expect(it == z.members_end); allocator.free(uncomp_mem); } const methods = [_]zip.method_t{ zip.method_t.ZIP_STORE, zip.method_t.ZIP_SHRINK, zip.method_t.ZIP_REDUCE1, zip.method_t.ZIP_REDUCE2, zip.method_t.ZIP_REDUCE3, zip.method_t.ZIP_REDUCE4, zip.method_t.ZIP_IMPLODE, zip.method_t.ZIP_DEFLATE, }; test "zip_write_methods" { const names = ([_][*:0]const u8{"hamlet"})[0..]; const data = [_][*]const u8{hamlet}; const sizes = ([_]u32{hamlet.len})[0..]; var mtimes: [1]time.time_t = undefined; var max_size: usize = 0; var size: usize = 0; var out: [*]u8 = undefined; var z: zip.zip_t = undefined; var m: zip.zipmemb_t = undefined; mtimes[0] = magic_time(); max_size = zip.zip_max_size(1, names, sizes, null); var out_mem = try allocator.alloc(u8, max_size); out = out_mem.ptr; for (methods) |_, mi| { size = try zip.zip_write(out, 1, names, &data, sizes, &mtimes, null, methods[mi], null); try expect(zip.zip_read(&z, out, size)); m = zip.zip_member(&z, z.members_begin); try expect(m.method == methods[mi]); try expect(m.crc32 == 0xb239_ac7c); try check_extract2(&m, hamlet, hamlet.len); if (methods[mi] == zip.method_t.ZIP_DEFLATE) { try expect(m.made_by_ver == 20); } else { try expect(m.made_by_ver == 10); } } allocator.free(out_mem); } test "zip_write_empty_member" { const names = ([_][*:0]const u8{"foo"})[0..]; const data = [_][*]const u8{""}; const sizes = ([_]u32{0})[0..]; var mtimes: [1]time.time_t = undefined; var max_size: usize = 0; var size: usize = 0; var out: [*]u8 = undefined; var z: zip.zip_t = undefined; var m: zip.zipmemb_t = undefined; mtimes[0] = magic_time(); max_size = zip.zip_max_size(1, names, sizes, null); var out_mem = try allocator.alloc(u8, max_size); out = out_mem.ptr; for (methods) |_, mi| { size = try zip.zip_write(out, 1, names, &data, sizes, &mtimes, null, methods[mi], null); try expect(zip.zip_read(&z, out, size)); m = zip.zip_member(&z, z.members_begin); try expect(m.method == zip.method_t.ZIP_STORE); try expect(m.comp_size == 0); try expect(m.uncomp_size == 0); try expect(m.crc32 == 0x0000_0000); try check_extract2(&m, "", 0); } allocator.free(out_mem); }
src/zip_test.zig
const std = @import("std"); const pike = @import("pike"); const sync = @import("sync.zig"); const os = std.os; const net = std.net; const mem = std.mem; const meta = std.meta; const atomic = std.atomic; usingnamespace @import("socket.zig"); pub fn Server(comptime opts: Options) type { return struct { const Self = @This(); const Node = struct { ptr: *Connection, next: ?*Node = null, }; const ServerSocket = Socket(.server, opts); const Protocol = opts.protocol_type; pub const Connection = struct { node: Node, socket: ServerSocket, frame: @Frame(Self.runConnection), }; protocol: Protocol, allocator: *mem.Allocator, notifier: *const pike.Notifier, socket: pike.Socket, lock: sync.Mutex = .{}, done: atomic.Bool = atomic.Bool.init(false), pool: [opts.max_connections_per_server]*Connection = undefined, pool_len: usize = 0, cleanup_counter: sync.Counter = .{}, cleanup_queue: ?*Node = null, frame: @Frame(Self.run) = undefined, pub fn init(protocol: Protocol, allocator: *mem.Allocator, notifier: *const pike.Notifier, address: net.Address) !Self { var self = Self{ .protocol = protocol, .allocator = allocator, .notifier = notifier, .socket = try pike.Socket.init(os.AF_INET, os.SOCK_STREAM, os.IPPROTO_TCP, 0), }; errdefer self.socket.deinit(); try self.socket.set(.reuse_address, true); try self.socket.bind(address); try self.socket.listen(128); return self; } pub fn deinit(self: *Self) void { if (self.done.xchg(true, .SeqCst)) return; self.socket.deinit(); await self.frame catch {}; self.close(); self.cleanup_counter.wait(); self.purge(); } pub fn close(self: *Self) void { var pool: [opts.max_connections_per_server]*Connection = undefined; var pool_len: usize = 0; { const held = self.lock.acquire(); defer held.release(); pool = self.pool; pool_len = self.pool_len; self.pool = undefined; self.pool_len = 0; } for (pool[0..pool_len]) |conn| { conn.socket.deinit(); if (comptime meta.trait.hasFn("close")(meta.Child(Protocol))) { self.protocol.close(.server, &conn.socket); } } } pub fn purge(self: *Self) void { const held = self.lock.acquire(); defer held.release(); while (self.cleanup_queue) |head| { await head.ptr.frame catch {}; self.cleanup_queue = head.next; if (comptime meta.trait.hasFn("purge")(meta.Child(Protocol))) { var items: [opts.write_queue_size]opts.message_type = undefined; const queue = &head.ptr.socket.write_queue; const remaining = queue.tail -% queue.head; var i: usize = 0; while (i < remaining) : (i += 1) { items[i] = queue.items[(queue.head + i) % queue.items.len]; } queue.head = queue.tail; self.protocol.purge(.server, &head.ptr.socket, items[0..remaining]); } self.allocator.destroy(head.ptr); } } fn cleanup(self: *Self, node: *Node) void { const held = self.lock.acquire(); defer held.release(); node.next = self.cleanup_queue; self.cleanup_queue = node; } pub fn serve(self: *Self) !void { try self.socket.registerTo(self.notifier); self.frame = async self.run(); } fn run(self: *Self) !void { yield(); defer if (!self.done.xchg(true, .SeqCst)) { self.socket.deinit(); self.close(); }; while (true) { self.accept() catch |err| switch (err) { error.SocketNotListening, error.OperationCancelled, => return, else => { continue; }, }; self.purge(); } } fn accept(self: *Self) !void { self.cleanup_counter.add(1); errdefer self.cleanup_counter.add(-1); const conn = try self.allocator.create(Connection); errdefer self.allocator.destroy(conn); conn.node = .{ .ptr = conn }; const peer = try self.socket.accept(); conn.socket = ServerSocket.init(peer.socket, peer.address); errdefer conn.socket.deinit(); try conn.socket.unwrap().registerTo(self.notifier); { const held = self.lock.acquire(); defer held.release(); if (self.pool_len + 1 == opts.max_connections_per_server) { return error.MaxConnectionLimitExceeded; } self.pool[self.pool_len] = conn; self.pool_len += 1; } conn.frame = async self.runConnection(conn); } fn deleteConnection(self: *Self, conn: *Connection) bool { const held = self.lock.acquire(); defer held.release(); var pool = self.pool[0..self.pool_len]; if (mem.indexOfScalar(*Connection, pool, conn)) |i| { mem.copy(*Connection, pool[i..], pool[i + 1 ..]); self.pool_len -= 1; return true; } return false; } fn runConnection(self: *Self, conn: *Connection) !void { defer { if (self.deleteConnection(conn)) { conn.socket.deinit(); if (comptime meta.trait.hasFn("close")(meta.Child(Protocol))) { self.protocol.close(.server, &conn.socket); } } self.cleanup(&conn.node); self.cleanup_counter.add(-1); } yield(); if (comptime meta.trait.hasFn("handshake")(meta.Child(Protocol))) { conn.socket.context = try self.protocol.handshake(.server, &conn.socket.inner); } try conn.socket.run(self.protocol); } }; }
server.zig
const std = @import("std.zig"); const debug = std.debug; const assert = debug.assert; const testing = std.testing; const math = std.math; const mem = std.mem; const meta = std.meta; const autoHash = std.hash.autoHash; const Wyhash = std.hash.Wyhash; const Allocator = mem.Allocator; const builtin = @import("builtin"); const want_modification_safety = builtin.mode != builtin.Mode.ReleaseFast; const debug_u32 = if (want_modification_safety) u32 else void; pub fn AutoHashMap(comptime K: type, comptime V: type) type { return HashMap(K, V, getAutoHashFn(K), getAutoEqlFn(K)); } pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u32, comptime eql: fn (a: K, b: K) bool) type { return struct { entries: []Entry, size: usize, max_distance_from_start_index: usize, allocator: *Allocator, // this is used to detect bugs where a hashtable is edited while an iterator is running. modification_count: debug_u32, const Self = @This(); pub const KV = struct { key: K, value: V, }; const Entry = struct { used: bool, distance_from_start_index: usize, kv: KV, }; pub const GetOrPutResult = struct { kv: *KV, found_existing: bool, }; pub const Iterator = struct { hm: *const Self, // how many items have we returned count: usize, // iterator through the entry array index: usize, // used to detect concurrent modification initial_modification_count: debug_u32, pub fn next(it: *Iterator) ?*KV { if (want_modification_safety) { assert(it.initial_modification_count == it.hm.modification_count); // concurrent modification } if (it.count >= it.hm.size) return null; while (it.index < it.hm.entries.len) : (it.index += 1) { const entry = &it.hm.entries[it.index]; if (entry.used) { it.index += 1; it.count += 1; return &entry.kv; } } unreachable; // no next item } // Reset the iterator to the initial index pub fn reset(it: *Iterator) void { it.count = 0; it.index = 0; // Resetting the modification count too it.initial_modification_count = it.hm.modification_count; } }; pub fn init(allocator: *Allocator) Self { return Self{ .entries = [_]Entry{}, .allocator = allocator, .size = 0, .max_distance_from_start_index = 0, .modification_count = if (want_modification_safety) 0 else {}, }; } pub fn deinit(hm: Self) void { hm.allocator.free(hm.entries); } pub fn clear(hm: *Self) void { for (hm.entries) |*entry| { entry.used = false; } hm.size = 0; hm.max_distance_from_start_index = 0; hm.incrementModificationCount(); } pub fn count(self: Self) usize { return self.size; } /// If key exists this function cannot fail. /// If there is an existing item with `key`, then the result /// kv pointer points to it, and found_existing is true. /// Otherwise, puts a new item with undefined value, and /// the kv pointer points to it. Caller should then initialize /// the data. pub fn getOrPut(self: *Self, key: K) !GetOrPutResult { // TODO this implementation can be improved - we should only // have to hash once and find the entry once. if (self.get(key)) |kv| { return GetOrPutResult{ .kv = kv, .found_existing = true, }; } self.incrementModificationCount(); try self.autoCapacity(); const put_result = self.internalPut(key); assert(put_result.old_kv == null); return GetOrPutResult{ .kv = &put_result.new_entry.kv, .found_existing = false, }; } pub fn getOrPutValue(self: *Self, key: K, value: V) !*KV { const res = try self.getOrPut(key); if (!res.found_existing) res.kv.value = value; return res.kv; } fn optimizedCapacity(expected_count: usize) usize { // ensure that the hash map will be at most 60% full if // expected_count items are put into it var optimized_capacity = expected_count * 5 / 3; // an overflow here would mean the amount of memory required would not // be representable in the address space return math.ceilPowerOfTwo(usize, optimized_capacity) catch unreachable; } /// Increases capacity so that the hash map will be at most /// 60% full when expected_count items are put into it pub fn ensureCapacity(self: *Self, expected_count: usize) !void { const optimized_capacity = optimizedCapacity(expected_count); return self.ensureCapacityExact(optimized_capacity); } /// Sets the capacity to the new capacity if the new /// capacity is greater than the current capacity. /// New capacity must be a power of two. fn ensureCapacityExact(self: *Self, new_capacity: usize) !void { // capacity must always be a power of two to allow for modulo // optimization in the constrainIndex fn assert(math.isPowerOfTwo(new_capacity)); if (new_capacity <= self.entries.len) { return; } const old_entries = self.entries; try self.initCapacity(new_capacity); self.incrementModificationCount(); if (old_entries.len > 0) { // dump all of the old elements into the new table for (old_entries) |*old_entry| { if (old_entry.used) { self.internalPut(old_entry.kv.key).new_entry.kv.value = old_entry.kv.value; } } self.allocator.free(old_entries); } } /// Returns the kv pair that was already there. pub fn put(self: *Self, key: K, value: V) !?KV { try self.autoCapacity(); return putAssumeCapacity(self, key, value); } /// Calls put() and asserts that no kv pair is clobbered. pub fn putNoClobber(self: *Self, key: K, value: V) !void { assert((try self.put(key, value)) == null); } pub fn putAssumeCapacity(self: *Self, key: K, value: V) ?KV { assert(self.count() < self.entries.len); self.incrementModificationCount(); const put_result = self.internalPut(key); put_result.new_entry.kv.value = value; return put_result.old_kv; } pub fn get(hm: *const Self, key: K) ?*KV { if (hm.entries.len == 0) { return null; } return hm.internalGet(key); } pub fn getValue(hm: *const Self, key: K) ?V { return if (hm.get(key)) |kv| kv.value else null; } pub fn contains(hm: *const Self, key: K) bool { return hm.get(key) != null; } /// Returns any kv pair that was removed. pub fn remove(hm: *Self, key: K) ?KV { if (hm.entries.len == 0) return null; hm.incrementModificationCount(); const start_index = hm.keyToIndex(key); { var roll_over: usize = 0; while (roll_over <= hm.max_distance_from_start_index) : (roll_over += 1) { const index = hm.constrainIndex(start_index + roll_over); var entry = &hm.entries[index]; if (!entry.used) return null; if (!eql(entry.kv.key, key)) continue; const removed_kv = entry.kv; while (roll_over < hm.entries.len) : (roll_over += 1) { const next_index = hm.constrainIndex(start_index + roll_over + 1); const next_entry = &hm.entries[next_index]; if (!next_entry.used or next_entry.distance_from_start_index == 0) { entry.used = false; hm.size -= 1; return removed_kv; } entry.* = next_entry.*; entry.distance_from_start_index -= 1; entry = next_entry; } unreachable; // shifting everything in the table } } return null; } /// Calls remove(), asserts that a kv pair is removed, and discards it. pub fn removeAssertDiscard(hm: *Self, key: K) void { assert(hm.remove(key) != null); } pub fn iterator(hm: *const Self) Iterator { return Iterator{ .hm = hm, .count = 0, .index = 0, .initial_modification_count = hm.modification_count, }; } pub fn clone(self: Self) !Self { var other = Self.init(self.allocator); try other.initCapacity(self.entries.len); var it = self.iterator(); while (it.next()) |entry| { try other.putNoClobber(entry.key, entry.value); } return other; } fn autoCapacity(self: *Self) !void { if (self.entries.len == 0) { return self.ensureCapacityExact(16); } // if we get too full (60%), double the capacity if (self.size * 5 >= self.entries.len * 3) { return self.ensureCapacityExact(self.entries.len * 2); } } fn initCapacity(hm: *Self, capacity: usize) !void { hm.entries = try hm.allocator.alloc(Entry, capacity); hm.size = 0; hm.max_distance_from_start_index = 0; for (hm.entries) |*entry| { entry.used = false; } } fn incrementModificationCount(hm: *Self) void { if (want_modification_safety) { hm.modification_count +%= 1; } } const InternalPutResult = struct { new_entry: *Entry, old_kv: ?KV, }; /// Returns a pointer to the new entry. /// Asserts that there is enough space for the new item. fn internalPut(self: *Self, orig_key: K) InternalPutResult { var key = orig_key; var value: V = undefined; const start_index = self.keyToIndex(key); var roll_over: usize = 0; var distance_from_start_index: usize = 0; var got_result_entry = false; var result = InternalPutResult{ .new_entry = undefined, .old_kv = null, }; while (roll_over < self.entries.len) : ({ roll_over += 1; distance_from_start_index += 1; }) { const index = self.constrainIndex(start_index + roll_over); const entry = &self.entries[index]; if (entry.used and !eql(entry.kv.key, key)) { if (entry.distance_from_start_index < distance_from_start_index) { // robin hood to the rescue const tmp = entry.*; self.max_distance_from_start_index = math.max(self.max_distance_from_start_index, distance_from_start_index); if (!got_result_entry) { got_result_entry = true; result.new_entry = entry; } entry.* = Entry{ .used = true, .distance_from_start_index = distance_from_start_index, .kv = KV{ .key = key, .value = value, }, }; key = tmp.kv.key; value = tmp.kv.value; distance_from_start_index = tmp.distance_from_start_index; } continue; } if (entry.used) { result.old_kv = entry.kv; } else { // adding an entry. otherwise overwriting old value with // same key self.size += 1; } self.max_distance_from_start_index = math.max(distance_from_start_index, self.max_distance_from_start_index); if (!got_result_entry) { result.new_entry = entry; } entry.* = Entry{ .used = true, .distance_from_start_index = distance_from_start_index, .kv = KV{ .key = key, .value = value, }, }; return result; } unreachable; // put into a full map } fn internalGet(hm: Self, key: K) ?*KV { const start_index = hm.keyToIndex(key); { var roll_over: usize = 0; while (roll_over <= hm.max_distance_from_start_index) : (roll_over += 1) { const index = hm.constrainIndex(start_index + roll_over); const entry = &hm.entries[index]; if (!entry.used) return null; if (eql(entry.kv.key, key)) return &entry.kv; } } return null; } fn keyToIndex(hm: Self, key: K) usize { return hm.constrainIndex(usize(hash(key))); } fn constrainIndex(hm: Self, i: usize) usize { // this is an optimization for modulo of power of two integers; // it requires hm.entries.len to always be a power of two return i & (hm.entries.len - 1); } }; } test "basic hash map usage" { var map = AutoHashMap(i32, i32).init(std.heap.direct_allocator); defer map.deinit(); testing.expect((try map.put(1, 11)) == null); testing.expect((try map.put(2, 22)) == null); testing.expect((try map.put(3, 33)) == null); testing.expect((try map.put(4, 44)) == null); try map.putNoClobber(5, 55); testing.expect((try map.put(5, 66)).?.value == 55); testing.expect((try map.put(5, 55)).?.value == 66); const gop1 = try map.getOrPut(5); testing.expect(gop1.found_existing == true); testing.expect(gop1.kv.value == 55); gop1.kv.value = 77; testing.expect(map.get(5).?.value == 77); const gop2 = try map.getOrPut(99); testing.expect(gop2.found_existing == false); gop2.kv.value = 42; testing.expect(map.get(99).?.value == 42); const gop3 = try map.getOrPutValue(5, 5); testing.expect(gop3.value == 77); const gop4 = try map.getOrPutValue(100, 41); testing.expect(gop4.value == 41); testing.expect(map.contains(2)); testing.expect(map.get(2).?.value == 22); testing.expect(map.getValue(2).? == 22); const rmv1 = map.remove(2); testing.expect(rmv1.?.key == 2); testing.expect(rmv1.?.value == 22); testing.expect(map.remove(2) == null); testing.expect(map.get(2) == null); testing.expect(map.getValue(2) == null); map.removeAssertDiscard(3); } test "iterator hash map" { var reset_map = AutoHashMap(i32, i32).init(std.heap.direct_allocator); defer reset_map.deinit(); try reset_map.putNoClobber(1, 11); try reset_map.putNoClobber(2, 22); try reset_map.putNoClobber(3, 33); // TODO this test depends on the hashing algorithm, because it assumes the // order of the elements in the hashmap. This should not be the case. var keys = [_]i32{ 1, 3, 2, }; var values = [_]i32{ 11, 33, 22, }; var it = reset_map.iterator(); var count: usize = 0; while (it.next()) |next| { testing.expect(next.key == keys[count]); testing.expect(next.value == values[count]); count += 1; } testing.expect(count == 3); testing.expect(it.next() == null); it.reset(); count = 0; while (it.next()) |next| { testing.expect(next.key == keys[count]); testing.expect(next.value == values[count]); count += 1; if (count == 2) break; } it.reset(); var entry = it.next().?; testing.expect(entry.key == keys[0]); testing.expect(entry.value == values[0]); } test "ensure capacity" { var map = AutoHashMap(i32, i32).init(std.heap.direct_allocator); defer map.deinit(); try map.ensureCapacity(20); const initialCapacity = map.entries.len; testing.expect(initialCapacity >= 20); var i: i32 = 0; while (i < 20) : (i += 1) { testing.expect(map.putAssumeCapacity(i, i + 10) == null); } // shouldn't resize from putAssumeCapacity testing.expect(initialCapacity == map.entries.len); } pub fn getHashPtrAddrFn(comptime K: type) (fn (K) u32) { return struct { fn hash(key: K) u32 { return getAutoHashFn(usize)(@ptrToInt(key)); } }.hash; } pub fn getTrivialEqlFn(comptime K: type) (fn (K, K) bool) { return struct { fn eql(a: K, b: K) bool { return a == b; } }.eql; } pub fn getAutoHashFn(comptime K: type) (fn (K) u32) { return struct { fn hash(key: K) u32 { var hasher = Wyhash.init(0); autoHash(&hasher, key); return @truncate(u32, hasher.final()); } }.hash; } pub fn getAutoEqlFn(comptime K: type) (fn (K, K) bool) { return struct { fn eql(a: K, b: K) bool { return meta.eql(a, b); } }.eql; }
std/hash_map.zig
const std = @import("../index.zig"); const mem = std.mem; pub const Token = struct { id: Id, start: usize, end: usize, pub const Keyword = struct { bytes: []const u8, id: Id, }; pub const keywords = []Keyword{ Keyword{ .bytes = "align", .id = Id.Keyword_align }, Keyword{ .bytes = "and", .id = Id.Keyword_and }, Keyword{ .bytes = "asm", .id = Id.Keyword_asm }, Keyword{ .bytes = "async", .id = Id.Keyword_async }, Keyword{ .bytes = "await", .id = Id.Keyword_await }, Keyword{ .bytes = "break", .id = Id.Keyword_break }, Keyword{ .bytes = "catch", .id = Id.Keyword_catch }, Keyword{ .bytes = "cancel", .id = Id.Keyword_cancel }, Keyword{ .bytes = "comptime", .id = Id.Keyword_comptime }, Keyword{ .bytes = "const", .id = Id.Keyword_const }, Keyword{ .bytes = "continue", .id = Id.Keyword_continue }, Keyword{ .bytes = "defer", .id = Id.Keyword_defer }, Keyword{ .bytes = "else", .id = Id.Keyword_else }, Keyword{ .bytes = "enum", .id = Id.Keyword_enum }, Keyword{ .bytes = "errdefer", .id = Id.Keyword_errdefer }, Keyword{ .bytes = "error", .id = Id.Keyword_error }, Keyword{ .bytes = "export", .id = Id.Keyword_export }, Keyword{ .bytes = "extern", .id = Id.Keyword_extern }, Keyword{ .bytes = "false", .id = Id.Keyword_false }, Keyword{ .bytes = "fn", .id = Id.Keyword_fn }, Keyword{ .bytes = "for", .id = Id.Keyword_for }, Keyword{ .bytes = "if", .id = Id.Keyword_if }, Keyword{ .bytes = "inline", .id = Id.Keyword_inline }, Keyword{ .bytes = "nakedcc", .id = Id.Keyword_nakedcc }, Keyword{ .bytes = "noalias", .id = Id.Keyword_noalias }, Keyword{ .bytes = "null", .id = Id.Keyword_null }, Keyword{ .bytes = "or", .id = Id.Keyword_or }, Keyword{ .bytes = "orelse", .id = Id.Keyword_orelse }, Keyword{ .bytes = "packed", .id = Id.Keyword_packed }, Keyword{ .bytes = "promise", .id = Id.Keyword_promise }, Keyword{ .bytes = "pub", .id = Id.Keyword_pub }, Keyword{ .bytes = "resume", .id = Id.Keyword_resume }, Keyword{ .bytes = "return", .id = Id.Keyword_return }, Keyword{ .bytes = "section", .id = Id.Keyword_section }, Keyword{ .bytes = "stdcallcc", .id = Id.Keyword_stdcallcc }, Keyword{ .bytes = "struct", .id = Id.Keyword_struct }, Keyword{ .bytes = "suspend", .id = Id.Keyword_suspend }, Keyword{ .bytes = "switch", .id = Id.Keyword_switch }, Keyword{ .bytes = "test", .id = Id.Keyword_test }, Keyword{ .bytes = "this", .id = Id.Keyword_this }, Keyword{ .bytes = "true", .id = Id.Keyword_true }, Keyword{ .bytes = "try", .id = Id.Keyword_try }, Keyword{ .bytes = "undefined", .id = Id.Keyword_undefined }, Keyword{ .bytes = "union", .id = Id.Keyword_union }, Keyword{ .bytes = "unreachable", .id = Id.Keyword_unreachable }, Keyword{ .bytes = "use", .id = Id.Keyword_use }, Keyword{ .bytes = "var", .id = Id.Keyword_var }, Keyword{ .bytes = "volatile", .id = Id.Keyword_volatile }, Keyword{ .bytes = "while", .id = Id.Keyword_while }, }; // TODO perfect hash at comptime fn getKeyword(bytes: []const u8) ?Id { for (keywords) |kw| { if (mem.eql(u8, kw.bytes, bytes)) { return kw.id; } } return null; } const StrLitKind = enum { Normal, C, }; pub const Id = union(enum) { Invalid, Identifier, StringLiteral: StrLitKind, MultilineStringLiteralLine: StrLitKind, CharLiteral, Eof, Builtin, Bang, Pipe, PipePipe, PipeEqual, Equal, EqualEqual, EqualAngleBracketRight, BangEqual, LParen, RParen, Semicolon, Percent, PercentEqual, LBrace, RBrace, LBracket, RBracket, Period, Ellipsis2, Ellipsis3, Caret, CaretEqual, Plus, PlusPlus, PlusEqual, PlusPercent, PlusPercentEqual, Minus, MinusEqual, MinusPercent, MinusPercentEqual, Asterisk, AsteriskEqual, AsteriskAsterisk, AsteriskPercent, AsteriskPercentEqual, Arrow, Colon, Slash, SlashEqual, Comma, Ampersand, AmpersandEqual, QuestionMark, AngleBracketLeft, AngleBracketLeftEqual, AngleBracketAngleBracketLeft, AngleBracketAngleBracketLeftEqual, AngleBracketRight, AngleBracketRightEqual, AngleBracketAngleBracketRight, AngleBracketAngleBracketRightEqual, Tilde, IntegerLiteral, FloatLiteral, LineComment, DocComment, BracketStarBracket, Keyword_align, Keyword_and, Keyword_asm, Keyword_async, Keyword_await, Keyword_break, Keyword_cancel, Keyword_catch, Keyword_comptime, Keyword_const, Keyword_continue, Keyword_defer, Keyword_else, Keyword_enum, Keyword_errdefer, Keyword_error, Keyword_export, Keyword_extern, Keyword_false, Keyword_fn, Keyword_for, Keyword_if, Keyword_inline, Keyword_nakedcc, Keyword_noalias, Keyword_null, Keyword_or, Keyword_orelse, Keyword_packed, Keyword_promise, Keyword_pub, Keyword_resume, Keyword_return, Keyword_section, Keyword_stdcallcc, Keyword_struct, Keyword_suspend, Keyword_switch, Keyword_test, Keyword_this, Keyword_true, Keyword_try, Keyword_undefined, Keyword_union, Keyword_unreachable, Keyword_use, Keyword_var, Keyword_volatile, Keyword_while, }; }; pub const Tokenizer = struct { buffer: []const u8, index: usize, pending_invalid_token: ?Token, /// For debugging purposes pub fn dump(self: *Tokenizer, token: *const Token) void { std.debug.warn("{} \"{}\"\n", @tagName(token.id), self.buffer[token.start..token.end]); } pub fn init(buffer: []const u8) Tokenizer { return Tokenizer{ .buffer = buffer, .index = 0, .pending_invalid_token = null, }; } const State = enum { Start, Identifier, Builtin, C, StringLiteral, StringLiteralBackslash, MultilineStringLiteralLine, CharLiteral, CharLiteralBackslash, CharLiteralEscape1, CharLiteralEscape2, CharLiteralEnd, Backslash, Equal, Bang, Pipe, Minus, MinusPercent, Asterisk, AsteriskPercent, Slash, LineCommentStart, LineComment, DocCommentStart, DocComment, Zero, IntegerLiteral, IntegerLiteralWithRadix, IntegerLiteralWithRadixHex, NumberDot, NumberDotHex, FloatFraction, FloatFractionHex, FloatExponentUnsigned, FloatExponentUnsignedHex, FloatExponentNumber, FloatExponentNumberHex, Ampersand, Caret, Percent, Plus, PlusPercent, AngleBracketLeft, AngleBracketAngleBracketLeft, AngleBracketRight, AngleBracketAngleBracketRight, Period, Period2, SawAtSign, LBracket, LBracketStar, }; pub fn next(self: *Tokenizer) Token { if (self.pending_invalid_token) |token| { self.pending_invalid_token = null; return token; } const start_index = self.index; var state = State.Start; var result = Token{ .id = Token.Id.Eof, .start = self.index, .end = undefined, }; while (self.index < self.buffer.len) : (self.index += 1) { const c = self.buffer[self.index]; switch (state) { State.Start => switch (c) { ' ' => { result.start = self.index + 1; }, '\n' => { result.start = self.index + 1; }, 'c' => { state = State.C; result.id = Token.Id.Identifier; }, '"' => { state = State.StringLiteral; result.id = Token.Id{ .StringLiteral = Token.StrLitKind.Normal }; }, '\'' => { state = State.CharLiteral; }, 'a'...'b', 'd'...'z', 'A'...'Z', '_' => { state = State.Identifier; result.id = Token.Id.Identifier; }, '@' => { state = State.SawAtSign; }, '=' => { state = State.Equal; }, '!' => { state = State.Bang; }, '|' => { state = State.Pipe; }, '(' => { result.id = Token.Id.LParen; self.index += 1; break; }, ')' => { result.id = Token.Id.RParen; self.index += 1; break; }, '[' => { state = State.LBracket; }, ']' => { result.id = Token.Id.RBracket; self.index += 1; break; }, ';' => { result.id = Token.Id.Semicolon; self.index += 1; break; }, ',' => { result.id = Token.Id.Comma; self.index += 1; break; }, '?' => { result.id = Token.Id.QuestionMark; self.index += 1; break; }, ':' => { result.id = Token.Id.Colon; self.index += 1; break; }, '%' => { state = State.Percent; }, '*' => { state = State.Asterisk; }, '+' => { state = State.Plus; }, '<' => { state = State.AngleBracketLeft; }, '>' => { state = State.AngleBracketRight; }, '^' => { state = State.Caret; }, '\\' => { state = State.Backslash; result.id = Token.Id{ .MultilineStringLiteralLine = Token.StrLitKind.Normal }; }, '{' => { result.id = Token.Id.LBrace; self.index += 1; break; }, '}' => { result.id = Token.Id.RBrace; self.index += 1; break; }, '~' => { result.id = Token.Id.Tilde; self.index += 1; break; }, '.' => { state = State.Period; }, '-' => { state = State.Minus; }, '/' => { state = State.Slash; }, '&' => { state = State.Ampersand; }, '0' => { state = State.Zero; result.id = Token.Id.IntegerLiteral; }, '1'...'9' => { state = State.IntegerLiteral; result.id = Token.Id.IntegerLiteral; }, else => { result.id = Token.Id.Invalid; self.index += 1; break; }, }, State.SawAtSign => switch (c) { '"' => { result.id = Token.Id.Identifier; state = State.StringLiteral; }, else => { // reinterpret as a builtin self.index -= 1; state = State.Builtin; result.id = Token.Id.Builtin; }, }, State.LBracket => switch (c) { '*' => { state = State.LBracketStar; }, else => { result.id = Token.Id.LBracket; break; }, }, State.LBracketStar => switch (c) { ']' => { result.id = Token.Id.BracketStarBracket; self.index += 1; break; }, else => { result.id = Token.Id.Invalid; break; }, }, State.Ampersand => switch (c) { '=' => { result.id = Token.Id.AmpersandEqual; self.index += 1; break; }, else => { result.id = Token.Id.Ampersand; break; }, }, State.Asterisk => switch (c) { '=' => { result.id = Token.Id.AsteriskEqual; self.index += 1; break; }, '*' => { result.id = Token.Id.AsteriskAsterisk; self.index += 1; break; }, '%' => { state = State.AsteriskPercent; }, else => { result.id = Token.Id.Asterisk; break; }, }, State.AsteriskPercent => switch (c) { '=' => { result.id = Token.Id.AsteriskPercentEqual; self.index += 1; break; }, else => { result.id = Token.Id.AsteriskPercent; break; }, }, State.Percent => switch (c) { '=' => { result.id = Token.Id.PercentEqual; self.index += 1; break; }, else => { result.id = Token.Id.Percent; break; }, }, State.Plus => switch (c) { '=' => { result.id = Token.Id.PlusEqual; self.index += 1; break; }, '+' => { result.id = Token.Id.PlusPlus; self.index += 1; break; }, '%' => { state = State.PlusPercent; }, else => { result.id = Token.Id.Plus; break; }, }, State.PlusPercent => switch (c) { '=' => { result.id = Token.Id.PlusPercentEqual; self.index += 1; break; }, else => { result.id = Token.Id.PlusPercent; break; }, }, State.Caret => switch (c) { '=' => { result.id = Token.Id.CaretEqual; self.index += 1; break; }, else => { result.id = Token.Id.Caret; break; }, }, State.Identifier => switch (c) { 'a'...'z', 'A'...'Z', '_', '0'...'9' => {}, else => { if (Token.getKeyword(self.buffer[result.start..self.index])) |id| { result.id = id; } break; }, }, State.Builtin => switch (c) { 'a'...'z', 'A'...'Z', '_', '0'...'9' => {}, else => break, }, State.Backslash => switch (c) { '\\' => { state = State.MultilineStringLiteralLine; }, else => break, }, State.C => switch (c) { '\\' => { state = State.Backslash; result.id = Token.Id{ .MultilineStringLiteralLine = Token.StrLitKind.C }; }, '"' => { state = State.StringLiteral; result.id = Token.Id{ .StringLiteral = Token.StrLitKind.C }; }, 'a'...'z', 'A'...'Z', '_', '0'...'9' => { state = State.Identifier; }, else => break, }, State.StringLiteral => switch (c) { '\\' => { state = State.StringLiteralBackslash; }, '"' => { self.index += 1; break; }, '\n' => break, // Look for this error later. else => self.checkLiteralCharacter(), }, State.StringLiteralBackslash => switch (c) { '\n' => break, // Look for this error later. else => { state = State.StringLiteral; }, }, State.CharLiteral => switch (c) { '\\' => { state = State.CharLiteralBackslash; }, '\'' => { result.id = Token.Id.Invalid; break; }, else => { if (c < 0x20 or c == 0x7f) { result.id = Token.Id.Invalid; break; } state = State.CharLiteralEnd; }, }, State.CharLiteralBackslash => switch (c) { '\n' => { result.id = Token.Id.Invalid; break; }, 'x' => { state = State.CharLiteralEscape1; }, else => { state = State.CharLiteralEnd; }, }, State.CharLiteralEscape1 => switch (c) { '0'...'9', 'a'...'z', 'A'...'F' => { state = State.CharLiteralEscape2; }, else => { result.id = Token.Id.Invalid; break; }, }, State.CharLiteralEscape2 => switch (c) { '0'...'9', 'a'...'z', 'A'...'F' => { state = State.CharLiteralEnd; }, else => { result.id = Token.Id.Invalid; break; }, }, State.CharLiteralEnd => switch (c) { '\'' => { result.id = Token.Id.CharLiteral; self.index += 1; break; }, else => { result.id = Token.Id.Invalid; break; }, }, State.MultilineStringLiteralLine => switch (c) { '\n' => { self.index += 1; break; }, else => self.checkLiteralCharacter(), }, State.Bang => switch (c) { '=' => { result.id = Token.Id.BangEqual; self.index += 1; break; }, else => { result.id = Token.Id.Bang; break; }, }, State.Pipe => switch (c) { '=' => { result.id = Token.Id.PipeEqual; self.index += 1; break; }, '|' => { result.id = Token.Id.PipePipe; self.index += 1; break; }, else => { result.id = Token.Id.Pipe; break; }, }, State.Equal => switch (c) { '=' => { result.id = Token.Id.EqualEqual; self.index += 1; break; }, '>' => { result.id = Token.Id.EqualAngleBracketRight; self.index += 1; break; }, else => { result.id = Token.Id.Equal; break; }, }, State.Minus => switch (c) { '>' => { result.id = Token.Id.Arrow; self.index += 1; break; }, '=' => { result.id = Token.Id.MinusEqual; self.index += 1; break; }, '%' => { state = State.MinusPercent; }, else => { result.id = Token.Id.Minus; break; }, }, State.MinusPercent => switch (c) { '=' => { result.id = Token.Id.MinusPercentEqual; self.index += 1; break; }, else => { result.id = Token.Id.MinusPercent; break; }, }, State.AngleBracketLeft => switch (c) { '<' => { state = State.AngleBracketAngleBracketLeft; }, '=' => { result.id = Token.Id.AngleBracketLeftEqual; self.index += 1; break; }, else => { result.id = Token.Id.AngleBracketLeft; break; }, }, State.AngleBracketAngleBracketLeft => switch (c) { '=' => { result.id = Token.Id.AngleBracketAngleBracketLeftEqual; self.index += 1; break; }, else => { result.id = Token.Id.AngleBracketAngleBracketLeft; break; }, }, State.AngleBracketRight => switch (c) { '>' => { state = State.AngleBracketAngleBracketRight; }, '=' => { result.id = Token.Id.AngleBracketRightEqual; self.index += 1; break; }, else => { result.id = Token.Id.AngleBracketRight; break; }, }, State.AngleBracketAngleBracketRight => switch (c) { '=' => { result.id = Token.Id.AngleBracketAngleBracketRightEqual; self.index += 1; break; }, else => { result.id = Token.Id.AngleBracketAngleBracketRight; break; }, }, State.Period => switch (c) { '.' => { state = State.Period2; }, else => { result.id = Token.Id.Period; break; }, }, State.Period2 => switch (c) { '.' => { result.id = Token.Id.Ellipsis3; self.index += 1; break; }, else => { result.id = Token.Id.Ellipsis2; break; }, }, State.Slash => switch (c) { '/' => { state = State.LineCommentStart; result.id = Token.Id.LineComment; }, '=' => { result.id = Token.Id.SlashEqual; self.index += 1; break; }, else => { result.id = Token.Id.Slash; break; }, }, State.LineCommentStart => switch (c) { '/' => { state = State.DocCommentStart; }, '\n' => break, else => { state = State.LineComment; self.checkLiteralCharacter(); }, }, State.DocCommentStart => switch (c) { '/' => { state = State.LineComment; }, '\n' => { result.id = Token.Id.DocComment; break; }, else => { state = State.DocComment; result.id = Token.Id.DocComment; self.checkLiteralCharacter(); }, }, State.LineComment, State.DocComment => switch (c) { '\n' => break, else => self.checkLiteralCharacter(), }, State.Zero => switch (c) { 'b', 'o' => { state = State.IntegerLiteralWithRadix; }, 'x' => { state = State.IntegerLiteralWithRadixHex; }, else => { // reinterpret as a normal number self.index -= 1; state = State.IntegerLiteral; }, }, State.IntegerLiteral => switch (c) { '.' => { state = State.NumberDot; }, 'p', 'P', 'e', 'E' => { state = State.FloatExponentUnsigned; }, '0'...'9' => {}, else => break, }, State.IntegerLiteralWithRadix => switch (c) { '.' => { state = State.NumberDot; }, '0'...'9' => {}, else => break, }, State.IntegerLiteralWithRadixHex => switch (c) { '.' => { state = State.NumberDotHex; }, 'p', 'P' => { state = State.FloatExponentUnsignedHex; }, '0'...'9', 'a'...'f', 'A'...'F' => {}, else => break, }, State.NumberDot => switch (c) { '.' => { self.index -= 1; state = State.Start; break; }, else => { self.index -= 1; result.id = Token.Id.FloatLiteral; state = State.FloatFraction; }, }, State.NumberDotHex => switch (c) { '.' => { self.index -= 1; state = State.Start; break; }, else => { self.index -= 1; result.id = Token.Id.FloatLiteral; state = State.FloatFractionHex; }, }, State.FloatFraction => switch (c) { 'e', 'E' => { state = State.FloatExponentUnsigned; }, '0'...'9' => {}, else => break, }, State.FloatFractionHex => switch (c) { 'p', 'P' => { state = State.FloatExponentUnsignedHex; }, '0'...'9', 'a'...'f', 'A'...'F' => {}, else => break, }, State.FloatExponentUnsigned => switch (c) { '+', '-' => { state = State.FloatExponentNumber; }, else => { // reinterpret as a normal exponent number self.index -= 1; state = State.FloatExponentNumber; }, }, State.FloatExponentUnsignedHex => switch (c) { '+', '-' => { state = State.FloatExponentNumberHex; }, else => { // reinterpret as a normal exponent number self.index -= 1; state = State.FloatExponentNumberHex; }, }, State.FloatExponentNumber => switch (c) { '0'...'9' => {}, else => break, }, State.FloatExponentNumberHex => switch (c) { '0'...'9', 'a'...'f', 'A'...'F' => {}, else => break, }, } } else if (self.index == self.buffer.len) { switch (state) { State.Start, State.C, State.IntegerLiteral, State.IntegerLiteralWithRadix, State.IntegerLiteralWithRadixHex, State.FloatFraction, State.FloatFractionHex, State.FloatExponentNumber, State.FloatExponentNumberHex, State.StringLiteral, // find this error later State.MultilineStringLiteralLine, State.Builtin, => {}, State.Identifier => { if (Token.getKeyword(self.buffer[result.start..self.index])) |id| { result.id = id; } }, State.LineCommentStart, State.LineComment => { result.id = Token.Id.LineComment; }, State.DocComment, State.DocCommentStart => { result.id = Token.Id.DocComment; }, State.NumberDot, State.NumberDotHex, State.FloatExponentUnsigned, State.FloatExponentUnsignedHex, State.SawAtSign, State.Backslash, State.CharLiteral, State.CharLiteralBackslash, State.CharLiteralEscape1, State.CharLiteralEscape2, State.CharLiteralEnd, State.StringLiteralBackslash, State.LBracketStar, => { result.id = Token.Id.Invalid; }, State.Equal => { result.id = Token.Id.Equal; }, State.Bang => { result.id = Token.Id.Bang; }, State.Minus => { result.id = Token.Id.Minus; }, State.Slash => { result.id = Token.Id.Slash; }, State.LBracket => { result.id = Token.Id.LBracket; }, State.Zero => { result.id = Token.Id.IntegerLiteral; }, State.Ampersand => { result.id = Token.Id.Ampersand; }, State.Period => { result.id = Token.Id.Period; }, State.Period2 => { result.id = Token.Id.Ellipsis2; }, State.Pipe => { result.id = Token.Id.Pipe; }, State.AngleBracketAngleBracketRight => { result.id = Token.Id.AngleBracketAngleBracketRight; }, State.AngleBracketRight => { result.id = Token.Id.AngleBracketRight; }, State.AngleBracketAngleBracketLeft => { result.id = Token.Id.AngleBracketAngleBracketLeft; }, State.AngleBracketLeft => { result.id = Token.Id.AngleBracketLeft; }, State.PlusPercent => { result.id = Token.Id.PlusPercent; }, State.Plus => { result.id = Token.Id.Plus; }, State.Percent => { result.id = Token.Id.Percent; }, State.Caret => { result.id = Token.Id.Caret; }, State.AsteriskPercent => { result.id = Token.Id.AsteriskPercent; }, State.Asterisk => { result.id = Token.Id.Asterisk; }, State.MinusPercent => { result.id = Token.Id.MinusPercent; }, } } if (result.id == Token.Id.Eof) { if (self.pending_invalid_token) |token| { self.pending_invalid_token = null; return token; } } result.end = self.index; return result; } fn checkLiteralCharacter(self: *Tokenizer) void { if (self.pending_invalid_token != null) return; const invalid_length = self.getInvalidCharacterLength(); if (invalid_length == 0) return; self.pending_invalid_token = Token{ .id = Token.Id.Invalid, .start = self.index, .end = self.index + invalid_length, }; } fn getInvalidCharacterLength(self: *Tokenizer) u3 { const c0 = self.buffer[self.index]; if (c0 < 0x80) { if (c0 < 0x20 or c0 == 0x7f) { // ascii control codes are never allowed // (note that \n was checked before we got here) return 1; } // looks fine to me. return 0; } else { // check utf8-encoded character. const length = std.unicode.utf8ByteSequenceLength(c0) catch return 1; if (self.index + length > self.buffer.len) { return @intCast(u3, self.buffer.len - self.index); } const bytes = self.buffer[self.index .. self.index + length]; switch (length) { 2 => { const value = std.unicode.utf8Decode2(bytes) catch return length; if (value == 0x85) return length; // U+0085 (NEL) }, 3 => { const value = std.unicode.utf8Decode3(bytes) catch return length; if (value == 0x2028) return length; // U+2028 (LS) if (value == 0x2029) return length; // U+2029 (PS) }, 4 => { _ = std.unicode.utf8Decode4(bytes) catch return length; }, else => unreachable, } self.index += length - 1; return 0; } } }; test "tokenizer" { testTokenize("test", []Token.Id{Token.Id.Keyword_test}); } test "tokenizer - unknown length pointer" { testTokenize( \\[*]u8 , []Token.Id{ Token.Id.BracketStarBracket, Token.Id.Identifier, }); } test "tokenizer - char literal with hex escape" { testTokenize( \\'\x1b' , []Token.Id{Token.Id.CharLiteral}); } test "tokenizer - float literal e exponent" { testTokenize("a = 4.94065645841246544177e-324;\n", []Token.Id{ Token.Id.Identifier, Token.Id.Equal, Token.Id.FloatLiteral, Token.Id.Semicolon, }); } test "tokenizer - float literal p exponent" { testTokenize("a = 0x1.a827999fcef32p+1022;\n", []Token.Id{ Token.Id.Identifier, Token.Id.Equal, Token.Id.FloatLiteral, Token.Id.Semicolon, }); } test "tokenizer - chars" { testTokenize("'c'", []Token.Id{Token.Id.CharLiteral}); } test "tokenizer - invalid token characters" { testTokenize("#", []Token.Id{Token.Id.Invalid}); testTokenize("`", []Token.Id{Token.Id.Invalid}); testTokenize("'c", []Token.Id{Token.Id.Invalid}); testTokenize("'", []Token.Id{Token.Id.Invalid}); testTokenize("''", []Token.Id{ Token.Id.Invalid, Token.Id.Invalid }); } test "tokenizer - invalid literal/comment characters" { testTokenize("\"\x00\"", []Token.Id{ Token.Id{ .StringLiteral = Token.StrLitKind.Normal }, Token.Id.Invalid, }); testTokenize("//\x00", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); testTokenize("//\x1f", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); testTokenize("//\x7f", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); } test "tokenizer - utf8" { testTokenize("//\xc2\x80", []Token.Id{Token.Id.LineComment}); testTokenize("//\xf4\x8f\xbf\xbf", []Token.Id{Token.Id.LineComment}); } test "tokenizer - invalid utf8" { testTokenize("//\x80", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); testTokenize("//\xbf", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); testTokenize("//\xf8", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); testTokenize("//\xff", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); testTokenize("//\xc2\xc0", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); testTokenize("//\xe0", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); testTokenize("//\xf0", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); testTokenize("//\xf0\x90\x80\xc0", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); } test "tokenizer - illegal unicode codepoints" { // unicode newline characters.U+0085, U+2028, U+2029 testTokenize("//\xc2\x84", []Token.Id{Token.Id.LineComment}); testTokenize("//\xc2\x85", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); testTokenize("//\xc2\x86", []Token.Id{Token.Id.LineComment}); testTokenize("//\xe2\x80\xa7", []Token.Id{Token.Id.LineComment}); testTokenize("//\xe2\x80\xa8", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); testTokenize("//\xe2\x80\xa9", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); testTokenize("//\xe2\x80\xaa", []Token.Id{Token.Id.LineComment}); } test "tokenizer - string identifier and builtin fns" { testTokenize( \\const @"if" = @import("std"); , []Token.Id{ Token.Id.Keyword_const, Token.Id.Identifier, Token.Id.Equal, Token.Id.Builtin, Token.Id.LParen, Token.Id{ .StringLiteral = Token.StrLitKind.Normal }, Token.Id.RParen, Token.Id.Semicolon, }); } test "tokenizer - pipe and then invalid" { testTokenize("||=", []Token.Id{ Token.Id.PipePipe, Token.Id.Equal, }); } test "tokenizer - line comment and doc comment" { testTokenize("//", []Token.Id{Token.Id.LineComment}); testTokenize("// a / b", []Token.Id{Token.Id.LineComment}); testTokenize("// /", []Token.Id{Token.Id.LineComment}); testTokenize("/// a", []Token.Id{Token.Id.DocComment}); testTokenize("///", []Token.Id{Token.Id.DocComment}); testTokenize("////", []Token.Id{Token.Id.LineComment}); } test "tokenizer - line comment followed by identifier" { testTokenize( \\ Unexpected, \\ // another \\ Another, , []Token.Id{ Token.Id.Identifier, Token.Id.Comma, Token.Id.LineComment, Token.Id.Identifier, Token.Id.Comma, }); } fn testTokenize(source: []const u8, expected_tokens: []const Token.Id) void { var tokenizer = Tokenizer.init(source); for (expected_tokens) |expected_token_id| { const token = tokenizer.next(); if (@TagType(Token.Id)(token.id) != @TagType(Token.Id)(expected_token_id)) { std.debug.panic("expected {}, found {}\n", @tagName(@TagType(Token.Id)(expected_token_id)), @tagName(@TagType(Token.Id)(token.id))); } switch (expected_token_id) { Token.Id.StringLiteral => |expected_kind| { std.debug.assert(expected_kind == switch (token.id) { Token.Id.StringLiteral => |kind| kind, else => unreachable, }); }, else => {}, } } const last_token = tokenizer.next(); std.debug.assert(last_token.id == Token.Id.Eof); }
std/zig/tokenizer.zig
const std = @import("std"); const TestContext = @import("../../src-self-hosted/test.zig").TestContext; // self-hosted does not yet support PE executable files / COFF object files // or mach-o files. So we do these test cases cross compiling for x86_64-linux. const linux_x64 = std.zig.CrossTarget{ .cpu_arch = .x86_64, .os_tag = .linux, }; pub fn addCases(ctx: *TestContext) !void { if (std.Target.current.os.tag != .linux or std.Target.current.cpu.arch != .x86_64) { // TODO implement self-hosted PE (.exe file) linking // TODO implement more ZIR so we don't depend on x86_64-linux return; } { var case = ctx.exe("hello world with updates", linux_x64); // Regular old hello world case.addCompareOutput( \\export fn _start() noreturn { \\ print(); \\ \\ exit(); \\} \\ \\fn print() void { \\ asm volatile ("syscall" \\ : \\ : [number] "{rax}" (1), \\ [arg1] "{rdi}" (1), \\ [arg2] "{rsi}" (@ptrToInt("Hello, World!\n")), \\ [arg3] "{rdx}" (14) \\ : "rcx", "r11", "memory" \\ ); \\ return; \\} \\ \\fn exit() noreturn { \\ asm volatile ("syscall" \\ : \\ : [number] "{rax}" (231), \\ [arg1] "{rdi}" (0) \\ : "rcx", "r11", "memory" \\ ); \\ unreachable; \\} , "Hello, World!\n", ); // Now change the message only case.addCompareOutput( \\export fn _start() noreturn { \\ print(); \\ \\ exit(); \\} \\ \\fn print() void { \\ asm volatile ("syscall" \\ : \\ : [number] "{rax}" (1), \\ [arg1] "{rdi}" (1), \\ [arg2] "{rsi}" (@ptrToInt("What is up? This is a longer message that will force the data to be relocated in virtual address space.\n")), \\ [arg3] "{rdx}" (104) \\ : "rcx", "r11", "memory" \\ ); \\ return; \\} \\ \\fn exit() noreturn { \\ asm volatile ("syscall" \\ : \\ : [number] "{rax}" (231), \\ [arg1] "{rdi}" (0) \\ : "rcx", "r11", "memory" \\ ); \\ unreachable; \\} , "What is up? This is a longer message that will force the data to be relocated in virtual address space.\n", ); // Now we print it twice. case.addCompareOutput( \\export fn _start() noreturn { \\ print(); \\ print(); \\ \\ exit(); \\} \\ \\fn print() void { \\ asm volatile ("syscall" \\ : \\ : [number] "{rax}" (1), \\ [arg1] "{rdi}" (1), \\ [arg2] "{rsi}" (@ptrToInt("What is up? This is a longer message that will force the data to be relocated in virtual address space.\n")), \\ [arg3] "{rdx}" (104) \\ : "rcx", "r11", "memory" \\ ); \\ return; \\} \\ \\fn exit() noreturn { \\ asm volatile ("syscall" \\ : \\ : [number] "{rax}" (231), \\ [arg1] "{rdi}" (0) \\ : "rcx", "r11", "memory" \\ ); \\ unreachable; \\} , \\What is up? This is a longer message that will force the data to be relocated in virtual address space. \\What is up? This is a longer message that will force the data to be relocated in virtual address space. \\ ); } }
test/stage2/compare_output.zig
const builtin = @import("builtin"); const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the hyperbolic tangent of z. pub fn tanh(z: anytype) @TypeOf(z) { const T = @TypeOf(z.re); return switch (T) { f32 => tanh32(z), f64 => tanh64(z), else => @compileError("tan not implemented for " ++ @typeName(z)), }; } fn tanh32(z: Complex(f32)) Complex(f32) { const x = z.re; const y = z.im; const hx = @bitCast(u32, x); const ix = hx & 0x7fffffff; if (ix >= 0x7f800000) { if (ix & 0x7fffff != 0) { const r = if (y == 0) y else x * y; return Complex(f32).new(x, r); } const xx = @bitCast(f32, hx - 0x40000000); const r = if (math.isInf(y)) y else math.sin(y) * math.cos(y); return Complex(f32).new(xx, math.copysign(f32, 0, r)); } if (!math.isFinite(y)) { const r = if (ix != 0) y - y else x; return Complex(f32).new(r, y - y); } // x >= 11 if (ix >= 0x41300000) { const exp_mx = math.exp(-math.fabs(x)); return Complex(f32).new(math.copysign(f32, 1, x), 4 * math.sin(y) * math.cos(y) * exp_mx * exp_mx); } // Kahan's algorithm const t = math.tan(y); const beta = 1.0 + t * t; const s = math.sinh(x); const rho = math.sqrt(1 + s * s); const den = 1 + beta * s * s; return Complex(f32).new((beta * rho * s) / den, t / den); } fn tanh64(z: Complex(f64)) Complex(f64) { const x = z.re; const y = z.im; const fx = @bitCast(u64, x); // TODO: zig should allow this conversion implicitly because it can notice that the value necessarily // fits in range. const hx = @intCast(u32, fx >> 32); const lx = @truncate(u32, fx); const ix = hx & 0x7fffffff; if (ix >= 0x7ff00000) { if ((ix & 0x7fffff) | lx != 0) { const r = if (y == 0) y else x * y; return Complex(f64).new(x, r); } const xx = @bitCast(f64, (@as(u64, hx - 0x40000000) << 32) | lx); const r = if (math.isInf(y)) y else math.sin(y) * math.cos(y); return Complex(f64).new(xx, math.copysign(f64, 0, r)); } if (!math.isFinite(y)) { const r = if (ix != 0) y - y else x; return Complex(f64).new(r, y - y); } // x >= 22 if (ix >= 0x40360000) { const exp_mx = math.exp(-math.fabs(x)); return Complex(f64).new(math.copysign(f64, 1, x), 4 * math.sin(y) * math.cos(y) * exp_mx * exp_mx); } // Kahan's algorithm const t = math.tan(y); const beta = 1.0 + t * t; const s = math.sinh(x); const rho = math.sqrt(1 + s * s); const den = 1 + beta * s * s; return Complex(f64).new((beta * rho * s) / den, t / den); } const epsilon = 0.0001; test "complex.ctanh32" { const a = Complex(f32).new(5, 3); const c = tanh(a); testing.expect(math.approxEqAbs(f32, c.re, 0.999913, epsilon)); testing.expect(math.approxEqAbs(f32, c.im, -0.000025, epsilon)); } test "complex.ctanh64" { const a = Complex(f64).new(5, 3); const c = tanh(a); testing.expect(math.approxEqAbs(f64, c.re, 0.999913, epsilon)); testing.expect(math.approxEqAbs(f64, c.im, -0.000025, epsilon)); }
lib/std/math/complex/tanh.zig
const std = @import("std"); const builtin = std.builtin; const Scope = @import("scope.zig").Scope; const Compilation = @import("compilation.zig").Compilation; const Value = @import("value.zig").Value; const llvm = @import("llvm.zig"); const event = std.event; const Allocator = std.mem.Allocator; const assert = std.debug.assert; pub const Type = struct { base: Value, id: Id, name: []const u8, abi_alignment: AbiAlignment, pub const AbiAlignment = event.Future(error{OutOfMemory}!u32); pub const Id = builtin.TypeId; pub fn destroy(base: *Type, comp: *Compilation) void { switch (base.id) { .Struct => @fieldParentPtr(Struct, "base", base).destroy(comp), .Fn => @fieldParentPtr(Fn, "base", base).destroy(comp), .Type => @fieldParentPtr(MetaType, "base", base).destroy(comp), .Void => @fieldParentPtr(Void, "base", base).destroy(comp), .Bool => @fieldParentPtr(Bool, "base", base).destroy(comp), .NoReturn => @fieldParentPtr(NoReturn, "base", base).destroy(comp), .Int => @fieldParentPtr(Int, "base", base).destroy(comp), .Float => @fieldParentPtr(Float, "base", base).destroy(comp), .Pointer => @fieldParentPtr(Pointer, "base", base).destroy(comp), .Array => @fieldParentPtr(Array, "base", base).destroy(comp), .ComptimeFloat => @fieldParentPtr(ComptimeFloat, "base", base).destroy(comp), .ComptimeInt => @fieldParentPtr(ComptimeInt, "base", base).destroy(comp), .EnumLiteral => @fieldParentPtr(EnumLiteral, "base", base).destroy(comp), .Undefined => @fieldParentPtr(Undefined, "base", base).destroy(comp), .Null => @fieldParentPtr(Null, "base", base).destroy(comp), .Optional => @fieldParentPtr(Optional, "base", base).destroy(comp), .ErrorUnion => @fieldParentPtr(ErrorUnion, "base", base).destroy(comp), .ErrorSet => @fieldParentPtr(ErrorSet, "base", base).destroy(comp), .Enum => @fieldParentPtr(Enum, "base", base).destroy(comp), .Union => @fieldParentPtr(Union, "base", base).destroy(comp), .BoundFn => @fieldParentPtr(BoundFn, "base", base).destroy(comp), .ArgTuple => @fieldParentPtr(ArgTuple, "base", base).destroy(comp), .Opaque => @fieldParentPtr(Opaque, "base", base).destroy(comp), .Frame => @fieldParentPtr(Frame, "base", base).destroy(comp), .AnyFrame => @fieldParentPtr(AnyFrame, "base", base).destroy(comp), .Vector => @fieldParentPtr(Vector, "base", base).destroy(comp), } } pub fn getLlvmType( base: *Type, allocator: *Allocator, llvm_context: *llvm.Context, ) error{OutOfMemory}!*llvm.Type { switch (base.id) { .Struct => return @fieldParentPtr(Struct, "base", base).getLlvmType(allocator, llvm_context), .Fn => return @fieldParentPtr(Fn, "base", base).getLlvmType(allocator, llvm_context), .Type => unreachable, .Void => unreachable, .Bool => return @fieldParentPtr(Bool, "base", base).getLlvmType(allocator, llvm_context), .NoReturn => unreachable, .Int => return @fieldParentPtr(Int, "base", base).getLlvmType(allocator, llvm_context), .Float => return @fieldParentPtr(Float, "base", base).getLlvmType(allocator, llvm_context), .Pointer => return @fieldParentPtr(Pointer, "base", base).getLlvmType(allocator, llvm_context), .Array => return @fieldParentPtr(Array, "base", base).getLlvmType(allocator, llvm_context), .ComptimeFloat => unreachable, .ComptimeInt => unreachable, .EnumLiteral => unreachable, .Undefined => unreachable, .Null => unreachable, .Optional => return @fieldParentPtr(Optional, "base", base).getLlvmType(allocator, llvm_context), .ErrorUnion => return @fieldParentPtr(ErrorUnion, "base", base).getLlvmType(allocator, llvm_context), .ErrorSet => return @fieldParentPtr(ErrorSet, "base", base).getLlvmType(allocator, llvm_context), .Enum => return @fieldParentPtr(Enum, "base", base).getLlvmType(allocator, llvm_context), .Union => return @fieldParentPtr(Union, "base", base).getLlvmType(allocator, llvm_context), .BoundFn => return @fieldParentPtr(BoundFn, "base", base).getLlvmType(allocator, llvm_context), .ArgTuple => unreachable, .Opaque => return @fieldParentPtr(Opaque, "base", base).getLlvmType(allocator, llvm_context), .Frame => return @fieldParentPtr(Frame, "base", base).getLlvmType(allocator, llvm_context), .AnyFrame => return @fieldParentPtr(AnyFrame, "base", base).getLlvmType(allocator, llvm_context), .Vector => return @fieldParentPtr(Vector, "base", base).getLlvmType(allocator, llvm_context), } } pub fn handleIsPtr(base: *Type) bool { switch (base.id) { .Type, .ComptimeFloat, .ComptimeInt, .EnumLiteral, .Undefined, .Null, .BoundFn, .ArgTuple, .Opaque, => unreachable, .NoReturn, .Void, .Bool, .Int, .Float, .Pointer, .ErrorSet, .Enum, .Fn, .Frame, .AnyFrame, .Vector, => return false, .Struct => @panic("TODO"), .Array => @panic("TODO"), .Optional => @panic("TODO"), .ErrorUnion => @panic("TODO"), .Union => @panic("TODO"), } } pub fn hasBits(base: *Type) bool { switch (base.id) { .Type, .ComptimeFloat, .ComptimeInt, .EnumLiteral, .Undefined, .Null, .BoundFn, .ArgTuple, .Opaque, => unreachable, .Void, .NoReturn, => return false, .Bool, .Int, .Float, .Fn, .Frame, .AnyFrame, .Vector, => return true, .Pointer => { const ptr_type = @fieldParentPtr(Pointer, "base", base); return ptr_type.key.child_type.hasBits(); }, .ErrorSet => @panic("TODO"), .Enum => @panic("TODO"), .Struct => @panic("TODO"), .Array => @panic("TODO"), .Optional => @panic("TODO"), .ErrorUnion => @panic("TODO"), .Union => @panic("TODO"), } } pub fn cast(base: *Type, comptime T: type) ?*T { if (base.id != @field(Id, @typeName(T))) return null; return @fieldParentPtr(T, "base", base); } pub fn dump(base: *const Type) void { std.debug.warn("{}", @tagName(base.id)); } fn init(base: *Type, comp: *Compilation, id: Id, name: []const u8) void { base.* = Type{ .base = Value{ .id = .Type, .typ = &MetaType.get(comp).base, .ref_count = std.atomic.Int(usize).init(1), }, .id = id, .name = name, .abi_alignment = AbiAlignment.init(), }; } /// If you happen to have an llvm context handy, use getAbiAlignmentInContext instead. /// Otherwise, this one will grab one from the pool and then release it. pub fn getAbiAlignment(base: *Type, comp: *Compilation) !u32 { if (base.abi_alignment.start()) |ptr| return ptr.*; { const held = try comp.zig_compiler.getAnyLlvmContext(); defer held.release(comp.zig_compiler); const llvm_context = held.node.data; base.abi_alignment.data = base.resolveAbiAlignment(comp, llvm_context); } base.abi_alignment.resolve(); return base.abi_alignment.data; } /// If you have an llvm conext handy, you can use it here. pub fn getAbiAlignmentInContext(base: *Type, comp: *Compilation, llvm_context: *llvm.Context) !u32 { if (base.abi_alignment.start()) |ptr| return ptr.*; base.abi_alignment.data = base.resolveAbiAlignment(comp, llvm_context); base.abi_alignment.resolve(); return base.abi_alignment.data; } /// Lower level function that does the work. See getAbiAlignment. fn resolveAbiAlignment(base: *Type, comp: *Compilation, llvm_context: *llvm.Context) !u32 { const llvm_type = try base.getLlvmType(comp.gpa(), llvm_context); return @intCast(u32, llvm.ABIAlignmentOfType(comp.target_data_ref, llvm_type)); } pub const Struct = struct { base: Type, decls: *Scope.Decls, pub fn destroy(self: *Struct, comp: *Compilation) void { comp.gpa().destroy(self); } pub fn getLlvmType(self: *Struct, allocator: *Allocator, llvm_context: *llvm.Context) *llvm.Type { @panic("TODO"); } }; pub const Fn = struct { base: Type, key: Key, non_key: NonKey, garbage_node: std.atomic.Stack(*Fn).Node, pub const Kind = enum { Normal, Generic, }; pub const NonKey = union { Normal: Normal, Generic: void, pub const Normal = struct { variable_list: std.ArrayList(*Scope.Var), }; }; pub const Key = struct { data: Data, alignment: ?u32, pub const Data = union(Kind) { Generic: Generic, Normal: Normal, }; pub const Normal = struct { params: []Param, return_type: *Type, is_var_args: bool, cc: CallingConvention, }; pub const Generic = struct { param_count: usize, cc: CallingConvention, }; pub fn hash(self: *const Key) u32 { var result: u32 = 0; result +%= hashAny(self.alignment, 0); switch (self.data) { .Generic => |generic| { result +%= hashAny(generic.param_count, 1); result +%= hashAny(generic.cc, 3); }, .Normal => |normal| { result +%= hashAny(normal.return_type, 4); result +%= hashAny(normal.is_var_args, 5); result +%= hashAny(normal.cc, 6); for (normal.params) |param| { result +%= hashAny(param.is_noalias, 7); result +%= hashAny(param.typ, 8); } }, } return result; } pub fn eql(self: *const Key, other: *const Key) bool { if ((self.alignment == null) != (other.alignment == null)) return false; if (self.alignment) |self_align| { if (self_align != other.alignment.?) return false; } if (@as(@TagType(Data), self.data) != @as(@TagType(Data), other.data)) return false; switch (self.data) { .Generic => |*self_generic| { const other_generic = &other.data.Generic; if (self_generic.param_count != other_generic.param_count) return false; if (self_generic.cc != other_generic.cc) return false; }, .Normal => |*self_normal| { const other_normal = &other.data.Normal; if (self_normal.cc != other_normal.cc) return false; if (self_normal.is_var_args != other_normal.is_var_args) return false; if (self_normal.return_type != other_normal.return_type) return false; for (self_normal.params) |*self_param, i| { const other_param = &other_normal.params[i]; if (self_param.is_noalias != other_param.is_noalias) return false; if (self_param.typ != other_param.typ) return false; } }, } return true; } pub fn deref(key: Key, comp: *Compilation) void { switch (key.data) { .Generic => {}, .Normal => |normal| { normal.return_type.base.deref(comp); for (normal.params) |param| { param.typ.base.deref(comp); } }, } } pub fn ref(key: Key) void { switch (key.data) { .Generic => {}, .Normal => |normal| { normal.return_type.base.ref(); for (normal.params) |param| { param.typ.base.ref(); } }, } } }; const CallingConvention = builtin.TypeInfo.CallingConvention; pub const Param = struct { is_noalias: bool, typ: *Type, }; fn ccFnTypeStr(cc: CallingConvention) []const u8 { return switch (cc) { .Unspecified => "", .C => "extern ", .Cold => "coldcc ", .Naked => "nakedcc ", .Stdcall => "stdcallcc ", .Async => "async ", }; } pub fn paramCount(self: *Fn) usize { return switch (self.key.data) { .Generic => |generic| generic.param_count, .Normal => |normal| normal.params.len, }; } /// takes ownership of key.Normal.params on success pub fn get(comp: *Compilation, key: Key) !*Fn { { const held = comp.fn_type_table.acquire(); defer held.release(); if (held.value.get(&key)) |entry| { entry.value.base.base.ref(); return entry.value; } } key.ref(); errdefer key.deref(comp); const self = try comp.gpa().create(Fn); self.* = Fn{ .base = undefined, .key = key, .non_key = undefined, .garbage_node = undefined, }; errdefer comp.gpa().destroy(self); var name_buf = try std.Buffer.initSize(comp.gpa(), 0); defer name_buf.deinit(); const name_stream = &std.io.BufferOutStream.init(&name_buf).stream; switch (key.data) { .Generic => |generic| { self.non_key = NonKey{ .Generic = {} }; const cc_str = ccFnTypeStr(generic.cc); try name_stream.print("{}fn(", cc_str); var param_i: usize = 0; while (param_i < generic.param_count) : (param_i += 1) { const arg = if (param_i == 0) "var" else ", var"; try name_stream.write(arg); } try name_stream.write(")"); if (key.alignment) |alignment| { try name_stream.print(" align({})", alignment); } try name_stream.write(" var"); }, .Normal => |normal| { self.non_key = NonKey{ .Normal = NonKey.Normal{ .variable_list = std.ArrayList(*Scope.Var).init(comp.gpa()) }, }; const cc_str = ccFnTypeStr(normal.cc); try name_stream.print("{}fn(", cc_str); for (normal.params) |param, i| { if (i != 0) try name_stream.write(", "); if (param.is_noalias) try name_stream.write("noalias "); try name_stream.write(param.typ.name); } if (normal.is_var_args) { if (normal.params.len != 0) try name_stream.write(", "); try name_stream.write("..."); } try name_stream.write(")"); if (key.alignment) |alignment| { try name_stream.print(" align({})", alignment); } try name_stream.print(" {}", normal.return_type.name); }, } self.base.init(comp, .Fn, name_buf.toOwnedSlice()); { const held = comp.fn_type_table.acquire(); defer held.release(); _ = try held.value.put(&self.key, self); } return self; } pub fn destroy(self: *Fn, comp: *Compilation) void { self.key.deref(comp); switch (self.key.data) { .Generic => {}, .Normal => { self.non_key.Normal.variable_list.deinit(); }, } comp.gpa().destroy(self); } pub fn getLlvmType(self: *Fn, allocator: *Allocator, llvm_context: *llvm.Context) !*llvm.Type { const normal = &self.key.data.Normal; const llvm_return_type = switch (normal.return_type.id) { .Void => llvm.VoidTypeInContext(llvm_context) orelse return error.OutOfMemory, else => try normal.return_type.getLlvmType(allocator, llvm_context), }; const llvm_param_types = try allocator.alloc(*llvm.Type, normal.params.len); defer allocator.free(llvm_param_types); for (llvm_param_types) |*llvm_param_type, i| { llvm_param_type.* = try normal.params[i].typ.getLlvmType(allocator, llvm_context); } return llvm.FunctionType( llvm_return_type, llvm_param_types.ptr, @intCast(c_uint, llvm_param_types.len), @boolToInt(normal.is_var_args), ) orelse error.OutOfMemory; } }; pub const MetaType = struct { base: Type, value: *Type, /// Adds 1 reference to the resulting type pub fn get(comp: *Compilation) *MetaType { comp.meta_type.base.base.ref(); return comp.meta_type; } pub fn destroy(self: *MetaType, comp: *Compilation) void { comp.gpa().destroy(self); } }; pub const Void = struct { base: Type, /// Adds 1 reference to the resulting type pub fn get(comp: *Compilation) *Void { comp.void_type.base.base.ref(); return comp.void_type; } pub fn destroy(self: *Void, comp: *Compilation) void { comp.gpa().destroy(self); } }; pub const Bool = struct { base: Type, /// Adds 1 reference to the resulting type pub fn get(comp: *Compilation) *Bool { comp.bool_type.base.base.ref(); return comp.bool_type; } pub fn destroy(self: *Bool, comp: *Compilation) void { comp.gpa().destroy(self); } pub fn getLlvmType(self: *Bool, allocator: *Allocator, llvm_context: *llvm.Context) *llvm.Type { @panic("TODO"); } }; pub const NoReturn = struct { base: Type, /// Adds 1 reference to the resulting type pub fn get(comp: *Compilation) *NoReturn { comp.noreturn_type.base.base.ref(); return comp.noreturn_type; } pub fn destroy(self: *NoReturn, comp: *Compilation) void { comp.gpa().destroy(self); } }; pub const Int = struct { base: Type, key: Key, garbage_node: std.atomic.Stack(*Int).Node, pub const Key = struct { bit_count: u32, is_signed: bool, pub fn hash(self: *const Key) u32 { var result: u32 = 0; result +%= hashAny(self.is_signed, 0); result +%= hashAny(self.bit_count, 1); return result; } pub fn eql(self: *const Key, other: *const Key) bool { return self.bit_count == other.bit_count and self.is_signed == other.is_signed; } }; pub fn get_u8(comp: *Compilation) *Int { comp.u8_type.base.base.ref(); return comp.u8_type; } pub fn get(comp: *Compilation, key: Key) !*Int { { const held = comp.int_type_table.acquire(); defer held.release(); if (held.value.get(&key)) |entry| { entry.value.base.base.ref(); return entry.value; } } const self = try comp.gpa().create(Int); self.* = Int{ .base = undefined, .key = key, .garbage_node = undefined, }; errdefer comp.gpa().destroy(self); const u_or_i = "ui"[@boolToInt(key.is_signed)]; const name = try std.fmt.allocPrint(comp.gpa(), "{c}{}", u_or_i, key.bit_count); errdefer comp.gpa().free(name); self.base.init(comp, .Int, name); { const held = comp.int_type_table.acquire(); defer held.release(); _ = try held.value.put(&self.key, self); } return self; } pub fn destroy(self: *Int, comp: *Compilation) void { self.garbage_node = std.atomic.Stack(*Int).Node{ .data = self, .next = undefined, }; comp.registerGarbage(Int, &self.garbage_node); } pub fn gcDestroy(self: *Int, comp: *Compilation) void { { const held = comp.int_type_table.acquire(); defer held.release(); _ = held.value.remove(&self.key).?; } // we allocated the name comp.gpa().free(self.base.name); comp.gpa().destroy(self); } pub fn getLlvmType(self: *Int, allocator: *Allocator, llvm_context: *llvm.Context) !*llvm.Type { return llvm.IntTypeInContext(llvm_context, self.key.bit_count) orelse return error.OutOfMemory; } }; pub const Float = struct { base: Type, pub fn destroy(self: *Float, comp: *Compilation) void { comp.gpa().destroy(self); } pub fn getLlvmType(self: *Float, allocator: *Allocator, llvm_context: *llvm.Context) *llvm.Type { @panic("TODO"); } }; pub const Pointer = struct { base: Type, key: Key, garbage_node: std.atomic.Stack(*Pointer).Node, pub const Key = struct { child_type: *Type, mut: Mut, vol: Vol, size: Size, alignment: Align, pub fn hash(self: *const Key) u32 { var result: u32 = 0; result +%= switch (self.alignment) { .Abi => 0xf201c090, .Override => |x| hashAny(x, 0), }; result +%= hashAny(self.child_type, 1); result +%= hashAny(self.mut, 2); result +%= hashAny(self.vol, 3); result +%= hashAny(self.size, 4); return result; } pub fn eql(self: *const Key, other: *const Key) bool { if (self.child_type != other.child_type or self.mut != other.mut or self.vol != other.vol or self.size != other.size or @as(@TagType(Align), self.alignment) != @as(@TagType(Align), other.alignment)) { return false; } switch (self.alignment) { .Abi => return true, .Override => |x| return x == other.alignment.Override, } } }; pub const Mut = enum { Mut, Const, }; pub const Vol = enum { Non, Volatile, }; pub const Align = union(enum) { Abi, Override: u32, }; pub const Size = builtin.TypeInfo.Pointer.Size; pub fn destroy(self: *Pointer, comp: *Compilation) void { self.garbage_node = std.atomic.Stack(*Pointer).Node{ .data = self, .next = undefined, }; comp.registerGarbage(Pointer, &self.garbage_node); } pub fn gcDestroy(self: *Pointer, comp: *Compilation) void { { const held = comp.ptr_type_table.acquire(); defer held.release(); _ = held.value.remove(&self.key).?; } self.key.child_type.base.deref(comp); comp.gpa().destroy(self); } pub fn getAlignAsInt(self: *Pointer, comp: *Compilation) u32 { switch (self.key.alignment) { .Abi => return self.key.child_type.getAbiAlignment(comp), .Override => |alignment| return alignment, } } pub fn get( comp: *Compilation, key: Key, ) !*Pointer { var normal_key = key; switch (key.alignment) { .Abi => {}, .Override => |alignment| { // TODO https://github.com/ziglang/zig/issues/3190 var align_spill = alignment; const abi_align = try key.child_type.getAbiAlignment(comp); if (abi_align == align_spill) { normal_key.alignment = .Abi; } }, } { const held = comp.ptr_type_table.acquire(); defer held.release(); if (held.value.get(&normal_key)) |entry| { entry.value.base.base.ref(); return entry.value; } } const self = try comp.gpa().create(Pointer); self.* = Pointer{ .base = undefined, .key = normal_key, .garbage_node = undefined, }; errdefer comp.gpa().destroy(self); const size_str = switch (self.key.size) { .One => "*", .Many => "[*]", .Slice => "[]", .C => "[*c]", }; const mut_str = switch (self.key.mut) { .Const => "const ", .Mut => "", }; const vol_str = switch (self.key.vol) { .Volatile => "volatile ", .Non => "", }; const name = switch (self.key.alignment) { .Abi => try std.fmt.allocPrint( comp.gpa(), "{}{}{}{}", size_str, mut_str, vol_str, self.key.child_type.name, ), .Override => |alignment| try std.fmt.allocPrint( comp.gpa(), "{}align<{}> {}{}{}", size_str, alignment, mut_str, vol_str, self.key.child_type.name, ), }; errdefer comp.gpa().free(name); self.base.init(comp, .Pointer, name); { const held = comp.ptr_type_table.acquire(); defer held.release(); _ = try held.value.put(&self.key, self); } return self; } pub fn getLlvmType(self: *Pointer, allocator: *Allocator, llvm_context: *llvm.Context) !*llvm.Type { const elem_llvm_type = try self.key.child_type.getLlvmType(allocator, llvm_context); return llvm.PointerType(elem_llvm_type, 0) orelse return error.OutOfMemory; } }; pub const Array = struct { base: Type, key: Key, garbage_node: std.atomic.Stack(*Array).Node, pub const Key = struct { elem_type: *Type, len: usize, pub fn hash(self: *const Key) u32 { var result: u32 = 0; result +%= hashAny(self.elem_type, 0); result +%= hashAny(self.len, 1); return result; } pub fn eql(self: *const Key, other: *const Key) bool { return self.elem_type == other.elem_type and self.len == other.len; } }; pub fn destroy(self: *Array, comp: *Compilation) void { self.key.elem_type.base.deref(comp); comp.gpa().destroy(self); } pub fn get(comp: *Compilation, key: Key) !*Array { key.elem_type.base.ref(); errdefer key.elem_type.base.deref(comp); { const held = comp.array_type_table.acquire(); defer held.release(); if (held.value.get(&key)) |entry| { entry.value.base.base.ref(); return entry.value; } } const self = try comp.gpa().create(Array); self.* = Array{ .base = undefined, .key = key, .garbage_node = undefined, }; errdefer comp.gpa().destroy(self); const name = try std.fmt.allocPrint(comp.gpa(), "[{}]{}", key.len, key.elem_type.name); errdefer comp.gpa().free(name); self.base.init(comp, .Array, name); { const held = comp.array_type_table.acquire(); defer held.release(); _ = try held.value.put(&self.key, self); } return self; } pub fn getLlvmType(self: *Array, allocator: *Allocator, llvm_context: *llvm.Context) !*llvm.Type { const elem_llvm_type = try self.key.elem_type.getLlvmType(allocator, llvm_context); return llvm.ArrayType(elem_llvm_type, @intCast(c_uint, self.key.len)) orelse return error.OutOfMemory; } }; pub const Vector = struct { base: Type, pub fn destroy(self: *Vector, comp: *Compilation) void { comp.gpa().destroy(self); } pub fn getLlvmType(self: *Vector, allocator: *Allocator, llvm_context: *llvm.Context) *llvm.Type { @panic("TODO"); } }; pub const ComptimeFloat = struct { base: Type, pub fn destroy(self: *ComptimeFloat, comp: *Compilation) void { comp.gpa().destroy(self); } }; pub const ComptimeInt = struct { base: Type, /// Adds 1 reference to the resulting type pub fn get(comp: *Compilation) *ComptimeInt { comp.comptime_int_type.base.base.ref(); return comp.comptime_int_type; } pub fn destroy(self: *ComptimeInt, comp: *Compilation) void { comp.gpa().destroy(self); } }; pub const EnumLiteral = struct { base: Type, /// Adds 1 reference to the resulting type pub fn get(comp: *Compilation) *EnumLiteral { comp.comptime_int_type.base.base.ref(); return comp.comptime_int_type; } pub fn destroy(self: *EnumLiteral, comp: *Compilation) void { comp.gpa().destroy(self); } }; pub const Undefined = struct { base: Type, pub fn destroy(self: *Undefined, comp: *Compilation) void { comp.gpa().destroy(self); } }; pub const Null = struct { base: Type, pub fn destroy(self: *Null, comp: *Compilation) void { comp.gpa().destroy(self); } }; pub const Optional = struct { base: Type, pub fn destroy(self: *Optional, comp: *Compilation) void { comp.gpa().destroy(self); } pub fn getLlvmType(self: *Optional, allocator: *Allocator, llvm_context: *llvm.Context) *llvm.Type { @panic("TODO"); } }; pub const ErrorUnion = struct { base: Type, pub fn destroy(self: *ErrorUnion, comp: *Compilation) void { comp.gpa().destroy(self); } pub fn getLlvmType(self: *ErrorUnion, allocator: *Allocator, llvm_context: *llvm.Context) *llvm.Type { @panic("TODO"); } }; pub const ErrorSet = struct { base: Type, pub fn destroy(self: *ErrorSet, comp: *Compilation) void { comp.gpa().destroy(self); } pub fn getLlvmType(self: *ErrorSet, allocator: *Allocator, llvm_context: *llvm.Context) *llvm.Type { @panic("TODO"); } }; pub const Enum = struct { base: Type, pub fn destroy(self: *Enum, comp: *Compilation) void { comp.gpa().destroy(self); } pub fn getLlvmType(self: *Enum, allocator: *Allocator, llvm_context: *llvm.Context) *llvm.Type { @panic("TODO"); } }; pub const Union = struct { base: Type, pub fn destroy(self: *Union, comp: *Compilation) void { comp.gpa().destroy(self); } pub fn getLlvmType(self: *Union, allocator: *Allocator, llvm_context: *llvm.Context) *llvm.Type { @panic("TODO"); } }; pub const BoundFn = struct { base: Type, pub fn destroy(self: *BoundFn, comp: *Compilation) void { comp.gpa().destroy(self); } pub fn getLlvmType(self: *BoundFn, allocator: *Allocator, llvm_context: *llvm.Context) *llvm.Type { @panic("TODO"); } }; pub const ArgTuple = struct { base: Type, pub fn destroy(self: *ArgTuple, comp: *Compilation) void { comp.gpa().destroy(self); } }; pub const Opaque = struct { base: Type, pub fn destroy(self: *Opaque, comp: *Compilation) void { comp.gpa().destroy(self); } pub fn getLlvmType(self: *Opaque, allocator: *Allocator, llvm_context: *llvm.Context) *llvm.Type { @panic("TODO"); } }; pub const Frame = struct { base: Type, pub fn destroy(self: *Frame, comp: *Compilation) void { comp.gpa().destroy(self); } pub fn getLlvmType(self: *Frame, allocator: *Allocator, llvm_context: *llvm.Context) *llvm.Type { @panic("TODO"); } }; pub const AnyFrame = struct { base: Type, pub fn destroy(self: *AnyFrame, comp: *Compilation) void { comp.gpa().destroy(self); } pub fn getLlvmType(self: *AnyFrame, allocator: *Allocator, llvm_context: *llvm.Context) *llvm.Type { @panic("TODO"); } }; }; fn hashAny(x: var, comptime seed: u64) u32 { switch (@typeInfo(@typeOf(x))) { .Int => |info| { comptime var rng = comptime std.rand.DefaultPrng.init(seed); const unsigned_x = @bitCast(@IntType(false, info.bits), x); if (info.bits <= 32) { return @as(u32, unsigned_x) *% comptime rng.random.scalar(u32); } else { return @truncate(u32, unsigned_x *% comptime rng.random.scalar(@typeOf(unsigned_x))); } }, .Pointer => |info| { switch (info.size) { .One => return hashAny(@ptrToInt(x), seed), .Many => @compileError("implement hash function"), .Slice => @compileError("implement hash function"), .C => unreachable, } }, .Enum => return hashAny(@enumToInt(x), seed), .Bool => { comptime var rng = comptime std.rand.DefaultPrng.init(seed); const vals = comptime [2]u32{ rng.random.scalar(u32), rng.random.scalar(u32) }; return vals[@boolToInt(x)]; }, .Optional => { if (x) |non_opt| { return hashAny(non_opt, seed); } else { return hashAny(@as(u32, 1), seed); } }, else => @compileError("implement hash function for " ++ @typeName(@typeOf(x))), } }
src-self-hosted/type.zig
const std = @import("std"); const DebugAllocator = @This(); const Stats = struct { mean: f64 = 0, mean_of_squares: f64 = 0, total: usize = 0, count: usize = 0, fn addSample(self: *Stats, value: usize) void { const count_f64 = @intToFloat(f64, self.count); self.mean = (self.mean * count_f64 + @intToFloat(f64, value)) / (count_f64 + 1); self.mean_of_squares = (self.mean_of_squares * count_f64 + @intToFloat(f64, value * value)) / (count_f64 + 1); self.total += value; self.count += 1; } fn stdDev(self: Stats) f64 { return std.math.sqrt(self.mean_of_squares - self.mean * self.mean); } }; pub const AllocationInfo = struct { allocation_stats: Stats = Stats{}, deallocation_count: usize = 0, deallocation_total: usize = 0, peak_allocated: usize = 0, reallocation_stats: Stats = Stats{}, shrink_stats: Stats = Stats{}, fn currentlyAllocated(self: AllocationInfo) usize { return self.allocation_stats.total + self.reallocation_stats.total - self.deallocation_total - self.shrink_stats.total; } pub fn format( self: AllocationInfo, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype, ) !void { @setEvalBranchQuota(2000); return std.fmt.format( out_stream, \\------------------------------------------ Allocation info ------------------------------------------ \\{} total allocations (total: {Bi:.2}, mean: {Bi:.2}, std. dev: {Bi:.2} MB), {} deallocations \\{} current allocations ({Bi:.2}), peak mem usage: {Bi:.2} \\{} reallocations (total: {Bi:.2}, mean: {Bi:.2}, std. dev: {Bi:.2}) \\{} shrinks (total: {Bi:.2}, mean: {Bi:.2}, std. dev: {Bi:.2}) \\----------------------------------------------------------------------------------------------------- , .{ self.allocation_stats.count, self.allocation_stats.total, self.allocation_stats.mean, self.allocation_stats.stdDev(), self.deallocation_count, self.allocation_stats.count - self.deallocation_count, self.currentlyAllocated(), self.peak_allocated, self.reallocation_stats.count, self.reallocation_stats.total, self.reallocation_stats.mean, self.reallocation_stats.stdDev(), self.shrink_stats.count, self.shrink_stats.total, self.shrink_stats.mean, self.shrink_stats.stdDev(), }, ); } }; const stack_addresses_size = 15; base_allocator: *std.mem.Allocator, info: AllocationInfo, max_bytes: usize, allocation_strack_addresses: std.AutoHashMap(usize, [stack_addresses_size]usize), // Interface implementation allocator: std.mem.Allocator, pub fn init(base_allocator: *std.mem.Allocator, max_bytes: usize) DebugAllocator { return .{ .base_allocator = base_allocator, .info = .{}, .max_bytes = max_bytes, .allocation_strack_addresses = std.AutoHashMap(usize, [stack_addresses_size]usize).init(base_allocator), .allocator = .{ .allocFn = alloc, .resizeFn = resize, }, }; } pub fn deinit(self: *DebugAllocator) void { self.allocation_strack_addresses.deinit(); } fn alloc(allocator: *std.mem.Allocator, len: usize, ptr_align: u29, len_align: u29) error{OutOfMemory}![]u8 { const self = @fieldParentPtr(DebugAllocator, "allocator", allocator); const ptr = try self.base_allocator.callAllocFn(len, ptr_align, len_align); self.info.allocation_stats.addSample(ptr.len); var stack_addresses = std.mem.zeroes([stack_addresses_size + 2]usize); var stack_trace = std.builtin.StackTrace{ .instruction_addresses = &stack_addresses, .index = 0, }; std.debug.captureStackTrace(@returnAddress(), &stack_trace); try self.allocation_strack_addresses.putNoClobber(@ptrToInt(ptr.ptr), stack_addresses[2..].*); const curr_allocs = self.info.currentlyAllocated(); if (self.max_bytes != 0 and curr_allocs >= self.max_bytes) { std.debug.print("Exceeded maximum bytes {}, exiting.\n", .{self.max_bytes}); std.process.exit(1); } if (curr_allocs > self.info.peak_allocated) { self.info.peak_allocated = curr_allocs; } return ptr; } fn resize(allocator: *std.mem.Allocator, old_mem: []u8, new_size: usize, len_align: u29) error{OutOfMemory}!usize { const self = @fieldParentPtr(DebugAllocator, "allocator", allocator); if (old_mem.len == 0) { std.log.debug(.debug_alloc, "Trying to resize empty slice\n", .{}); std.process.exit(1); } if (self.allocation_strack_addresses.get(@ptrToInt(old_mem.ptr)) == null) { @panic("error - resize call on block not allocated by debug allocator"); } if (new_size == 0) { if (self.info.allocation_stats.count == self.info.deallocation_count) { @panic("error - too many calls to free, most likely double free"); } self.info.deallocation_total += old_mem.len; self.info.deallocation_count += 1; self.allocation_strack_addresses.removeAssertDiscard(@ptrToInt(old_mem.ptr)); } else if (new_size > old_mem.len) { self.info.reallocation_stats.addSample(new_size - old_mem.len); } else if (new_size < old_mem.len) { self.info.shrink_stats.addSample(old_mem.len - new_size); } const curr_allocs = self.info.currentlyAllocated(); if (self.max_bytes != 0 and curr_allocs >= self.max_bytes) { std.log.debug(.debug_alloc, "Exceeded maximum bytes {}, exiting.\n", .{self.max_bytes}); std.process.exit(1); } if (curr_allocs > self.info.peak_allocated) { self.info.peak_allocated = curr_allocs; } return self.base_allocator.callResizeFn(old_mem, new_size, len_align) catch |e| { return e; }; } pub fn printRemainingStackTraces(self: DebugAllocator) void { std.debug.print( \\{} allocations - stack traces follow \\------------------------------------ , .{self.allocation_strack_addresses.count()}); var it = self.allocation_strack_addresses.iterator(); var idx: usize = 1; while (it.next()) |entry| : (idx += 1) { std.debug.print("\nAllocation {}\n-------------\n", .{idx}); var len: usize = 0; while (len < stack_addresses_size and entry.value[len] != 0) : (len += 1) {} const stack_trace = std.builtin.StackTrace{ .instruction_addresses = &entry.value, .index = len, }; std.debug.dumpStackTrace(stack_trace); } }
src/debug_allocator.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const log = std.log.scoped(.lexer); const Error = error{ InvalidToken, ReachedEof, }; pub const TokenId = enum(u16) { identifier = 255, literal_int, literal_uint, literal_float, literal_char, literal_string, literal_hex, literal_oct, literal_bin, kwd_include, kwd_if, kwd_else, kwd_while, kwd_for, kwd_switch, kwd_break, kwd_continue, kwd_return, kwd_inline, kwd_extern, kwd_struct, kwd_union, kwd_enum, kwd_int, kwd_uint, kwd_float, kwd_byte, kwd_char, kwd_void, kwd_null, kwd_true, kwd_false, kwd_and, kwd_or, kwd_error, kwd_type, kwd_fn, kwd_const, op_assign, op_add, op_sub, op_mul, op_div, op_mod, op_at, op_add_inline, op_sub_inline, op_mul_inline, op_div_inline, op_mod_inline, op_at_inline, op_ampersand, op_cond_not, op_cond_eq, op_cond_neq, op_cond_lt, op_cond_leq, op_cond_gt, op_cond_geq, op_bit_lshift, op_bit_rshift, op_bit_or, // op_bit_and, // op_ampersand, gotta do extra work in the parser ;) op_bit_xor, op_bit_not, op_bit_lshift_inline, op_bit_rshift_inline, op_bit_and_inline, op_bit_or_inline, op_bit_xor_inline, sep_arrow, sep_big_arrow, sep_dot, // could be operator sep_semicolon, sep_brace_l, sep_brace_r, sep_bracket_l, sep_bracket_r, sep_paren_l, sep_paren_r, sep_comma, sep_colon, sep_double_colon, sep_colon_equals, end_of_file, }; const Reserved = struct { src: []const u8, tag: TokenId }; const reserved_atoms = .{ Reserved{ .src = "@import", .tag = .kwd_include }, Reserved{ .src = "type", .tag = .kwd_type }, Reserved{ .src = "if", .tag = .kwd_if }, Reserved{ .src = "else", .tag = .kwd_else }, Reserved{ .src = "while", .tag = .kwd_while }, Reserved{ .src = "for", .tag = .kwd_for }, Reserved{ .src = "switch", .tag = .kwd_switch }, Reserved{ .src = "continue", .tag = .kwd_continue }, Reserved{ .src = "break", .tag = .kwd_break }, Reserved{ .src = "return", .tag = .kwd_return }, Reserved{ .src = "fn", .tag = .kwd_fn }, Reserved{ .src = "inline", .tag = .kwd_inline }, Reserved{ .src = "extern", .tag = .kwd_extern }, Reserved{ .src = "struct", .tag = .kwd_struct }, Reserved{ .src = "union", .tag = .kwd_union }, Reserved{ .src = "enum", .tag = .kwd_enum }, Reserved{ .src = "const", .tag = .kwd_const }, //Reserved{ .src = "int", .tag = .kwd_int }, //Reserved{ .src = "uint", .tag = .kwd_uint }, //Reserved{ .src = "float", .tag = .kwd_float }, //Reserved{ .src = "byte", .tag = .kwd_byte }, //Reserved{ .src = "char", .tag = .kwd_char }, //Reserved{ .src = "void", .tag = .kwd_void }, Reserved{ .src = "null", .tag = .kwd_null }, Reserved{ .src = "true", .tag = .kwd_true }, Reserved{ .src = "false", .tag = .kwd_false }, Reserved{ .src = "and", .tag = .kwd_and }, Reserved{ .src = "or", .tag = .kwd_or }, }; pub const Token = struct { tag: TokenId, pos: usize, len: usize, line: usize = 0, col: usize = 0, str: []const u8, data: ?Data = null, const Data = union { str_value: []const u8, f32_value: f32, f64_value: f64, uint_value: u128, int_value: i128, }; }; fn match_op_or_sep(src: [:0]const u8, pos: usize) ?Token { if (pos >= src.len) return null; const c = src[pos]; const has_next = pos + 1 < src.len; const has_next_equals = has_next and src[pos + 1] == '='; var t: Token = undefined; t.pos = pos; t.len = 1; switch (c) { ':' => { const has_next_colon = has_next and src[pos + 1] == ':'; if (has_next_colon) { t.tag = .sep_double_colon; t.len += 1; } else if (has_next_equals) { t.tag = .sep_colon_equals; t.len += 1; } else { t.tag = .sep_colon; } }, '=' => { if (has_next_equals) { t.tag = .op_cond_eq; t.len += 1; } else if (has_next and src[pos + 1] == '>') { t.tag = .sep_big_arrow; t.len += 1; } else { t.tag = .op_assign; } }, '-' => { if (has_next_equals) { t.tag = .op_sub_inline; t.len += 1; } else if (has_next and src[pos + 1] == '>') { t.tag = .sep_arrow; t.len += 1; } else { t.tag = .op_sub; } }, '<' => { if (has_next_equals) { t.tag = .op_cond_leq; t.len += 1; } else if (has_next and src[pos + 1] == '<') { t.tag = .op_bit_lshift; t.len += 1; } else { t.tag = .op_cond_lt; } }, '>' => { if (has_next_equals) { t.tag = .op_cond_geq; t.len += 1; } else if (has_next and src[pos + 1] == '>') { t.tag = .op_bit_rshift; t.len += 1; } else { t.tag = .op_cond_gt; } }, '!' => { if (has_next_equals) { t.tag = .op_cond_neq; t.len += 1; } else { t.tag = .op_cond_not; } }, '+' => { if (has_next_equals) { t.tag = .op_add_inline; t.len += 1; } else { t.tag = .op_add; } }, '*' => { if (has_next_equals) { t.tag = .op_mul_inline; t.len += 1; } else { t.tag = .op_mul; } }, '/' => { if (has_next_equals) { t.tag = .op_div_inline; t.len += 1; } else { t.tag = .op_div; } }, '%' => { if (has_next_equals) { t.tag = .op_mod_inline; t.len += 1; } else { t.tag = .op_mod; } }, '@' => { if (has_next_equals) { t.tag = .op_at_inline; t.len += 1; } else { t.tag = .op_at; } }, '&' => { if (has_next_equals) { t.tag = .op_bit_and_inline; t.len += 1; } else { t.tag = .op_ampersand; } }, '|' => { if (has_next_equals) { t.tag = .op_bit_or_inline; t.len += 1; } else { t.tag = .op_bit_or; } }, '^' => { if (has_next_equals) { t.tag = .op_bit_xor_inline; t.len += 1; } else { t.tag = .op_bit_xor; } }, '(' => { t.tag = .sep_paren_l; }, ')' => { t.tag = .sep_paren_r; }, '[' => { t.tag = .sep_bracket_l; }, ']' => { t.tag = .sep_bracket_r; }, '{' => { t.tag = .sep_brace_l; }, '}' => { t.tag = .sep_brace_r; }, ';' => { t.tag = .sep_semicolon; }, '.' => { t.tag = .sep_dot; }, ',' => { t.tag = .sep_comma; }, '\x00' => { t.tag = .end_of_file; }, else => return null, } t.str = src[pos .. pos + t.len]; return t; } fn is_identifier_char(c: u8) bool { return std.ascii.isAlNum(c) or c == '_'; } /// match integer literals prefixed with `0b`, `0o`, or `0x` for binary, octal, and hexadecimal literals, respectively. fn match_int_literal(src: [:0]const u8, pos: usize) !?Token { if (src[pos] != '0' or pos + 2 >= src.len) return null; var token: Token = undefined; token.tag = switch (src[pos + 1]) { 'b' => .literal_bin, 'o' => .literal_oct, 'x' => .literal_hex, else => return null, }; token.pos = pos; token.len = 2; while (pos + token.len < src.len and is_identifier_char(src[pos + token.len])) token.len += 1; token.data = Token.Data{ .uint_value = try std.fmt.parseUnsigned(u128, src[pos .. pos + token.len], 0) }; token.str = src[pos .. pos + token.len]; return token; } /// match literal integers and floats. fn match_numeric_literal(src: [:0]const u8, pos: usize) !?Token { if (try match_int_literal(src, pos)) |t| return t; const has_next = pos + 1 < src.len; var seen_dot = src[pos] == '.'; if ((!std.ascii.isDigit(src[pos]) and !seen_dot) or (has_next and seen_dot and !std.ascii.isDigit(src[pos + 1]))) { return null; } var token: Token = undefined; token.pos = pos; token.len = 0; seen_dot = false; var seen_e = false; while (pos + token.len < src.len) { switch (src[pos + token.len]) { '.' => if (seen_dot or seen_e) return Error.InvalidToken, 'e', 'E' => if (seen_e) return Error.InvalidToken, '-' => { const prev_char = src[pos + token.len - 1]; if (!seen_e or (prev_char != 'e' and prev_char != 'E')) break; }, '_', '0'...'9' => {}, 'a'...'d', 'f'...'z', 'A'...'D', 'F'...'Z' => return Error.InvalidToken, else => break, } seen_dot = seen_dot or src[pos + token.len] == '.'; seen_e = seen_e or src[pos + token.len] == 'e' or src[pos + token.len] == 'E'; token.len += 1; } token.tag = if (seen_dot or seen_e) .literal_float else .literal_int; token.data = if (token.tag == .literal_float) .{ .f64_value = try std.fmt.parseFloat(f64, src[pos .. pos + token.len]), } else .{ .uint_value = try std.fmt.parseUnsigned(u128, src[pos .. pos + token.len], 10), }; token.str = src[pos .. pos + token.len]; return token; } fn match_string_or_char_literal(src: [:0]const u8, pos: usize) !?Token { if (pos >= src.len or (src[pos] != '"' and src[pos] != '\'')) return null; var token: Token = undefined; token.pos = pos; token.len = 1; const end_char = src[pos]; token.tag = if (end_char == '"') .literal_string else .literal_char; while (pos + token.len < src.len and src[pos + token.len] != end_char) { token.len += 1 + @intCast(usize, @boolToInt(src[pos + token.len] == '\\')); } if (src[pos + token.len] != end_char) return Error.ReachedEof; token.len += 1; token.data = Token.Data{ .str_value = src[pos .. pos + token.len] }; token.str = src[pos .. pos + token.len]; return token; } fn match_identifier_or_kwd(src: [:0]const u8, pos: usize) ?Token { // zig fmt: off if ( (pos >= src.len or (!std.ascii.isAlpha(src[pos]) and src[pos] != '_')) or (pos + 1 < src.len and src[pos] == '@' and !std.ascii.isAlpha(src[pos + 1])) ) return null; // zig fmt: on var token: Token = undefined; token.pos = pos; token.len = 1; while (pos + token.len < src.len and is_identifier_char(src[pos + token.len])) { token.len += 1; } token.str = src[pos .. pos + token.len]; // TODO(mia): use comptime string hash map token.tag = .identifier; inline for (reserved_atoms) |a| { if (a.src.len == token.len and std.mem.eql(u8, a.src, token.str)) { token.tag = a.tag; break; } } return token; } pub const Lexer = struct { src: [:0]const u8, pos: usize = 0, cur_line: usize = 0, cur_col: usize = 0, pub fn get_next_token(l: *Lexer) !Token { var pos = l.pos; var line = l.cur_line; var col = l.cur_col; const src = l.src; var token = Token{ .tag = .end_of_file, .pos = pos, .len = 1, .data = null, .str = "" }; while (pos < src.len) { // skip whitespace while (pos < src.len and std.ascii.isSpace(src[pos])) { if (src[pos] == '\n') { line += 1; col = 0; } else { col += 1; } pos += 1; } // skip comments if (pos + 1 < src.len and src[pos] == '/' and src[pos + 1] == '/') { while (pos < src.len and src[pos] != '\n') { pos += 1; } line += 1; col = 0; pos += 1; } if (pos >= src.len) break; if (try match_numeric_literal(src, pos)) |t| { token = t; break; } if (try match_string_or_char_literal(src, pos)) |t| { token = t; break; } if (match_identifier_or_kwd(src, pos)) |t| { token = t; break; } if (match_op_or_sep(src, pos)) |t| { token = t; break; } pos += 1; col += 1; } token.line = line; token.col = col; l.pos = pos + token.len; l.cur_line = line; l.cur_col = col + token.len; return token; } }; pub fn tokenize(allocator: Allocator, src: [:0]const u8) ![]Token { var tokens = std.ArrayList(Token).init(allocator); errdefer tokens.deinit(); var l = Lexer{ .src = src }; while (l.pos <= l.src.len) { const t = try l.get_next_token(); try tokens.append(t); } log.debug("tokens:", .{}); for (tokens.items) |t| { log.debug("{?}", .{t}); } return tokens.toOwnedSlice(); } test "basic lexing" { const src = \\rand :: @import("std").rand; \\foo :: inline (x: int) -> int { \\ y := rand(); \\ if (y < 0.5) { \\ return x + 1; \\ } else { \\ // hot dog \\ print("hot dog\n"); \\ return x - 1; \\ } \\} ; var l = Lexer{ .src = src }; while (l.pos <= l.src.len) { const t = try l.get_next_token(); std.debug.warn("{}\n", .{t}); } } test "basic lexing into buffer" { const src = \\include rand; \\foo :: inline (x: int) -> int { \\ y := rand(); \\ if (y < 0.5) { \\ return x + 1; \\ } else { \\ // hot dog \\ print("hot dog\n"); \\ return x - 1; \\ } \\} ; var allocator = std.heap.GeneralPurposeAllocator(.{}){}; const gpa = allocator.allocator(); _ = try tokenize(gpa, src); } fn assert_match(src: [:0]const u8, tags: []const TokenId) !void { var l = Lexer{ .src = src }; var i: usize = 0; while (l.pos < l.src.len and i < tags.len) : (i += 1) { const t = try l.get_next_token(); std.debug.warn("{}\n", .{t}); if (t.tag != tags[i]) { std.debug.panic("expected {s}, got {s}\n", .{ tags[i], t.tag }); } } if (i == tags.len) std.debug.panic("reached end of string before finishing\n", .{}); } test "lex literals" { const src = \\0 1 1 0b10 0x29a 0o400 1.3 0.1 .32 1e2 9.42e-3 "hello\n" '0' ; const tags = &[_]TokenId{ .literal_int, .literal_int, .literal_int, .literal_bin, .literal_hex, .literal_oct, .literal_float, .literal_float, .literal_float, .literal_float, .literal_float, .literal_string, .literal_char, .end_of_file, }; try assert_match(src, tags[0..]); } test "lex identifiers" { const src = \\foo foo0 foo_ _foo _foo0 _foo _foo0_ foo_0 _foo_0_ _foo_0 foo_0_ ; const tags = &[_]TokenId{ .identifier, .identifier, .identifier, .identifier, .identifier, .identifier, .identifier, .identifier, .identifier, .identifier, .identifier, .end_of_file, }; try assert_match(src, tags[0..]); }
src/lexer.zig
const std = @import("std"); const mem = std.mem; pub const Alphabetic = @import("components/autogen/DerivedCoreProperties/Alphabetic.zig"); pub const CccMap = @import("components/autogen/DerivedCombiningClass/CccMap.zig"); pub const Control = @import("components/autogen/DerivedGeneralCategory/Control.zig"); pub const DecomposeMap = @import("components/autogen/UnicodeData/DecomposeMap.zig"); pub const Extend = @import("components/autogen/GraphemeBreakProperty/Extend.zig"); pub const ExtPic = @import("components/autogen/emoji-data/ExtendedPictographic.zig"); pub const Format = @import("components/autogen/DerivedGeneralCategory/Format.zig"); pub const HangulMap = @import("components/autogen/HangulSyllableType/HangulMap.zig"); pub const Prepend = @import("components/autogen/GraphemeBreakProperty/Prepend.zig"); pub const Regional = @import("components/autogen/GraphemeBreakProperty/RegionalIndicator.zig"); pub const Width = @import("components/aggregate/Width.zig"); // Letter pub const CaseFoldMap = @import("components/autogen/CaseFolding/CaseFoldMap.zig"); pub const CaseFold = CaseFoldMap.CaseFold; pub const Cased = @import("components/autogen/DerivedCoreProperties/Cased.zig"); pub const Lower = @import("components/autogen/DerivedGeneralCategory/LowercaseLetter.zig"); pub const LowerMap = @import("components/autogen/UnicodeData/LowerMap.zig"); pub const ModifierLetter = @import("components/autogen/DerivedGeneralCategory/ModifierLetter.zig"); pub const OtherLetter = @import("components/autogen/DerivedGeneralCategory/OtherLetter.zig"); pub const Title = @import("components/autogen/DerivedGeneralCategory/TitlecaseLetter.zig"); pub const TitleMap = @import("components/autogen/UnicodeData/TitleMap.zig"); pub const Upper = @import("components/autogen/DerivedGeneralCategory/UppercaseLetter.zig"); pub const UpperMap = @import("components/autogen/UnicodeData/UpperMap.zig"); // Mark pub const Enclosing = @import("components/autogen/DerivedGeneralCategory/EnclosingMark.zig"); pub const Nonspacing = @import("components/autogen/DerivedGeneralCategory/NonspacingMark.zig"); pub const Spacing = @import("components/autogen/DerivedGeneralCategory/SpacingMark.zig"); // Number pub const Decimal = @import("components/autogen/DerivedGeneralCategory/DecimalNumber.zig"); pub const Digit = @import("components/autogen/DerivedNumericType/Digit.zig"); pub const Hex = @import("components/autogen/PropList/HexDigit.zig"); pub const LetterNumber = @import("components/autogen/DerivedGeneralCategory/LetterNumber.zig"); pub const OtherNumber = @import("components/autogen/DerivedGeneralCategory/OtherNumber.zig"); // Punct pub const Close = @import("components/autogen/DerivedGeneralCategory/ClosePunctuation.zig"); pub const Connector = @import("components/autogen/DerivedGeneralCategory/ConnectorPunctuation.zig"); pub const Dash = @import("components/autogen/DerivedGeneralCategory/DashPunctuation.zig"); pub const Final = @import("components/autogen/UnicodeData/FinalPunctuation.zig"); pub const Initial = @import("components/autogen/DerivedGeneralCategory/InitialPunctuation.zig"); pub const Open = @import("components/autogen/DerivedGeneralCategory/OpenPunctuation.zig"); pub const OtherPunct = @import("components/autogen/DerivedGeneralCategory/OtherPunctuation.zig"); // Space pub const WhiteSpace = @import("components/autogen/PropList/WhiteSpace.zig"); pub const Space = @import("components/autogen/DerivedGeneralCategory/SpaceSeparator.zig"); // Symbol pub const Currency = @import("components/autogen/DerivedGeneralCategory/CurrencySymbol.zig"); pub const Math = @import("components/autogen/DerivedGeneralCategory/MathSymbol.zig"); pub const ModifierSymbol = @import("components/autogen/DerivedGeneralCategory/ModifierSymbol.zig"); pub const OtherSymbol = @import("components/autogen/DerivedGeneralCategory/OtherSymbol.zig"); // Width const Ambiguous = @import("components/autogen/DerivedEastAsianWidth/Ambiguous.zig"); const Fullwidth = @import("components/autogen/DerivedEastAsianWidth/Fullwidth.zig"); const Narrow = @import("components/autogen/DerivedEastAsianWidth/Narrow.zig"); const Wide = @import("components/autogen/DerivedEastAsianWidth/Wide.zig"); allocator: *mem.Allocator, alphabetic: ?Alphabetic = null, ccc_map: ?CccMap = null, control: ?Control = null, decomp_map: ?DecomposeMap = null, extend: ?Extend = null, extpic: ?ExtPic = null, format: ?Format = null, hangul_map: ?HangulMap = null, prepend: ?Prepend = null, regional: ?Regional = null, ambiguous: ?Ambiguous = null, fullwidth: ?Fullwidth = null, narrow: ?Narrow = null, wide: ?Wide = null, fold_map: ?CaseFoldMap = null, cased: ?Cased = null, lower: ?Lower = null, lower_map: ?LowerMap = null, modifier_letter: ?ModifierLetter = null, other_letter: ?OtherLetter = null, title: ?Title = null, title_map: ?TitleMap = null, upper: ?Upper = null, upper_map: ?UpperMap = null, enclosing: ?Enclosing = null, nonspacing: ?Nonspacing = null, spacing: ?Spacing = null, decimal: ?Decimal = null, digit: ?Digit = null, hex: ?Hex = null, letter_number: ?LetterNumber = null, other_number: ?OtherNumber = null, close: ?Close = null, connector: ?Connector = null, dash: ?Dash = null, final: ?Final = null, initial: ?Initial = null, open: ?Open = null, other_punct: ?OtherPunct = null, whitespace: ?WhiteSpace = null, space: ?Space = null, currency: ?Currency = null, math: ?Math = null, modifier_symbol: ?ModifierSymbol = null, other_symbol: ?OtherSymbol = null, const Self = @This(); pub fn init(allocator: *mem.Allocator) Self { return Self{ .allocator = allocator }; } pub fn deinit(self: *Self) void { if (self.alphabetic) |*alphabetic_| { alphabetic_.deinit(); } if (self.ccc_map) |*ccc_map_| { ccc_map_.deinit(); } if (self.control) |*control_| { control_.deinit(); } if (self.decomp_map) |*decomp_map_| { decomp_map_.deinit(); } if (self.extend) |*extend_| { extend_.deinit(); } if (self.extpic) |*extpic_| { extpic_.deinit(); } if (self.format) |*format_| { format_.deinit(); } if (self.hangul_map) |*hangul_map_| { hangul_map_.deinit(); } if (self.prepend) |*prepend_| { prepend_.deinit(); } if (self.regional) |*regional_| { regional_.deinit(); } if (self.fold_map) |*fold_map_| { fold_map_.deinit(); } if (self.cased) |*cased_| { cased_.deinit(); } if (self.lower) |*lower_| { lower_.deinit(); } if (self.lower_map) |*lower_map_| { lower_map_.deinit(); } if (self.modifier_letter) |*modifier_letter_| { modifier_letter_.deinit(); } if (self.other_letter) |*other_letter_| { other_letter_.deinit(); } if (self.title) |*title_| { title_.deinit(); } if (self.title_map) |*title_map_| { title_map_.deinit(); } if (self.upper) |*upper_| { upper_.deinit(); } if (self.upper_map) |*upper_map_| { upper_map_.deinit(); } if (self.enclosing) |*enclosing_| { enclosing_.deinit(); } if (self.nonspacing) |*nonspacing_| { nonspacing_.deinit(); } if (self.spacing) |*spacing_| { spacing_.deinit(); } if (self.decimal) |*decimal_| { decimal_.deinit(); } if (self.digit) |*digit_| { digit_.deinit(); } if (self.hex) |*hex_| { hex_.deinit(); } if (self.letter_number) |*letter_number_| { letter_number_.deinit(); } if (self.other_number) |*other_number_| { other_number_.deinit(); } if (self.close) |*close_| { close_.deinit(); } if (self.connector) |*connector_| { connector_.deinit(); } if (self.dash) |*dash_| { dash_.deinit(); } if (self.final) |*final_| { final_.deinit(); } if (self.initial) |*initial_| { initial_.deinit(); } if (self.open) |*open_| { open_.deinit(); } if (self.other_punct) |*other_punct_| { other_punct_.deinit(); } if (self.whitespace) |*whitespace_| { whitespace_.deinit(); } if (self.space) |*space_| { space_.deinit(); } if (self.currency) |*currency_| { currency_.deinit(); } if (self.math) |*math_| { math_.deinit(); } if (self.modifier_symbol) |*modifier_symbol_| { modifier_symbol_.deinit(); } if (self.other_symbol) |*other_symbol_| { other_symbol_.deinit(); } if (self.fullwidth) |*fullwidth_| { fullwidth_.deinit(); } if (self.narrow) |*narrow_| { narrow_.deinit(); } if (self.wide) |*wide_| { wide_.deinit(); } if (self.ambiguous) |*ambiguous| { ambiguous.deinit(); } } pub fn getAlphabetic(self: *Self) !*Alphabetic { if (self.alphabetic) |*alphabetic| { return alphabetic; } else { self.alphabetic = try Alphabetic.init(self.allocator); return &self.alphabetic.?; } } pub fn getCccMap(self: *Self) !*CccMap { if (self.ccc_map) |*ccc_map| { return ccc_map; } else { self.ccc_map = try CccMap.init(self.allocator); return &self.ccc_map.?; } } pub fn getControl(self: *Self) !*Control { if (self.control) |*control| { return control; } else { self.control = try Control.init(self.allocator); return &self.control.?; } } pub fn getDecomposeMap(self: *Self) !*DecomposeMap { if (self.decomp_map) |*decomp_map| { return decomp_map; } else { self.decomp_map = try DecomposeMap.init(self.allocator); return &self.decomp_map.?; } } pub fn getExtend(self: *Self) !*Extend { if (self.extend) |*extend| { return extend; } else { self.extend = try Extend.init(self.allocator); return &self.extend.?; } } pub fn getExtPic(self: *Self) !*ExtPic { if (self.extpic) |*extpic| { return extpic; } else { self.extpic = try ExtPic.init(self.allocator); return &self.extpic.?; } } pub fn getFormat(self: *Self) !*Format { if (self.format) |*format| { return format; } else { self.format = try Format.init(self.allocator); return &self.format.?; } } pub fn getHangulMap(self: *Self) !*HangulMap { if (self.hangul_map) |*hangul_map| { return hangul_map; } else { self.hangul_map = try HangulMap.init(self.allocator); return &self.hangul_map.?; } } pub fn getPrepend(self: *Self) !*Prepend { if (self.prepend) |*prepend| { return prepend; } else { self.prepend = try Prepend.init(self.allocator); return &self.prepend.?; } } pub fn getRegional(self: *Self) !*Regional { if (self.regional) |*regional| { return regional; } else { self.regional = try Regional.init(self.allocator); return &self.regional.?; } } pub fn getCaseFoldMap(self: *Self) !*CaseFoldMap { if (self.fold_map) |*fold_map| { return fold_map; } else { self.fold_map = try CaseFoldMap.init(self.allocator); return &self.fold_map.?; } } pub fn getCased(self: *Self) !*Cased { if (self.cased) |*cased| { return cased; } else { self.cased = try Cased.init(self.allocator); return &self.cased.?; } } pub fn getLower(self: *Self) !*Lower { if (self.lower) |*lower| { return lower; } else { self.lower = try Lower.init(self.allocator); return &self.lower.?; } } pub fn getLowerMap(self: *Self) !*LowerMap { if (self.lower_map) |*lower_map| { return lower_map; } else { self.lower_map = try LowerMap.init(self.allocator); return &self.lower_map.?; } } pub fn getModifierLetter(self: *Self) !*ModifierLetter { if (self.modifier_letter) |*modifier_letter| { return modifier_letter; } else { self.modifier_letter = try ModifierLetter.init(self.allocator); return &self.modifier_letter.?; } } pub fn getOtherLetter(self: *Self) !*OtherLetter { if (self.other_letter) |*other_letter| { return other_letter; } else { self.other_letter = try OtherLetter.init(self.allocator); return &self.other_letter.?; } } pub fn getTitle(self: *Self) !*Title { if (self.title) |*title| { return title; } else { self.title = try Title.init(self.allocator); return &self.title.?; } } pub fn getTitleMap(self: *Self) !*TitleMap { if (self.title_map) |*title_map| { return title_map; } else { self.title_map = try TitleMap.init(self.allocator); return &self.title_map.?; } } pub fn getUpper(self: *Self) !*Upper { if (self.upper) |*upper| { return upper; } else { self.upper = try Upper.init(self.allocator); return &self.upper.?; } } pub fn getUpperMap(self: *Self) !*UpperMap { if (self.upper_map) |*upper_map| { return upper_map; } else { self.upper_map = try UpperMap.init(self.allocator); return &self.upper_map.?; } } pub fn getEnclosing(self: *Self) !*Enclosing { if (self.enclosing) |*enclosing| { return enclosing; } else { self.enclosing = try Enclosing.init(self.allocator); return &self.enclosing.?; } } pub fn getNonspacing(self: *Self) !*Nonspacing { if (self.nonspacing) |*nonspacing| { return nonspacing; } else { self.nonspacing = try Nonspacing.init(self.allocator); return &self.nonspacing.?; } } pub fn getSpacing(self: *Self) !*Spacing { if (self.spacing) |*spacing| { return spacing; } else { self.spacing = try Spacing.init(self.allocator); return &self.spacing.?; } } pub fn getDecimal(self: *Self) !*Decimal { if (self.decimal) |*decimal| { return decimal; } else { self.decimal = try Decimal.init(self.allocator); return &self.decimal.?; } } pub fn getDigit(self: *Self) !*Digit { if (self.digit) |*digit| { return digit; } else { self.digit = try Digit.init(self.allocator); return &self.digit.?; } } pub fn getHex(self: *Self) !*Hex { if (self.hex) |*hex| { return hex; } else { self.hex = try Hex.init(self.allocator); return &self.hex.?; } } pub fn getLetterNumber(self: *Self) !*LetterNumber { if (self.letter_number) |*letter_number| { return letter_number; } else { self.letter_number = try LetterNumber.init(self.allocator); return &self.letter_number.?; } } pub fn getOtherNumber(self: *Self) !*OtherNumber { if (self.other_number) |*other_number| { return other_number; } else { self.other_number = try OtherNumber.init(self.allocator); return &self.other_number.?; } } pub fn getClose(self: *Self) !*Close { if (self.close) |*close| { return close; } else { self.close = try Close.init(self.allocator); return &self.close.?; } } pub fn getConnector(self: *Self) !*Connector { if (self.connector) |*connector| { return connector; } else { self.connector = try Connector.init(self.allocator); return &self.connector.?; } } pub fn getDash(self: *Self) !*Dash { if (self.dash) |*dash| { return dash; } else { self.dash = try Dash.init(self.allocator); return &self.dash.?; } } pub fn getFinal(self: *Self) !*Final { if (self.final) |*final| { return final; } else { self.final = try Final.init(self.allocator); return &self.final.?; } } pub fn getInitial(self: *Self) !*Initial { if (self.initial) |*initial| { return initial; } else { self.initial = try Initial.init(self.allocator); return &self.initial.?; } } pub fn getOpen(self: *Self) !*Open { if (self.open) |*open| { return open; } else { self.open = try Open.init(self.allocator); return &self.open.?; } } pub fn getOtherPunct(self: *Self) !*OtherPunct { if (self.other_punct) |*other_punct| { return other_punct; } else { self.other_punct = try OtherPunct.init(self.allocator); return &self.other_punct.?; } } pub fn getWhiteSpace(self: *Self) !*WhiteSpace { if (self.whitespace) |*whitespace| { return whitespace; } else { self.whitespace = try WhiteSpace.init(self.allocator); return &self.whitespace.?; } } pub fn getSpace(self: *Self) !*Space { if (self.space) |*space| { return space; } else { self.space = try Space.init(self.allocator); return &self.space.?; } } pub fn getCurrency(self: *Self) !*Currency { if (self.currency) |*currency| { return currency; } else { self.currency = try Currency.init(self.allocator); return &self.currency.?; } } pub fn getMath(self: *Self) !*Math { if (self.math) |*math| { return math; } else { self.math = try Math.init(self.allocator); return &self.math.?; } } pub fn getModifierSymbol(self: *Self) !*ModifierSymbol { if (self.modifier_symbol) |*modifier_symbol| { return modifier_symbol; } else { self.modifier_symbol = try ModifierSymbol.init(self.allocator); return &self.modifier_symbol.?; } } pub fn getOtherSymbol(self: *Self) !*OtherSymbol { if (self.other_symbol) |*other_symbol| { return other_symbol; } else { self.other_symbol = try OtherSymbol.init(self.allocator); return &self.other_symbol.?; } } pub fn getFullwidth(self: *Self) !*Fullwidth { if (self.fullwidth) |*fullwidth| { return fullwidth; } else { self.fullwidth = try Fullwidth.init(self.allocator); return &self.fullwidth.?; } } pub fn getNarrow(self: *Self) !*Narrow { if (self.narrow) |*narrow| { return narrow; } else { self.narrow = try Narrow.init(self.allocator); return &self.narrow.?; } } pub fn getWide(self: *Self) !*Wide { if (self.wide) |*wide| { return wide; } else { self.wide = try Wide.init(self.allocator); return &self.wide.?; } } pub fn getAmbiguous(self: *Self) !*Ambiguous { if (self.ambiguous) |*ambiguous| { return ambiguous; } else { self.ambiguous = try Ambiguous.init(self.allocator); return &self.ambiguous.?; } }
src/Context.zig
const print = @import("std").debug.print; // As mentioned before, we'll soon understand why these two // numbers don't need explicit types. Hang in there! const ingredients = 4; const foods = 4; const Food = struct { name: []const u8, requires: [ingredients]bool, }; // Chili Macaroni Tomato Sauce Cheese // ------------------------------------------------------ // Mac & Cheese x x // Chili Mac x x // Pasta x x // Cheesy Chili x x // ------------------------------------------------------ const menu: [foods]Food = [_]Food{ Food{ .name = "Mac & Cheese", .requires = [ingredients]bool{ false, true, false, true }, }, Food{ .name = "Chili Mac", .requires = [ingredients]bool{ true, true, false, false }, }, Food{ .name = "Pasta", .requires = [ingredients]bool{ false, true, true, false }, }, Food{ .name = "Cheesy Chili", .requires = [ingredients]bool{ true, false, false, true }, }, }; pub fn main() void { // Welcome to Cafeteria USA! Choose your favorite ingredients // and we'll produce a delicious meal. // // Cafeteria Customer Note: Not all ingredient combinations // make a meal. The default meal is macaroni and cheese. // // Software Developer Note: Hard-coding the ingredient // numbers (based on array position) will be fine for our // tiny example, but it would be downright criminal in a real // application! const wanted_ingredients = [_]u8{ 0, 3 }; // Chili, Cheese // Look at each Food on the menu... var meal = food_loop: for (menu) |food| { // Now look at each required ingredient for the Food... for (food.requires) |required, required_ingredient| { // This ingredient isn't required, so skip it. if (!required) continue; // See if the customer wanted this ingredient. // (Remember that want_it will be the index number of // the ingredient based on its position in the // required ingredient list for each food.) var found = for (wanted_ingredients) |want_it| { if (required_ingredient == want_it) break true; } else false; // We did not find this required ingredient, so we // can't make this Food. Continue the outer loop. if (!found) continue :food_loop; } // If we get this far, the required ingredients were all // wanted for this Food. // // Please return this Food from the loop. break :food_loop food; } else menu[0]; // ^ Oops! We forgot to return Mac & Cheese as the default // Food when the requested ingredients aren't found. print("Enjoy your {s}!\n", .{meal.name}); } // Challenge: You can also do away with the 'found' variable in // the inner loop. See if you can figure out how to do that!
exercises/063_labels.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const StringHashMap = std.StringHashMap; const interface = @import("interface.zig"); //; // is there a way to use command ids, less error prone // dont really like the "stringly typed" aspect // its not so bad, i think the alternatives are kindof complicated // TODO maybe namespace Arg_ ? // TODO maybe have more precice types, f32 f64, etc pub const ArgValue = union(enum) { Symbol: []const u8, Int: i64, Float: f64, Boolean: bool, }; pub const ArgType = @TagType(ArgValue); pub const ArgDef = struct { ty: ArgType, name: []const u8 = "", default: ?ArgValue = null, }; pub const CommandDef = struct { name: []const u8, info: []const u8 = "", arg_defs: []const ArgDef, listener_ids: []const CommandLine.ListenerId, }; pub const AliasDef = struct { name: []const u8, real_name: []const u8, // command_def: *const CommandDef, }; pub const Listener = struct { pub const VTable = struct { listen: fn (Listener, []const u8, []const ArgValue) void, }; impl: interface.Impl, vtable: *const VTable, pub fn init(impl: interface.Impl, vtable: *const VTable) Self { return .{ .id = undefined, .impl = impl, .vtable = vtable, }; } }; pub const CommandLine = struct { pub const Self = @This(); pub const Error = error{DuplicateName} || Allocator.Error; pub const ListenerId = usize; listeners: ArrayList(Listener), command_defs: StringHashMap(CommandDef), arg_values: ArrayList(ArgValue), pub fn init(allocator: *Allocator) Self { return .{ .listeners = ArrayList(Listener).init(allocator), .command_defs = StringHashMap(CommandDef).init(allocator), .arg_values = ArrayList(ArgValue).init(allocator), }; } pub fn deinit(self: *Self) void { self.arg_values.deinit(); self.command_defs.deinit(); self.listeners.deinit(); } //; // TODO this autogenerates listener ids // obviously less error prone, but is it as useful as being able to choose them yourself // basically you cant create commands for listeners that dont exist yet pub fn addListener(self: *Self, listener: Listener) Allocator.Error!ListenerId { const id = self.listeners.items.len; try self.listeners.append(listener); return id; } pub fn addCommandDef(self: *Self, def: CommandDef) Error!void { if (self.command_defs.contains(def.name)) { return error.DuplicateName; } try self.command_defs.putNoClobber(def.name, def); } pub fn run(self: *Self, str: []const u8) !void { var iter = std.mem.tokenize(str, " "); const command = iter.next() orelse return error.InvalidCommand; const command_def = self.command_defs.get(command) orelse return error.CommandNotFound; self.arg_values.items.len = 0; for (command_def.arg_defs) |arg_def, i| { if (iter.next()) |token| { try self.arg_values.append(switch (arg_def.ty) { .Symbol => .{ .Symbol = token }, .Int => .{ .Int = try std.fmt.parseInt(i64, token, 10) }, .Float => .{ .Float = try std.fmt.parseFloat(f64, token) }, .Boolean => .{ .Boolean = if (std.mem.eql(u8, token, "#t")) blk: { break :blk true; } else if (std.mem.eql(u8, token, "#f")) blk: { break :blk false; } else { return error.InvalidValue; }, }, }); } else { try self.arg_values.append(arg_def.default orelse return error.MissingValue); } } for (command_def.listener_ids) |id| { var listener = self.listeners.items[id]; listener.vtable.listen(listener, command, self.arg_values.items); } } }; // tests === const testing = std.testing; const expect = testing.expect; const Global = struct { const Self = @This(); x: u8, y: bool, //; fn listener(self: *Self) Listener { return .{ .impl = interface.Impl.init(self), .vtable = &comptime Listener.VTable{ .listen = listen, }, }; } fn listen( l: Listener, msg: []const u8, args: []const ArgValue, ) void { var self = l.impl.cast(Self); if (std.mem.eql(u8, msg, "do-x")) { self.x = @intCast(u8, args[0].Int); } if (std.mem.eql(u8, msg, "do-y")) { self.y = args[0].Boolean; } } }; test "cmd CommandLine" { var g: Global = .{ .x = 0, .y = false, }; var cmd = CommandLine.init(testing.allocator); defer cmd.deinit(); const g_id = try cmd.addListener(g.listener()); try cmd.addCommandDef(.{ .name = "do-x", .arg_defs = &[_]ArgDef{ .{ .ty = .Int, .name = "number", }, }, .listener_ids = &[_]CommandLine.ListenerId{ g_id, }, }); try cmd.addCommandDef(.{ .name = "do-y", .arg_defs = &[_]ArgDef{ .{ .ty = .Boolean, .name = "t/f value", }, }, .listener_ids = &[_]CommandLine.ListenerId{ g_id, }, }); expect(g.x == 0); try cmd.run("do-x 1"); expect(g.x == 1); expect(!g.y); try cmd.run("do-y #t"); expect(g.y); }
src/cmd.zig