code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std.zig"); const math = std.math; const mem = std.mem; const io = std.io; const os = std.os; const fs = std.fs; const process = std.process; const elf = std.elf; const DW = std.dwarf; const macho = std.macho; const coff = std.coff; const pdb = std.pdb; const ArrayList = std.ArrayList; const builtin = @import("builtin"); const root = @import("root"); const maxInt = std.math.maxInt; const File = std.fs.File; const windows = std.os.windows; pub const leb = @import("debug/leb128.zig"); pub const FailingAllocator = @import("debug/failing_allocator.zig").FailingAllocator; pub const failing_allocator = &FailingAllocator.init(global_allocator, 0).allocator; pub const runtime_safety = switch (builtin.mode) { .Debug, .ReleaseSafe => true, .ReleaseFast, .ReleaseSmall => false, }; const Module = struct { mod_info: pdb.ModInfo, module_name: []u8, obj_file_name: []u8, populated: bool, symbols: []u8, subsect_info: []u8, checksum_offset: ?usize, }; /// Tries to write to stderr, unbuffered, and ignores any error returned. /// Does not append a newline. var stderr_file: File = undefined; var stderr_file_out_stream: File.OutStream = undefined; var stderr_stream: ?*io.OutStream(File.WriteError) = null; var stderr_mutex = std.Mutex.init(); pub fn warn(comptime fmt: []const u8, args: var) void { const held = stderr_mutex.acquire(); defer held.release(); const stderr = getStderrStream(); stderr.print(fmt, args) catch return; } pub fn getStderrStream() *io.OutStream(File.WriteError) { if (stderr_stream) |st| { return st; } else { stderr_file = io.getStdErr(); stderr_file_out_stream = stderr_file.outStream(); const st = &stderr_file_out_stream.stream; stderr_stream = st; return st; } } pub fn getStderrMutex() *std.Mutex { return &stderr_mutex; } /// TODO multithreaded awareness var self_debug_info: ?DebugInfo = null; pub fn getSelfDebugInfo() !*DebugInfo { if (self_debug_info) |*info| { return info; } else { self_debug_info = try openSelfDebugInfo(getDebugInfoAllocator()); return &self_debug_info.?; } } fn wantTtyColor() bool { var bytes: [128]u8 = undefined; const allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator; return if (process.getEnvVarOwned(allocator, "ZIG_DEBUG_COLOR")) |_| true else |_| stderr_file.isTty(); } /// Tries to print the current stack trace to stderr, unbuffered, and ignores any error returned. /// TODO multithreaded awareness pub fn dumpCurrentStackTrace(start_addr: ?usize) void { const stderr = getStderrStream(); if (builtin.strip_debug_info) { stderr.print("Unable to dump stack trace: debug info stripped\n", .{}) catch return; return; } const debug_info = getSelfDebugInfo() catch |err| { stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", .{@errorName(err)}) catch return; return; }; writeCurrentStackTrace(stderr, debug_info, wantTtyColor(), start_addr) catch |err| { stderr.print("Unable to dump stack trace: {}\n", .{@errorName(err)}) catch return; return; }; } /// Tries to print the stack trace starting from the supplied base pointer to stderr, /// unbuffered, and ignores any error returned. /// TODO multithreaded awareness pub fn dumpStackTraceFromBase(bp: usize, ip: usize) void { const stderr = getStderrStream(); if (builtin.strip_debug_info) { stderr.print("Unable to dump stack trace: debug info stripped\n", .{}) catch return; return; } const debug_info = getSelfDebugInfo() catch |err| { stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", .{@errorName(err)}) catch return; return; }; const tty_color = wantTtyColor(); printSourceAtAddress(debug_info, stderr, ip, tty_color) catch return; const first_return_address = @intToPtr(*const usize, bp + @sizeOf(usize)).*; printSourceAtAddress(debug_info, stderr, first_return_address - 1, tty_color) catch return; var it = StackIterator{ .first_addr = null, .fp = bp, }; while (it.next()) |return_address| { printSourceAtAddress(debug_info, stderr, return_address - 1, tty_color) catch return; } } /// Returns a slice with the same pointer as addresses, with a potentially smaller len. /// On Windows, when first_address is not null, we ask for at least 32 stack frames, /// and then try to find the first address. If addresses.len is more than 32, we /// capture that many stack frames exactly, and then look for the first address, /// chopping off the irrelevant frames and shifting so that the returned addresses pointer /// equals the passed in addresses pointer. pub fn captureStackTrace(first_address: ?usize, stack_trace: *builtin.StackTrace) void { if (builtin.os == .windows) { const addrs = stack_trace.instruction_addresses; const u32_addrs_len = @intCast(u32, addrs.len); const first_addr = first_address orelse { stack_trace.index = windows.ntdll.RtlCaptureStackBackTrace( 0, u32_addrs_len, @ptrCast(**c_void, addrs.ptr), null, ); return; }; var addr_buf_stack: [32]usize = undefined; const addr_buf = if (addr_buf_stack.len > addrs.len) addr_buf_stack[0..] else addrs; const n = windows.ntdll.RtlCaptureStackBackTrace(0, u32_addrs_len, @ptrCast(**c_void, addr_buf.ptr), null); const first_index = for (addr_buf[0..n]) |addr, i| { if (addr == first_addr) { break i; } } else { stack_trace.index = 0; return; }; const slice = addr_buf[first_index..n]; // We use a for loop here because slice and addrs may alias. for (slice) |addr, i| { addrs[i] = addr; } stack_trace.index = slice.len; } else { var it = StackIterator.init(first_address); for (stack_trace.instruction_addresses) |*addr, i| { addr.* = it.next() orelse { stack_trace.index = i; return; }; } stack_trace.index = stack_trace.instruction_addresses.len; } } /// Tries to print a stack trace to stderr, unbuffered, and ignores any error returned. /// TODO multithreaded awareness pub fn dumpStackTrace(stack_trace: builtin.StackTrace) void { const stderr = getStderrStream(); if (builtin.strip_debug_info) { stderr.print("Unable to dump stack trace: debug info stripped\n", .{}) catch return; return; } const debug_info = getSelfDebugInfo() catch |err| { stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", .{@errorName(err)}) catch return; return; }; writeStackTrace(stack_trace, stderr, getDebugInfoAllocator(), debug_info, wantTtyColor()) catch |err| { stderr.print("Unable to dump stack trace: {}\n", .{@errorName(err)}) catch return; return; }; } /// This function invokes undefined behavior when `ok` is `false`. /// In Debug and ReleaseSafe modes, calls to this function are always /// generated, and the `unreachable` statement triggers a panic. /// In ReleaseFast and ReleaseSmall modes, calls to this function are /// optimized away, and in fact the optimizer is able to use the assertion /// in its heuristics. /// Inside a test block, it is best to use the `std.testing` module rather /// than this function, because this function may not detect a test failure /// in ReleaseFast and ReleaseSmall mode. Outside of a test block, this assert /// function is the correct function to use. pub fn assert(ok: bool) void { if (!ok) unreachable; // assertion failure } pub fn panic(comptime format: []const u8, args: var) noreturn { @setCold(true); // TODO: remove conditional once wasi / LLVM defines __builtin_return_address const first_trace_addr = if (builtin.os == .wasi) null else @returnAddress(); panicExtra(null, first_trace_addr, format, args); } /// TODO multithreaded awareness var panicking: u8 = 0; // TODO make this a bool pub fn panicExtra(trace: ?*const builtin.StackTrace, first_trace_addr: ?usize, comptime format: []const u8, args: var) noreturn { @setCold(true); if (enable_segfault_handler) { // If a segfault happens while panicking, we want it to actually segfault, not trigger // the handler. resetSegfaultHandler(); } if (@atomicRmw(u8, &panicking, builtin.AtomicRmwOp.Xchg, 1, builtin.AtomicOrder.SeqCst) == 1) { // Panicked during a panic. // TODO detect if a different thread caused the panic, because in that case // we would want to return here instead of calling abort, so that the thread // which first called panic can finish printing a stack trace. os.abort(); } const stderr = getStderrStream(); stderr.print(format ++ "\n", args) catch os.abort(); if (trace) |t| { dumpStackTrace(t.*); } dumpCurrentStackTrace(first_trace_addr); os.abort(); } const RED = "\x1b[31;1m"; const GREEN = "\x1b[32;1m"; const CYAN = "\x1b[36;1m"; const WHITE = "\x1b[37;1m"; const DIM = "\x1b[2m"; const RESET = "\x1b[0m"; pub fn writeStackTrace( stack_trace: builtin.StackTrace, out_stream: var, allocator: *mem.Allocator, debug_info: *DebugInfo, tty_color: bool, ) !void { if (builtin.strip_debug_info) return error.MissingDebugInfo; var frame_index: usize = 0; var frames_left: usize = std.math.min(stack_trace.index, stack_trace.instruction_addresses.len); while (frames_left != 0) : ({ frames_left -= 1; frame_index = (frame_index + 1) % stack_trace.instruction_addresses.len; }) { const return_address = stack_trace.instruction_addresses[frame_index]; try printSourceAtAddress(debug_info, out_stream, return_address - 1, tty_color); } } pub const StackIterator = struct { first_addr: ?usize, fp: usize, pub fn init(first_addr: ?usize) StackIterator { return StackIterator{ .first_addr = first_addr, .fp = @frameAddress(), }; } // On some architectures such as x86 the frame pointer is the address where // the previous fp is stored, while on some other architectures such as // RISC-V it points to the "top" of the frame, just above where the previous // fp and the return address are stored. const fp_adjust_factor = if (builtin.arch == .riscv32 or builtin.arch == .riscv64) 2 * @sizeOf(usize) else 0; fn next(self: *StackIterator) ?usize { if (self.fp <= fp_adjust_factor) return null; self.fp = @intToPtr(*const usize, self.fp - fp_adjust_factor).*; if (self.fp <= fp_adjust_factor) return null; if (self.first_addr) |addr| { while (self.fp > fp_adjust_factor) : (self.fp = @intToPtr(*const usize, self.fp - fp_adjust_factor).*) { const return_address = @intToPtr(*const usize, self.fp - fp_adjust_factor + @sizeOf(usize)).*; if (addr == return_address) { self.first_addr = null; return return_address; } } } const return_address = @intToPtr(*const usize, self.fp - fp_adjust_factor + @sizeOf(usize)).*; return return_address; } }; pub fn writeCurrentStackTrace(out_stream: var, debug_info: *DebugInfo, tty_color: bool, start_addr: ?usize) !void { if (builtin.os == .windows) { return writeCurrentStackTraceWindows(out_stream, debug_info, tty_color, start_addr); } var it = StackIterator.init(start_addr); while (it.next()) |return_address| { try printSourceAtAddress(debug_info, out_stream, return_address - 1, tty_color); } } pub fn writeCurrentStackTraceWindows( out_stream: var, debug_info: *DebugInfo, tty_color: bool, start_addr: ?usize, ) !void { var addr_buf: [1024]usize = undefined; const n = windows.ntdll.RtlCaptureStackBackTrace(0, addr_buf.len, @ptrCast(**c_void, &addr_buf), null); const addrs = addr_buf[0..n]; var start_i: usize = if (start_addr) |saddr| blk: { for (addrs) |addr, i| { if (addr == saddr) break :blk i; } return; } else 0; for (addrs[start_i..]) |addr| { try printSourceAtAddress(debug_info, out_stream, addr, tty_color); } } /// TODO once https://github.com/ziglang/zig/issues/3157 is fully implemented, /// make this `noasync fn` and remove the individual noasync calls. pub fn printSourceAtAddress(debug_info: *DebugInfo, out_stream: var, address: usize, tty_color: bool) !void { if (builtin.os == .windows) { return noasync printSourceAtAddressWindows(debug_info, out_stream, address, tty_color); } if (comptime std.Target.current.isDarwin()) { return noasync printSourceAtAddressMacOs(debug_info, out_stream, address, tty_color); } return noasync printSourceAtAddressPosix(debug_info, out_stream, address, tty_color); } fn printSourceAtAddressWindows(di: *DebugInfo, out_stream: var, relocated_address: usize, tty_color: bool) !void { const allocator = getDebugInfoAllocator(); const base_address = process.getBaseAddress(); const relative_address = relocated_address - base_address; var coff_section: *coff.Section = undefined; const mod_index = for (di.sect_contribs) |sect_contrib| { if (sect_contrib.Section > di.coff.sections.len) continue; // Remember that SectionContribEntry.Section is 1-based. coff_section = &di.coff.sections.toSlice()[sect_contrib.Section - 1]; const vaddr_start = coff_section.header.virtual_address + sect_contrib.Offset; const vaddr_end = vaddr_start + sect_contrib.Size; if (relative_address >= vaddr_start and relative_address < vaddr_end) { break sect_contrib.ModuleIndex; } } else { // we have no information to add to the address if (tty_color) { try out_stream.print("???:?:?: ", .{}); setTtyColor(TtyColor.Dim); try out_stream.print("0x{x} in ??? (???)", .{relocated_address}); setTtyColor(TtyColor.Reset); try out_stream.print("\n\n\n", .{}); } else { try out_stream.print("???:?:?: 0x{x} in ??? (???)\n\n\n", .{relocated_address}); } return; }; const mod = &di.modules[mod_index]; try populateModule(di, mod); const obj_basename = fs.path.basename(mod.obj_file_name); var symbol_i: usize = 0; const symbol_name = if (!mod.populated) "???" else while (symbol_i != mod.symbols.len) { const prefix = @ptrCast(*pdb.RecordPrefix, &mod.symbols[symbol_i]); if (prefix.RecordLen < 2) return error.InvalidDebugInfo; switch (prefix.RecordKind) { pdb.SymbolKind.S_LPROC32 => { const proc_sym = @ptrCast(*pdb.ProcSym, &mod.symbols[symbol_i + @sizeOf(pdb.RecordPrefix)]); const vaddr_start = coff_section.header.virtual_address + proc_sym.CodeOffset; const vaddr_end = vaddr_start + proc_sym.CodeSize; if (relative_address >= vaddr_start and relative_address < vaddr_end) { break mem.toSliceConst(u8, @ptrCast([*:0]u8, proc_sym) + @sizeOf(pdb.ProcSym)); } }, else => {}, } symbol_i += prefix.RecordLen + @sizeOf(u16); if (symbol_i > mod.symbols.len) return error.InvalidDebugInfo; } else "???"; const subsect_info = mod.subsect_info; var sect_offset: usize = 0; var skip_len: usize = undefined; const opt_line_info = subsections: { const checksum_offset = mod.checksum_offset orelse break :subsections null; while (sect_offset != subsect_info.len) : (sect_offset += skip_len) { const subsect_hdr = @ptrCast(*pdb.DebugSubsectionHeader, &subsect_info[sect_offset]); skip_len = subsect_hdr.Length; sect_offset += @sizeOf(pdb.DebugSubsectionHeader); switch (subsect_hdr.Kind) { pdb.DebugSubsectionKind.Lines => { var line_index = sect_offset; const line_hdr = @ptrCast(*pdb.LineFragmentHeader, &subsect_info[line_index]); if (line_hdr.RelocSegment == 0) return error.MissingDebugInfo; line_index += @sizeOf(pdb.LineFragmentHeader); const frag_vaddr_start = coff_section.header.virtual_address + line_hdr.RelocOffset; const frag_vaddr_end = frag_vaddr_start + line_hdr.CodeSize; if (relative_address >= frag_vaddr_start and relative_address < frag_vaddr_end) { // There is an unknown number of LineBlockFragmentHeaders (and their accompanying line and column records) // from now on. We will iterate through them, and eventually find a LineInfo that we're interested in, // breaking out to :subsections. If not, we will make sure to not read anything outside of this subsection. const subsection_end_index = sect_offset + subsect_hdr.Length; while (line_index < subsection_end_index) { const block_hdr = @ptrCast(*pdb.LineBlockFragmentHeader, &subsect_info[line_index]); line_index += @sizeOf(pdb.LineBlockFragmentHeader); const start_line_index = line_index; const has_column = line_hdr.Flags.LF_HaveColumns; // All line entries are stored inside their line block by ascending start address. // Heuristic: we want to find the last line entry that has a vaddr_start <= relative_address. // This is done with a simple linear search. var line_i: u32 = 0; while (line_i < block_hdr.NumLines) : (line_i += 1) { const line_num_entry = @ptrCast(*pdb.LineNumberEntry, &subsect_info[line_index]); line_index += @sizeOf(pdb.LineNumberEntry); const vaddr_start = frag_vaddr_start + line_num_entry.Offset; if (relative_address <= vaddr_start) { break; } } // line_i == 0 would mean that no matching LineNumberEntry was found. if (line_i > 0) { const subsect_index = checksum_offset + block_hdr.NameIndex; const chksum_hdr = @ptrCast(*pdb.FileChecksumEntryHeader, &mod.subsect_info[subsect_index]); const strtab_offset = @sizeOf(pdb.PDBStringTableHeader) + chksum_hdr.FileNameOffset; try di.pdb.string_table.seekTo(strtab_offset); const source_file_name = try di.pdb.string_table.readNullTermString(allocator); const line_entry_idx = line_i - 1; const column = if (has_column) blk: { const start_col_index = start_line_index + @sizeOf(pdb.LineNumberEntry) * block_hdr.NumLines; const col_index = start_col_index + @sizeOf(pdb.ColumnNumberEntry) * line_entry_idx; const col_num_entry = @ptrCast(*pdb.ColumnNumberEntry, &subsect_info[col_index]); break :blk col_num_entry.StartColumn; } else 0; const found_line_index = start_line_index + line_entry_idx * @sizeOf(pdb.LineNumberEntry); const line_num_entry = @ptrCast(*pdb.LineNumberEntry, &subsect_info[found_line_index]); const flags = @ptrCast(*pdb.LineNumberEntry.Flags, &line_num_entry.Flags); break :subsections LineInfo{ .allocator = allocator, .file_name = source_file_name, .line = flags.Start, .column = column, }; } } // Checking that we are not reading garbage after the (possibly) multiple block fragments. if (line_index != subsection_end_index) { return error.InvalidDebugInfo; } } }, else => {}, } if (sect_offset > subsect_info.len) return error.InvalidDebugInfo; } else { break :subsections null; } }; if (tty_color) { setTtyColor(TtyColor.White); if (opt_line_info) |li| { try out_stream.print("{}:{}:{}", .{ li.file_name, li.line, li.column }); } else { try out_stream.print("???:?:?", .{}); } setTtyColor(TtyColor.Reset); try out_stream.print(": ", .{}); setTtyColor(TtyColor.Dim); try out_stream.print("0x{x} in {} ({})", .{ relocated_address, symbol_name, obj_basename }); setTtyColor(TtyColor.Reset); if (opt_line_info) |line_info| { try out_stream.print("\n", .{}); if (printLineFromFileAnyOs(out_stream, line_info)) { if (line_info.column == 0) { try out_stream.write("\n"); } else { { var col_i: usize = 1; while (col_i < line_info.column) : (col_i += 1) { try out_stream.writeByte(' '); } } setTtyColor(TtyColor.Green); try out_stream.write("^"); setTtyColor(TtyColor.Reset); try out_stream.write("\n"); } } else |err| switch (err) { error.EndOfFile => {}, error.FileNotFound => { setTtyColor(TtyColor.Dim); try out_stream.write("file not found\n\n"); setTtyColor(TtyColor.White); }, else => return err, } } else { try out_stream.print("\n\n\n", .{}); } } else { if (opt_line_info) |li| { try out_stream.print("{}:{}:{}: 0x{x} in {} ({})\n\n\n", .{ li.file_name, li.line, li.column, relocated_address, symbol_name, obj_basename, }); } else { try out_stream.print("???:?:?: 0x{x} in {} ({})\n\n\n", .{ relocated_address, symbol_name, obj_basename, }); } } } const TtyColor = enum { Red, Green, Cyan, White, Dim, Bold, Reset, }; /// TODO this is a special case hack right now. clean it up and maybe make it part of std.fmt fn setTtyColor(tty_color: TtyColor) void { if (stderr_file.supportsAnsiEscapeCodes()) { switch (tty_color) { TtyColor.Red => { stderr_file.write(RED) catch return; }, TtyColor.Green => { stderr_file.write(GREEN) catch return; }, TtyColor.Cyan => { stderr_file.write(CYAN) catch return; }, TtyColor.White, TtyColor.Bold => { stderr_file.write(WHITE) catch return; }, TtyColor.Dim => { stderr_file.write(DIM) catch return; }, TtyColor.Reset => { stderr_file.write(RESET) catch return; }, } } else { const S = struct { var attrs: windows.WORD = undefined; var init_attrs = false; }; if (!S.init_attrs) { S.init_attrs = true; var info: windows.CONSOLE_SCREEN_BUFFER_INFO = undefined; // TODO handle error _ = windows.kernel32.GetConsoleScreenBufferInfo(stderr_file.handle, &info); S.attrs = info.wAttributes; } // TODO handle errors switch (tty_color) { TtyColor.Red => { _ = windows.SetConsoleTextAttribute(stderr_file.handle, windows.FOREGROUND_RED | windows.FOREGROUND_INTENSITY) catch {}; }, TtyColor.Green => { _ = windows.SetConsoleTextAttribute(stderr_file.handle, windows.FOREGROUND_GREEN | windows.FOREGROUND_INTENSITY) catch {}; }, TtyColor.Cyan => { _ = windows.SetConsoleTextAttribute(stderr_file.handle, windows.FOREGROUND_GREEN | windows.FOREGROUND_BLUE | windows.FOREGROUND_INTENSITY) catch {}; }, TtyColor.White, TtyColor.Bold => { _ = windows.SetConsoleTextAttribute(stderr_file.handle, windows.FOREGROUND_RED | windows.FOREGROUND_GREEN | windows.FOREGROUND_BLUE | windows.FOREGROUND_INTENSITY) catch {}; }, TtyColor.Dim => { _ = windows.SetConsoleTextAttribute(stderr_file.handle, windows.FOREGROUND_INTENSITY) catch {}; }, TtyColor.Reset => { _ = windows.SetConsoleTextAttribute(stderr_file.handle, S.attrs) catch {}; }, } } } fn populateModule(di: *DebugInfo, mod: *Module) !void { if (mod.populated) return; const allocator = getDebugInfoAllocator(); // At most one can be non-zero. if (mod.mod_info.C11ByteSize != 0 and mod.mod_info.C13ByteSize != 0) return error.InvalidDebugInfo; if (mod.mod_info.C13ByteSize == 0) return; const modi = di.pdb.getStreamById(mod.mod_info.ModuleSymStream) orelse return error.MissingDebugInfo; const signature = try modi.stream.readIntLittle(u32); if (signature != 4) return error.InvalidDebugInfo; mod.symbols = try allocator.alloc(u8, mod.mod_info.SymByteSize - 4); try modi.stream.readNoEof(mod.symbols); mod.subsect_info = try allocator.alloc(u8, mod.mod_info.C13ByteSize); try modi.stream.readNoEof(mod.subsect_info); var sect_offset: usize = 0; var skip_len: usize = undefined; while (sect_offset != mod.subsect_info.len) : (sect_offset += skip_len) { const subsect_hdr = @ptrCast(*pdb.DebugSubsectionHeader, &mod.subsect_info[sect_offset]); skip_len = subsect_hdr.Length; sect_offset += @sizeOf(pdb.DebugSubsectionHeader); switch (subsect_hdr.Kind) { pdb.DebugSubsectionKind.FileChecksums => { mod.checksum_offset = sect_offset; break; }, else => {}, } if (sect_offset > mod.subsect_info.len) return error.InvalidDebugInfo; } mod.populated = true; } fn machoSearchSymbols(symbols: []const MachoSymbol, address: usize) ?*const MachoSymbol { var min: usize = 0; var max: usize = symbols.len - 1; // Exclude sentinel. while (min < max) { const mid = min + (max - min) / 2; const curr = &symbols[mid]; const next = &symbols[mid + 1]; if (address >= next.address()) { min = mid + 1; } else if (address < curr.address()) { max = mid; } else { return curr; } } return null; } fn printSourceAtAddressMacOs(di: *DebugInfo, out_stream: var, address: usize, tty_color: bool) !void { const base_addr = process.getBaseAddress(); const adjusted_addr = 0x100000000 + (address - base_addr); const symbol = machoSearchSymbols(di.symbols, adjusted_addr) orelse { if (tty_color) { try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? (???)" ++ RESET ++ "\n\n\n", .{address}); } else { try out_stream.print("???:?:?: 0x{x} in ??? (???)\n\n\n", .{address}); } return; }; const symbol_name = mem.toSliceConst(u8, @ptrCast([*:0]const u8, di.strings.ptr + symbol.nlist.n_strx)); const compile_unit_name = if (symbol.ofile) |ofile| blk: { const ofile_path = mem.toSliceConst(u8, @ptrCast([*:0]const u8, di.strings.ptr + ofile.n_strx)); break :blk fs.path.basename(ofile_path); } else "???"; if (getLineNumberInfoMacOs(di, symbol.*, adjusted_addr)) |line_info| { defer line_info.deinit(); try printLineInfo( out_stream, line_info, address, symbol_name, compile_unit_name, tty_color, printLineFromFileAnyOs, ); } else |err| switch (err) { error.MissingDebugInfo, error.InvalidDebugInfo => { if (tty_color) { try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in {} ({})" ++ RESET ++ "\n\n\n", .{ address, symbol_name, compile_unit_name, }); } else { try out_stream.print("???:?:?: 0x{x} in {} ({})\n\n\n", .{ address, symbol_name, compile_unit_name }); } }, else => return err, } } pub fn printSourceAtAddressPosix(debug_info: *DebugInfo, out_stream: var, address: usize, tty_color: bool) !void { return debug_info.printSourceAtAddress(out_stream, address, tty_color, printLineFromFileAnyOs); } fn printLineInfo( out_stream: var, line_info: LineInfo, address: usize, symbol_name: []const u8, compile_unit_name: []const u8, tty_color: bool, comptime printLineFromFile: var, ) !void { if (tty_color) { try out_stream.print(WHITE ++ "{}:{}:{}" ++ RESET ++ ": " ++ DIM ++ "0x{x} in {} ({})" ++ RESET ++ "\n", .{ line_info.file_name, line_info.line, line_info.column, address, symbol_name, compile_unit_name, }); if (printLineFromFile(out_stream, line_info)) { if (line_info.column == 0) { try out_stream.write("\n"); } else { { var col_i: usize = 1; while (col_i < line_info.column) : (col_i += 1) { try out_stream.writeByte(' '); } } try out_stream.write(GREEN ++ "^" ++ RESET ++ "\n"); } } else |err| switch (err) { error.EndOfFile, error.FileNotFound => {}, else => return err, } } else { try out_stream.print("{}:{}:{}: 0x{x} in {} ({})\n", .{ line_info.file_name, line_info.line, line_info.column, address, symbol_name, compile_unit_name, }); } } // TODO use this pub const OpenSelfDebugInfoError = error{ MissingDebugInfo, OutOfMemory, UnsupportedOperatingSystem, }; /// TODO once https://github.com/ziglang/zig/issues/3157 is fully implemented, /// make this `noasync fn` and remove the individual noasync calls. pub fn openSelfDebugInfo(allocator: *mem.Allocator) !DebugInfo { if (builtin.strip_debug_info) return error.MissingDebugInfo; if (@hasDecl(root, "os") and @hasDecl(root.os, "debug") and @hasDecl(root.os.debug, "openSelfDebugInfo")) { return noasync root.os.debug.openSelfDebugInfo(allocator); } if (builtin.os == .windows) { return noasync openSelfDebugInfoWindows(allocator); } if (comptime std.Target.current.isDarwin()) { return noasync openSelfDebugInfoMacOs(allocator); } return noasync openSelfDebugInfoPosix(allocator); } fn openSelfDebugInfoWindows(allocator: *mem.Allocator) !DebugInfo { const self_file = try fs.openSelfExe(); defer self_file.close(); const coff_obj = try allocator.create(coff.Coff); coff_obj.* = coff.Coff.init(allocator, self_file); var di = DebugInfo{ .coff = coff_obj, .pdb = undefined, .sect_contribs = undefined, .modules = undefined, }; try di.coff.loadHeader(); var path_buf: [windows.MAX_PATH]u8 = undefined; const len = try di.coff.getPdbPath(path_buf[0..]); const raw_path = path_buf[0..len]; const path = try fs.path.resolve(allocator, &[_][]const u8{raw_path}); try di.pdb.openFile(di.coff, path); var pdb_stream = di.pdb.getStream(pdb.StreamType.Pdb) orelse return error.InvalidDebugInfo; const version = try pdb_stream.stream.readIntLittle(u32); const signature = try pdb_stream.stream.readIntLittle(u32); const age = try pdb_stream.stream.readIntLittle(u32); var guid: [16]u8 = undefined; try pdb_stream.stream.readNoEof(&guid); if (version != 20000404) // VC70, only value observed by LLVM team return error.UnknownPDBVersion; if (!mem.eql(u8, &di.coff.guid, &guid) or di.coff.age != age) return error.PDBMismatch; // We validated the executable and pdb match. const string_table_index = str_tab_index: { const name_bytes_len = try pdb_stream.stream.readIntLittle(u32); const name_bytes = try allocator.alloc(u8, name_bytes_len); try pdb_stream.stream.readNoEof(name_bytes); const HashTableHeader = packed struct { Size: u32, Capacity: u32, fn maxLoad(cap: u32) u32 { return cap * 2 / 3 + 1; } }; const hash_tbl_hdr = try pdb_stream.stream.readStruct(HashTableHeader); if (hash_tbl_hdr.Capacity == 0) return error.InvalidDebugInfo; if (hash_tbl_hdr.Size > HashTableHeader.maxLoad(hash_tbl_hdr.Capacity)) return error.InvalidDebugInfo; const present = try readSparseBitVector(&pdb_stream.stream, allocator); if (present.len != hash_tbl_hdr.Size) return error.InvalidDebugInfo; const deleted = try readSparseBitVector(&pdb_stream.stream, allocator); const Bucket = struct { first: u32, second: u32, }; const bucket_list = try allocator.alloc(Bucket, present.len); for (present) |_| { const name_offset = try pdb_stream.stream.readIntLittle(u32); const name_index = try pdb_stream.stream.readIntLittle(u32); const name = mem.toSlice(u8, @ptrCast([*:0]u8, name_bytes.ptr + name_offset)); if (mem.eql(u8, name, "/names")) { break :str_tab_index name_index; } } return error.MissingDebugInfo; }; di.pdb.string_table = di.pdb.getStreamById(string_table_index) orelse return error.MissingDebugInfo; di.pdb.dbi = di.pdb.getStream(pdb.StreamType.Dbi) orelse return error.MissingDebugInfo; const dbi = di.pdb.dbi; // Dbi Header const dbi_stream_header = try dbi.stream.readStruct(pdb.DbiStreamHeader); if (dbi_stream_header.VersionHeader != 19990903) // V70, only value observed by LLVM team return error.UnknownPDBVersion; if (dbi_stream_header.Age != age) return error.UnmatchingPDB; const mod_info_size = dbi_stream_header.ModInfoSize; const section_contrib_size = dbi_stream_header.SectionContributionSize; var modules = ArrayList(Module).init(allocator); // Module Info Substream var mod_info_offset: usize = 0; while (mod_info_offset != mod_info_size) { const mod_info = try dbi.stream.readStruct(pdb.ModInfo); var this_record_len: usize = @sizeOf(pdb.ModInfo); const module_name = try dbi.readNullTermString(allocator); this_record_len += module_name.len + 1; const obj_file_name = try dbi.readNullTermString(allocator); this_record_len += obj_file_name.len + 1; if (this_record_len % 4 != 0) { const round_to_next_4 = (this_record_len | 0x3) + 1; const march_forward_bytes = round_to_next_4 - this_record_len; try dbi.seekBy(@intCast(isize, march_forward_bytes)); this_record_len += march_forward_bytes; } try modules.append(Module{ .mod_info = mod_info, .module_name = module_name, .obj_file_name = obj_file_name, .populated = false, .symbols = undefined, .subsect_info = undefined, .checksum_offset = null, }); mod_info_offset += this_record_len; if (mod_info_offset > mod_info_size) return error.InvalidDebugInfo; } di.modules = modules.toOwnedSlice(); // Section Contribution Substream var sect_contribs = ArrayList(pdb.SectionContribEntry).init(allocator); var sect_cont_offset: usize = 0; if (section_contrib_size != 0) { const ver = @intToEnum(pdb.SectionContrSubstreamVersion, try dbi.stream.readIntLittle(u32)); if (ver != pdb.SectionContrSubstreamVersion.Ver60) return error.InvalidDebugInfo; sect_cont_offset += @sizeOf(u32); } while (sect_cont_offset != section_contrib_size) { const entry = try sect_contribs.addOne(); entry.* = try dbi.stream.readStruct(pdb.SectionContribEntry); sect_cont_offset += @sizeOf(pdb.SectionContribEntry); if (sect_cont_offset > section_contrib_size) return error.InvalidDebugInfo; } di.sect_contribs = sect_contribs.toOwnedSlice(); return di; } fn readSparseBitVector(stream: var, allocator: *mem.Allocator) ![]usize { const num_words = try stream.readIntLittle(u32); var word_i: usize = 0; var list = ArrayList(usize).init(allocator); while (word_i != num_words) : (word_i += 1) { const word = try stream.readIntLittle(u32); var bit_i: u5 = 0; while (true) : (bit_i += 1) { if (word & (@as(u32, 1) << bit_i) != 0) { try list.append(word_i * 32 + bit_i); } if (bit_i == maxInt(u5)) break; } } return list.toOwnedSlice(); } fn findDwarfSectionFromElf(elf_file: *elf.Elf, name: []const u8) !?DwarfInfo.Section { const elf_header = (try elf_file.findSection(name)) orelse return null; return DwarfInfo.Section{ .offset = elf_header.offset, .size = elf_header.size, }; } /// Initialize DWARF info. The caller has the responsibility to initialize most /// the DwarfInfo fields before calling. These fields can be left undefined: /// * abbrev_table_list /// * compile_unit_list pub fn openDwarfDebugInfo(di: *DwarfInfo, allocator: *mem.Allocator) !void { di.abbrev_table_list = ArrayList(AbbrevTableHeader).init(allocator); di.compile_unit_list = ArrayList(CompileUnit).init(allocator); di.func_list = ArrayList(Func).init(allocator); try di.scanAllFunctions(); try di.scanAllCompileUnits(); } pub fn openElfDebugInfo( allocator: *mem.Allocator, elf_seekable_stream: *DwarfSeekableStream, elf_in_stream: *DwarfInStream, ) !DwarfInfo { var efile = try elf.Elf.openStream(allocator, elf_seekable_stream, elf_in_stream); errdefer efile.close(); var di = DwarfInfo{ .dwarf_seekable_stream = elf_seekable_stream, .dwarf_in_stream = elf_in_stream, .endian = efile.endian, .debug_info = (try findDwarfSectionFromElf(&efile, ".debug_info")) orelse return error.MissingDebugInfo, .debug_abbrev = (try findDwarfSectionFromElf(&efile, ".debug_abbrev")) orelse return error.MissingDebugInfo, .debug_str = (try findDwarfSectionFromElf(&efile, ".debug_str")) orelse return error.MissingDebugInfo, .debug_line = (try findDwarfSectionFromElf(&efile, ".debug_line")) orelse return error.MissingDebugInfo, .debug_ranges = (try findDwarfSectionFromElf(&efile, ".debug_ranges")), .abbrev_table_list = undefined, .compile_unit_list = undefined, .func_list = undefined, }; try openDwarfDebugInfo(&di, allocator); return di; } fn openSelfDebugInfoPosix(allocator: *mem.Allocator) !DwarfInfo { const S = struct { var self_exe_file: File = undefined; var self_exe_mmap_seekable: io.SliceSeekableInStream = undefined; }; S.self_exe_file = try fs.openSelfExe(); errdefer S.self_exe_file.close(); const self_exe_len = math.cast(usize, try S.self_exe_file.getEndPos()) catch return error.DebugInfoTooLarge; const self_exe_mmap_len = mem.alignForward(self_exe_len, mem.page_size); const self_exe_mmap = try os.mmap( null, self_exe_mmap_len, os.PROT_READ, os.MAP_SHARED, S.self_exe_file.handle, 0, ); errdefer os.munmap(self_exe_mmap); S.self_exe_mmap_seekable = io.SliceSeekableInStream.init(self_exe_mmap); return openElfDebugInfo( allocator, // TODO https://github.com/ziglang/zig/issues/764 @ptrCast(*DwarfSeekableStream, &S.self_exe_mmap_seekable.seekable_stream), // TODO https://github.com/ziglang/zig/issues/764 @ptrCast(*DwarfInStream, &S.self_exe_mmap_seekable.stream), ); } fn openSelfDebugInfoMacOs(allocator: *mem.Allocator) !DebugInfo { const hdr = &std.c._mh_execute_header; assert(hdr.magic == std.macho.MH_MAGIC_64); const hdr_base = @ptrCast([*]u8, hdr); var ptr = hdr_base + @sizeOf(macho.mach_header_64); var ncmd: u32 = hdr.ncmds; const symtab = while (ncmd != 0) : (ncmd -= 1) { const lc = @ptrCast(*std.macho.load_command, ptr); switch (lc.cmd) { std.macho.LC_SYMTAB => break @ptrCast(*std.macho.symtab_command, ptr), else => {}, } ptr += lc.cmdsize; // TODO https://github.com/ziglang/zig/issues/1403 } else { return error.MissingDebugInfo; }; const syms = @ptrCast([*]macho.nlist_64, @alignCast(@alignOf(macho.nlist_64), hdr_base + symtab.symoff))[0..symtab.nsyms]; const strings = @ptrCast([*]u8, hdr_base + symtab.stroff)[0..symtab.strsize]; const symbols_buf = try allocator.alloc(MachoSymbol, syms.len); var ofile: ?*macho.nlist_64 = null; var reloc: u64 = 0; var symbol_index: usize = 0; var last_len: u64 = 0; for (syms) |*sym| { if (sym.n_type & std.macho.N_STAB != 0) { switch (sym.n_type) { std.macho.N_OSO => { ofile = sym; reloc = 0; }, std.macho.N_FUN => { if (sym.n_sect == 0) { last_len = sym.n_value; } else { symbols_buf[symbol_index] = MachoSymbol{ .nlist = sym, .ofile = ofile, .reloc = reloc, }; symbol_index += 1; } }, std.macho.N_BNSYM => { if (reloc == 0) { reloc = sym.n_value; } }, else => continue, } } } const sentinel = try allocator.create(macho.nlist_64); sentinel.* = macho.nlist_64{ .n_strx = 0, .n_type = 36, .n_sect = 0, .n_desc = 0, .n_value = symbols_buf[symbol_index - 1].nlist.n_value + last_len, }; const symbols = allocator.shrink(symbols_buf, symbol_index); // Even though lld emits symbols in ascending order, this debug code // should work for programs linked in any valid way. // This sort is so that we can binary search later. std.sort.sort(MachoSymbol, symbols, MachoSymbol.addressLessThan); return DebugInfo{ .ofiles = DebugInfo.OFileTable.init(allocator), .symbols = symbols, .strings = strings, }; } fn printLineFromFileAnyOs(out_stream: var, line_info: LineInfo) !void { var f = try fs.cwd().openFile(line_info.file_name, .{}); defer f.close(); // TODO fstat and make sure that the file has the correct size var buf: [mem.page_size]u8 = undefined; var line: usize = 1; var column: usize = 1; var abs_index: usize = 0; while (true) { const amt_read = try f.read(buf[0..]); const slice = buf[0..amt_read]; for (slice) |byte| { if (line == line_info.line) { try out_stream.writeByte(byte); if (byte == '\n') { return; } } if (byte == '\n') { line += 1; column = 1; } else { column += 1; } } if (amt_read < buf.len) return error.EndOfFile; } } const MachoSymbol = struct { nlist: *macho.nlist_64, ofile: ?*macho.nlist_64, reloc: u64, /// Returns the address from the macho file fn address(self: MachoSymbol) u64 { return self.nlist.n_value; } fn addressLessThan(lhs: MachoSymbol, rhs: MachoSymbol) bool { return lhs.address() < rhs.address(); } }; const MachOFile = struct { bytes: []align(@alignOf(macho.mach_header_64)) const u8, sect_debug_info: ?*const macho.section_64, sect_debug_line: ?*const macho.section_64, }; pub const DwarfSeekableStream = io.SeekableStream(anyerror, anyerror); pub const DwarfInStream = io.InStream(anyerror); pub const DwarfInfo = struct { dwarf_seekable_stream: *DwarfSeekableStream, dwarf_in_stream: *DwarfInStream, endian: builtin.Endian, debug_info: Section, debug_abbrev: Section, debug_str: Section, debug_line: Section, debug_ranges: ?Section, abbrev_table_list: ArrayList(AbbrevTableHeader), compile_unit_list: ArrayList(CompileUnit), func_list: ArrayList(Func), pub const Section = struct { offset: u64, size: u64, }; pub fn allocator(self: DwarfInfo) *mem.Allocator { return self.abbrev_table_list.allocator; } pub fn readString(self: *DwarfInfo) ![]u8 { return readStringRaw(self.allocator(), self.dwarf_in_stream); } /// This function works in freestanding mode. /// fn printLineFromFile(out_stream: var, line_info: LineInfo) !void pub fn printSourceAtAddress( self: *DwarfInfo, out_stream: var, address: usize, tty_color: bool, comptime printLineFromFile: var, ) !void { const compile_unit = self.findCompileUnit(address) catch { if (tty_color) { try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? (???)" ++ RESET ++ "\n\n\n", .{address}); } else { try out_stream.print("???:?:?: 0x{x} in ??? (???)\n\n\n", .{address}); } return; }; const compile_unit_name = try compile_unit.die.getAttrString(self, DW.AT_name); if (self.getLineNumberInfo(compile_unit.*, address)) |line_info| { defer line_info.deinit(); const symbol_name = self.getSymbolName(address) orelse "???"; try printLineInfo( out_stream, line_info, address, symbol_name, compile_unit_name, tty_color, printLineFromFile, ); } else |err| switch (err) { error.MissingDebugInfo, error.InvalidDebugInfo => { if (tty_color) { try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? ({})" ++ RESET ++ "\n\n\n", .{ address, compile_unit_name, }); } else { try out_stream.print("???:?:?: 0x{x} in ??? ({})\n\n\n", .{ address, compile_unit_name }); } }, else => return err, } } fn getSymbolName(di: *DwarfInfo, address: u64) ?[]const u8 { for (di.func_list.toSliceConst()) |*func| { if (func.pc_range) |range| { if (address >= range.start and address < range.end) { return func.name; } } } return null; } fn scanAllFunctions(di: *DwarfInfo) !void { const debug_info_end = di.debug_info.offset + di.debug_info.size; var this_unit_offset = di.debug_info.offset; while (this_unit_offset < debug_info_end) { try di.dwarf_seekable_stream.seekTo(this_unit_offset); var is_64: bool = undefined; const unit_length = try readInitialLength(@TypeOf(di.dwarf_in_stream.readFn).ReturnType.ErrorSet, di.dwarf_in_stream, &is_64); if (unit_length == 0) return; const next_offset = unit_length + (if (is_64) @as(usize, 12) else @as(usize, 4)); const version = try di.dwarf_in_stream.readInt(u16, di.endian); if (version < 2 or version > 5) return error.InvalidDebugInfo; const debug_abbrev_offset = if (is_64) try di.dwarf_in_stream.readInt(u64, di.endian) else try di.dwarf_in_stream.readInt(u32, di.endian); const address_size = try di.dwarf_in_stream.readByte(); if (address_size != @sizeOf(usize)) return error.InvalidDebugInfo; const compile_unit_pos = try di.dwarf_seekable_stream.getPos(); const abbrev_table = try di.getAbbrevTable(debug_abbrev_offset); try di.dwarf_seekable_stream.seekTo(compile_unit_pos); const next_unit_pos = this_unit_offset + next_offset; while ((try di.dwarf_seekable_stream.getPos()) < next_unit_pos) { const die_obj = (try di.parseDie(abbrev_table, is_64)) orelse continue; const after_die_offset = try di.dwarf_seekable_stream.getPos(); switch (die_obj.tag_id) { DW.TAG_subprogram, DW.TAG_inlined_subroutine, DW.TAG_subroutine, DW.TAG_entry_point => { const fn_name = x: { var depth: i32 = 3; var this_die_obj = die_obj; // Prenvent endless loops while (depth > 0) : (depth -= 1) { if (this_die_obj.getAttr(DW.AT_name)) |_| { const name = try this_die_obj.getAttrString(di, DW.AT_name); break :x name; } else if (this_die_obj.getAttr(DW.AT_abstract_origin)) |ref| { // Follow the DIE it points to and repeat const ref_offset = try this_die_obj.getAttrRef(DW.AT_abstract_origin); if (ref_offset > next_offset) return error.InvalidDebugInfo; try di.dwarf_seekable_stream.seekTo(this_unit_offset + ref_offset); this_die_obj = (try di.parseDie(abbrev_table, is_64)) orelse return error.InvalidDebugInfo; } else if (this_die_obj.getAttr(DW.AT_specification)) |ref| { // Follow the DIE it points to and repeat const ref_offset = try this_die_obj.getAttrRef(DW.AT_specification); if (ref_offset > next_offset) return error.InvalidDebugInfo; try di.dwarf_seekable_stream.seekTo(this_unit_offset + ref_offset); this_die_obj = (try di.parseDie(abbrev_table, is_64)) orelse return error.InvalidDebugInfo; } else { break :x null; } } break :x null; }; const pc_range = x: { if (die_obj.getAttrAddr(DW.AT_low_pc)) |low_pc| { if (die_obj.getAttr(DW.AT_high_pc)) |high_pc_value| { const pc_end = switch (high_pc_value.*) { FormValue.Address => |value| value, FormValue.Const => |value| b: { const offset = try value.asUnsignedLe(); break :b (low_pc + offset); }, else => return error.InvalidDebugInfo, }; break :x PcRange{ .start = low_pc, .end = pc_end, }; } else { break :x null; } } else |err| { if (err != error.MissingDebugInfo) return err; break :x null; } }; try di.func_list.append(Func{ .name = fn_name, .pc_range = pc_range, }); }, else => { continue; }, } try di.dwarf_seekable_stream.seekTo(after_die_offset); } this_unit_offset += next_offset; } } fn scanAllCompileUnits(di: *DwarfInfo) !void { const debug_info_end = di.debug_info.offset + di.debug_info.size; var this_unit_offset = di.debug_info.offset; while (this_unit_offset < debug_info_end) { try di.dwarf_seekable_stream.seekTo(this_unit_offset); var is_64: bool = undefined; const unit_length = try readInitialLength(@TypeOf(di.dwarf_in_stream.readFn).ReturnType.ErrorSet, di.dwarf_in_stream, &is_64); if (unit_length == 0) return; const next_offset = unit_length + (if (is_64) @as(usize, 12) else @as(usize, 4)); const version = try di.dwarf_in_stream.readInt(u16, di.endian); if (version < 2 or version > 5) return error.InvalidDebugInfo; const debug_abbrev_offset = if (is_64) try di.dwarf_in_stream.readInt(u64, di.endian) else try di.dwarf_in_stream.readInt(u32, di.endian); const address_size = try di.dwarf_in_stream.readByte(); if (address_size != @sizeOf(usize)) return error.InvalidDebugInfo; const compile_unit_pos = try di.dwarf_seekable_stream.getPos(); const abbrev_table = try di.getAbbrevTable(debug_abbrev_offset); try di.dwarf_seekable_stream.seekTo(compile_unit_pos); const compile_unit_die = try di.allocator().create(Die); compile_unit_die.* = (try di.parseDie(abbrev_table, is_64)) orelse return error.InvalidDebugInfo; if (compile_unit_die.tag_id != DW.TAG_compile_unit) return error.InvalidDebugInfo; const pc_range = x: { if (compile_unit_die.getAttrAddr(DW.AT_low_pc)) |low_pc| { if (compile_unit_die.getAttr(DW.AT_high_pc)) |high_pc_value| { const pc_end = switch (high_pc_value.*) { FormValue.Address => |value| value, FormValue.Const => |value| b: { const offset = try value.asUnsignedLe(); break :b (low_pc + offset); }, else => return error.InvalidDebugInfo, }; break :x PcRange{ .start = low_pc, .end = pc_end, }; } else { break :x null; } } else |err| { if (err != error.MissingDebugInfo) return err; break :x null; } }; try di.compile_unit_list.append(CompileUnit{ .version = version, .is_64 = is_64, .pc_range = pc_range, .die = compile_unit_die, }); this_unit_offset += next_offset; } } fn findCompileUnit(di: *DwarfInfo, target_address: u64) !*const CompileUnit { for (di.compile_unit_list.toSlice()) |*compile_unit| { if (compile_unit.pc_range) |range| { if (target_address >= range.start and target_address < range.end) return compile_unit; } if (compile_unit.die.getAttrSecOffset(DW.AT_ranges)) |ranges_offset| { var base_address: usize = 0; if (di.debug_ranges) |debug_ranges| { try di.dwarf_seekable_stream.seekTo(debug_ranges.offset + ranges_offset); while (true) { const begin_addr = try di.dwarf_in_stream.readIntLittle(usize); const end_addr = try di.dwarf_in_stream.readIntLittle(usize); if (begin_addr == 0 and end_addr == 0) { break; } if (begin_addr == maxInt(usize)) { base_address = begin_addr; continue; } if (target_address >= begin_addr and target_address < end_addr) { return compile_unit; } } } } else |err| { if (err != error.MissingDebugInfo) return err; continue; } } return error.MissingDebugInfo; } /// Gets an already existing AbbrevTable given the abbrev_offset, or if not found, /// seeks in the stream and parses it. fn getAbbrevTable(di: *DwarfInfo, abbrev_offset: u64) !*const AbbrevTable { for (di.abbrev_table_list.toSlice()) |*header| { if (header.offset == abbrev_offset) { return &header.table; } } try di.dwarf_seekable_stream.seekTo(di.debug_abbrev.offset + abbrev_offset); try di.abbrev_table_list.append(AbbrevTableHeader{ .offset = abbrev_offset, .table = try di.parseAbbrevTable(), }); return &di.abbrev_table_list.items[di.abbrev_table_list.len - 1].table; } fn parseAbbrevTable(di: *DwarfInfo) !AbbrevTable { var result = AbbrevTable.init(di.allocator()); while (true) { const abbrev_code = try leb.readULEB128(u64, di.dwarf_in_stream); if (abbrev_code == 0) return result; try result.append(AbbrevTableEntry{ .abbrev_code = abbrev_code, .tag_id = try leb.readULEB128(u64, di.dwarf_in_stream), .has_children = (try di.dwarf_in_stream.readByte()) == DW.CHILDREN_yes, .attrs = ArrayList(AbbrevAttr).init(di.allocator()), }); const attrs = &result.items[result.len - 1].attrs; while (true) { const attr_id = try leb.readULEB128(u64, di.dwarf_in_stream); const form_id = try leb.readULEB128(u64, di.dwarf_in_stream); if (attr_id == 0 and form_id == 0) break; try attrs.append(AbbrevAttr{ .attr_id = attr_id, .form_id = form_id, }); } } } fn parseDie(di: *DwarfInfo, abbrev_table: *const AbbrevTable, is_64: bool) !?Die { const abbrev_code = try leb.readULEB128(u64, di.dwarf_in_stream); if (abbrev_code == 0) return null; const table_entry = getAbbrevTableEntry(abbrev_table, abbrev_code) orelse return error.InvalidDebugInfo; var result = Die{ .tag_id = table_entry.tag_id, .has_children = table_entry.has_children, .attrs = ArrayList(Die.Attr).init(di.allocator()), }; try result.attrs.resize(table_entry.attrs.len); for (table_entry.attrs.toSliceConst()) |attr, i| { result.attrs.items[i] = Die.Attr{ .id = attr.attr_id, .value = try parseFormValue(di.allocator(), di.dwarf_in_stream, attr.form_id, is_64), }; } return result; } fn getLineNumberInfo(di: *DwarfInfo, compile_unit: CompileUnit, target_address: usize) !LineInfo { const compile_unit_cwd = try compile_unit.die.getAttrString(di, DW.AT_comp_dir); const line_info_offset = try compile_unit.die.getAttrSecOffset(DW.AT_stmt_list); assert(line_info_offset < di.debug_line.size); try di.dwarf_seekable_stream.seekTo(di.debug_line.offset + line_info_offset); var is_64: bool = undefined; const unit_length = try readInitialLength(@TypeOf(di.dwarf_in_stream.readFn).ReturnType.ErrorSet, di.dwarf_in_stream, &is_64); if (unit_length == 0) { return error.MissingDebugInfo; } const next_offset = unit_length + (if (is_64) @as(usize, 12) else @as(usize, 4)); const version = try di.dwarf_in_stream.readInt(u16, di.endian); // TODO support 3 and 5 if (version != 2 and version != 4) return error.InvalidDebugInfo; const prologue_length = if (is_64) try di.dwarf_in_stream.readInt(u64, di.endian) else try di.dwarf_in_stream.readInt(u32, di.endian); const prog_start_offset = (try di.dwarf_seekable_stream.getPos()) + prologue_length; const minimum_instruction_length = try di.dwarf_in_stream.readByte(); if (minimum_instruction_length == 0) return error.InvalidDebugInfo; if (version >= 4) { // maximum_operations_per_instruction _ = try di.dwarf_in_stream.readByte(); } const default_is_stmt = (try di.dwarf_in_stream.readByte()) != 0; const line_base = try di.dwarf_in_stream.readByteSigned(); const line_range = try di.dwarf_in_stream.readByte(); if (line_range == 0) return error.InvalidDebugInfo; const opcode_base = try di.dwarf_in_stream.readByte(); const standard_opcode_lengths = try di.allocator().alloc(u8, opcode_base - 1); { var i: usize = 0; while (i < opcode_base - 1) : (i += 1) { standard_opcode_lengths[i] = try di.dwarf_in_stream.readByte(); } } var include_directories = ArrayList([]u8).init(di.allocator()); try include_directories.append(compile_unit_cwd); while (true) { const dir = try di.readString(); if (dir.len == 0) break; try include_directories.append(dir); } var file_entries = ArrayList(FileEntry).init(di.allocator()); var prog = LineNumberProgram.init(default_is_stmt, include_directories.toSliceConst(), &file_entries, target_address); while (true) { const file_name = try di.readString(); if (file_name.len == 0) break; const dir_index = try leb.readULEB128(usize, di.dwarf_in_stream); const mtime = try leb.readULEB128(usize, di.dwarf_in_stream); const len_bytes = try leb.readULEB128(usize, di.dwarf_in_stream); try file_entries.append(FileEntry{ .file_name = file_name, .dir_index = dir_index, .mtime = mtime, .len_bytes = len_bytes, }); } try di.dwarf_seekable_stream.seekTo(prog_start_offset); while (true) { const opcode = try di.dwarf_in_stream.readByte(); if (opcode == DW.LNS_extended_op) { const op_size = try leb.readULEB128(u64, di.dwarf_in_stream); if (op_size < 1) return error.InvalidDebugInfo; var sub_op = try di.dwarf_in_stream.readByte(); switch (sub_op) { DW.LNE_end_sequence => { prog.end_sequence = true; if (try prog.checkLineMatch()) |info| return info; return error.MissingDebugInfo; }, DW.LNE_set_address => { const addr = try di.dwarf_in_stream.readInt(usize, di.endian); prog.address = addr; }, DW.LNE_define_file => { const file_name = try di.readString(); const dir_index = try leb.readULEB128(usize, di.dwarf_in_stream); const mtime = try leb.readULEB128(usize, di.dwarf_in_stream); const len_bytes = try leb.readULEB128(usize, di.dwarf_in_stream); try file_entries.append(FileEntry{ .file_name = file_name, .dir_index = dir_index, .mtime = mtime, .len_bytes = len_bytes, }); }, else => { const fwd_amt = math.cast(isize, op_size - 1) catch return error.InvalidDebugInfo; try di.dwarf_seekable_stream.seekBy(fwd_amt); }, } } else if (opcode >= opcode_base) { // special opcodes const adjusted_opcode = opcode - opcode_base; const inc_addr = minimum_instruction_length * (adjusted_opcode / line_range); const inc_line = @as(i32, line_base) + @as(i32, adjusted_opcode % line_range); prog.line += inc_line; prog.address += inc_addr; if (try prog.checkLineMatch()) |info| return info; prog.basic_block = false; } else { switch (opcode) { DW.LNS_copy => { if (try prog.checkLineMatch()) |info| return info; prog.basic_block = false; }, DW.LNS_advance_pc => { const arg = try leb.readULEB128(usize, di.dwarf_in_stream); prog.address += arg * minimum_instruction_length; }, DW.LNS_advance_line => { const arg = try leb.readILEB128(i64, di.dwarf_in_stream); prog.line += arg; }, DW.LNS_set_file => { const arg = try leb.readULEB128(usize, di.dwarf_in_stream); prog.file = arg; }, DW.LNS_set_column => { const arg = try leb.readULEB128(u64, di.dwarf_in_stream); prog.column = arg; }, DW.LNS_negate_stmt => { prog.is_stmt = !prog.is_stmt; }, DW.LNS_set_basic_block => { prog.basic_block = true; }, DW.LNS_const_add_pc => { const inc_addr = minimum_instruction_length * ((255 - opcode_base) / line_range); prog.address += inc_addr; }, DW.LNS_fixed_advance_pc => { const arg = try di.dwarf_in_stream.readInt(u16, di.endian); prog.address += arg; }, DW.LNS_set_prologue_end => {}, else => { if (opcode - 1 >= standard_opcode_lengths.len) return error.InvalidDebugInfo; const len_bytes = standard_opcode_lengths[opcode - 1]; try di.dwarf_seekable_stream.seekBy(len_bytes); }, } } } return error.MissingDebugInfo; } fn getString(di: *DwarfInfo, offset: u64) ![]u8 { const pos = di.debug_str.offset + offset; try di.dwarf_seekable_stream.seekTo(pos); return di.readString(); } }; pub const DebugInfo = switch (builtin.os) { .macosx, .ios, .watchos, .tvos => struct { symbols: []const MachoSymbol, strings: []const u8, ofiles: OFileTable, const OFileTable = std.HashMap( *macho.nlist_64, MachOFile, std.hash_map.getHashPtrAddrFn(*macho.nlist_64), std.hash_map.getTrivialEqlFn(*macho.nlist_64), ); pub fn allocator(self: DebugInfo) *mem.Allocator { return self.ofiles.allocator; } }, .uefi, .windows => struct { pdb: pdb.Pdb, coff: *coff.Coff, sect_contribs: []pdb.SectionContribEntry, modules: []Module, }, else => DwarfInfo, }; const PcRange = struct { start: u64, end: u64, }; const CompileUnit = struct { version: u16, is_64: bool, die: *Die, pc_range: ?PcRange, }; const AbbrevTable = ArrayList(AbbrevTableEntry); const AbbrevTableHeader = struct { // offset from .debug_abbrev offset: u64, table: AbbrevTable, }; const AbbrevTableEntry = struct { has_children: bool, abbrev_code: u64, tag_id: u64, attrs: ArrayList(AbbrevAttr), }; const AbbrevAttr = struct { attr_id: u64, form_id: u64, }; const FormValue = union(enum) { Address: u64, Block: []u8, Const: Constant, ExprLoc: []u8, Flag: bool, SecOffset: u64, Ref: u64, RefAddr: u64, String: []u8, StrPtr: u64, }; const Constant = struct { payload: u64, signed: bool, fn asUnsignedLe(self: *const Constant) !u64 { if (self.signed) return error.InvalidDebugInfo; return self.payload; } }; const Die = struct { tag_id: u64, has_children: bool, attrs: ArrayList(Attr), const Attr = struct { id: u64, value: FormValue, }; fn getAttr(self: *const Die, id: u64) ?*const FormValue { for (self.attrs.toSliceConst()) |*attr| { if (attr.id == id) return &attr.value; } return null; } fn getAttrAddr(self: *const Die, id: u64) !u64 { const form_value = self.getAttr(id) orelse return error.MissingDebugInfo; return switch (form_value.*) { FormValue.Address => |value| value, else => error.InvalidDebugInfo, }; } fn getAttrSecOffset(self: *const Die, id: u64) !u64 { const form_value = self.getAttr(id) orelse return error.MissingDebugInfo; return switch (form_value.*) { FormValue.Const => |value| value.asUnsignedLe(), FormValue.SecOffset => |value| value, else => error.InvalidDebugInfo, }; } fn getAttrUnsignedLe(self: *const Die, id: u64) !u64 { const form_value = self.getAttr(id) orelse return error.MissingDebugInfo; return switch (form_value.*) { FormValue.Const => |value| value.asUnsignedLe(), else => error.InvalidDebugInfo, }; } fn getAttrRef(self: *const Die, id: u64) !u64 { const form_value = self.getAttr(id) orelse return error.MissingDebugInfo; return switch (form_value.*) { FormValue.Ref => |value| value, else => error.InvalidDebugInfo, }; } fn getAttrString(self: *const Die, di: *DwarfInfo, id: u64) ![]u8 { const form_value = self.getAttr(id) orelse return error.MissingDebugInfo; return switch (form_value.*) { FormValue.String => |value| value, FormValue.StrPtr => |offset| di.getString(offset), else => error.InvalidDebugInfo, }; } }; const FileEntry = struct { file_name: []const u8, dir_index: usize, mtime: usize, len_bytes: usize, }; pub const LineInfo = struct { line: u64, column: u64, file_name: []const u8, allocator: ?*mem.Allocator, fn deinit(self: LineInfo) void { const allocator = self.allocator orelse return; allocator.free(self.file_name); } }; const LineNumberProgram = struct { address: usize, file: usize, line: i64, column: u64, is_stmt: bool, basic_block: bool, end_sequence: bool, target_address: usize, include_dirs: []const []const u8, file_entries: *ArrayList(FileEntry), prev_address: usize, prev_file: usize, prev_line: i64, prev_column: u64, prev_is_stmt: bool, prev_basic_block: bool, prev_end_sequence: bool, pub fn init(is_stmt: bool, include_dirs: []const []const u8, file_entries: *ArrayList(FileEntry), target_address: usize) LineNumberProgram { return LineNumberProgram{ .address = 0, .file = 1, .line = 1, .column = 0, .is_stmt = is_stmt, .basic_block = false, .end_sequence = false, .include_dirs = include_dirs, .file_entries = file_entries, .target_address = target_address, .prev_address = 0, .prev_file = undefined, .prev_line = undefined, .prev_column = undefined, .prev_is_stmt = undefined, .prev_basic_block = undefined, .prev_end_sequence = undefined, }; } pub fn checkLineMatch(self: *LineNumberProgram) !?LineInfo { if (self.target_address >= self.prev_address and self.target_address < self.address) { const file_entry = if (self.prev_file == 0) { return error.MissingDebugInfo; } else if (self.prev_file - 1 >= self.file_entries.len) { return error.InvalidDebugInfo; } else &self.file_entries.items[self.prev_file - 1]; const dir_name = if (file_entry.dir_index >= self.include_dirs.len) { return error.InvalidDebugInfo; } else self.include_dirs[file_entry.dir_index]; const file_name = try fs.path.join(self.file_entries.allocator, &[_][]const u8{ dir_name, file_entry.file_name }); errdefer self.file_entries.allocator.free(file_name); return LineInfo{ .line = if (self.prev_line >= 0) @intCast(u64, self.prev_line) else 0, .column = self.prev_column, .file_name = file_name, .allocator = self.file_entries.allocator, }; } self.prev_address = self.address; self.prev_file = self.file; self.prev_line = self.line; self.prev_column = self.column; self.prev_is_stmt = self.is_stmt; self.prev_basic_block = self.basic_block; self.prev_end_sequence = self.end_sequence; return null; } }; // TODO the noasyncs here are workarounds fn readStringRaw(allocator: *mem.Allocator, in_stream: var) ![]u8 { var buf = ArrayList(u8).init(allocator); while (true) { const byte = try noasync in_stream.readByte(); if (byte == 0) break; try buf.append(byte); } return buf.toSlice(); } // TODO the noasyncs here are workarounds fn readAllocBytes(allocator: *mem.Allocator, in_stream: var, size: usize) ![]u8 { const buf = try allocator.alloc(u8, size); errdefer allocator.free(buf); if ((try noasync in_stream.read(buf)) < size) return error.EndOfFile; return buf; } fn parseFormValueBlockLen(allocator: *mem.Allocator, in_stream: var, size: usize) !FormValue { const buf = try readAllocBytes(allocator, in_stream, size); return FormValue{ .Block = buf }; } // TODO the noasyncs here are workarounds fn parseFormValueBlock(allocator: *mem.Allocator, in_stream: var, size: usize) !FormValue { const block_len = try noasync in_stream.readVarInt(usize, builtin.Endian.Little, size); return parseFormValueBlockLen(allocator, in_stream, block_len); } fn parseFormValueConstant(allocator: *mem.Allocator, in_stream: var, signed: bool, comptime size: i32) !FormValue { // TODO: Please forgive me, I've worked around zig not properly spilling some intermediate values here. // `noasync` should be removed from all the function calls once it is fixed. return FormValue{ .Const = Constant{ .signed = signed, .payload = switch (size) { 1 => try noasync in_stream.readIntLittle(u8), 2 => try noasync in_stream.readIntLittle(u16), 4 => try noasync in_stream.readIntLittle(u32), 8 => try noasync in_stream.readIntLittle(u64), -1 => blk: { if (signed) { const x = try noasync leb.readILEB128(i64, in_stream); break :blk @bitCast(u64, x); } else { const x = try noasync leb.readULEB128(u64, in_stream); break :blk x; } }, else => @compileError("Invalid size"), }, }, }; } // TODO the noasyncs here are workarounds fn parseFormValueDwarfOffsetSize(in_stream: var, is_64: bool) !u64 { return if (is_64) try noasync in_stream.readIntLittle(u64) else @as(u64, try noasync in_stream.readIntLittle(u32)); } // TODO the noasyncs here are workarounds fn parseFormValueTargetAddrSize(in_stream: var) !u64 { if (@sizeOf(usize) == 4) { // TODO this cast should not be needed return @as(u64, try noasync in_stream.readIntLittle(u32)); } else if (@sizeOf(usize) == 8) { return noasync in_stream.readIntLittle(u64); } else { unreachable; } } // TODO the noasyncs here are workarounds fn parseFormValueRef(allocator: *mem.Allocator, in_stream: var, size: i32) !FormValue { return FormValue{ .Ref = switch (size) { 1 => try noasync in_stream.readIntLittle(u8), 2 => try noasync in_stream.readIntLittle(u16), 4 => try noasync in_stream.readIntLittle(u32), 8 => try noasync in_stream.readIntLittle(u64), -1 => try noasync leb.readULEB128(u64, in_stream), else => unreachable, }, }; } // TODO the noasyncs here are workarounds fn parseFormValue(allocator: *mem.Allocator, in_stream: var, form_id: u64, is_64: bool) anyerror!FormValue { return switch (form_id) { DW.FORM_addr => FormValue{ .Address = try parseFormValueTargetAddrSize(in_stream) }, DW.FORM_block1 => parseFormValueBlock(allocator, in_stream, 1), DW.FORM_block2 => parseFormValueBlock(allocator, in_stream, 2), DW.FORM_block4 => parseFormValueBlock(allocator, in_stream, 4), DW.FORM_block => x: { const block_len = try noasync leb.readULEB128(usize, in_stream); return parseFormValueBlockLen(allocator, in_stream, block_len); }, DW.FORM_data1 => parseFormValueConstant(allocator, in_stream, false, 1), DW.FORM_data2 => parseFormValueConstant(allocator, in_stream, false, 2), DW.FORM_data4 => parseFormValueConstant(allocator, in_stream, false, 4), DW.FORM_data8 => parseFormValueConstant(allocator, in_stream, false, 8), DW.FORM_udata, DW.FORM_sdata => { const signed = form_id == DW.FORM_sdata; return parseFormValueConstant(allocator, in_stream, signed, -1); }, DW.FORM_exprloc => { const size = try noasync leb.readULEB128(usize, in_stream); const buf = try readAllocBytes(allocator, in_stream, size); return FormValue{ .ExprLoc = buf }; }, DW.FORM_flag => FormValue{ .Flag = (try noasync in_stream.readByte()) != 0 }, DW.FORM_flag_present => FormValue{ .Flag = true }, DW.FORM_sec_offset => FormValue{ .SecOffset = try parseFormValueDwarfOffsetSize(in_stream, is_64) }, DW.FORM_ref1 => parseFormValueRef(allocator, in_stream, 1), DW.FORM_ref2 => parseFormValueRef(allocator, in_stream, 2), DW.FORM_ref4 => parseFormValueRef(allocator, in_stream, 4), DW.FORM_ref8 => parseFormValueRef(allocator, in_stream, 8), DW.FORM_ref_udata => parseFormValueRef(allocator, in_stream, -1), DW.FORM_ref_addr => FormValue{ .RefAddr = try parseFormValueDwarfOffsetSize(in_stream, is_64) }, DW.FORM_ref_sig8 => FormValue{ .Ref = try noasync in_stream.readIntLittle(u64) }, DW.FORM_string => FormValue{ .String = try readStringRaw(allocator, in_stream) }, DW.FORM_strp => FormValue{ .StrPtr = try parseFormValueDwarfOffsetSize(in_stream, is_64) }, DW.FORM_indirect => { const child_form_id = try noasync leb.readULEB128(u64, in_stream); const F = @TypeOf(async parseFormValue(allocator, in_stream, child_form_id, is_64)); var frame = try allocator.create(F); defer allocator.destroy(frame); return await @asyncCall(frame, {}, parseFormValue, allocator, in_stream, child_form_id, is_64); }, else => error.InvalidDebugInfo, }; } fn getAbbrevTableEntry(abbrev_table: *const AbbrevTable, abbrev_code: u64) ?*const AbbrevTableEntry { for (abbrev_table.toSliceConst()) |*table_entry| { if (table_entry.abbrev_code == abbrev_code) return table_entry; } return null; } fn getLineNumberInfoMacOs(di: *DebugInfo, symbol: MachoSymbol, target_address: usize) !LineInfo { const ofile = symbol.ofile orelse return error.MissingDebugInfo; const gop = try di.ofiles.getOrPut(ofile); const mach_o_file = if (gop.found_existing) &gop.kv.value else blk: { errdefer _ = di.ofiles.remove(ofile); const ofile_path = mem.toSliceConst(u8, @ptrCast([*:0]const u8, di.strings.ptr + ofile.n_strx)); gop.kv.value = MachOFile{ .bytes = try std.fs.cwd().readFileAllocAligned( di.ofiles.allocator, ofile_path, maxInt(usize), @alignOf(macho.mach_header_64), ), .sect_debug_info = null, .sect_debug_line = null, }; const hdr = @ptrCast(*const macho.mach_header_64, gop.kv.value.bytes.ptr); if (hdr.magic != std.macho.MH_MAGIC_64) return error.InvalidDebugInfo; const hdr_base = @ptrCast([*]const u8, hdr); var ptr = hdr_base + @sizeOf(macho.mach_header_64); var ncmd: u32 = hdr.ncmds; const segcmd = while (ncmd != 0) : (ncmd -= 1) { const lc = @ptrCast(*const std.macho.load_command, ptr); switch (lc.cmd) { std.macho.LC_SEGMENT_64 => break @ptrCast(*const std.macho.segment_command_64, @alignCast(@alignOf(std.macho.segment_command_64), ptr)), else => {}, } ptr += lc.cmdsize; // TODO https://github.com/ziglang/zig/issues/1403 } else { return error.MissingDebugInfo; }; const sections = @ptrCast([*]const macho.section_64, @alignCast(@alignOf(macho.section_64), ptr + @sizeOf(std.macho.segment_command_64)))[0..segcmd.nsects]; for (sections) |*sect| { if (sect.flags & macho.SECTION_TYPE == macho.S_REGULAR and (sect.flags & macho.SECTION_ATTRIBUTES) & macho.S_ATTR_DEBUG == macho.S_ATTR_DEBUG) { const sect_name = mem.toSliceConst(u8, @ptrCast([*:0]const u8, &sect.sectname)); if (mem.eql(u8, sect_name, "__debug_line")) { gop.kv.value.sect_debug_line = sect; } else if (mem.eql(u8, sect_name, "__debug_info")) { gop.kv.value.sect_debug_info = sect; } } } break :blk &gop.kv.value; }; const sect_debug_line = mach_o_file.sect_debug_line orelse return error.MissingDebugInfo; var ptr = mach_o_file.bytes.ptr + sect_debug_line.offset; var is_64: bool = undefined; const unit_length = try readInitialLengthMem(&ptr, &is_64); if (unit_length == 0) return error.MissingDebugInfo; const version = readIntMem(&ptr, u16, builtin.Endian.Little); // TODO support 3 and 5 if (version != 2 and version != 4) return error.InvalidDebugInfo; const prologue_length = if (is_64) readIntMem(&ptr, u64, builtin.Endian.Little) else readIntMem(&ptr, u32, builtin.Endian.Little); const prog_start = ptr + prologue_length; const minimum_instruction_length = readByteMem(&ptr); if (minimum_instruction_length == 0) return error.InvalidDebugInfo; if (version >= 4) { // maximum_operations_per_instruction ptr += 1; } const default_is_stmt = readByteMem(&ptr) != 0; const line_base = readByteSignedMem(&ptr); const line_range = readByteMem(&ptr); if (line_range == 0) return error.InvalidDebugInfo; const opcode_base = readByteMem(&ptr); const standard_opcode_lengths = ptr[0 .. opcode_base - 1]; ptr += opcode_base - 1; var include_directories = ArrayList([]const u8).init(di.allocator()); try include_directories.append(""); while (true) { const dir = readStringMem(&ptr); if (dir.len == 0) break; try include_directories.append(dir); } var file_entries = ArrayList(FileEntry).init(di.allocator()); var prog = LineNumberProgram.init(default_is_stmt, include_directories.toSliceConst(), &file_entries, target_address); while (true) { const file_name = readStringMem(&ptr); if (file_name.len == 0) break; const dir_index = try leb.readULEB128Mem(usize, &ptr); const mtime = try leb.readULEB128Mem(usize, &ptr); const len_bytes = try leb.readULEB128Mem(usize, &ptr); try file_entries.append(FileEntry{ .file_name = file_name, .dir_index = dir_index, .mtime = mtime, .len_bytes = len_bytes, }); } ptr = prog_start; while (true) { const opcode = readByteMem(&ptr); if (opcode == DW.LNS_extended_op) { const op_size = try leb.readULEB128Mem(u64, &ptr); if (op_size < 1) return error.InvalidDebugInfo; var sub_op = readByteMem(&ptr); switch (sub_op) { DW.LNE_end_sequence => { prog.end_sequence = true; if (try prog.checkLineMatch()) |info| return info; return error.MissingDebugInfo; }, DW.LNE_set_address => { const addr = readIntMem(&ptr, usize, builtin.Endian.Little); prog.address = symbol.reloc + addr; }, DW.LNE_define_file => { const file_name = readStringMem(&ptr); const dir_index = try leb.readULEB128Mem(usize, &ptr); const mtime = try leb.readULEB128Mem(usize, &ptr); const len_bytes = try leb.readULEB128Mem(usize, &ptr); try file_entries.append(FileEntry{ .file_name = file_name, .dir_index = dir_index, .mtime = mtime, .len_bytes = len_bytes, }); }, else => { ptr += op_size - 1; }, } } else if (opcode >= opcode_base) { // special opcodes const adjusted_opcode = opcode - opcode_base; const inc_addr = minimum_instruction_length * (adjusted_opcode / line_range); const inc_line = @as(i32, line_base) + @as(i32, adjusted_opcode % line_range); prog.line += inc_line; prog.address += inc_addr; if (try prog.checkLineMatch()) |info| return info; prog.basic_block = false; } else { switch (opcode) { DW.LNS_copy => { if (try prog.checkLineMatch()) |info| return info; prog.basic_block = false; }, DW.LNS_advance_pc => { const arg = try leb.readULEB128Mem(usize, &ptr); prog.address += arg * minimum_instruction_length; }, DW.LNS_advance_line => { const arg = try leb.readILEB128Mem(i64, &ptr); prog.line += arg; }, DW.LNS_set_file => { const arg = try leb.readULEB128Mem(usize, &ptr); prog.file = arg; }, DW.LNS_set_column => { const arg = try leb.readULEB128Mem(u64, &ptr); prog.column = arg; }, DW.LNS_negate_stmt => { prog.is_stmt = !prog.is_stmt; }, DW.LNS_set_basic_block => { prog.basic_block = true; }, DW.LNS_const_add_pc => { const inc_addr = minimum_instruction_length * ((255 - opcode_base) / line_range); prog.address += inc_addr; }, DW.LNS_fixed_advance_pc => { const arg = readIntMem(&ptr, u16, builtin.Endian.Little); prog.address += arg; }, DW.LNS_set_prologue_end => {}, else => { if (opcode - 1 >= standard_opcode_lengths.len) return error.InvalidDebugInfo; const len_bytes = standard_opcode_lengths[opcode - 1]; ptr += len_bytes; }, } } } return error.MissingDebugInfo; } const Func = struct { pc_range: ?PcRange, name: ?[]u8, }; fn readIntMem(ptr: *[*]const u8, comptime T: type, endian: builtin.Endian) T { // TODO https://github.com/ziglang/zig/issues/863 const size = (T.bit_count + 7) / 8; const result = mem.readIntSlice(T, ptr.*[0..size], endian); ptr.* += size; return result; } fn readByteMem(ptr: *[*]const u8) u8 { const result = ptr.*[0]; ptr.* += 1; return result; } fn readByteSignedMem(ptr: *[*]const u8) i8 { return @bitCast(i8, readByteMem(ptr)); } fn readInitialLengthMem(ptr: *[*]const u8, is_64: *bool) !u64 { // TODO this code can be improved with https://github.com/ziglang/zig/issues/863 const first_32_bits = mem.readIntSliceLittle(u32, ptr.*[0..4]); is_64.* = (first_32_bits == 0xffffffff); if (is_64.*) { ptr.* += 4; const result = mem.readIntSliceLittle(u64, ptr.*[0..8]); ptr.* += 8; return result; } else { if (first_32_bits >= 0xfffffff0) return error.InvalidDebugInfo; ptr.* += 4; // TODO this cast should not be needed return @as(u64, first_32_bits); } } fn readStringMem(ptr: *[*]const u8) [:0]const u8 { const result = mem.toSliceConst(u8, @ptrCast([*:0]const u8, ptr.*)); ptr.* += result.len + 1; return result; } fn readInitialLength(comptime E: type, in_stream: *io.InStream(E), is_64: *bool) !u64 { const first_32_bits = try in_stream.readIntLittle(u32); is_64.* = (first_32_bits == 0xffffffff); if (is_64.*) { return in_stream.readIntLittle(u64); } else { if (first_32_bits >= 0xfffffff0) return error.InvalidDebugInfo; // TODO this cast should not be needed return @as(u64, first_32_bits); } } /// This should only be used in temporary test programs. pub const global_allocator = &global_fixed_allocator.allocator; var global_fixed_allocator = std.heap.ThreadSafeFixedBufferAllocator.init(global_allocator_mem[0..]); var global_allocator_mem: [100 * 1024]u8 = undefined; /// TODO multithreaded awareness var debug_info_allocator: ?*mem.Allocator = null; var debug_info_arena_allocator: std.heap.ArenaAllocator = undefined; fn getDebugInfoAllocator() *mem.Allocator { if (debug_info_allocator) |a| return a; debug_info_arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator); debug_info_allocator = &debug_info_arena_allocator.allocator; return &debug_info_arena_allocator.allocator; } /// Whether or not the current target can print useful debug information when a segfault occurs. pub const have_segfault_handling_support = builtin.os == .linux or builtin.os == .windows; pub const enable_segfault_handler: bool = if (@hasDecl(root, "enable_segfault_handler")) root.enable_segfault_handler else runtime_safety and have_segfault_handling_support; pub fn maybeEnableSegfaultHandler() void { if (enable_segfault_handler) { std.debug.attachSegfaultHandler(); } } var windows_segfault_handle: ?windows.HANDLE = null; /// Attaches a global SIGSEGV handler which calls @panic("segmentation fault"); pub fn attachSegfaultHandler() void { if (!have_segfault_handling_support) { @compileError("segfault handler not supported for this target"); } if (builtin.os == .windows) { windows_segfault_handle = windows.kernel32.AddVectoredExceptionHandler(0, handleSegfaultWindows); return; } var act = os.Sigaction{ .sigaction = handleSegfaultLinux, .mask = os.empty_sigset, .flags = (os.SA_SIGINFO | os.SA_RESTART | os.SA_RESETHAND), }; os.sigaction(os.SIGSEGV, &act, null); } fn resetSegfaultHandler() void { if (builtin.os == .windows) { if (windows_segfault_handle) |handle| { assert(windows.kernel32.RemoveVectoredExceptionHandler(handle) != 0); windows_segfault_handle = null; } return; } var act = os.Sigaction{ .sigaction = os.SIG_DFL, .mask = os.empty_sigset, .flags = 0, }; os.sigaction(os.SIGSEGV, &act, null); } extern fn handleSegfaultLinux(sig: i32, info: *const os.siginfo_t, ctx_ptr: *const c_void) noreturn { // Reset to the default handler so that if a segfault happens in this handler it will crash // the process. Also when this handler returns, the original instruction will be repeated // and the resulting segfault will crash the process rather than continually dump stack traces. resetSegfaultHandler(); const addr = @ptrToInt(info.fields.sigfault.addr); std.debug.warn("Segmentation fault at address 0x{x}\n", .{addr}); switch (builtin.arch) { .i386 => { const ctx = @ptrCast(*const os.ucontext_t, @alignCast(@alignOf(os.ucontext_t), ctx_ptr)); const ip = @intCast(usize, ctx.mcontext.gregs[os.REG_EIP]); const bp = @intCast(usize, ctx.mcontext.gregs[os.REG_EBP]); dumpStackTraceFromBase(bp, ip); }, .x86_64 => { const ctx = @ptrCast(*const os.ucontext_t, @alignCast(@alignOf(os.ucontext_t), ctx_ptr)); const ip = @intCast(usize, ctx.mcontext.gregs[os.REG_RIP]); const bp = @intCast(usize, ctx.mcontext.gregs[os.REG_RBP]); dumpStackTraceFromBase(bp, ip); }, .arm => { const ctx = @ptrCast(*const os.ucontext_t, @alignCast(@alignOf(os.ucontext_t), ctx_ptr)); const ip = @intCast(usize, ctx.mcontext.arm_pc); const bp = @intCast(usize, ctx.mcontext.arm_fp); dumpStackTraceFromBase(bp, ip); }, .aarch64 => { const ctx = @ptrCast(*const os.ucontext_t, @alignCast(@alignOf(os.ucontext_t), ctx_ptr)); const ip = @intCast(usize, ctx.mcontext.pc); // x29 is the ABI-designated frame pointer const bp = @intCast(usize, ctx.mcontext.regs[29]); dumpStackTraceFromBase(bp, ip); }, else => {}, } // We cannot allow the signal handler to return because when it runs the original instruction // again, the memory may be mapped and undefined behavior would occur rather than repeating // the segfault. So we simply abort here. os.abort(); } stdcallcc fn handleSegfaultWindows(info: *windows.EXCEPTION_POINTERS) c_long { const exception_address = @ptrToInt(info.ExceptionRecord.ExceptionAddress); switch (info.ExceptionRecord.ExceptionCode) { windows.EXCEPTION_DATATYPE_MISALIGNMENT => panicExtra(null, exception_address, "Unaligned Memory Access", .{}), windows.EXCEPTION_ACCESS_VIOLATION => panicExtra(null, exception_address, "Segmentation fault at address 0x{x}", .{info.ExceptionRecord.ExceptionInformation[1]}), windows.EXCEPTION_ILLEGAL_INSTRUCTION => panicExtra(null, exception_address, "Illegal Instruction", .{}), windows.EXCEPTION_STACK_OVERFLOW => panicExtra(null, exception_address, "Stack Overflow", .{}), else => return windows.EXCEPTION_CONTINUE_SEARCH, } } pub fn dumpStackPointerAddr(prefix: []const u8) void { const sp = asm ("" : [argc] "={rsp}" (-> usize) ); std.debug.warn("{} sp = 0x{x}\n", .{ prefix, sp }); } // Reference everything so it gets tested. test "" { _ = leb; }
lib/std/debug.zig
const std = @import("../std.zig"); const mem = std.mem; const math = std.math; const debug = std.debug; const htest = @import("test.zig"); pub const Sha3_224 = Keccak(224, 0x06); pub const Sha3_256 = Keccak(256, 0x06); pub const Sha3_384 = Keccak(384, 0x06); pub const Sha3_512 = Keccak(512, 0x06); fn Keccak(comptime bits: usize, comptime delim: u8) type { return struct { const Self = @This(); pub const block_length = 200; pub const digest_length = bits / 8; pub const Options = struct {}; s: [200]u8, offset: usize, rate: usize, pub fn init(options: Options) Self { return Self{ .s = [_]u8{0} ** 200, .offset = 0, .rate = 200 - (bits / 4) }; } pub fn hash(b: []const u8, out: *[digest_length]u8, options: Options) void { var d = Self.init(options); d.update(b); d.final(out); } pub fn update(d: *Self, b: []const u8) void { var ip: usize = 0; var len = b.len; var rate = d.rate - d.offset; var offset = d.offset; // absorb while (len >= rate) { for (d.s[offset .. offset + rate]) |*r, i| r.* ^= b[ip..][i]; keccakF(1600, &d.s); ip += rate; len -= rate; rate = d.rate; offset = 0; } for (d.s[offset .. offset + len]) |*r, i| r.* ^= b[ip..][i]; d.offset = offset + len; } pub fn final(d: *Self, out: *[digest_length]u8) void { // padding d.s[d.offset] ^= delim; d.s[d.rate - 1] ^= 0x80; keccakF(1600, &d.s); // squeeze var op: usize = 0; var len: usize = bits / 8; while (len >= d.rate) { mem.copy(u8, out[op..], d.s[0..d.rate]); keccakF(1600, &d.s); op += d.rate; len -= d.rate; } mem.copy(u8, out[op..], d.s[0..len]); } }; } const RC = [_]u64{ 0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000, 0x000000000000808b, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, 0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a, 0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003, 0x8000000000008002, 0x8000000000000080, 0x000000000000800a, 0x800000008000000a, 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008, }; const ROTC = [_]usize{ 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 2, 14, 27, 41, 56, 8, 25, 43, 62, 18, 39, 61, 20, 44, }; const PIL = [_]usize{ 10, 7, 11, 17, 18, 3, 5, 16, 8, 21, 24, 4, 15, 23, 19, 13, 12, 2, 20, 14, 22, 9, 6, 1, }; const M5 = [_]usize{ 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, }; fn keccakF(comptime F: usize, d: *[F / 8]u8) void { const B = F / 25; const no_rounds = comptime x: { break :x 12 + 2 * math.log2(B); }; var s = [_]u64{0} ** 25; var t = [_]u64{0} ** 1; var c = [_]u64{0} ** 5; for (s) |*r, i| { r.* = mem.readIntLittle(u64, d[8 * i ..][0..8]); } comptime var x: usize = 0; comptime var y: usize = 0; for (RC[0..no_rounds]) |round| { // theta x = 0; inline while (x < 5) : (x += 1) { c[x] = s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]; } x = 0; inline while (x < 5) : (x += 1) { t[0] = c[M5[x + 4]] ^ math.rotl(u64, c[M5[x + 1]], @as(usize, 1)); y = 0; inline while (y < 5) : (y += 1) { s[x + y * 5] ^= t[0]; } } // rho+pi t[0] = s[1]; x = 0; inline while (x < 24) : (x += 1) { c[0] = s[PIL[x]]; s[PIL[x]] = math.rotl(u64, t[0], ROTC[x]); t[0] = c[0]; } // chi y = 0; inline while (y < 5) : (y += 1) { x = 0; inline while (x < 5) : (x += 1) { c[x] = s[x + y * 5]; } x = 0; inline while (x < 5) : (x += 1) { s[x + y * 5] = c[x] ^ (~c[M5[x + 1]] & c[M5[x + 2]]); } } // iota s[0] ^= round; } for (s) |r, i| { mem.writeIntLittle(u64, d[8 * i ..][0..8], r); } } test "sha3-224 single" { htest.assertEqualHash(Sha3_224, "6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7", ""); htest.assertEqualHash(Sha3_224, "e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", "abc"); htest.assertEqualHash(Sha3_224, "543e6868e1666c1a643630df77367ae5a62a85070a51c14cbf665cbc", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); } test "sha3-224 streaming" { var h = Sha3_224.init(.{}); var out: [28]u8 = undefined; h.final(out[0..]); htest.assertEqual("6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7", out[0..]); h = Sha3_224.init(.{}); h.update("abc"); h.final(out[0..]); htest.assertEqual("e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", out[0..]); h = Sha3_224.init(.{}); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual("e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", out[0..]); } test "sha3-256 single" { htest.assertEqualHash(Sha3_256, "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", ""); htest.assertEqualHash(Sha3_256, "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", "abc"); htest.assertEqualHash(Sha3_256, "916f6061fe879741ca6469b43971dfdb28b1a32dc36cb3254e812be27aad1d18", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); } test "sha3-256 streaming" { var h = Sha3_256.init(.{}); var out: [32]u8 = undefined; h.final(out[0..]); htest.assertEqual("a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", out[0..]); h = Sha3_256.init(.{}); h.update("abc"); h.final(out[0..]); htest.assertEqual("3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", out[0..]); h = Sha3_256.init(.{}); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual("3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", out[0..]); } test "sha3-256 aligned final" { var block = [_]u8{0} ** Sha3_256.block_length; var out: [Sha3_256.digest_length]u8 = undefined; var h = Sha3_256.init(.{}); h.update(&block); h.final(out[0..]); } test "sha3-384 single" { const h1 = "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004"; htest.assertEqualHash(Sha3_384, h1, ""); const h2 = "ec01498288516fc926459f58e2c6ad8df9b473cb0fc08c2596da7cf0e49be4b298d88cea927ac7f539f1edf228376d25"; htest.assertEqualHash(Sha3_384, h2, "abc"); const h3 = "79407d3b5916b59c3e30b09822974791c313fb9ecc849e406f23592d04f625dc8c709b98b43b3852b337216179aa7fc7"; htest.assertEqualHash(Sha3_384, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); } test "sha3-384 streaming" { var h = Sha3_384.init(.{}); var out: [48]u8 = undefined; const h1 = "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004"; h.final(out[0..]); htest.assertEqual(h1, out[0..]); const h2 = "ec01498288516fc926459f58e2c6ad8df9b473cb0fc08c2596da7cf0e49be4b298d88cea927ac7f539f1edf228376d25"; h = Sha3_384.init(.{}); h.update("abc"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); h = Sha3_384.init(.{}); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); } test "sha3-512 single" { const h1 = "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26"; htest.assertEqualHash(Sha3_512, h1, ""); const h2 = "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0"; htest.assertEqualHash(Sha3_512, h2, "abc"); const h3 = "afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185"; htest.assertEqualHash(Sha3_512, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); } test "sha3-512 streaming" { var h = Sha3_512.init(.{}); var out: [64]u8 = undefined; const h1 = "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26"; h.final(out[0..]); htest.assertEqual(h1, out[0..]); const h2 = "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0"; h = Sha3_512.init(.{}); h.update("abc"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); h = Sha3_512.init(.{}); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); } test "sha3-512 aligned final" { var block = [_]u8{0} ** Sha3_512.block_length; var out: [Sha3_512.digest_length]u8 = undefined; var h = Sha3_512.init(.{}); h.update(&block); h.final(out[0..]); }
lib/std/crypto/sha3.zig
const std = @import("std"); const print = std.debug.print; const mem = std.mem; const log = std.log.scoped(.keys); const Dirs = @import("core").Dirs; const Allocator = std.mem.Allocator; const crypto = std.crypto; const Atomic = std.atomic.Atomic; const Ed25519 = crypto.sign.Ed25519; const Blake3 = crypto.hash.Blake3; const KeyPair = Ed25519.KeyPair; const str = []const u8; pub const Tag = enum { nop, add, del }; pub const Keys = @This(); pair: KeyPair, pub fn file(a: Allocator) !?std.fs.File { const hdir = try Dirs.getPath(Dirs.home, a) catch "~/"; const idir = std.fs.path.join(a, .{hdir, ".idla"}); const id = try std.fs.openDirAbsolute(idir, .{}); const kfile = try id.openFile(".keys", .{}); if (kfile) |f| return f; return null; } pub fn initFromFile(a: Allocator) !?Keys { const hdir = try Dirs.getPath(Dirs.home, a) catch "~/"; const idir = std.fs.path.join(a, .{hdir, ".idla"}); const id = try std.fs.openDirAbsolute(idir, .{}); const kfile = try id.openFile(".keys", .{}); const kstr = try kfile.readToEndAlloc(a, 512); const kp = try std.json.Parser.init(a, true).parse(kstr); var pvk: [Ed25519.secret_length]u8 = undefined; pvk = kp.root.Object.get("privatekey") orelse null; if (pvk == null) { return null; } else return try Ed25519.KeyPair.fromSecretKey(&pvk); return null; } pub fn init(seed: ?[Ed25519.seed_length]u8) !Keys { return Keys { .pair = try KeyPair.create(seed) }; } pub fn toStr(self: Keys, a: Allocator) !str { const pkey = self.pair.public_key; const priv = self.pair.secret_key[0..Ed25519.secret_length]; const cmb = try std.mem.join(a, "\n", [_][]u8{ pkey, priv }); return cmb; } pub fn toFile(self: Keys, a: Allocator, ) !void { if (try Keys.file(a)) |f| { try f.writer().writeAll(try self.toStr()); } } pub fn printPair(self: Keys) void { const fmtHex = std.fmt.fmtSliceHexLower; print("\n\x1b[32;1mpubkey\x1b[0m: {}\n", .{fmtHex(&self.pair.public_key)}); print("\x1b[34;1mseckey\x1b[0m: {}\n", .{fmtHex(self.pair.secret_key[0..Ed25519.secret_length])}); } pub fn sign(keys: Keys, msg: str) ![64]u8 { return Ed25519.sign(msg, keys.pair, null); } /// Local record of modification pub const Entry = struct { id: [32]u8 = undefined, len: u32 = 0, signature: [64]u8 = undefined, tag: Tag = Tag.nop, sender_id: [32]u8, sender_nonce: u64 = 0, data: [*]u8 = @ptrCast([*]u8, ""), created: i64 = std.time.timestamp(), pub fn hash(self: *Entry) ![32]u8 { var b: [32]u8 = undefined; var hasher = Blake3.init(.{}); try self.write(hasher.writer()); hasher.final(&b); return b; } pub fn initMsg(a: Allocator, data: []const u8, keys: Keys) !*Entry { return Entry.init(a, 0, data, keys, Tag.nop); } pub fn init(a: Allocator, nonce: u64, data: []const u8, keys: Keys, tag: Tag) !*Entry{ const byt = try a.alignedAlloc(u8, std.math.max(@alignOf(Entry), @alignOf(u8)), @sizeOf(Entry) + data.len); errdefer a.free(byt); var entry = @ptrCast(*Entry, byt.ptr); std.mem.copy(u8, entry.data[0..data.len], data); entry.len = @intCast(u32, data.len); entry.tag = tag; entry.sender_id = keys.pair.public_key; entry.sender_nonce = nonce; entry.signature = try keys.sign(data); entry.id = try entry.hash(); return entry; } pub fn write(self: Entry, w: anytype) !void { try w.writeAll(&self.sender_id); try w.writeAll(&self.signature); try w.writeIntLittle(u32, self.len); try w.writeIntLittle(u64, self.sender_nonce); try w.writeIntLittle(u64, @intCast(u64, self.created)); try w.writeIntLittle(u8, @enumToInt(self.tag)); try w.writeAll(self.data[0..self.len]); } pub fn read(gpa: mem.Allocator, reader: anytype) !*Entry { var ent = try gpa.create(Entry); errdefer gpa.destroy(ent); ent.sender_id = reader.readBytesNoEof(32); ent.signature = reader.readBytesNoEof(64); ent.len = reader.readIntLittle(u32); if (ent.len > 65536) return error.DataTooLarge; ent = @ptrCast(*Entry, try gpa.realloc(std.mem.span(std.mem.asBytes(ent)), @sizeOf(Entry) + ent.len)); ent.sender_nonce = try reader.readIntLittle(u64); ent.created = try reader.readIntLittle(u64); ent.tag = try reader.readEnum(Entry.Tag, .Little); ent.data = @ptrCast([*]u8, ent.data.ptr) + @sizeOf(Entry); try reader.readNoEof(ent.data[0..ent.len]); ent.id = try Entry.hash(&ent); return ent; } };
src/keys.zig
const std = @import("std"); const span = std.mem.span; const bog = @import("bog.zig"); const gpa = std.heap.c_allocator; //! ABI WARNING -- REMEMBER TO CHANGE include/bog.h const Error = extern enum { None, OutOfMemory, TokenizeError, ParseError, CompileError, RuntimeError, MalformedByteCode, NotAMap, NoSuchMember, NotAFunction, InvalidArgCount, NativeFunctionsUnsupported, IoError, }; export fn bog_Vm_init(vm: **bog.Vm, import_files: bool) Error { const ptr = gpa.create(bog.Vm) catch |e| switch (e) { error.OutOfMemory => return .OutOfMemory, }; ptr.* = bog.Vm.init(gpa, .{ .import_files = import_files }); vm.* = ptr; return .None; } export fn bog_Vm_deinit(vm: *bog.Vm) void { vm.deinit(); } fn bog_Vm_addStd(vm: *bog.Vm) callconv(.C) Error { vm.addStd() catch |e| switch (e) { error.OutOfMemory => return .OutOfMemory, }; return .None; } fn bog_Vm_addStdNoIo(vm: *bog.Vm) callconv(.C) Error { vm.addStdNoIo() catch |e| switch (e) { error.OutOfMemory => return .OutOfMemory, }; return .None; } comptime { const build_options = @import("build_options"); if (!build_options.no_std) @export(bog_Vm_addStd, .{ .name = "bog_Vm_addStd", .linkage = .Strong }); if (!build_options.no_std_no_io) @export(bog_Vm_addStdNoIo, .{ .name = "bog_Vm_addStdNoIo", .linkage = .Strong }); } export fn bog_Vm_run(vm: *bog.Vm, res: **bog.Value, source: [*:0]const u8) Error { res.* = vm.run(span(source)) catch |e| switch (e) { error.OutOfMemory => return .OutOfMemory, error.TokenizeError => return .TokenizeError, error.ParseError => return .ParseError, error.CompileError => return .CompileError, error.RuntimeError => return .RuntimeError, error.MalformedByteCode => return .MalformedByteCode, }; return .None; } export fn bog_Vm_call(vm: *bog.Vm, res: **bog.Value, container: *bog.Value, func_name: [*:0]const u8) Error { res.* = vm.call(container, span(func_name), .{}) catch |e| switch (e) { error.OutOfMemory => return .OutOfMemory, error.RuntimeError => return .RuntimeError, error.MalformedByteCode => return .MalformedByteCode, error.NotAMap => return .NotAMap, error.NoSuchMember => return .NoSuchMember, error.NotAFunction => return .NotAFunction, error.InvalidArgCount => return .InvalidArgCount, error.NativeFunctionsUnsupported => return .NativeFunctionsUnsupported, }; return .None; } export fn bog_Vm_renderErrors(vm: *bog.Vm, source: [*:0]const u8, out: *std.c.FILE) Error { vm.errors.render(span(source), std.io.cWriter(out)) catch return .IoError; return .None; } export fn bog_Errors_init(errors: **bog.Errors) Error { const ptr = gpa.create(bog.Errors) catch |e| switch (e) { error.OutOfMemory => return .OutOfMemory, }; ptr.* = bog.Errors.init(gpa); errors.* = ptr; return .None; } export fn bog_Errors_deinit(errors: *bog.Errors) void { errors.deinit(); } export fn bog_Errors_render(errors: *bog.Errors, source: [*:0]const u8, out: *std.c.FILE) Error { errors.render(span(source), std.io.cWriter(out)) catch return .IoError; return .None; } export fn bog_parse(tree: **bog.Tree, source: [*:0]const u8, errors: *bog.Errors) Error { tree.* = bog.parse(gpa, span(source), errors) catch |e| switch (e) { error.OutOfMemory => return .OutOfMemory, error.TokenizeError => return .TokenizeError, error.ParseError => return .ParseError, }; return .None; } export fn bog_Tree_deinit(tree: *bog.Tree) void { tree.deinit(); } export fn bog_Tree_render(tree: *bog.Tree, out: *std.c.FILE, changed: ?*bool) Error { const c = tree.render(std.io.cWriter(out)) catch return .IoError; if (changed) |some| { some.* = c; } return .None; }
src/lib.zig
const std = @import("../index.zig"); const crypto = std.crypto; const debug = std.debug; const mem = std.mem; pub const HmacMd5 = Hmac(crypto.Md5); pub const HmacSha1 = Hmac(crypto.Sha1); pub const HmacSha256 = Hmac(crypto.Sha256); pub fn Hmac(comptime Hash: type) type { return struct { const Self = @This(); pub const mac_length = Hash.digest_length; pub const minimum_key_length = 0; o_key_pad: [Hash.block_length]u8, i_key_pad: [Hash.block_length]u8, scratch: [Hash.block_length]u8, hash: Hash, // HMAC(k, m) = H(o_key_pad | H(i_key_pad | msg)) where | is concatenation pub fn create(out: []u8, msg: []const u8, key: []const u8) void { var ctx = Self.init(key); ctx.update(msg); ctx.final(out[0..]); } pub fn init(key: []const u8) Self { var ctx: Self = undefined; // Normalize key length to block size of hash if (key.len > Hash.block_length) { Hash.hash(key, ctx.scratch[0..mac_length]); mem.set(u8, ctx.scratch[mac_length..Hash.block_length], 0); } else if (key.len < Hash.block_length) { mem.copy(u8, ctx.scratch[0..key.len], key); mem.set(u8, ctx.scratch[key.len..Hash.block_length], 0); } else { mem.copy(u8, ctx.scratch[0..], key); } for (ctx.o_key_pad) |*b, i| { b.* = ctx.scratch[i] ^ 0x5c; } for (ctx.i_key_pad) |*b, i| { b.* = ctx.scratch[i] ^ 0x36; } ctx.hash = Hash.init(); ctx.hash.update(ctx.i_key_pad[0..]); return ctx; } pub fn update(ctx: *Self, msg: []const u8) void { ctx.hash.update(msg); } pub fn final(ctx: *Self, out: []u8) void { debug.assert(Hash.block_length >= out.len and out.len >= mac_length); ctx.hash.final(ctx.scratch[0..mac_length]); ctx.hash.reset(); ctx.hash.update(ctx.o_key_pad[0..]); ctx.hash.update(ctx.scratch[0..mac_length]); ctx.hash.final(out[0..mac_length]); } }; } const htest = @import("test.zig"); test "hmac md5" { var out: [HmacMd5.mac_length]u8 = undefined; HmacMd5.create(out[0..], "", ""); htest.assertEqual("74e6f7298a9c2d168935f58c001bad88", out[0..]); HmacMd5.create(out[0..], "The quick brown fox jumps over the lazy dog", "key"); htest.assertEqual("<KEY>", out[0..]); } test "hmac sha1" { var out: [HmacSha1.mac_length]u8 = undefined; HmacSha1.create(out[0..], "", ""); htest.assertEqual("fbdb1d1b18aa6c08324b7d64b71fb76370690e1d", out[0..]); HmacSha1.create(out[0..], "The quick brown fox jumps over the lazy dog", "key"); htest.assertEqual("de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9", out[0..]); } test "hmac sha256" { var out: [HmacSha256.mac_length]u8 = undefined; HmacSha256.create(out[0..], "", ""); htest.assertEqual("b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad", out[0..]); HmacSha256.create(out[0..], "The quick brown fox jumps over the lazy dog", "key"); htest.assertEqual("f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8", out[0..]); }
std/crypto/hmac.zig
const assert = @import("std").debug.assert; const mem = @import("std").mem; const reflection = @This(); test "reflection: array, pointer, optional, error union type child" { comptime { assert(([10]u8).Child == u8); assert((*u8).Child == u8); assert((error!u8).Payload == u8); assert((?u8).Child == u8); } } test "reflection: function return type, var args, and param types" { comptime { assert(@typeOf(dummy).ReturnType == i32); assert(!@typeOf(dummy).is_var_args); assert(@typeOf(dummy_varargs).is_var_args); assert(@typeOf(dummy).arg_count == 3); assert(@ArgType(@typeOf(dummy), 0) == bool); assert(@ArgType(@typeOf(dummy), 1) == i32); assert(@ArgType(@typeOf(dummy), 2) == f32); } } fn dummy(a: bool, b: i32, c: f32) i32 { return 1234; } fn dummy_varargs(args: ...) void {} test "reflection: struct member types and names" { comptime { assert(@memberCount(Foo) == 3); assert(@memberType(Foo, 0) == i32); assert(@memberType(Foo, 1) == bool); assert(@memberType(Foo, 2) == void); assert(mem.eql(u8, @memberName(Foo, 0), "one")); assert(mem.eql(u8, @memberName(Foo, 1), "two")); assert(mem.eql(u8, @memberName(Foo, 2), "three")); } } test "reflection: enum member types and names" { comptime { assert(@memberCount(Bar) == 4); assert(@memberType(Bar, 0) == void); assert(@memberType(Bar, 1) == i32); assert(@memberType(Bar, 2) == bool); assert(@memberType(Bar, 3) == f64); assert(mem.eql(u8, @memberName(Bar, 0), "One")); assert(mem.eql(u8, @memberName(Bar, 1), "Two")); assert(mem.eql(u8, @memberName(Bar, 2), "Three")); assert(mem.eql(u8, @memberName(Bar, 3), "Four")); } } test "reflection: @field" { var f = Foo{ .one = 42, .two = true, .three = void{}, }; assert(f.one == f.one); assert(@field(f, "o" ++ "ne") == f.one); assert(@field(f, "t" ++ "wo") == f.two); assert(@field(f, "th" ++ "ree") == f.three); assert(@field(Foo, "const" ++ "ant") == Foo.constant); assert(@field(Bar, "O" ++ "ne") == Bar.One); assert(@field(Bar, "T" ++ "wo") == Bar.Two); assert(@field(Bar, "Th" ++ "ree") == Bar.Three); assert(@field(Bar, "F" ++ "our") == Bar.Four); assert(@field(reflection, "dum" ++ "my")(true, 1, 2) == dummy(true, 1, 2)); @field(f, "o" ++ "ne") = 4; assert(f.one == 4); } const Foo = struct { const constant = 52; one: i32, two: bool, three: void, }; const Bar = union(enum) { One: void, Two: i32, Three: bool, Four: f64, };
test/cases/reflection.zig
const std = @import("std"); const mach = @import("mach"); const gpu = @import("gpu"); const glfw = @import("glfw"); const zm = @import("zmath"); const Vertex = @import("cube_mesh.zig").Vertex; const vertices = @import("cube_mesh.zig").vertices; const App = mach.App(*FrameParams, .{}); const UniformBufferObject = struct { mat: zm.Mat, }; var timer: std.time.Timer = undefined; pub fn main() !void { timer = try std.time.Timer.start(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = gpa.allocator(); const ctx = try allocator.create(FrameParams); var app = try App.init(allocator, ctx, .{}); app.window.setKeyCallback(struct { fn callback(window: glfw.Window, key: glfw.Key, scancode: i32, action: glfw.Action, mods: glfw.Mods) void { _ = scancode; _ = mods; if (action == .press) { switch (key) { .space => window.setShouldClose(true), else => {}, } } } }.callback); try app.window.setSizeLimits(.{ .width = 20, .height = 20 }, .{ .width = null, .height = null }); const vs_module = app.device.createShaderModule(&.{ .label = "my vertex shader", .code = .{ .wgsl = @embedFile("vert.wgsl") }, }); const vertex_attributes = [_]gpu.VertexAttribute{ .{ .format = .float32x4, .offset = @offsetOf(Vertex, "pos"), .shader_location = 0 }, .{ .format = .float32x2, .offset = @offsetOf(Vertex, "uv"), .shader_location = 1 }, }; const vertex_buffer_layout = gpu.VertexBufferLayout{ .array_stride = @sizeOf(Vertex), .step_mode = .vertex, .attribute_count = vertex_attributes.len, .attributes = &vertex_attributes, }; const fs_module = app.device.createShaderModule(&.{ .label = "my fragment shader", .code = .{ .wgsl = @embedFile("frag.wgsl") }, }); const color_target = gpu.ColorTargetState{ .format = app.swap_chain_format, .blend = null, .write_mask = gpu.ColorWriteMask.all, }; const fragment = gpu.FragmentState{ .module = fs_module, .entry_point = "main", .targets = &.{color_target}, .constants = null, }; const bgle = gpu.BindGroupLayout.Entry.buffer(0, .{ .vertex = true }, .uniform, true, 0); const bgl = app.device.createBindGroupLayout( &gpu.BindGroupLayout.Descriptor{ .entries = &.{bgle}, }, ); const bind_group_layouts = [_]gpu.BindGroupLayout{bgl}; const pipeline_layout = app.device.createPipelineLayout(&.{ .bind_group_layouts = &bind_group_layouts, }); const pipeline_descriptor = gpu.RenderPipeline.Descriptor{ .fragment = &fragment, .layout = pipeline_layout, .depth_stencil = null, .vertex = .{ .module = vs_module, .entry_point = "main", .buffers = &.{vertex_buffer_layout}, }, .multisample = .{ .count = 1, .mask = 0xFFFFFFFF, .alpha_to_coverage_enabled = false, }, .primitive = .{ .front_face = .ccw, .cull_mode = .back, .topology = .triangle_list, .strip_index_format = .none, }, }; const vertex_buffer = app.device.createBuffer(&.{ .usage = .{ .vertex = true }, .size = @sizeOf(Vertex) * vertices.len, .mapped_at_creation = true, }); var vertex_mapped = vertex_buffer.getMappedRange(Vertex, 0, vertices.len); std.mem.copy(Vertex, vertex_mapped, vertices[0..]); vertex_buffer.unmap(); defer vertex_buffer.release(); const x_count = 4; const y_count = 4; const num_instances = x_count * y_count; const uniform_buffer = app.device.createBuffer(&.{ .usage = .{ .copy_dst = true, .uniform = true }, .size = @sizeOf(UniformBufferObject) * num_instances, .mapped_at_creation = false, }); defer uniform_buffer.release(); const bind_group = app.device.createBindGroup( &gpu.BindGroup.Descriptor{ .layout = bgl, .entries = &.{ gpu.BindGroup.Entry.buffer(0, uniform_buffer, 0, @sizeOf(UniformBufferObject) * num_instances), }, }, ); defer bind_group.release(); ctx.* = FrameParams{ .pipeline = app.device.createRenderPipeline(&pipeline_descriptor), .queue = app.device.getQueue(), .vertex_buffer = vertex_buffer, .uniform_buffer = uniform_buffer, .bind_group = bind_group, }; vs_module.release(); fs_module.release(); pipeline_layout.release(); bgl.release(); try app.run(.{ .frame = frame }); } const FrameParams = struct { pipeline: gpu.RenderPipeline, queue: gpu.Queue, vertex_buffer: gpu.Buffer, uniform_buffer: gpu.Buffer, bind_group: gpu.BindGroup, }; var i: u32 = 0; fn frame(app: *App, params: *FrameParams) !void { i += 1; const back_buffer_view = app.swap_chain.?.getCurrentTextureView(); const color_attachment = gpu.RenderPassColorAttachment{ .view = back_buffer_view, .resolve_target = null, .clear_value = std.mem.zeroes(gpu.Color), .load_op = .clear, .store_op = .store, }; const encoder = app.device.createCommandEncoder(null); const render_pass_info = gpu.RenderPassEncoder.Descriptor{ .color_attachments = &.{color_attachment}, }; { const proj = zm.perspectiveFovRh( (std.math.pi / 3.0), @intToFloat(f32, app.current_desc.width) / @intToFloat(f32, app.current_desc.height), 10, 30, ); var ubos: [16]UniformBufferObject = undefined; const time = @intToFloat(f32, timer.read()) / @as(f32, std.time.ns_per_s); const step: f32 = 4.0; var m: u8 = 0; var x: u8 = 0; while (x < 4) : (x += 1) { var y: u8 = 0; while (y < 4) : (y += 1) { const trans = zm.translation(step * (@intToFloat(f32, x) - 2.0 + 0.5), step * (@intToFloat(f32, y) - 2.0 + 0.5), -20); const localTime = time + @intToFloat(f32, m) * 0.5; const model = zm.mul(zm.mul(zm.mul(zm.rotationX(localTime * (std.math.pi / 2.1)), zm.rotationY(localTime * (std.math.pi / 0.9))), zm.rotationZ(localTime * (std.math.pi / 1.3))), trans); const mvp = zm.mul(model, proj); const ubo = UniformBufferObject{ .mat = mvp, }; ubos[m] = ubo; m += 1; } } encoder.writeBuffer(params.uniform_buffer, 0, UniformBufferObject, &ubos); } const pass = encoder.beginRenderPass(&render_pass_info); pass.setPipeline(params.pipeline); pass.setVertexBuffer(0, params.vertex_buffer, 0, @sizeOf(Vertex) * vertices.len); pass.setBindGroup(0, params.bind_group, &.{0}); pass.draw(vertices.len, 16, 0, 0); pass.end(); pass.release(); var command = encoder.finish(null); encoder.release(); params.queue.submit(&.{command}); command.release(); app.swap_chain.?.present(); back_buffer_view.release(); }
examples/instanced-cube/main.zig
const aoc = @import("../aoc.zig"); const std = @import("std"); const Operand = union(enum) { constant: u16, wire: []const u8, fn parse(op: []const u8) Operand { const constant = std.fmt.parseInt(u16, op, 10) catch return Operand { .wire = op }; return Operand { .constant = constant }; } fn evaluate(self: Operand, cache: *WireCache) u16 { return switch (self) { .wire => |w| cache.get(w), .constant => |c| c, }; } }; const LogicGate = enum { AND, OR, LSHIFT, RSHIFT, NOT, BUFFER }; const Operation = struct { op1: Operand = .{.constant = 0}, op2: Operand = .{.constant = 0}, gate: LogicGate = undefined, fn evaluate(self: *Operation, cache: *WireCache) u16 { const op1 = self.op1.evaluate(cache); const op2 = self.op2.evaluate(cache); return switch (self.gate) { .AND => op1 & op2, .OR => op1 | op2, .LSHIFT => op1 << @intCast(u4, op2), .RSHIFT => op1 >> @intCast(u4, op2), .NOT => ~op2, .BUFFER => op1, }; } }; const OutputMap = std.StringHashMap(Operation); const WireCache = struct { backing: WireCacheBacking, outputs: OutputMap, const WireCacheBacking = std.StringHashMap(u16); fn init(allocator: std.mem.Allocator, outputs: OutputMap) WireCache { return WireCache { .backing = WireCacheBacking.init(allocator), .outputs = outputs }; } fn deinit(self: *WireCache) void { self.backing.deinit(); } fn get(self: *WireCache, output: []const u8) u16 { const cached_value = self.backing.get(output); if (cached_value) |v| { return v; } const value = self.outputs.get(output).?.evaluate(self); _ = self.backing.put(output, value) catch unreachable; return value; } }; const TokenState = enum { operand1_not, gate_arrow, operand2, arrow, output }; pub fn run(problem: *aoc.Problem) !aoc.Solution { var outputs = OutputMap.init(problem.allocator); defer outputs.deinit(); while (problem.line()) |line| { var operation = Operation {}; var output: []const u8 = undefined; var state = TokenState.operand1_not; var tokens = std.mem.tokenize(u8, line, " "); while (tokens.next()) |token| { switch (state) { .operand1_not => { if (std.mem.eql(u8, token, "NOT")) { operation.gate = .NOT; state = .operand2; } else { operation.op1 = Operand.parse(token); state = .gate_arrow; } }, .gate_arrow => { if (std.mem.eql(u8, token, "->")) { operation.gate = .BUFFER; state = .output; } else if (std.mem.eql(u8, token, "AND")) { operation.gate = .AND; state = .operand2; } else if (std.mem.eql(u8, token, "OR")) { operation.gate = .OR; state = .operand2; } else if (std.mem.eql(u8, token, "LSHIFT")) { operation.gate = .LSHIFT; state = .operand2; } else if (std.mem.eql(u8, token, "RSHIFT")) { operation.gate = .RSHIFT; state = .operand2; } }, .operand2 => { operation.op2 = Operand.parse(token); state = .arrow; }, .arrow => state = .output, .output => output = token, } } _ = try outputs.put(output, operation); } var cache1 = WireCache.init(problem.allocator, outputs); defer cache1.deinit(); const part1 = outputs.get("a").?.evaluate(&cache1); outputs.getPtr("b").?.op1.constant = part1; var cache2 = WireCache.init(problem.allocator, outputs); defer cache2.deinit(); const part2 = outputs.get("a").?.evaluate(&cache2); return problem.solution(part1, part2); }
src/main/zig/2015/day07.zig
pub const QOS_MAX_OBJECT_STRING_LENGTH = @as(u32, 256); pub const QOS_TRAFFIC_GENERAL_ID_BASE = @as(u32, 4000); pub const SERVICETYPE_NOTRAFFIC = @as(u32, 0); pub const SERVICETYPE_BESTEFFORT = @as(u32, 1); pub const SERVICETYPE_CONTROLLEDLOAD = @as(u32, 2); pub const SERVICETYPE_GUARANTEED = @as(u32, 3); pub const SERVICETYPE_NETWORK_UNAVAILABLE = @as(u32, 4); pub const SERVICETYPE_GENERAL_INFORMATION = @as(u32, 5); pub const SERVICETYPE_NOCHANGE = @as(u32, 6); pub const SERVICETYPE_NONCONFORMING = @as(u32, 9); pub const SERVICETYPE_NETWORK_CONTROL = @as(u32, 10); pub const SERVICETYPE_QUALITATIVE = @as(u32, 13); pub const SERVICE_BESTEFFORT = @as(u32, 2147549184); pub const SERVICE_CONTROLLEDLOAD = @as(u32, 2147614720); pub const SERVICE_GUARANTEED = @as(u32, 2147745792); pub const SERVICE_QUALITATIVE = @as(u32, 2149580800); pub const SERVICE_NO_TRAFFIC_CONTROL = @as(u32, 2164260864); pub const SERVICE_NO_QOS_SIGNALING = @as(u32, 1073741824); pub const QOS_NOT_SPECIFIED = @as(u32, 4294967295); pub const POSITIVE_INFINITY_RATE = @as(u32, 4294967294); pub const QOS_GENERAL_ID_BASE = @as(u32, 2000); pub const TC_NONCONF_BORROW = @as(u32, 0); pub const TC_NONCONF_SHAPE = @as(u32, 1); pub const TC_NONCONF_DISCARD = @as(u32, 2); pub const TC_NONCONF_BORROW_PLUS = @as(u32, 3); pub const SESSFLG_E_Police = @as(u32, 1); pub const Opt_Share_mask = @as(u32, 24); pub const Opt_Distinct = @as(u32, 8); pub const Opt_Shared = @as(u32, 16); pub const Opt_SndSel_mask = @as(u32, 7); pub const Opt_Wildcard = @as(u32, 1); pub const Opt_Explicit = @as(u32, 2); pub const ERROR_SPECF_InPlace = @as(u32, 1); pub const ERROR_SPECF_NotGuilty = @as(u32, 2); pub const ERR_FORWARD_OK = @as(u32, 32768); pub const ERR_Usage_globl = @as(u32, 0); pub const ERR_Usage_local = @as(u32, 16); pub const ERR_Usage_serv = @as(u32, 17); pub const ERR_global_mask = @as(u32, 4095); pub const GENERAL_INFO = @as(u32, 1); pub const GUARANTEED_SERV = @as(u32, 2); pub const PREDICTIVE_SERV = @as(u32, 3); pub const CONTROLLED_DELAY_SERV = @as(u32, 4); pub const CONTROLLED_LOAD_SERV = @as(u32, 5); pub const QUALITATIVE_SERV = @as(u32, 6); pub const INTSERV_VERS_MASK = @as(u32, 240); pub const INTSERV_VERSION0 = @as(u32, 0); pub const ISSH_BREAK_BIT = @as(u32, 128); pub const ISPH_FLG_INV = @as(u32, 128); pub const RSVP_PATH = @as(u32, 1); pub const RSVP_RESV = @as(u32, 2); pub const RSVP_PATH_ERR = @as(u32, 3); pub const RSVP_RESV_ERR = @as(u32, 4); pub const RSVP_PATH_TEAR = @as(u32, 5); pub const RSVP_RESV_TEAR = @as(u32, 6); pub const RSVP_Err_NONE = @as(u32, 0); pub const RSVP_Erv_Nonev = @as(u32, 0); pub const RSVP_Err_ADMISSION = @as(u32, 1); pub const RSVP_Erv_Other = @as(u32, 0); pub const RSVP_Erv_DelayBnd = @as(u32, 1); pub const RSVP_Erv_Bandwidth = @as(u32, 2); pub const RSVP_Erv_MTU = @as(u32, 3); pub const RSVP_Erv_Flow_Rate = @as(u32, 32769); pub const RSVP_Erv_Bucket_szie = @as(u32, 32770); pub const RSVP_Erv_Peak_Rate = @as(u32, 32771); pub const RSVP_Erv_Min_Policied_size = @as(u32, 32772); pub const RSVP_Err_POLICY = @as(u32, 2); pub const POLICY_ERRV_NO_MORE_INFO = @as(u32, 1); pub const POLICY_ERRV_UNSUPPORTED_CREDENTIAL_TYPE = @as(u32, 2); pub const POLICY_ERRV_INSUFFICIENT_PRIVILEGES = @as(u32, 3); pub const POLICY_ERRV_EXPIRED_CREDENTIALS = @as(u32, 4); pub const POLICY_ERRV_IDENTITY_CHANGED = @as(u32, 5); pub const POLICY_ERRV_UNKNOWN = @as(u32, 0); pub const POLICY_ERRV_GLOBAL_DEF_FLOW_COUNT = @as(u32, 1); pub const POLICY_ERRV_GLOBAL_GRP_FLOW_COUNT = @as(u32, 2); pub const POLICY_ERRV_GLOBAL_USER_FLOW_COUNT = @as(u32, 3); pub const POLICY_ERRV_GLOBAL_UNAUTH_USER_FLOW_COUNT = @as(u32, 4); pub const POLICY_ERRV_SUBNET_DEF_FLOW_COUNT = @as(u32, 5); pub const POLICY_ERRV_SUBNET_GRP_FLOW_COUNT = @as(u32, 6); pub const POLICY_ERRV_SUBNET_USER_FLOW_COUNT = @as(u32, 7); pub const POLICY_ERRV_SUBNET_UNAUTH_USER_FLOW_COUNT = @as(u32, 8); pub const POLICY_ERRV_GLOBAL_DEF_FLOW_DURATION = @as(u32, 9); pub const POLICY_ERRV_GLOBAL_GRP_FLOW_DURATION = @as(u32, 10); pub const POLICY_ERRV_GLOBAL_USER_FLOW_DURATION = @as(u32, 11); pub const POLICY_ERRV_GLOBAL_UNAUTH_USER_FLOW_DURATION = @as(u32, 12); pub const POLICY_ERRV_SUBNET_DEF_FLOW_DURATION = @as(u32, 13); pub const POLICY_ERRV_SUBNET_GRP_FLOW_DURATION = @as(u32, 14); pub const POLICY_ERRV_SUBNET_USER_FLOW_DURATION = @as(u32, 15); pub const POLICY_ERRV_SUBNET_UNAUTH_USER_FLOW_DURATION = @as(u32, 16); pub const POLICY_ERRV_GLOBAL_DEF_FLOW_RATE = @as(u32, 17); pub const POLICY_ERRV_GLOBAL_GRP_FLOW_RATE = @as(u32, 18); pub const POLICY_ERRV_GLOBAL_USER_FLOW_RATE = @as(u32, 19); pub const POLICY_ERRV_GLOBAL_UNAUTH_USER_FLOW_RATE = @as(u32, 20); pub const POLICY_ERRV_SUBNET_DEF_FLOW_RATE = @as(u32, 21); pub const POLICY_ERRV_SUBNET_GRP_FLOW_RATE = @as(u32, 22); pub const POLICY_ERRV_SUBNET_USER_FLOW_RATE = @as(u32, 23); pub const POLICY_ERRV_SUBNET_UNAUTH_USER_FLOW_RATE = @as(u32, 24); pub const POLICY_ERRV_GLOBAL_DEF_PEAK_RATE = @as(u32, 25); pub const POLICY_ERRV_GLOBAL_GRP_PEAK_RATE = @as(u32, 26); pub const POLICY_ERRV_GLOBAL_USER_PEAK_RATE = @as(u32, 27); pub const POLICY_ERRV_GLOBAL_UNAUTH_USER_PEAK_RATE = @as(u32, 28); pub const POLICY_ERRV_SUBNET_DEF_PEAK_RATE = @as(u32, 29); pub const POLICY_ERRV_SUBNET_GRP_PEAK_RATE = @as(u32, 30); pub const POLICY_ERRV_SUBNET_USER_PEAK_RATE = @as(u32, 31); pub const POLICY_ERRV_SUBNET_UNAUTH_USER_PEAK_RATE = @as(u32, 32); pub const POLICY_ERRV_GLOBAL_DEF_SUM_FLOW_RATE = @as(u32, 33); pub const POLICY_ERRV_GLOBAL_GRP_SUM_FLOW_RATE = @as(u32, 34); pub const POLICY_ERRV_GLOBAL_USER_SUM_FLOW_RATE = @as(u32, 35); pub const POLICY_ERRV_GLOBAL_UNAUTH_USER_SUM_FLOW_RATE = @as(u32, 36); pub const POLICY_ERRV_SUBNET_DEF_SUM_FLOW_RATE = @as(u32, 37); pub const POLICY_ERRV_SUBNET_GRP_SUM_FLOW_RATE = @as(u32, 38); pub const POLICY_ERRV_SUBNET_USER_SUM_FLOW_RATE = @as(u32, 39); pub const POLICY_ERRV_SUBNET_UNAUTH_USER_SUM_FLOW_RATE = @as(u32, 40); pub const POLICY_ERRV_GLOBAL_DEF_SUM_PEAK_RATE = @as(u32, 41); pub const POLICY_ERRV_GLOBAL_GRP_SUM_PEAK_RATE = @as(u32, 42); pub const POLICY_ERRV_GLOBAL_USER_SUM_PEAK_RATE = @as(u32, 43); pub const POLICY_ERRV_GLOBAL_UNAUTH_USER_SUM_PEAK_RATE = @as(u32, 44); pub const POLICY_ERRV_SUBNET_DEF_SUM_PEAK_RATE = @as(u32, 45); pub const POLICY_ERRV_SUBNET_GRP_SUM_PEAK_RATE = @as(u32, 46); pub const POLICY_ERRV_SUBNET_USER_SUM_PEAK_RATE = @as(u32, 47); pub const POLICY_ERRV_SUBNET_UNAUTH_USER_SUM_PEAK_RATE = @as(u32, 48); pub const POLICY_ERRV_UNKNOWN_USER = @as(u32, 49); pub const POLICY_ERRV_NO_PRIVILEGES = @as(u32, 50); pub const POLICY_ERRV_EXPIRED_USER_TOKEN = @as(u32, 51); pub const POLICY_ERRV_NO_RESOURCES = @as(u32, 52); pub const POLICY_ERRV_PRE_EMPTED = @as(u32, 53); pub const POLICY_ERRV_USER_CHANGED = @as(u32, 54); pub const POLICY_ERRV_NO_ACCEPTS = @as(u32, 55); pub const POLICY_ERRV_NO_MEMORY = @as(u32, 56); pub const POLICY_ERRV_CRAZY_FLOWSPEC = @as(u32, 57); pub const RSVP_Err_NO_PATH = @as(u32, 3); pub const RSVP_Err_NO_SENDER = @as(u32, 4); pub const RSVP_Err_BAD_STYLE = @as(u32, 5); pub const RSVP_Err_UNKNOWN_STYLE = @as(u32, 6); pub const RSVP_Err_BAD_DSTPORT = @as(u32, 7); pub const RSVP_Err_BAD_SNDPORT = @as(u32, 8); pub const RSVP_Err_AMBIG_FILTER = @as(u32, 9); pub const RSVP_Err_PREEMPTED = @as(u32, 12); pub const RSVP_Err_UNKN_OBJ_CLASS = @as(u32, 13); pub const RSVP_Err_UNKNOWN_CTYPE = @as(u32, 14); pub const RSVP_Err_API_ERROR = @as(u32, 20); pub const RSVP_Err_TC_ERROR = @as(u32, 21); pub const RSVP_Erv_Conflict_Serv = @as(u32, 1); pub const RSVP_Erv_No_Serv = @as(u32, 2); pub const RSVP_Erv_Crazy_Flowspec = @as(u32, 3); pub const RSVP_Erv_Crazy_Tspec = @as(u32, 4); pub const RSVP_Err_TC_SYS_ERROR = @as(u32, 22); pub const RSVP_Err_RSVP_SYS_ERROR = @as(u32, 23); pub const RSVP_Erv_MEMORY = @as(u32, 1); pub const RSVP_Erv_API = @as(u32, 2); pub const LPM_PE_USER_IDENTITY = @as(u32, 2); pub const LPM_PE_APP_IDENTITY = @as(u32, 3); pub const ERROR_NO_MORE_INFO = @as(u32, 1); pub const UNSUPPORTED_CREDENTIAL_TYPE = @as(u32, 2); pub const INSUFFICIENT_PRIVILEGES = @as(u32, 3); pub const EXPIRED_CREDENTIAL = @as(u32, 4); pub const IDENTITY_CHANGED = @as(u32, 5); pub const LPM_OK = @as(u32, 0); pub const INV_LPM_HANDLE = @as(u32, 1); pub const LPM_TIME_OUT = @as(u32, 2); pub const INV_REQ_HANDLE = @as(u32, 3); pub const DUP_RESULTS = @as(u32, 4); pub const INV_RESULTS = @as(u32, 5); pub const LPM_PE_ALL_TYPES = @as(u32, 0); pub const LPM_API_VERSION_1 = @as(u32, 1); pub const PCM_VERSION_1 = @as(u32, 1); pub const LPV_RESERVED = @as(u32, 0); pub const LPV_MIN_PRIORITY = @as(u32, 1); pub const LPV_MAX_PRIORITY = @as(u32, 65280); pub const LPV_DROP_MSG = @as(u32, 65533); pub const LPV_DONT_CARE = @as(u32, 65534); pub const LPV_REJECT = @as(u32, 65535); pub const FORCE_IMMEDIATE_REFRESH = @as(u32, 1); pub const LPM_RESULT_READY = @as(u32, 0); pub const LPM_RESULT_DEFER = @as(u32, 1); pub const RCVD_PATH_TEAR = @as(u32, 1); pub const RCVD_RESV_TEAR = @as(u32, 2); pub const ADM_CTRL_FAILED = @as(u32, 3); pub const STATE_TIMEOUT = @as(u32, 4); pub const FLOW_DURATION = @as(u32, 5); pub const RESOURCES_ALLOCATED = @as(u32, 1); pub const RESOURCES_MODIFIED = @as(u32, 2); pub const CURRENT_TCI_VERSION = @as(u32, 2); pub const TC_NOTIFY_IFC_UP = @as(u32, 1); pub const TC_NOTIFY_IFC_CLOSE = @as(u32, 2); pub const TC_NOTIFY_IFC_CHANGE = @as(u32, 3); pub const TC_NOTIFY_PARAM_CHANGED = @as(u32, 4); pub const TC_NOTIFY_FLOW_CLOSE = @as(u32, 5); pub const MAX_STRING_LENGTH = @as(u32, 256); pub const QOS_OUTGOING_DEFAULT_MINIMUM_BANDWIDTH = @as(u32, 4294967295); pub const QOS_QUERYFLOW_FRESH = @as(u32, 1); pub const QOS_NON_ADAPTIVE_FLOW = @as(u32, 2); pub const RSVP_OBJECT_ID_BASE = @as(u32, 1000); pub const RSVP_DEFAULT_STYLE = @as(u32, 0); pub const RSVP_WILDCARD_STYLE = @as(u32, 1); pub const RSVP_FIXED_FILTER_STYLE = @as(u32, 2); pub const RSVP_SHARED_EXPLICIT_STYLE = @as(u32, 3); pub const AD_FLAG_BREAK_BIT = @as(u32, 1); pub const QOSSPBASE = @as(u32, 50000); pub const ALLOWED_TO_SEND_DATA = @as(u32, 50001); pub const ABLE_TO_RECV_RSVP = @as(u32, 50002); pub const LINE_RATE = @as(u32, 50003); pub const LOCAL_TRAFFIC_CONTROL = @as(u32, 50004); pub const LOCAL_QOSABILITY = @as(u32, 50005); pub const END_TO_END_QOSABILITY = @as(u32, 50006); pub const INFO_NOT_AVAILABLE = @as(u32, 4294967295); pub const ANY_DEST_ADDR = @as(u32, 4294967295); pub const MODERATELY_DELAY_SENSITIVE = @as(u32, 4294967293); pub const HIGHLY_DELAY_SENSITIVE = @as(u32, 4294967294); pub const QOSSP_ERR_BASE = @as(u32, 56000); pub const GQOS_NO_ERRORCODE = @as(u32, 0); pub const GQOS_NO_ERRORVALUE = @as(u32, 0); pub const GQOS_ERRORCODE_UNKNOWN = @as(u32, 4294967295); pub const GQOS_ERRORVALUE_UNKNOWN = @as(u32, 4294967295); pub const GQOS_NET_ADMISSION = @as(u32, 56100); pub const GQOS_NET_POLICY = @as(u32, 56200); pub const GQOS_RSVP = @as(u32, 56300); pub const GQOS_API = @as(u32, 56400); pub const GQOS_KERNEL_TC_SYS = @as(u32, 56500); pub const GQOS_RSVP_SYS = @as(u32, 56600); pub const GQOS_KERNEL_TC = @as(u32, 56700); pub const PE_TYPE_APPID = @as(u32, 3); pub const PE_ATTRIB_TYPE_POLICY_LOCATOR = @as(u32, 1); pub const POLICY_LOCATOR_SUB_TYPE_ASCII_DN = @as(u32, 1); pub const POLICY_LOCATOR_SUB_TYPE_UNICODE_DN = @as(u32, 2); pub const POLICY_LOCATOR_SUB_TYPE_ASCII_DN_ENC = @as(u32, 3); pub const POLICY_LOCATOR_SUB_TYPE_UNICODE_DN_ENC = @as(u32, 4); pub const PE_ATTRIB_TYPE_CREDENTIAL = @as(u32, 2); pub const CREDENTIAL_SUB_TYPE_ASCII_ID = @as(u32, 1); pub const CREDENTIAL_SUB_TYPE_UNICODE_ID = @as(u32, 2); pub const CREDENTIAL_SUB_TYPE_KERBEROS_TKT = @as(u32, 3); pub const CREDENTIAL_SUB_TYPE_X509_V3_CERT = @as(u32, 4); pub const CREDENTIAL_SUB_TYPE_PGP_CERT = @as(u32, 5); pub const TCBASE = @as(u32, 7500); pub const ERROR_INCOMPATIBLE_TCI_VERSION = @as(u32, 7501); pub const ERROR_INVALID_SERVICE_TYPE = @as(u32, 7502); pub const ERROR_INVALID_TOKEN_RATE = @as(u32, 7503); pub const ERROR_INVALID_PEAK_RATE = @as(u32, 7504); pub const ERROR_INVALID_SD_MODE = @as(u32, 7505); pub const ERROR_INVALID_QOS_PRIORITY = @as(u32, 7506); pub const ERROR_INVALID_TRAFFIC_CLASS = @as(u32, 7507); pub const ERROR_INVALID_ADDRESS_TYPE = @as(u32, 7508); pub const ERROR_DUPLICATE_FILTER = @as(u32, 7509); pub const ERROR_FILTER_CONFLICT = @as(u32, 7510); pub const ERROR_ADDRESS_TYPE_NOT_SUPPORTED = @as(u32, 7511); pub const ERROR_TC_SUPPORTED_OBJECTS_EXIST = @as(u32, 7512); pub const ERROR_INCOMPATABLE_QOS = @as(u32, 7513); pub const ERROR_TC_NOT_SUPPORTED = @as(u32, 7514); pub const ERROR_TC_OBJECT_LENGTH_INVALID = @as(u32, 7515); pub const ERROR_INVALID_FLOW_MODE = @as(u32, 7516); pub const ERROR_INVALID_DIFFSERV_FLOW = @as(u32, 7517); pub const ERROR_DS_MAPPING_EXISTS = @as(u32, 7518); pub const ERROR_INVALID_SHAPE_RATE = @as(u32, 7519); pub const ERROR_INVALID_DS_CLASS = @as(u32, 7520); pub const ERROR_TOO_MANY_CLIENTS = @as(u32, 7521); pub const GUID_QOS_REMAINING_BANDWIDTH = Guid.initString("c4c51720-40ec-11d1-2c91-00aa00574915"); pub const GUID_QOS_BESTEFFORT_BANDWIDTH = Guid.initString("ed885290-40ec-11d1-2c91-00aa00574915"); pub const GUID_QOS_LATENCY = Guid.initString("fc408ef0-40ec-11d1-2c91-00aa00574915"); pub const GUID_QOS_FLOW_COUNT = Guid.initString("1147f880-40ed-11d1-2c91-00aa00574915"); pub const GUID_QOS_NON_BESTEFFORT_LIMIT = Guid.initString("185c44e0-40ed-11d1-2c91-00aa00574915"); pub const GUID_QOS_MAX_OUTSTANDING_SENDS = Guid.initString("161ffa86-6120-11d1-2c91-00aa00574915"); pub const GUID_QOS_STATISTICS_BUFFER = Guid.initString("bb2c0980-e900-11d1-b07e-0080c71382bf"); pub const GUID_QOS_FLOW_MODE = Guid.initString("5c82290a-515a-11d2-8e58-00c04fc9bfcb"); pub const GUID_QOS_ISSLOW_FLOW = Guid.initString("abf273a4-ee07-11d2-be1b-00a0c99ee63b"); pub const GUID_QOS_TIMER_RESOLUTION = Guid.initString("ba10cc88-f13e-11d2-be1b-00a0c99ee63b"); pub const GUID_QOS_FLOW_IP_CONFORMING = Guid.initString("07f99a8b-fcd2-11d2-be1e-00a0c99ee63b"); pub const GUID_QOS_FLOW_IP_NONCONFORMING = Guid.initString("087a5987-fcd2-11d2-be1e-00a0c99ee63b"); pub const GUID_QOS_FLOW_8021P_CONFORMING = Guid.initString("08c1e013-fcd2-11d2-be1e-00a0c99ee63b"); pub const GUID_QOS_FLOW_8021P_NONCONFORMING = Guid.initString("09023f91-fcd2-11d2-be1e-00a0c99ee63b"); pub const GUID_QOS_ENABLE_AVG_STATS = Guid.initString("bafb6d11-27c4-4801-a46f-ef8080c188c8"); pub const GUID_QOS_ENABLE_WINDOW_ADJUSTMENT = Guid.initString("aa966725-d3e9-4c55-b335-2a00279a1e64"); pub const FSCTL_TCP_BASE = @as(u32, 18); pub const IF_MIB_STATS_ID = @as(u32, 1); pub const IP_MIB_STATS_ID = @as(u32, 1); pub const IP_MIB_ADDRTABLE_ENTRY_ID = @as(u32, 258); pub const IP_INTFC_INFO_ID = @as(u32, 259); pub const MAX_PHYSADDR_SIZE = @as(u32, 8); pub const SIPAEV_PREBOOT_CERT = @as(u32, 0); pub const SIPAEV_POST_CODE = @as(u32, 1); pub const SIPAEV_UNUSED = @as(u32, 2); pub const SIPAEV_NO_ACTION = @as(u32, 3); pub const SIPAEV_SEPARATOR = @as(u32, 4); pub const SIPAEV_ACTION = @as(u32, 5); pub const SIPAEV_EVENT_TAG = @as(u32, 6); pub const SIPAEV_S_CRTM_CONTENTS = @as(u32, 7); pub const SIPAEV_S_CRTM_VERSION = @as(u32, 8); pub const SIPAEV_CPU_MICROCODE = @as(u32, 9); pub const SIPAEV_PLATFORM_CONFIG_FLAGS = @as(u32, 10); pub const SIPAEV_TABLE_OF_DEVICES = @as(u32, 11); pub const SIPAEV_COMPACT_HASH = @as(u32, 12); pub const SIPAEV_IPL = @as(u32, 13); pub const SIPAEV_IPL_PARTITION_DATA = @as(u32, 14); pub const SIPAEV_NONHOST_CODE = @as(u32, 15); pub const SIPAEV_NONHOST_CONFIG = @as(u32, 16); pub const SIPAEV_NONHOST_INFO = @as(u32, 17); pub const SIPAEV_OMIT_BOOT_DEVICE_EVENTS = @as(u32, 18); pub const SIPAEV_EFI_EVENT_BASE = @as(u32, 2147483648); pub const SIPAEV_EFI_VARIABLE_DRIVER_CONFIG = @as(u32, 2147483649); pub const SIPAEV_EFI_VARIABLE_BOOT = @as(u32, 2147483650); pub const SIPAEV_EFI_BOOT_SERVICES_APPLICATION = @as(u32, 2147483651); pub const SIPAEV_EFI_BOOT_SERVICES_DRIVER = @as(u32, 2147483652); pub const SIPAEV_EFI_RUNTIME_SERVICES_DRIVER = @as(u32, 2147483653); pub const SIPAEV_EFI_GPT_EVENT = @as(u32, 2147483654); pub const SIPAEV_EFI_ACTION = @as(u32, 2147483655); pub const SIPAEV_EFI_PLATFORM_FIRMWARE_BLOB = @as(u32, 2147483656); pub const SIPAEV_EFI_HANDOFF_TABLES = @as(u32, 2147483657); pub const SIPAEV_EFI_PLATFORM_FIRMWARE_BLOB2 = @as(u32, 2147483658); pub const SIPAEV_EFI_HANDOFF_TABLES2 = @as(u32, 2147483659); pub const SIPAEV_EFI_HCRTM_EVENT = @as(u32, 2147483664); pub const SIPAEV_EFI_VARIABLE_AUTHORITY = @as(u32, 2147483872); pub const SIPAEV_EFI_SPDM_FIRMWARE_BLOB = @as(u32, 2147483873); pub const SIPAEV_EFI_SPDM_FIRMWARE_CONFIG = @as(u32, 2147483874); pub const SIPAEV_TXT_EVENT_BASE = @as(u32, 1024); pub const SIPAEV_TXT_PCR_MAPPING = @as(u32, 1025); pub const SIPAEV_TXT_HASH_START = @as(u32, 1026); pub const SIPAEV_TXT_COMBINED_HASH = @as(u32, 1027); pub const SIPAEV_TXT_MLE_HASH = @as(u32, 1028); pub const SIPAEV_TXT_BIOSAC_REG_DATA = @as(u32, 1034); pub const SIPAEV_TXT_CPU_SCRTM_STAT = @as(u32, 1035); pub const SIPAEV_TXT_LCP_CONTROL_HASH = @as(u32, 1036); pub const SIPAEV_TXT_ELEMENTS_HASH = @as(u32, 1037); pub const SIPAEV_TXT_STM_HASH = @as(u32, 1038); pub const SIPAEV_TXT_OSSINITDATA_CAP_HASH = @as(u32, 1039); pub const SIPAEV_TXT_SINIT_PUBKEY_HASH = @as(u32, 1040); pub const SIPAEV_TXT_LCP_HASH = @as(u32, 1041); pub const SIPAEV_TXT_LCP_DETAILS_HASH = @as(u32, 1042); pub const SIPAEV_TXT_LCP_AUTHORITIES_HASH = @as(u32, 1043); pub const SIPAEV_TXT_NV_INFO_HASH = @as(u32, 1044); pub const SIPAEV_TXT_COLD_BOOT_BIOS_HASH = @as(u32, 1045); pub const SIPAEV_TXT_KM_HASH = @as(u32, 1046); pub const SIPAEV_TXT_BPM_HASH = @as(u32, 1047); pub const SIPAEV_TXT_KM_INFO_HASH = @as(u32, 1048); pub const SIPAEV_TXT_BPM_INFO_HASH = @as(u32, 1049); pub const SIPAEV_TXT_BOOT_POL_HASH = @as(u32, 1050); pub const SIPAEV_TXT_RANDOM_VALUE = @as(u32, 1278); pub const SIPAEV_TXT_CAP_VALUE = @as(u32, 1279); pub const SIPAEV_AMD_SL_EVENT_BASE = @as(u32, 32768); pub const SIPAEV_AMD_SL_LOAD = @as(u32, 32769); pub const SIPAEV_AMD_SL_PSP_FW_SPLT = @as(u32, 32770); pub const SIPAEV_AMD_SL_TSME_RB_FUSE = @as(u32, 32771); pub const SIPAEV_AMD_SL_PUB_KEY = @as(u32, 32772); pub const SIPAEV_AMD_SL_SVN = @as(u32, 32773); pub const SIPAEV_AMD_SL_LOAD_1 = @as(u32, 32774); pub const SIPAEV_AMD_SL_SEPARATOR = @as(u32, 32775); pub const SIPAEVENTTYPE_NONMEASURED = @as(u32, 2147483648); pub const SIPAEVENTTYPE_AGGREGATION = @as(u32, 1073741824); pub const SIPAEVENTTYPE_CONTAINER = @as(u32, 65536); pub const SIPAEVENTTYPE_INFORMATION = @as(u32, 131072); pub const SIPAEVENTTYPE_ERROR = @as(u32, 196608); pub const SIPAEVENTTYPE_PREOSPARAMETER = @as(u32, 262144); pub const SIPAEVENTTYPE_OSPARAMETER = @as(u32, 327680); pub const SIPAEVENTTYPE_AUTHORITY = @as(u32, 393216); pub const SIPAEVENTTYPE_LOADEDMODULE = @as(u32, 458752); pub const SIPAEVENTTYPE_TRUSTPOINT = @as(u32, 524288); pub const SIPAEVENTTYPE_ELAM = @as(u32, 589824); pub const SIPAEVENTTYPE_VBS = @as(u32, 655360); pub const SIPAEVENTTYPE_KSR = @as(u32, 720896); pub const SIPAEVENTTYPE_DRTM = @as(u32, 786432); pub const SIPAERROR_FIRMWAREFAILURE = @as(u32, 196609); pub const SIPAERROR_INTERNALFAILURE = @as(u32, 196611); pub const SIPAEVENT_INFORMATION = @as(u32, 131073); pub const SIPAEVENT_BOOTCOUNTER = @as(u32, 131074); pub const SIPAEVENT_TRANSFER_CONTROL = @as(u32, 131075); pub const SIPAEVENT_APPLICATION_RETURN = @as(u32, 131076); pub const SIPAEVENT_BITLOCKER_UNLOCK = @as(u32, 131077); pub const SIPAEVENT_EVENTCOUNTER = @as(u32, 131078); pub const SIPAEVENT_COUNTERID = @as(u32, 131079); pub const SIPAEVENT_MORBIT_NOT_CANCELABLE = @as(u32, 131080); pub const SIPAEVENT_APPLICATION_SVN = @as(u32, 131081); pub const SIPAEVENT_SVN_CHAIN_STATUS = @as(u32, 131082); pub const SIPAEVENT_MORBIT_API_STATUS = @as(u32, 131083); pub const SIPAEVENT_BOOTDEBUGGING = @as(u32, 262145); pub const SIPAEVENT_BOOT_REVOCATION_LIST = @as(u32, 262146); pub const SIPAEVENT_OSKERNELDEBUG = @as(u32, 327681); pub const SIPAEVENT_CODEINTEGRITY = @as(u32, 327682); pub const SIPAEVENT_TESTSIGNING = @as(u32, 327683); pub const SIPAEVENT_DATAEXECUTIONPREVENTION = @as(u32, 327684); pub const SIPAEVENT_SAFEMODE = @as(u32, 327685); pub const SIPAEVENT_WINPE = @as(u32, 327686); pub const SIPAEVENT_PHYSICALADDRESSEXTENSION = @as(u32, 327687); pub const SIPAEVENT_OSDEVICE = @as(u32, 327688); pub const SIPAEVENT_SYSTEMROOT = @as(u32, 327689); pub const SIPAEVENT_HYPERVISOR_LAUNCH_TYPE = @as(u32, 327690); pub const SIPAEVENT_HYPERVISOR_PATH = @as(u32, 327691); pub const SIPAEVENT_HYPERVISOR_IOMMU_POLICY = @as(u32, 327692); pub const SIPAEVENT_HYPERVISOR_DEBUG = @as(u32, 327693); pub const SIPAEVENT_DRIVER_LOAD_POLICY = @as(u32, 327694); pub const SIPAEVENT_SI_POLICY = @as(u32, 327695); pub const SIPAEVENT_HYPERVISOR_MMIO_NX_POLICY = @as(u32, 327696); pub const SIPAEVENT_HYPERVISOR_MSR_FILTER_POLICY = @as(u32, 327697); pub const SIPAEVENT_VSM_LAUNCH_TYPE = @as(u32, 327698); pub const SIPAEVENT_OS_REVOCATION_LIST = @as(u32, 327699); pub const SIPAEVENT_SMT_STATUS = @as(u32, 327700); pub const SIPAEVENT_VSM_IDK_INFO = @as(u32, 327712); pub const SIPAEVENT_FLIGHTSIGNING = @as(u32, 327713); pub const SIPAEVENT_PAGEFILE_ENCRYPTION_ENABLED = @as(u32, 327714); pub const SIPAEVENT_VSM_IDKS_INFO = @as(u32, 327715); pub const SIPAEVENT_HIBERNATION_DISABLED = @as(u32, 327716); pub const SIPAEVENT_DUMPS_DISABLED = @as(u32, 327717); pub const SIPAEVENT_DUMP_ENCRYPTION_ENABLED = @as(u32, 327718); pub const SIPAEVENT_DUMP_ENCRYPTION_KEY_DIGEST = @as(u32, 327719); pub const SIPAEVENT_LSAISO_CONFIG = @as(u32, 327720); pub const SIPAEVENT_SBCP_INFO = @as(u32, 327721); pub const SIPAEVENT_HYPERVISOR_BOOT_DMA_PROTECTION = @as(u32, 327728); pub const SIPAEVENT_NOAUTHORITY = @as(u32, 393217); pub const SIPAEVENT_AUTHORITYPUBKEY = @as(u32, 393218); pub const SIPAEVENT_FILEPATH = @as(u32, 458753); pub const SIPAEVENT_IMAGESIZE = @as(u32, 458754); pub const SIPAEVENT_HASHALGORITHMID = @as(u32, 458755); pub const SIPAEVENT_AUTHENTICODEHASH = @as(u32, 458756); pub const SIPAEVENT_AUTHORITYISSUER = @as(u32, 458757); pub const SIPAEVENT_AUTHORITYSERIAL = @as(u32, 458758); pub const SIPAEVENT_IMAGEBASE = @as(u32, 458759); pub const SIPAEVENT_AUTHORITYPUBLISHER = @as(u32, 458760); pub const SIPAEVENT_AUTHORITYSHA1THUMBPRINT = @as(u32, 458761); pub const SIPAEVENT_IMAGEVALIDATED = @as(u32, 458762); pub const SIPAEVENT_MODULE_SVN = @as(u32, 458763); pub const SIPAEVENT_ELAM_KEYNAME = @as(u32, 589825); pub const SIPAEVENT_ELAM_CONFIGURATION = @as(u32, 589826); pub const SIPAEVENT_ELAM_POLICY = @as(u32, 589827); pub const SIPAEVENT_ELAM_MEASURED = @as(u32, 589828); pub const SIPAEVENT_VBS_VSM_REQUIRED = @as(u32, 655361); pub const SIPAEVENT_VBS_SECUREBOOT_REQUIRED = @as(u32, 655362); pub const SIPAEVENT_VBS_IOMMU_REQUIRED = @as(u32, 655363); pub const SIPAEVENT_VBS_MMIO_NX_REQUIRED = @as(u32, 655364); pub const SIPAEVENT_VBS_MSR_FILTERING_REQUIRED = @as(u32, 655365); pub const SIPAEVENT_VBS_MANDATORY_ENFORCEMENT = @as(u32, 655366); pub const SIPAEVENT_VBS_HVCI_POLICY = @as(u32, 655367); pub const SIPAEVENT_VBS_MICROSOFT_BOOT_CHAIN_REQUIRED = @as(u32, 655368); pub const SIPAEVENT_VBS_DUMP_USES_AMEROOT = @as(u32, 655369); pub const SIPAEVENT_VBS_VSM_NOSECRETS_ENFORCED = @as(u32, 655370); pub const SIPAEVENT_KSR_SIGNATURE = @as(u32, 720897); pub const SIPAEVENT_DRTM_STATE_AUTH = @as(u32, 786433); pub const SIPAEVENT_DRTM_SMM_LEVEL = @as(u32, 786434); pub const SIPAEVENT_DRTM_AMD_SMM_HASH = @as(u32, 786435); pub const SIPAEVENT_DRTM_AMD_SMM_SIGNER_KEY = @as(u32, 786436); pub const FVEB_UNLOCK_FLAG_NONE = @as(u32, 0); pub const FVEB_UNLOCK_FLAG_CACHED = @as(u32, 1); pub const FVEB_UNLOCK_FLAG_MEDIA = @as(u32, 2); pub const FVEB_UNLOCK_FLAG_TPM = @as(u32, 4); pub const FVEB_UNLOCK_FLAG_PIN = @as(u32, 16); pub const FVEB_UNLOCK_FLAG_EXTERNAL = @as(u32, 32); pub const FVEB_UNLOCK_FLAG_RECOVERY = @as(u32, 64); pub const FVEB_UNLOCK_FLAG_PASSPHRASE = @as(u32, 128); pub const FVEB_UNLOCK_FLAG_NBP = @as(u32, 256); pub const FVEB_UNLOCK_FLAG_AUK_OSFVEINFO = @as(u32, 512); pub const OSDEVICE_TYPE_UNKNOWN = @as(u32, 0); pub const OSDEVICE_TYPE_BLOCKIO_HARDDISK = @as(u32, 65537); pub const OSDEVICE_TYPE_BLOCKIO_REMOVABLEDISK = @as(u32, 65538); pub const OSDEVICE_TYPE_BLOCKIO_CDROM = @as(u32, 65539); pub const OSDEVICE_TYPE_BLOCKIO_PARTITION = @as(u32, 65540); pub const OSDEVICE_TYPE_BLOCKIO_FILE = @as(u32, 65541); pub const OSDEVICE_TYPE_BLOCKIO_RAMDISK = @as(u32, 65542); pub const OSDEVICE_TYPE_BLOCKIO_VIRTUALHARDDISK = @as(u32, 65543); pub const OSDEVICE_TYPE_SERIAL = @as(u32, 131072); pub const OSDEVICE_TYPE_UDP = @as(u32, 196608); pub const OSDEVICE_TYPE_VMBUS = @as(u32, 262144); pub const OSDEVICE_TYPE_COMPOSITE = @as(u32, 327680); pub const SIPAHDRSIGNATURE = @as(u32, 1279476311); pub const SIPALOGVERSION = @as(u32, 1); pub const SIPAKSRHDRSIGNATURE = @as(u32, 1297240907); pub const WBCL_DIGEST_ALG_ID_SHA_1 = @as(u32, 4); pub const WBCL_DIGEST_ALG_ID_SHA_2_256 = @as(u32, 11); pub const WBCL_DIGEST_ALG_ID_SHA_2_384 = @as(u32, 12); pub const WBCL_DIGEST_ALG_ID_SHA_2_512 = @as(u32, 13); pub const WBCL_DIGEST_ALG_ID_SM3_256 = @as(u32, 18); pub const WBCL_DIGEST_ALG_ID_SHA3_256 = @as(u32, 39); pub const WBCL_DIGEST_ALG_ID_SHA3_384 = @as(u32, 40); pub const WBCL_DIGEST_ALG_ID_SHA3_512 = @as(u32, 41); pub const WBCL_DIGEST_ALG_BITMAP_SHA_1 = @as(u32, 1); pub const WBCL_DIGEST_ALG_BITMAP_SHA_2_256 = @as(u32, 2); pub const WBCL_DIGEST_ALG_BITMAP_SHA_2_384 = @as(u32, 4); pub const WBCL_DIGEST_ALG_BITMAP_SHA_2_512 = @as(u32, 8); pub const WBCL_DIGEST_ALG_BITMAP_SM3_256 = @as(u32, 16); pub const WBCL_DIGEST_ALG_BITMAP_SHA3_256 = @as(u32, 32); pub const WBCL_DIGEST_ALG_BITMAP_SHA3_384 = @as(u32, 64); pub const WBCL_DIGEST_ALG_BITMAP_SHA3_512 = @as(u32, 128); pub const WBCL_HASH_LEN_SHA1 = @as(u32, 20); pub const IS_GUAR_RSPEC = @as(i32, 130); pub const GUAR_ADSPARM_C = @as(i32, 131); pub const GUAR_ADSPARM_D = @as(i32, 132); pub const GUAR_ADSPARM_Ctot = @as(i32, 133); pub const GUAR_ADSPARM_Dtot = @as(i32, 134); pub const GUAR_ADSPARM_Csum = @as(i32, 135); pub const GUAR_ADSPARM_Dsum = @as(i32, 136); //-------------------------------------------------------------------------------- // Section: Types (112) //-------------------------------------------------------------------------------- pub const LPM_HANDLE = isize; pub const RHANDLE = isize; pub const FLOWSPEC = extern struct { TokenRate: u32, TokenBucketSize: u32, PeakBandwidth: u32, Latency: u32, DelayVariation: u32, ServiceType: u32, MaxSduSize: u32, MinimumPolicedSize: u32, }; pub const QOS_OBJECT_HDR = extern struct { ObjectType: u32, ObjectLength: u32, }; pub const QOS_SD_MODE = extern struct { ObjectHdr: QOS_OBJECT_HDR, ShapeDiscardMode: u32, }; pub const QOS_SHAPING_RATE = extern struct { ObjectHdr: QOS_OBJECT_HDR, ShapingRate: u32, }; pub const RsvpObjHdr = extern struct { obj_length: u16, obj_class: u8, obj_ctype: u8, }; pub const Session_IPv4 = extern struct { sess_destaddr: IN_ADDR, sess_protid: u8, sess_flags: u8, sess_destport: u16, }; pub const RSVP_SESSION = extern struct { sess_header: RsvpObjHdr, sess_u: extern union { sess_ipv4: Session_IPv4, }, }; pub const Rsvp_Hop_IPv4 = extern struct { hop_ipaddr: IN_ADDR, hop_LIH: u32, }; pub const RSVP_HOP = extern struct { hop_header: RsvpObjHdr, hop_u: extern union { hop_ipv4: Rsvp_Hop_IPv4, }, }; pub const RESV_STYLE = extern struct { style_header: RsvpObjHdr, style_word: u32, }; pub const Filter_Spec_IPv4 = extern struct { filt_ipaddr: IN_ADDR, filt_unused: u16, filt_port: u16, }; pub const Filter_Spec_IPv4GPI = extern struct { filt_ipaddr: IN_ADDR, filt_gpi: u32, }; pub const FILTER_SPEC = extern struct { filt_header: RsvpObjHdr, filt_u: extern union { filt_ipv4: Filter_Spec_IPv4, filt_ipv4gpi: Filter_Spec_IPv4GPI, }, }; pub const Scope_list_ipv4 = extern struct { scopl_ipaddr: [1]IN_ADDR, }; pub const RSVP_SCOPE = extern struct { scopl_header: RsvpObjHdr, scope_u: extern union { scopl_ipv4: Scope_list_ipv4, }, }; pub const Error_Spec_IPv4 = extern struct { errs_errnode: IN_ADDR, errs_flags: u8, errs_code: u8, errs_value: u16, }; pub const ERROR_SPEC = extern struct { errs_header: RsvpObjHdr, errs_u: extern union { errs_ipv4: Error_Spec_IPv4, }, }; pub const POLICY_DATA = extern struct { PolicyObjHdr: RsvpObjHdr, usPeOffset: u16, usReserved: u16, }; pub const POLICY_ELEMENT = extern struct { usPeLength: u16, usPeType: u16, ucPeData: [4]u8, }; pub const int_serv_wkp = enum(i32) { HOP_CNT = 4, PATH_BW = 6, MIN_LATENCY = 8, COMPOSED_MTU = 10, TB_TSPEC = 127, Q_TSPEC = 128, }; pub const IS_WKP_HOP_CNT = int_serv_wkp.HOP_CNT; pub const IS_WKP_PATH_BW = int_serv_wkp.PATH_BW; pub const IS_WKP_MIN_LATENCY = int_serv_wkp.MIN_LATENCY; pub const IS_WKP_COMPOSED_MTU = int_serv_wkp.COMPOSED_MTU; pub const IS_WKP_TB_TSPEC = int_serv_wkp.TB_TSPEC; pub const IS_WKP_Q_TSPEC = int_serv_wkp.Q_TSPEC; pub const IntServMainHdr = extern struct { ismh_version: u8, ismh_unused: u8, ismh_len32b: u16, }; pub const IntServServiceHdr = extern struct { issh_service: u8, issh_flags: u8, issh_len32b: u16, }; pub const IntServParmHdr = extern struct { isph_parm_num: u8, isph_flags: u8, isph_len32b: u16, }; pub const GenTspecParms = extern struct { TB_Tspec_r: f32, TB_Tspec_b: f32, TB_Tspec_p: f32, TB_Tspec_m: u32, TB_Tspec_M: u32, }; pub const GenTspec = extern struct { gen_Tspec_serv_hdr: IntServServiceHdr, gen_Tspec_parm_hdr: IntServParmHdr, gen_Tspec_parms: GenTspecParms, }; pub const QualTspecParms = extern struct { TB_Tspec_M: u32, }; pub const QualTspec = extern struct { qual_Tspec_serv_hdr: IntServServiceHdr, qual_Tspec_parm_hdr: IntServParmHdr, qual_Tspec_parms: QualTspecParms, }; pub const QualAppFlowSpec = extern struct { Q_spec_serv_hdr: IntServServiceHdr, Q_spec_parm_hdr: IntServParmHdr, Q_spec_parms: QualTspecParms, }; pub const IntServTspecBody = extern struct { st_mh: IntServMainHdr, tspec_u: extern union { gen_stspec: GenTspec, qual_stspec: QualTspec, }, }; pub const SENDER_TSPEC = extern struct { stspec_header: RsvpObjHdr, stspec_body: IntServTspecBody, }; pub const CtrlLoadFlowspec = extern struct { CL_spec_serv_hdr: IntServServiceHdr, CL_spec_parm_hdr: IntServParmHdr, CL_spec_parms: GenTspecParms, }; pub const GuarRspec = extern struct { Guar_R: f32, Guar_S: u32, }; pub const GuarFlowSpec = extern struct { Guar_serv_hdr: IntServServiceHdr, Guar_Tspec_hdr: IntServParmHdr, Guar_Tspec_parms: GenTspecParms, Guar_Rspec_hdr: IntServParmHdr, Guar_Rspec: GuarRspec, }; pub const IntServFlowSpec = extern struct { spec_mh: IntServMainHdr, spec_u: extern union { CL_spec: CtrlLoadFlowspec, G_spec: GuarFlowSpec, Q_spec: QualAppFlowSpec, }, }; pub const IS_FLOWSPEC = extern struct { flow_header: RsvpObjHdr, flow_body: IntServFlowSpec, }; pub const flow_desc = extern struct { u1: extern union { stspec: ?*SENDER_TSPEC, isflow: ?*IS_FLOWSPEC, }, u2: extern union { stemp: ?*FILTER_SPEC, fspec: ?*FILTER_SPEC, }, }; pub const Gads_parms_t = extern struct { Gads_serv_hdr: IntServServiceHdr, Gads_Ctot_hdr: IntServParmHdr, Gads_Ctot: u32, Gads_Dtot_hdr: IntServParmHdr, Gads_Dtot: u32, Gads_Csum_hdr: IntServParmHdr, Gads_Csum: u32, Gads_Dsum_hdr: IntServParmHdr, Gads_Dsum: u32, }; pub const GenAdspecParams = extern struct { gen_parm_hdr: IntServServiceHdr, gen_parm_hopcnt_hdr: IntServParmHdr, gen_parm_hopcnt: u32, gen_parm_pathbw_hdr: IntServParmHdr, gen_parm_path_bw: f32, gen_parm_minlat_hdr: IntServParmHdr, gen_parm_min_latency: u32, gen_parm_compmtu_hdr: IntServParmHdr, gen_parm_composed_MTU: u32, }; pub const IS_ADSPEC_BODY = extern struct { adspec_mh: IntServMainHdr, adspec_genparms: GenAdspecParams, }; pub const ADSPEC = extern struct { adspec_header: RsvpObjHdr, adspec_body: IS_ADSPEC_BODY, }; pub const ID_ERROR_OBJECT = extern struct { usIdErrLength: u16, ucAType: u8, ucSubType: u8, usReserved: u16, usIdErrorValue: u16, ucIdErrData: [4]u8, }; pub const RSVP_MSG_OBJS = extern struct { RsvpMsgType: i32, pRsvpSession: ?*RSVP_SESSION, pRsvpFromHop: ?*RSVP_HOP, pRsvpToHop: ?*RSVP_HOP, pResvStyle: ?*RESV_STYLE, pRsvpScope: ?*RSVP_SCOPE, FlowDescCount: i32, pFlowDescs: ?*flow_desc, PdObjectCount: i32, ppPdObjects: ?*?*POLICY_DATA, pErrorSpec: ?*ERROR_SPEC, pAdspec: ?*ADSPEC, }; pub const PALLOCMEM = fn( Size: u32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub const PFREEMEM = fn( pv: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const policy_decision = extern struct { lpvResult: u32, wPolicyErrCode: u16, wPolicyErrValue: u16, }; pub const CBADMITRESULT = fn( LpmHandle: LPM_HANDLE, RequestHandle: RHANDLE, ulPcmActionFlags: u32, LpmError: i32, PolicyDecisionsCount: i32, pPolicyDecisions: ?*policy_decision, ) callconv(@import("std").os.windows.WINAPI) ?*u32; pub const CBGETRSVPOBJECTS = fn( LpmHandle: LPM_HANDLE, RequestHandle: RHANDLE, LpmError: i32, RsvpObjectsCount: i32, ppRsvpObjects: ?*?*RsvpObjHdr, ) callconv(@import("std").os.windows.WINAPI) ?*u32; pub const LPM_INIT_INFO = extern struct { PcmVersionNumber: u32, ResultTimeLimit: u32, ConfiguredLpmCount: i32, AllocMemory: ?PALLOCMEM, FreeMemory: ?PFREEMEM, PcmAdmitResultCallback: ?CBADMITRESULT, GetRsvpObjectsCallback: ?CBGETRSVPOBJECTS, }; pub const lpmiptable = extern struct { ulIfIndex: u32, MediaType: u32, IfIpAddr: IN_ADDR, IfNetMask: IN_ADDR, }; pub const QOS_TRAFFIC_TYPE = enum(i32) { BestEffort = 0, Background = 1, ExcellentEffort = 2, AudioVideo = 3, Voice = 4, Control = 5, }; pub const QOSTrafficTypeBestEffort = QOS_TRAFFIC_TYPE.BestEffort; pub const QOSTrafficTypeBackground = QOS_TRAFFIC_TYPE.Background; pub const QOSTrafficTypeExcellentEffort = QOS_TRAFFIC_TYPE.ExcellentEffort; pub const QOSTrafficTypeAudioVideo = QOS_TRAFFIC_TYPE.AudioVideo; pub const QOSTrafficTypeVoice = QOS_TRAFFIC_TYPE.Voice; pub const QOSTrafficTypeControl = QOS_TRAFFIC_TYPE.Control; pub const QOS_SET_FLOW = enum(i32) { TrafficType = 0, OutgoingRate = 1, OutgoingDSCPValue = 2, }; pub const QOSSetTrafficType = QOS_SET_FLOW.TrafficType; pub const QOSSetOutgoingRate = QOS_SET_FLOW.OutgoingRate; pub const QOSSetOutgoingDSCPValue = QOS_SET_FLOW.OutgoingDSCPValue; pub const QOS_PACKET_PRIORITY = extern struct { ConformantDSCPValue: u32, NonConformantDSCPValue: u32, ConformantL2Value: u32, NonConformantL2Value: u32, }; pub const QOS_FLOW_FUNDAMENTALS = extern struct { BottleneckBandwidthSet: BOOL, BottleneckBandwidth: u64, AvailableBandwidthSet: BOOL, AvailableBandwidth: u64, RTTSet: BOOL, RTT: u32, }; pub const QOS_FLOWRATE_REASON = enum(i32) { NotApplicable = 0, ContentChange = 1, Congestion = 2, HigherContentEncoding = 3, UserCaused = 4, }; pub const QOSFlowRateNotApplicable = QOS_FLOWRATE_REASON.NotApplicable; pub const QOSFlowRateContentChange = QOS_FLOWRATE_REASON.ContentChange; pub const QOSFlowRateCongestion = QOS_FLOWRATE_REASON.Congestion; pub const QOSFlowRateHigherContentEncoding = QOS_FLOWRATE_REASON.HigherContentEncoding; pub const QOSFlowRateUserCaused = QOS_FLOWRATE_REASON.UserCaused; pub const QOS_SHAPING = enum(i32) { ShapeOnly = 0, ShapeAndMark = 1, UseNonConformantMarkings = 2, }; pub const QOSShapeOnly = QOS_SHAPING.ShapeOnly; pub const QOSShapeAndMark = QOS_SHAPING.ShapeAndMark; pub const QOSUseNonConformantMarkings = QOS_SHAPING.UseNonConformantMarkings; pub const QOS_FLOWRATE_OUTGOING = extern struct { Bandwidth: u64, ShapingBehavior: QOS_SHAPING, Reason: QOS_FLOWRATE_REASON, }; pub const QOS_QUERY_FLOW = enum(i32) { FlowFundamentals = 0, PacketPriority = 1, OutgoingRate = 2, }; pub const QOSQueryFlowFundamentals = QOS_QUERY_FLOW.FlowFundamentals; pub const QOSQueryPacketPriority = QOS_QUERY_FLOW.PacketPriority; pub const QOSQueryOutgoingRate = QOS_QUERY_FLOW.OutgoingRate; pub const QOS_NOTIFY_FLOW = enum(i32) { Congested = 0, Uncongested = 1, Available = 2, }; pub const QOSNotifyCongested = QOS_NOTIFY_FLOW.Congested; pub const QOSNotifyUncongested = QOS_NOTIFY_FLOW.Uncongested; pub const QOSNotifyAvailable = QOS_NOTIFY_FLOW.Available; pub const QOS_VERSION = extern struct { MajorVersion: u16, MinorVersion: u16, }; pub const QOS_FRIENDLY_NAME = extern struct { ObjectHdr: QOS_OBJECT_HDR, FriendlyName: [256]u16, }; pub const QOS_TRAFFIC_CLASS = extern struct { ObjectHdr: QOS_OBJECT_HDR, TrafficClass: u32, }; pub const QOS_DS_CLASS = extern struct { ObjectHdr: QOS_OBJECT_HDR, DSField: u32, }; pub const QOS_DIFFSERV = extern struct { ObjectHdr: QOS_OBJECT_HDR, DSFieldCount: u32, DiffservRule: [1]u8, }; pub const QOS_DIFFSERV_RULE = extern struct { InboundDSField: u8, ConformingOutboundDSField: u8, NonConformingOutboundDSField: u8, ConformingUserPriority: u8, NonConformingUserPriority: u8, }; pub const QOS_TCP_TRAFFIC = extern struct { ObjectHdr: QOS_OBJECT_HDR, }; pub const TCI_NOTIFY_HANDLER = fn( ClRegCtx: ?HANDLE, ClIfcCtx: ?HANDLE, Event: u32, SubCode: ?HANDLE, BufSize: u32, // TODO: what to do with BytesParamIndex 4? Buffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const TCI_ADD_FLOW_COMPLETE_HANDLER = fn( ClFlowCtx: ?HANDLE, Status: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const TCI_MOD_FLOW_COMPLETE_HANDLER = fn( ClFlowCtx: ?HANDLE, Status: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const TCI_DEL_FLOW_COMPLETE_HANDLER = fn( ClFlowCtx: ?HANDLE, Status: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const TCI_CLIENT_FUNC_LIST = extern struct { ClNotifyHandler: ?TCI_NOTIFY_HANDLER, ClAddFlowCompleteHandler: ?TCI_ADD_FLOW_COMPLETE_HANDLER, ClModifyFlowCompleteHandler: ?TCI_MOD_FLOW_COMPLETE_HANDLER, ClDeleteFlowCompleteHandler: ?TCI_DEL_FLOW_COMPLETE_HANDLER, }; pub const ADDRESS_LIST_DESCRIPTOR = extern struct { MediaType: u32, AddressList: NETWORK_ADDRESS_LIST, }; pub const TC_IFC_DESCRIPTOR = extern struct { Length: u32, pInterfaceName: ?PWSTR, pInterfaceID: ?PWSTR, AddressListDesc: ADDRESS_LIST_DESCRIPTOR, }; pub const TC_SUPPORTED_INFO_BUFFER = extern struct { InstanceIDLength: u16, InstanceID: [256]u16, InterfaceLuid: u64, AddrListDesc: ADDRESS_LIST_DESCRIPTOR, }; pub const TC_GEN_FILTER = extern struct { AddressType: u16, PatternSize: u32, Pattern: ?*anyopaque, Mask: ?*anyopaque, }; pub const TC_GEN_FLOW = extern struct { SendingFlowspec: FLOWSPEC, ReceivingFlowspec: FLOWSPEC, TcObjectsLength: u32, TcObjects: [1]QOS_OBJECT_HDR, }; pub const IP_PATTERN = extern struct { Reserved1: u32, Reserved2: u32, SrcAddr: u32, DstAddr: u32, S_un: extern union { S_un_ports: extern struct { s_srcport: u16, s_dstport: u16, }, S_un_icmp: extern struct { s_type: u8, s_code: u8, filler: u16, }, S_Spi: u32, }, ProtocolId: u8, Reserved3: [3]u8, }; pub const IPX_PATTERN = extern struct { Src: extern struct { NetworkAddress: u32, NodeAddress: [6]u8, Socket: u16, }, Dest: extern struct { NetworkAddress: u32, NodeAddress: [6]u8, Socket: u16, }, }; pub const ENUMERATION_BUFFER = extern struct { Length: u32, OwnerProcessId: u32, FlowNameLength: u16, FlowName: [256]u16, pFlow: ?*TC_GEN_FLOW, NumberOfFilters: u32, GenericFilter: [1]TC_GEN_FILTER, }; pub const IN_ADDR_IPV4 = extern union { Addr: u32, AddrBytes: [4]u8, }; pub const IN_ADDR_IPV6 = extern struct { Addr: [16]u8, }; pub const RSVP_FILTERSPEC_V4 = extern struct { Address: IN_ADDR_IPV4, Unused: u16, Port: u16, }; pub const RSVP_FILTERSPEC_V6 = extern struct { Address: IN_ADDR_IPV6, UnUsed: u16, Port: u16, }; pub const RSVP_FILTERSPEC_V6_FLOW = extern struct { Address: IN_ADDR_IPV6, UnUsed: u8, FlowLabel: [3]u8, }; pub const RSVP_FILTERSPEC_V4_GPI = extern struct { Address: IN_ADDR_IPV4, GeneralPortId: u32, }; pub const RSVP_FILTERSPEC_V6_GPI = extern struct { Address: IN_ADDR_IPV6, GeneralPortId: u32, }; pub const FilterType = enum(i32) { V4 = 1, V6 = 2, V6_FLOW = 3, V4_GPI = 4, V6_GPI = 5, _END = 6, }; pub const FILTERSPECV4 = FilterType.V4; pub const FILTERSPECV6 = FilterType.V6; pub const FILTERSPECV6_FLOW = FilterType.V6_FLOW; pub const FILTERSPECV4_GPI = FilterType.V4_GPI; pub const FILTERSPECV6_GPI = FilterType.V6_GPI; pub const FILTERSPEC_END = FilterType._END; pub const RSVP_FILTERSPEC = extern struct { Type: FilterType, Anonymous: extern union { FilterSpecV4: RSVP_FILTERSPEC_V4, FilterSpecV6: RSVP_FILTERSPEC_V6, FilterSpecV6Flow: RSVP_FILTERSPEC_V6_FLOW, FilterSpecV4Gpi: RSVP_FILTERSPEC_V4_GPI, FilterSpecV6Gpi: RSVP_FILTERSPEC_V6_GPI, }, }; pub const FLOWDESCRIPTOR = extern struct { FlowSpec: FLOWSPEC, NumFilters: u32, FilterList: ?*RSVP_FILTERSPEC, }; pub const RSVP_POLICY = extern struct { Len: u16, Type: u16, Info: [4]u8, }; pub const RSVP_POLICY_INFO = extern struct { ObjectHdr: QOS_OBJECT_HDR, NumPolicyElement: u32, PolicyElement: [1]RSVP_POLICY, }; pub const RSVP_RESERVE_INFO = extern struct { ObjectHdr: QOS_OBJECT_HDR, Style: u32, ConfirmRequest: u32, PolicyElementList: ?*RSVP_POLICY_INFO, NumFlowDesc: u32, FlowDescList: ?*FLOWDESCRIPTOR, }; pub const RSVP_STATUS_INFO = extern struct { ObjectHdr: QOS_OBJECT_HDR, StatusCode: u32, ExtendedStatus1: u32, ExtendedStatus2: u32, }; pub const QOS_DESTADDR = extern struct { ObjectHdr: QOS_OBJECT_HDR, SocketAddress: ?*const SOCKADDR, SocketAddressLength: u32, }; pub const AD_GENERAL_PARAMS = extern struct { IntServAwareHopCount: u32, PathBandwidthEstimate: u32, MinimumLatency: u32, PathMTU: u32, Flags: u32, }; pub const AD_GUARANTEED = extern struct { CTotal: u32, DTotal: u32, CSum: u32, DSum: u32, }; pub const PARAM_BUFFER = extern struct { ParameterId: u32, Length: u32, Buffer: [1]u8, }; pub const CONTROL_SERVICE = extern struct { Length: u32, Service: u32, Overrides: AD_GENERAL_PARAMS, Anonymous: extern union { Guaranteed: AD_GUARANTEED, ParamBuffer: [1]PARAM_BUFFER, }, }; pub const RSVP_ADSPEC = extern struct { ObjectHdr: QOS_OBJECT_HDR, GeneralParams: AD_GENERAL_PARAMS, NumberOfServices: u32, Services: [1]CONTROL_SERVICE, }; pub const IDPE_ATTR = extern struct { PeAttribLength: u16, PeAttribType: u8, PeAttribSubType: u8, PeAttribValue: [4]u8, }; pub const WBCL_Iterator = packed struct { firstElementPtr: ?*anyopaque, logSize: u32, currentElementPtr: ?*anyopaque, currentElementSize: u32, digestSize: u16, logFormat: u16, numberOfDigests: u32, digestSizes: ?*anyopaque, supportedAlgorithms: u32, hashAlgorithm: u16, }; pub const TCG_PCClientPCREventStruct = packed struct { pcrIndex: u32, eventType: u32, digest: [20]u8, eventDataSize: u32, event: [1]u8, }; pub const TCG_PCClientTaggedEventStruct = packed struct { EventID: u32, EventDataSize: u32, EventData: [1]u8, }; pub const WBCL_LogHdr = packed struct { signature: u32, version: u32, entries: u32, length: u32, }; pub const tag_SIPAEVENT_VSM_IDK_RSA_INFO = packed struct { KeyBitLength: u32, PublicExpLengthBytes: u32, ModulusSizeBytes: u32, PublicKeyData: [1]u8, }; pub const tag_SIPAEVENT_VSM_IDK_INFO_PAYLOAD = packed struct { KeyAlgID: u32, Anonymous: extern union { RsaKeyInfo: tag_SIPAEVENT_VSM_IDK_RSA_INFO, }, }; pub const tag_SIPAEVENT_SI_POLICY_PAYLOAD = packed struct { PolicyVersion: u64, PolicyNameLength: u16, HashAlgID: u16, DigestLength: u32, VarLengthData: [1]u8, }; pub const tag_SIPAEVENT_REVOCATION_LIST_PAYLOAD = packed struct { CreationTime: i64, DigestLength: u32, HashAlgID: u16, Digest: [1]u8, }; pub const tag_SIPAEVENT_KSR_SIGNATURE_PAYLOAD = packed struct { SignAlgID: u32, SignatureLength: u32, Signature: [1]u8, }; pub const tag_SIPAEVENT_SBCP_INFO_PAYLOAD_V1 = packed struct { PayloadVersion: u32, VarDataOffset: u32, HashAlgID: u16, DigestLength: u16, Options: u32, SignersCount: u32, VarData: [1]u8, }; pub const QOS = extern struct { SendingFlowspec: FLOWSPEC, ReceivingFlowspec: FLOWSPEC, ProviderSpecific: WSABUF, }; //-------------------------------------------------------------------------------- // Section: Functions (31) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSCreateHandle( Version: ?*QOS_VERSION, QOSHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSCloseHandle( QOSHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSStartTrackingClient( QOSHandle: ?HANDLE, DestAddr: ?*SOCKADDR, Flags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSStopTrackingClient( QOSHandle: ?HANDLE, DestAddr: ?*SOCKADDR, Flags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSEnumerateFlows( QOSHandle: ?HANDLE, Size: ?*u32, // TODO: what to do with BytesParamIndex 1? Buffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSAddSocketToFlow( QOSHandle: ?HANDLE, Socket: ?SOCKET, DestAddr: ?*SOCKADDR, TrafficType: QOS_TRAFFIC_TYPE, Flags: u32, FlowId: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' // This function from dll 'qwave' is being skipped because it has some sort of issue pub fn QOSRemoveSocketFromFlow() void { @panic("this function is not working"); } // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSSetFlow( QOSHandle: ?HANDLE, FlowId: u32, Operation: QOS_SET_FLOW, Size: u32, // TODO: what to do with BytesParamIndex 3? Buffer: ?*anyopaque, Flags: u32, Overlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSQueryFlow( QOSHandle: ?HANDLE, FlowId: u32, Operation: QOS_QUERY_FLOW, Size: ?*u32, // TODO: what to do with BytesParamIndex 3? Buffer: ?*anyopaque, Flags: u32, Overlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSNotifyFlow( QOSHandle: ?HANDLE, FlowId: u32, Operation: QOS_NOTIFY_FLOW, Size: ?*u32, // TODO: what to do with BytesParamIndex 3? Buffer: ?*anyopaque, Flags: u32, Overlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "qwave" fn QOSCancel( QOSHandle: ?HANDLE, Overlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcRegisterClient( TciVersion: u32, ClRegCtx: ?HANDLE, ClientHandlerList: ?*TCI_CLIENT_FUNC_LIST, pClientHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcEnumerateInterfaces( ClientHandle: ?HANDLE, pBufferSize: ?*u32, InterfaceBuffer: ?*TC_IFC_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcOpenInterfaceA( pInterfaceName: ?PSTR, ClientHandle: ?HANDLE, ClIfcCtx: ?HANDLE, pIfcHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcOpenInterfaceW( pInterfaceName: ?PWSTR, ClientHandle: ?HANDLE, ClIfcCtx: ?HANDLE, pIfcHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcCloseInterface( IfcHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcQueryInterface( IfcHandle: ?HANDLE, pGuidParam: ?*Guid, NotifyChange: BOOLEAN, pBufferSize: ?*u32, // TODO: what to do with BytesParamIndex 3? Buffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcSetInterface( IfcHandle: ?HANDLE, pGuidParam: ?*Guid, BufferSize: u32, // TODO: what to do with BytesParamIndex 2? Buffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcQueryFlowA( pFlowName: ?PSTR, pGuidParam: ?*Guid, pBufferSize: ?*u32, // TODO: what to do with BytesParamIndex 2? Buffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcQueryFlowW( pFlowName: ?PWSTR, pGuidParam: ?*Guid, pBufferSize: ?*u32, // TODO: what to do with BytesParamIndex 2? Buffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcSetFlowA( pFlowName: ?PSTR, pGuidParam: ?*Guid, BufferSize: u32, // TODO: what to do with BytesParamIndex 2? Buffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcSetFlowW( pFlowName: ?PWSTR, pGuidParam: ?*Guid, BufferSize: u32, // TODO: what to do with BytesParamIndex 2? Buffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcAddFlow( IfcHandle: ?HANDLE, ClFlowCtx: ?HANDLE, Flags: u32, pGenericFlow: ?*TC_GEN_FLOW, pFlowHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcGetFlowNameA( FlowHandle: ?HANDLE, StrSize: u32, pFlowName: [*:0]u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcGetFlowNameW( FlowHandle: ?HANDLE, StrSize: u32, pFlowName: [*:0]u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcModifyFlow( FlowHandle: ?HANDLE, pGenericFlow: ?*TC_GEN_FLOW, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcAddFilter( FlowHandle: ?HANDLE, pGenericFilter: ?*TC_GEN_FILTER, pFilterHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcDeregisterClient( ClientHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcDeleteFlow( FlowHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcDeleteFilter( FilterHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "TRAFFIC" fn TcEnumerateFlows( IfcHandle: ?HANDLE, pEnumHandle: ?*?HANDLE, pFlowCount: ?*u32, pBufSize: ?*u32, Buffer: ?*ENUMERATION_BUFFER, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (4) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const TcOpenInterface = thismodule.TcOpenInterfaceA; pub const TcQueryFlow = thismodule.TcQueryFlowA; pub const TcSetFlow = thismodule.TcSetFlowA; pub const TcGetFlowName = thismodule.TcGetFlowNameA; }, .wide => struct { pub const TcOpenInterface = thismodule.TcOpenInterfaceW; pub const TcQueryFlow = thismodule.TcQueryFlowW; pub const TcSetFlow = thismodule.TcSetFlowW; pub const TcGetFlowName = thismodule.TcGetFlowNameW; }, .unspecified => if (@import("builtin").is_test) struct { pub const TcOpenInterface = *opaque{}; pub const TcQueryFlow = *opaque{}; pub const TcSetFlow = *opaque{}; pub const TcGetFlowName = *opaque{}; } else struct { pub const TcOpenInterface = @compileError("'TcOpenInterface' requires that UNICODE be set to true or false in the root module"); pub const TcQueryFlow = @compileError("'TcQueryFlow' requires that UNICODE be set to true or false in the root module"); pub const TcSetFlow = @compileError("'TcSetFlow' requires that UNICODE be set to true or false in the root module"); pub const TcGetFlowName = @compileError("'TcGetFlowName' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (12) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BOOLEAN = @import("../foundation.zig").BOOLEAN; const HANDLE = @import("../foundation.zig").HANDLE; const IN_ADDR = @import("../networking/win_sock.zig").IN_ADDR; const NETWORK_ADDRESS_LIST = @import("../network_management/ndis.zig").NETWORK_ADDRESS_LIST; const OVERLAPPED = @import("../system/io.zig").OVERLAPPED; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const SOCKADDR = @import("../networking/win_sock.zig").SOCKADDR; const SOCKET = @import("../networking/win_sock.zig").SOCKET; const WSABUF = @import("../networking/win_sock.zig").WSABUF; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PALLOCMEM")) { _ = PALLOCMEM; } if (@hasDecl(@This(), "PFREEMEM")) { _ = PFREEMEM; } if (@hasDecl(@This(), "CBADMITRESULT")) { _ = CBADMITRESULT; } if (@hasDecl(@This(), "CBGETRSVPOBJECTS")) { _ = CBGETRSVPOBJECTS; } if (@hasDecl(@This(), "TCI_NOTIFY_HANDLER")) { _ = TCI_NOTIFY_HANDLER; } if (@hasDecl(@This(), "TCI_ADD_FLOW_COMPLETE_HANDLER")) { _ = TCI_ADD_FLOW_COMPLETE_HANDLER; } if (@hasDecl(@This(), "TCI_MOD_FLOW_COMPLETE_HANDLER")) { _ = TCI_MOD_FLOW_COMPLETE_HANDLER; } if (@hasDecl(@This(), "TCI_DEL_FLOW_COMPLETE_HANDLER")) { _ = TCI_DEL_FLOW_COMPLETE_HANDLER; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/network_management/qo_s.zig
const std = @import("std"); const hash_map = std.hash_map; const murmur = std.hash.murmur; const WordMap = std.HashMap([]const u8, u32, hashString, hash_map.eqlString, 80); pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const ally = &arena.allocator; var words = WordMap.init(ally); const stdin = std.io.getStdIn().reader(); comptime const buf_len: usize = 65536; var buf: [buf_len + 8]u8 align(@alignOf(u64)) = undefined; var numread: usize = try stdin.read(buf[0..buf_len]); while (numread > 0) { // margin word to stop the loop without bound checks buf[numread] = ' '; buf[numread + 1] = 'a'; buf[numread + 2] = ' '; // find words and count them var wstart: usize = 0; while (true) { while (buf[wstart] <= ' ') : (wstart += 1) {} var wend = wstart; while (buf[wend] > ' ') : (wend += 1) { buf[wend] = std.ascii.toLower(buf[wend]); } if (wend >= numread) break; const word = buf[wstart..wend]; const ret = try words.getOrPut(word); if (ret.found_existing) { ret.entry.value += 1; } else { ret.entry.key = try ally.dupe(u8, word); ret.entry.value = 1; } wstart = wend + 1; } // copy the unprocessed chars to the front of buffer var remain: usize = 0; if (wstart < numread) { std.mem.copy(u8, &buf, buf[wstart..numread]); remain = numread - wstart; } // fill the buffer again numread = try stdin.read(buf[remain..buf_len]); if (numread > 0) numread += remain; } // extract unique words and sort them based on counts const words_slice = try ally.alloc(WordMap.Entry, words.count()); var i: usize = 0; var it = words.iterator(); while (it.next()) |entry| : (i += 1) { words_slice[i] = entry.*; } std.sort.sort(WordMap.Entry, words_slice, {}, compare); // print sorted values in words_slice var stdout = std.io.bufferedWriter(std.io.getStdOut().writer()); for (words_slice) |entry| { try stdout.writer().print("{s} {d}\n", .{ entry.key, entry.value }); } try stdout.flush(); } fn compare(_: void, a: WordMap.Entry, b: WordMap.Entry) bool { return a.value > b.value; } pub fn hashString(s: []const u8) u64 { return std.hash.Murmur2_32.hash(s); }
optimized.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const testing = std.testing; const adler32 = @import("./adler32.zig"); const crc32 = @import("./crc-32.zig"); test "adler32 - updateByteArray" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var allocator = &arena.allocator; var string = "Hello, world"; var cs_adler = adler32.Adler32().init(allocator); try cs_adler.checksum.updateByteArray(string[0..string.len]); testing.expect(cs_adler.checksum_value == 466879593); cs_adler.checksum.close(); } test "adler32 - updateByteArrayRange" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var allocator = &arena.allocator; var string = "<NAME>!"; var cs_adler = adler32.Adler32().init(allocator); try cs_adler.checksum.updateByteArrayRange(string, 0, string.len); testing.expect(cs_adler.checksum_value == 449578005); cs_adler.checksum.reset(); try cs_adler.checksum.updateByteArrayRange(string, 0, 5); try cs_adler.checksum.updateByteArrayRange(string, 5, string.len - 5); testing.expect(cs_adler.checksum_value == 449578005); cs_adler.checksum.close(); } test "adler32 - updateByte" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var allocator = &arena.allocator; var string = "<NAME>"; var cs_adler = adler32.Adler32().init(allocator); for (string) |b| { try cs_adler.checksum.updateByte(b); } testing.expect(cs_adler.checksum_value == 379651033); cs_adler.checksum.close(); } test "crc-32 - updateByteArray" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var allocator = &arena.allocator; const string = "Hello, world"; var cs_crc32 = crc32.Crc32().init(allocator); try cs_crc32.checksum.updateByteArray(string[0..string.len]); testing.expect(cs_crc32.checksum_value == 3885672898); cs_crc32.checksum.close(); } test "crc-32 - updateByteArrayRange" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var allocator = &arena.allocator; const string = "<NAME>!"; var cs_crc32 = crc32.Crc32().init(allocator); try cs_crc32.checksum.updateByteArrayRange(string, 0, string.len); testing.expect(cs_crc32.checksum_value == 3494030786); cs_crc32.checksum.reset(); try cs_crc32.checksum.updateByteArrayRange(string, 0, 10); try cs_crc32.checksum.updateByteArrayRange(string, 10, string.len - 10); cs_crc32.checksum.close(); } test "crc-32 - updateByte" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var allocator = &arena.allocator; const string = "<NAME>"; var cs_crc32 = crc32.Crc32().init(allocator); for (string) |b| { try cs_crc32.checksum.updateByte(b); } testing.expect(cs_crc32.checksum_value == 1317902423); cs_crc32.checksum.close(); }
src/lib.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); // version "generale" pas du tout specialisée pour l'input // dans l'input il y a genre 2 repetitions donc genre a(b*)c(d*) ou un truc comme ça // mais du coup c'est un peu lent. -> memoize et voilà. const Grammar = struct { arena: std.heap.ArenaAllocator, rules: []Rule, memoize_cache: ?MemoizeCache = null, const empty_rule = Grammar.Rule{ .alts = &[0]Grammar.Alternative{}, .min_len = 0 }; const MemoizeCache = std.AutoHashMap(struct { ptr: usize, len: u8, r: u8 }, bool); fn init(alloc: std.mem.Allocator) !Grammar { var g = Grammar{ .arena = std.heap.ArenaAllocator.init(alloc), .rules = undefined, }; g.rules = try g.arena.allocator().alloc(Rule, 200); std.mem.set(Rule, g.rules, empty_rule); return g; } fn deinit(self: *@This()) void { if (self.memoize_cache) |*memo| memo.deinit(); self.arena.deinit(); } fn newLit(self: *@This(), lit: []const u8) !Node { return Node{ .lit = try self.arena.allocator().dupe(u8, lit) }; } fn newLitJoined(self: *@This(), lit1: []const u8, lit2: []const u8) !Node { const lit = self.arena.allocator().alloc(u8, lit1.len + lit2.len); std.mem.copy(u8, lit[0..lit1.len], lit1); std.mem.copy(u8, lit[lit1.len..], lit2); return Node{ .lit = lit }; } fn newRuleLit(self: *@This(), lit: []const u8) !Rule { const alts = try self.arena.allocator().alloc(Grammar.Alternative, 1); const seq = try self.arena.allocator().alloc(Grammar.Node, 1); seq[0] = try self.newLit(lit); alts[0].seq = seq; return Rule{ .alts = alts, .min_len = @intCast(u8, lit.len) }; } fn newRuleSimple(self: *@This(), sub_rules: []const []const u8) !Rule { const alts = try self.arena.allocator().alloc(Grammar.Alternative, sub_rules.len); for (sub_rules) |s, i| { const seq = try self.arena.allocator().alloc(Grammar.Node, s.len); for (s) |r, j| { seq[j] = Node{ .rule = r }; } alts[i].seq = seq; } return Rule{ .alts = alts, .min_len = 0 }; } fn debugPrint(self: *const @This()) void { std.debug.print("======================================\n", .{}); for (self.rules) |r, rule_idx| { if (r.alts.len == 0) continue; //empty_rule std.debug.print("rule n° {}: (len>={})", .{ rule_idx, r.min_len }); for (r.alts) |a, i| { if (i > 0) std.debug.print("| ", .{}); for (a.seq) |node| { std.debug.print("{} ", .{node}); } } std.debug.print("\n", .{}); } std.debug.print("======================================\n", .{}); } const Node = union(enum) { lit: []const u8, rule: u8, }; const Alternative = struct { seq: []Node }; const Rule = struct { alts: []Alternative, min_len: u8 }; }; fn reduce(grammar: *const Grammar, allocator: std.mem.Allocator) !Grammar { var g = try Grammar.init(allocator); errdefer g.deinit(); { for (g.rules) |*r, i| { r.alts = try g.arena.allocator().dupe(Grammar.Alternative, grammar.rules[i].alts); r.min_len = 0; for (r.alts) |*alt| { alt.seq = try g.arena.allocator().dupe(Grammar.Node, alt.seq); } } } const do_inline = true; const do_constprop = true; const do_fusing = true; const do_distrib = true; const do_dce = true; const max_pass = ~@as(usize, 0); var dirty = true; var max_rule = g.rules.len; var pass: usize = 0; while (dirty and pass < max_pass) : (pass += 1) { dirty = false; if (false) { for (g.rules[0..max_rule]) |r, rule_idx| { if (r.alts.len == 0) continue; //empty_rule std.debug.print("rule n° {}: ", .{rule_idx}); for (r.alts) |a, i| { if (i > 0) std.debug.print("| ", .{}); for (a.seq) |node| { std.debug.print("{} ", .{node}); } } std.debug.print("\n", .{}); } std.debug.print("======================================\n", .{}); } next_rule: for (g.rules) |*rule| { if (rule.alts.len == 0) continue; // empty_rule if (do_inline) { // direct inlining if (rule.alts.len == 1 and rule.alts[0].seq.len == 1 and rule.alts[0].seq[0] == .rule) { rule.alts = g.rules[rule.alts[0].seq[0].rule].alts; dirty = true; } } for (rule.alts) |*alt, alt_idx| { if (do_constprop) { // constant prop: next_node: for (alt.seq) |*node, node_idx| { if (node.* == .rule) { const sub_rule = g.rules[node.rule]; assert(sub_rule.alts.len > 0); if (sub_rule.alts.len == 1 and sub_rule.alts[0].seq.len == 1) { node.* = sub_rule.alts[0].seq[0]; dirty = true; } else if (sub_rule.alts.len == 1) { const sub_seq = sub_rule.alts[0].seq; const new_seq = try g.arena.allocator().alloc(Grammar.Node, alt.seq.len + sub_seq.len - 1); std.mem.copy(Grammar.Node, new_seq[0..node_idx], alt.seq[0..node_idx]); std.mem.copy(Grammar.Node, new_seq[node_idx .. node_idx + sub_seq.len], sub_seq); std.mem.copy(Grammar.Node, new_seq[node_idx + sub_seq.len ..], alt.seq[node_idx + 1 ..]); alt.seq = new_seq; dirty = true; break :next_node; } } } } if (do_fusing) { // litteral fusing var i: usize = alt.seq.len - 1; while (i > 0) : (i -= 1) { const lhs = alt.seq[i - 1]; const rhs = alt.seq[i]; if (lhs == .lit and rhs == .lit) { const new_lit = try g.arena.allocator().alloc(u8, lhs.lit.len + rhs.lit.len); std.mem.copy(u8, new_lit[0..lhs.lit.len], lhs.lit); std.mem.copy(u8, new_lit[lhs.lit.len..], rhs.lit); alt.seq[i - 1] = Grammar.Node{ .lit = new_lit }; std.mem.copy(Grammar.Node, alt.seq[i .. alt.seq.len - 1], alt.seq[i + 1 ..]); alt.seq.len -= 1; dirty = true; } } } if (do_distrib) { // distribution var i: usize = alt.seq.len - 1; while (i > 0) : (i -= 1) { const lhs = alt.seq[i - 1]; const rhs = alt.seq[i]; if (lhs == .rule and rhs == .lit) { assert(g.rules[lhs.rule].alts.len > 0); const nb = g.rules[lhs.rule].alts.len; const new_alts = try g.arena.allocator().alloc(Grammar.Alternative, rule.alts.len + nb - 1); std.mem.copy(Grammar.Alternative, new_alts[0..alt_idx], rule.alts[0..alt_idx]); std.mem.copy(Grammar.Alternative, new_alts[alt_idx .. rule.alts.len - 1], rule.alts[alt_idx + 1 ..]); var new_idx = rule.alts.len - 1; for (g.rules[lhs.rule].alts) |sub| { const new_seq = try g.arena.allocator().alloc(Grammar.Node, alt.seq.len + sub.seq.len - 1); std.mem.copy(Grammar.Node, new_seq[0 .. i - 1], alt.seq[0 .. i - 1]); std.mem.copy(Grammar.Node, new_seq[i - 1 .. i - 1 + sub.seq.len], sub.seq); std.mem.copy(Grammar.Node, new_seq[i - 1 + sub.seq.len ..], alt.seq[i..]); new_alts[new_idx].seq = new_seq; new_idx += 1; } assert(new_idx == new_alts.len); rule.alts = new_alts; dirty = true; continue :next_rule; // cur rule.alts changed... } else if (lhs == .lit and rhs == .rule) { assert(g.rules[rhs.rule].alts.len > 0); const nb = g.rules[rhs.rule].alts.len; const new_alts = try g.arena.allocator().alloc(Grammar.Alternative, rule.alts.len + nb - 1); std.mem.copy(Grammar.Alternative, new_alts[0..alt_idx], rule.alts[0..alt_idx]); std.mem.copy(Grammar.Alternative, new_alts[alt_idx .. rule.alts.len - 1], rule.alts[alt_idx + 1 ..]); var new_idx = rule.alts.len - 1; for (g.rules[rhs.rule].alts) |sub| { const new_seq = try g.arena.allocator().alloc(Grammar.Node, alt.seq.len + sub.seq.len - 1); std.mem.copy(Grammar.Node, new_seq[0..i], alt.seq[0..i]); std.mem.copy(Grammar.Node, new_seq[i .. i + sub.seq.len], sub.seq); std.mem.copy(Grammar.Node, new_seq[i + sub.seq.len ..], alt.seq[i + 1 ..]); new_alts[new_idx].seq = new_seq; new_idx += 1; } assert(new_idx == new_alts.len); rule.alts = new_alts; dirty = true; continue :next_rule; // cur rule.alts changed... } } } } } { for (g.rules[0..max_rule]) |*r| { if (r.alts.len == 0) continue; //empty_rule var min_len: u8 = 255; for (r.alts) |a| { var seq_len: usize = 0; for (a.seq) |n| { seq_len += if (n == .rule) g.rules[n.rule].min_len else n.lit.len; } if (seq_len < min_len) { min_len = @intCast(u8, seq_len); } } if (r.min_len < min_len) { r.min_len = min_len; dirty = true; } } } if (do_dce) { // dce max_rule = 0; var used = [_]bool{false} ** 200; used[0] = true; // pin entry-point for (g.rules) |r| { for (r.alts) |a| { for (a.seq) |n| { if (n == .rule) used[n.rule] = true; } } } for (g.rules) |*r, i| { if (!used[i]) { r.* = Grammar.empty_rule; } else { max_rule = i + 1; assert(r.alts.len > 0); } } } } if (false) { g.debugPrint(); } return g; } fn matchSeq(text: []const u8, seq: []const Grammar.Node, grammar: *Grammar) bool { if (seq.len == 0) { return (text.len == 0); } //std.debug.print(" {} vs {}\n", .{ text, seq[0] }); switch (seq[0]) { .lit => |l| { if (!std.mem.startsWith(u8, text, l)) return false; return matchSeq(text[l.len..], seq[1..], grammar); }, .rule => |sub| { const min_len_rest = blk: { var l: usize = 0; for (seq[1..]) |s| { switch (s) { .lit => |lit| l += lit.len, .rule => |r| l += grammar.rules[r].min_len, } } break :blk l; }; if (text.len < min_len_rest) return false; var sub_len: usize = grammar.rules[sub].min_len; while (sub_len <= text.len - min_len_rest) : (sub_len += 1) { if (match(text[0..sub_len], sub, grammar) and matchSeq(text[sub_len..], seq[1..], grammar)) { return true; } } return false; }, } } fn match(text: []const u8, r: u8, g: *Grammar) bool { if (text.len < g.rules[r].min_len) return false; if (g.memoize_cache == null) { g.memoize_cache = Grammar.MemoizeCache.init(g.arena.allocator()); } if (g.memoize_cache) |*memo| { if (memo.get(.{ .ptr = @ptrToInt(text.ptr), .len = @intCast(u8, text.len), .r = r })) |v| return v; } const ok = for (g.rules[r].alts) |alt| { if (matchSeq(text, alt.seq, g)) break true; } else false; if (g.memoize_cache) |*memo| { memo.put(.{ .ptr = @ptrToInt(text.ptr), .len = @intCast(u8, text.len), .r = r }, ok) catch unreachable; } return ok; } pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); var grammar = try Grammar.init(allocator); defer grammar.deinit(); const param: struct { mesgs: [][]const u8, } = blk: { var mesgs = std.ArrayList([]const u8).init(arena.allocator()); const rules = grammar.rules; var it = std.mem.tokenize(u8, input_text, "\n\r"); while (it.next()) |line| { if (tools.match_pattern("{}: \"{}\"", line)) |fields| { //44: "a" const name = @intCast(u8, fields[0].imm); const lit = fields[1].lit; assert(lit.len == 1); assert(rules[name].alts.len == 0); rules[name] = try grammar.newRuleLit(lit); } else if (tools.match_pattern("{}: {} {} | {} {}", line)) |fields| { //44: 82 117 | 26 54 const name = @intCast(u8, fields[0].imm); const r0 = @intCast(u8, fields[1].imm); const r1 = @intCast(u8, fields[2].imm); const r2 = @intCast(u8, fields[3].imm); const r3 = @intCast(u8, fields[4].imm); assert(rules[name].alts.len == 0); rules[name] = try grammar.newRuleSimple(&[_][]u8{ &[_]u8{ r0, r1 }, &[_]u8{ r2, r3 } }); } else if (tools.match_pattern("{}: {} | {}", line)) |fields| { //44: 82 | 54 const name = @intCast(u8, fields[0].imm); const r0 = @intCast(u8, fields[1].imm); const r1 = @intCast(u8, fields[2].imm); assert(rules[name].alts.len == 0); rules[name] = try grammar.newRuleSimple(&[_][]u8{ &[_]u8{r0}, &[_]u8{r1} }); } else if (tools.match_pattern("{}: {} {}", line)) |fields| { //44: 82 117 const name = @intCast(u8, fields[0].imm); const r0 = @intCast(u8, fields[1].imm); const r1 = @intCast(u8, fields[2].imm); assert(rules[name].alts.len == 0); rules[name] = try grammar.newRuleSimple(&[_][]u8{&[_]u8{ r0, r1 }}); } else if (tools.match_pattern("{}: {}", line)) |fields| { //44: 82 const name = @intCast(u8, fields[0].imm); const r0 = @intCast(u8, fields[1].imm); assert(rules[name].alts.len == 0); rules[name] = try grammar.newRuleSimple(&[_][]u8{&[_]u8{r0}}); } else { assert(std.mem.indexOfScalar(u8, line, ':') == null); try mesgs.append(line); } } //grammar.debugPrint(); break :blk .{ .mesgs = mesgs.items, }; }; const ans1 = ans: { var g = try reduce(&grammar, allocator); defer g.deinit(); var nb: usize = 0; for (param.mesgs) |msg| { if (match(msg, 0, &g)) nb += 1; } break :ans nb; }; const ans2 = ans: { // 8: 42 | 42 8 // 11: 42 31 | 42 11 31 grammar.rules[8] = try grammar.newRuleSimple(&[_][]const u8{ &[_]u8{42}, &[_]u8{ 42, 8 } }); grammar.rules[11] = try grammar.newRuleSimple(&[_][]const u8{ &[_]u8{ 42, 31 }, &[_]u8{ 42, 11, 31 } }); var g = try reduce(&grammar, allocator); defer g.deinit(); var nb: usize = 0; for (param.mesgs) |msg| { if (match(msg, 0, &g)) nb += 1; } break :ans nb; }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2020/input_day19.txt", run);
2020/day19.zig
const std = @import("std"); const buildLibressl = @import("vendor/zelda/zig-libressl/build.zig"); pub fn getAllPkg(comptime T: type) CalculatePkg(T) { const info: std.builtin.TypeInfo = @typeInfo(T); const declarations: []const std.builtin.TypeInfo.Declaration = info.Struct.decls; var pkgs: CalculatePkg(T) = undefined; var index: usize = 0; inline for (declarations) |d| { if (d.data == .Var) { pkgs[index] = @field(T, d.name); index += 1; } } return pkgs; } fn CalculatePkg(comptime T: type) type { const info: std.builtin.TypeInfo = @typeInfo(T); const declarations: []const std.builtin.TypeInfo.Declaration = info.Struct.decls; var count: usize = 0; for (declarations) |d| { if (d.data == .Var) { count += 1; } } return [count]std.build.Pkg; } pub fn build(b: *std.build.Builder) void { const pkgs = struct { pub const hzzp = std.build.Pkg{ .name = "hzzp", .path = std.build.FileSource.relative("vendor/zelda/hzzp/src/main.zig"), }; pub const zuri = std.build.Pkg{ .name = "zuri", .path = std.build.FileSource.relative("vendor/zelda/zuri/src/zuri.zig"), }; pub const libressl = std.build.Pkg{ .name = "zig-libressl", .path = std.build.FileSource.relative("vendor/zelda/zig-libressl/src/main.zig"), }; pub const zelda = std.build.Pkg{ .name = "zelda", .path = .{ .path = "vendor/zelda/src/main.zig" }, .dependencies = &[_]std.build.Pkg{ hzzp, zuri, libressl, }, }; const tvg = std.build.Pkg{ .name = "tinyvg", .path = .{ .path = "vendor/sdk/src/lib/tinyvg.zig" }, .dependencies = &.{ptk}, }; const ptk = std.build.Pkg{ .name = "parser-toolkit", .path = .{ .path = "vendor/sdk/vendor/parser-toolkit/src/main.zig" }, }; const args = std.build.Pkg{ .name = "zig-args", .path = .{ .path = "vendor/sdk/vendor/zig-args/args.zig" }, }; }; const packages = getAllPkg(pkgs); // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const strip: bool = b.option(bool, "strip", "Stripts the release build (false by default)") orelse false; const exe = b.addExecutable("cloudwords-hackernews-zig", "src/main.zig"); exe.linkLibC(); for (&packages) |package| { exe.addPackage(package); } exe.setTarget(target); exe.setBuildMode(mode); if (mode != .Debug or mode != .ReleaseSafe) { exe.strip = strip; } if (target.getOsTag() == .windows) { exe.addLibPath("C:/Program Files/LibreSSL/lib"); exe.addIncludeDir("C:/Program Files/LibreSSL/include"); } buildLibressl.useLibreSslForStep(b, exe, "vendor/zelda/zig-libressl/libressl"); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const exe_tests = b.addTest("src/main.zig"); exe_tests.setTarget(target); exe_tests.setBuildMode(mode); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&exe_tests.step); }
build.zig
const Dylib = @This(); const std = @import("std"); const assert = std.debug.assert; const fs = std.fs; const fmt = std.fmt; const log = std.log.scoped(.link); const macho = std.macho; const math = std.math; const mem = std.mem; const fat = @import("fat.zig"); const Allocator = mem.Allocator; const LibStub = @import("../tapi.zig").LibStub; const MachO = @import("../MachO.zig"); file: fs.File, name: []const u8, header: ?macho.mach_header_64 = null, // The actual dylib contents we care about linking with will be embedded at // an offset within a file if we are linking against a fat lib library_offset: u64 = 0, load_commands: std.ArrayListUnmanaged(macho.LoadCommand) = .{}, symtab_cmd_index: ?u16 = null, dysymtab_cmd_index: ?u16 = null, id_cmd_index: ?u16 = null, id: ?Id = null, /// Parsed symbol table represented as hash map of symbols' /// names. We can and should defer creating *Symbols until /// a symbol is referenced by an object file. symbols: std.StringArrayHashMapUnmanaged(void) = .{}, pub const Id = struct { name: []const u8, timestamp: u32, current_version: u32, compatibility_version: u32, pub fn default(allocator: Allocator, name: []const u8) !Id { return Id{ .name = try allocator.dupe(u8, name), .timestamp = 2, .current_version = 0x10000, .compatibility_version = 0x10000, }; } pub fn fromLoadCommand(allocator: Allocator, lc: macho.GenericCommandWithData(macho.dylib_command)) !Id { const dylib = lc.inner.dylib; const dylib_name = @ptrCast([*:0]const u8, lc.data[dylib.name - @sizeOf(macho.dylib_command) ..]); const name = try allocator.dupe(u8, mem.sliceTo(dylib_name, 0)); return Id{ .name = name, .timestamp = dylib.timestamp, .current_version = dylib.current_version, .compatibility_version = dylib.compatibility_version, }; } pub fn deinit(id: Id, allocator: Allocator) void { allocator.free(id.name); } pub const ParseError = fmt.ParseIntError || fmt.BufPrintError; pub fn parseCurrentVersion(id: *Id, version: anytype) ParseError!void { id.current_version = try parseVersion(version); } pub fn parseCompatibilityVersion(id: *Id, version: anytype) ParseError!void { id.compatibility_version = try parseVersion(version); } fn parseVersion(version: anytype) ParseError!u32 { const string = blk: { switch (version) { .int => |int| { var out: u32 = 0; const major = math.cast(u16, int) orelse return error.Overflow; out += @intCast(u32, major) << 16; return out; }, .float => |float| { var buf: [256]u8 = undefined; break :blk try fmt.bufPrint(&buf, "{d:.2}", .{float}); }, .string => |string| { break :blk string; }, } }; var out: u32 = 0; var values: [3][]const u8 = undefined; var split = mem.split(u8, string, "."); var count: u4 = 0; while (split.next()) |value| { if (count > 2) { log.debug("malformed version field: {s}", .{string}); return 0x10000; } values[count] = value; count += 1; } if (count > 2) { out += try fmt.parseInt(u8, values[2], 10); } if (count > 1) { out += @intCast(u32, try fmt.parseInt(u8, values[1], 10)) << 8; } out += @intCast(u32, try fmt.parseInt(u16, values[0], 10)) << 16; return out; } }; pub fn deinit(self: *Dylib, allocator: Allocator) void { for (self.load_commands.items) |*lc| { lc.deinit(allocator); } self.load_commands.deinit(allocator); for (self.symbols.keys()) |key| { allocator.free(key); } self.symbols.deinit(allocator); allocator.free(self.name); if (self.id) |*id| { id.deinit(allocator); } } pub fn parse(self: *Dylib, allocator: Allocator, target: std.Target, dependent_libs: anytype) !void { log.debug("parsing shared library '{s}'", .{self.name}); self.library_offset = try fat.getLibraryOffset(self.file.reader(), target); try self.file.seekTo(self.library_offset); var reader = self.file.reader(); self.header = try reader.readStruct(macho.mach_header_64); if (self.header.?.filetype != macho.MH_DYLIB) { log.debug("invalid filetype: expected 0x{x}, found 0x{x}", .{ macho.MH_DYLIB, self.header.?.filetype }); return error.NotDylib; } const this_arch: std.Target.Cpu.Arch = try fat.decodeArch(self.header.?.cputype, true); if (this_arch != target.cpu.arch) { log.err("mismatched cpu architecture: expected {s}, found {s}", .{ target.cpu.arch, this_arch }); return error.MismatchedCpuArchitecture; } try self.readLoadCommands(allocator, reader, dependent_libs); try self.parseId(allocator); try self.parseSymbols(allocator); } fn readLoadCommands(self: *Dylib, allocator: Allocator, reader: anytype, dependent_libs: anytype) !void { const should_lookup_reexports = self.header.?.flags & macho.MH_NO_REEXPORTED_DYLIBS == 0; try self.load_commands.ensureUnusedCapacity(allocator, self.header.?.ncmds); var i: u16 = 0; while (i < self.header.?.ncmds) : (i += 1) { var cmd = try macho.LoadCommand.read(allocator, reader); switch (cmd.cmd()) { .SYMTAB => { self.symtab_cmd_index = i; }, .DYSYMTAB => { self.dysymtab_cmd_index = i; }, .ID_DYLIB => { self.id_cmd_index = i; }, .REEXPORT_DYLIB => { if (should_lookup_reexports) { // Parse install_name to dependent dylib. var id = try Id.fromLoadCommand(allocator, cmd.dylib); try dependent_libs.writeItem(id); } }, else => { log.debug("Unknown load command detected: 0x{x}.", .{cmd.cmd()}); }, } self.load_commands.appendAssumeCapacity(cmd); } } fn parseId(self: *Dylib, allocator: Allocator) !void { const index = self.id_cmd_index orelse { log.debug("no LC_ID_DYLIB load command found; using hard-coded defaults...", .{}); self.id = try Id.default(allocator, self.name); return; }; self.id = try Id.fromLoadCommand(allocator, self.load_commands.items[index].dylib); } fn parseSymbols(self: *Dylib, allocator: Allocator) !void { const index = self.symtab_cmd_index orelse return; const symtab_cmd = self.load_commands.items[index].symtab; const symtab = try allocator.alloc(u8, @sizeOf(macho.nlist_64) * symtab_cmd.nsyms); defer allocator.free(symtab); _ = try self.file.preadAll(symtab, symtab_cmd.symoff + self.library_offset); const slice = @alignCast(@alignOf(macho.nlist_64), mem.bytesAsSlice(macho.nlist_64, symtab)); const strtab = try allocator.alloc(u8, symtab_cmd.strsize); defer allocator.free(strtab); _ = try self.file.preadAll(strtab, symtab_cmd.stroff + self.library_offset); for (slice) |sym| { const add_to_symtab = sym.ext() and (sym.sect() or sym.indr()); if (!add_to_symtab) continue; const sym_name = mem.sliceTo(@ptrCast([*:0]const u8, strtab.ptr + sym.n_strx), 0); const name = try allocator.dupe(u8, sym_name); try self.symbols.putNoClobber(allocator, name, {}); } } fn addObjCClassSymbol(self: *Dylib, allocator: Allocator, sym_name: []const u8) !void { const expanded = &[_][]const u8{ try std.fmt.allocPrint(allocator, "_OBJC_CLASS_$_{s}", .{sym_name}), try std.fmt.allocPrint(allocator, "_OBJC_METACLASS_$_{s}", .{sym_name}), }; for (expanded) |sym| { if (self.symbols.contains(sym)) continue; try self.symbols.putNoClobber(allocator, sym, {}); } } fn addObjCIVarSymbol(self: *Dylib, allocator: Allocator, sym_name: []const u8) !void { const expanded = try std.fmt.allocPrint(allocator, "_OBJC_IVAR_$_{s}", .{sym_name}); if (self.symbols.contains(expanded)) return; try self.symbols.putNoClobber(allocator, expanded, {}); } fn addObjCEhTypeSymbol(self: *Dylib, allocator: Allocator, sym_name: []const u8) !void { const expanded = try std.fmt.allocPrint(allocator, "_OBJC_EHTYPE_$_{s}", .{sym_name}); if (self.symbols.contains(expanded)) return; try self.symbols.putNoClobber(allocator, expanded, {}); } fn addSymbol(self: *Dylib, allocator: Allocator, sym_name: []const u8) !void { if (self.symbols.contains(sym_name)) return; try self.symbols.putNoClobber(allocator, try allocator.dupe(u8, sym_name), {}); } const TargetMatcher = struct { allocator: Allocator, target: std.Target, target_strings: std.ArrayListUnmanaged([]const u8) = .{}, fn init(allocator: Allocator, target: std.Target) !TargetMatcher { var self = TargetMatcher{ .allocator = allocator, .target = target, }; try self.target_strings.append(allocator, try targetToAppleString(allocator, target)); if (target.abi == .simulator) { // For Apple simulator targets, linking gets tricky as we need to link against the simulator // hosts dylibs too. const host_target = try targetToAppleString(allocator, (std.zig.CrossTarget{ .cpu_arch = target.cpu.arch, .os_tag = .macos, }).toTarget()); try self.target_strings.append(allocator, host_target); } return self; } fn deinit(self: *TargetMatcher) void { for (self.target_strings.items) |t| { self.allocator.free(t); } self.target_strings.deinit(self.allocator); } fn targetToAppleString(allocator: Allocator, target: std.Target) ![]const u8 { const arch = switch (target.cpu.arch) { .aarch64 => "arm64", .x86_64 => "x86_64", else => unreachable, }; const os = @tagName(target.os.tag); const abi: ?[]const u8 = switch (target.abi) { .none => null, .simulator => "simulator", .macabi => "maccatalyst", else => unreachable, }; if (abi) |x| { return std.fmt.allocPrint(allocator, "{s}-{s}-{s}", .{ arch, os, x }); } return std.fmt.allocPrint(allocator, "{s}-{s}", .{ arch, os }); } fn hasValue(stack: []const []const u8, needle: []const u8) bool { for (stack) |v| { if (mem.eql(u8, v, needle)) return true; } return false; } fn matchesTarget(self: TargetMatcher, targets: []const []const u8) bool { for (self.target_strings.items) |t| { if (hasValue(targets, t)) return true; } return false; } fn matchesArch(self: TargetMatcher, archs: []const []const u8) bool { return hasValue(archs, @tagName(self.target.cpu.arch)); } }; pub fn parseFromStub( self: *Dylib, allocator: Allocator, target: std.Target, lib_stub: LibStub, dependent_libs: anytype, ) !void { if (lib_stub.inner.len == 0) return error.EmptyStubFile; log.debug("parsing shared library from stub '{s}'", .{self.name}); const umbrella_lib = lib_stub.inner[0]; { var id = try Id.default(allocator, umbrella_lib.installName()); if (umbrella_lib.currentVersion()) |version| { try id.parseCurrentVersion(version); } if (umbrella_lib.compatibilityVersion()) |version| { try id.parseCompatibilityVersion(version); } self.id = id; } var umbrella_libs = std.StringHashMap(void).init(allocator); defer umbrella_libs.deinit(); log.debug(" (install_name '{s}')", .{umbrella_lib.installName()}); var matcher = try TargetMatcher.init(allocator, target); defer matcher.deinit(); for (lib_stub.inner) |elem, stub_index| { const is_match = switch (elem) { .v3 => |stub| matcher.matchesArch(stub.archs), .v4 => |stub| matcher.matchesTarget(stub.targets), }; if (!is_match) continue; if (stub_index > 0) { // TODO I thought that we could switch on presence of `parent-umbrella` map; // however, turns out `libsystem_notify.dylib` is fully reexported by `libSystem.dylib` // BUT does not feature a `parent-umbrella` map as the only sublib. Apple's bug perhaps? try umbrella_libs.put(elem.installName(), {}); } switch (elem) { .v3 => |stub| { if (stub.exports) |exports| { for (exports) |exp| { if (!matcher.matchesArch(exp.archs)) continue; if (exp.symbols) |symbols| { for (symbols) |sym_name| { try self.addSymbol(allocator, sym_name); } } if (exp.objc_classes) |objc_classes| { for (objc_classes) |class_name| { try self.addObjCClassSymbol(allocator, class_name); } } if (exp.objc_ivars) |objc_ivars| { for (objc_ivars) |ivar| { try self.addObjCIVarSymbol(allocator, ivar); } } if (exp.objc_eh_types) |objc_eh_types| { for (objc_eh_types) |eht| { try self.addObjCEhTypeSymbol(allocator, eht); } } // TODO track which libs were already parsed in different steps if (exp.re_exports) |re_exports| { for (re_exports) |lib| { if (umbrella_libs.contains(lib)) continue; log.debug(" (found re-export '{s}')", .{lib}); var dep_id = try Id.default(allocator, lib); try dependent_libs.writeItem(dep_id); } } } } }, .v4 => |stub| { if (stub.exports) |exports| { for (exports) |exp| { if (!matcher.matchesTarget(exp.targets)) continue; if (exp.symbols) |symbols| { for (symbols) |sym_name| { try self.addSymbol(allocator, sym_name); } } if (exp.objc_classes) |classes| { for (classes) |sym_name| { try self.addObjCClassSymbol(allocator, sym_name); } } if (exp.objc_ivars) |objc_ivars| { for (objc_ivars) |ivar| { try self.addObjCIVarSymbol(allocator, ivar); } } if (exp.objc_eh_types) |objc_eh_types| { for (objc_eh_types) |eht| { try self.addObjCEhTypeSymbol(allocator, eht); } } } } if (stub.reexports) |reexports| { for (reexports) |reexp| { if (!matcher.matchesTarget(reexp.targets)) continue; if (reexp.symbols) |symbols| { for (symbols) |sym_name| { try self.addSymbol(allocator, sym_name); } } if (reexp.objc_classes) |classes| { for (classes) |sym_name| { try self.addObjCClassSymbol(allocator, sym_name); } } if (reexp.objc_ivars) |objc_ivars| { for (objc_ivars) |ivar| { try self.addObjCIVarSymbol(allocator, ivar); } } if (reexp.objc_eh_types) |objc_eh_types| { for (objc_eh_types) |eht| { try self.addObjCEhTypeSymbol(allocator, eht); } } } } if (stub.objc_classes) |classes| { for (classes) |sym_name| { try self.addObjCClassSymbol(allocator, sym_name); } } if (stub.objc_ivars) |objc_ivars| { for (objc_ivars) |ivar| { try self.addObjCIVarSymbol(allocator, ivar); } } if (stub.objc_eh_types) |objc_eh_types| { for (objc_eh_types) |eht| { try self.addObjCEhTypeSymbol(allocator, eht); } } }, } } // For V4, we add dependent libs in a separate pass since some stubs such as libSystem include // re-exports directly in the stub file. for (lib_stub.inner) |elem| { if (elem == .v3) break; const stub = elem.v4; // TODO track which libs were already parsed in different steps if (stub.reexported_libraries) |reexports| { for (reexports) |reexp| { if (!matcher.matchesTarget(reexp.targets)) continue; for (reexp.libraries) |lib| { if (umbrella_libs.contains(lib)) continue; log.debug(" (found re-export '{s}')", .{lib}); var dep_id = try Id.default(allocator, lib); try dependent_libs.writeItem(dep_id); } } } } }
src/link/MachO/Dylib.zig
const std = @import("std"); const Uart = @import("./mmio.zig").Uart; const interpreter = @import("./interpreter.zig"); const heap = @import("./heap.zig"); const debug = @import("build_options").log_uart; /// Initialize the UART. Should be called very, *very* early. Must /// have been called before any write/read occurs. pub fn init() void { // Set word length Uart.lcr.write(u8, 0b0000_0011); Uart.fcr.write(u8, 0b0000_0001); // Enable received data interrupt Uart.ier.write(u8, 0b0000_0001); // Enable divisor latch Uart.lcr.write(u8, 0b1000_0011); // Set up signaling rate, values from http://osblog.stephenmarz.com/ch2.html const divisor: u16 = 592; // Write divisor halves const div_lower = @truncate(u8, divisor); Uart.base.write(u8, div_lower); const div_upper = @intCast(u8, divisor >> 8); Uart.ier.write(u8, div_upper); // Disable divisor latch Uart.lcr.write(u8, 0b0000_0011); if (comptime debug) print("init uart...\n", .{}); } /// Formatted printing! Yay! pub fn print(comptime format: []const u8, args: var) void { std.fmt.format(TermOutStream{ .context = {} }, format, args) catch unreachable; } // Boilerplate for using the stdlib's formatted printing const TermOutStream = std.io.OutStream(void, error{}, termOutStreamWriteCallback); fn termOutStreamWriteCallback(ctx: void, bytes: []const u8) error{}!usize { for (bytes) |byte| { put(byte); } return bytes.len; } /// Print a single character to the UART. pub fn put(c: u8) void { Uart.base.write(u8, c); } /// Return a as of yet unread char or null. fn read() ?u8 { if (Uart.lsr.read(u8) & 0b0000_0001 == 1) { return Uart.base.read(u8); } else { return null; } } /// Shamelessly stolen from Wikipedia, useful ANSI sequences pub const ANSIFormat = struct { pub const CSI = "\x1b["; pub const SGR = struct { pub const reset = CSI ++ "0m"; pub const bold = CSI ++ "1m"; pub const italic = CSI ++ "3m"; pub const underline = CSI ++ "4m"; pub const set_fg = CSI ++ "38;5;"; pub const set_bg = CSI ++ "48;5;"; pub const Color = enum { black, red, green, yellow, blue, magenta, cyan, white, pub const Black = "0m"; pub const Red = "1m"; pub const Green = "2m"; pub const Yellow = "3m"; pub const Blue = "4m"; pub const Magenta = "5m"; pub const Cyan = "6m"; pub const White = "7m"; pub fn string(self: Color) []const u8 { return switch (self) { .black => Black, .red => Red, .green => Green, .yellow => Yellow, .blue => Blue, .magenta => Magenta, .cyan => Cyan, .white => White, }; } }; pub const RenderOpts = struct { bold: bool = false, italic: bool = false, underline: bool = false, fg: ?SGR.Color = null, bg: ?SGR.Color = null, }; pub fn render(comptime str: []const u8, comptime opts: RenderOpts) []const u8 { comptime var buf = [_]u8{0} ** (str.len + 64); const fmt_bold = if (opts.bold) bold else ""; const fmt_italic = if (opts.italic) italic else ""; const fmt_underline = if (opts.underline) underline else ""; const fmt_fg = if (opts.fg) |color| set_fg ++ color.string() else ""; const fmt_bg = if (opts.bg) |color| set_bg ++ color.string() else ""; return comptime std.fmt.bufPrint( &buf, // these look so sad as a workaround for ziglang/zig#5401 "{:<}{:<}{:<}{:<}{:<}{:<}{:<}", .{ fmt_bold, fmt_italic, fmt_underline, fmt_fg, fmt_bg, str, reset }, ) catch unreachable; } }; }; /// A stack for temporarily storing things that look like escape sequences var input_stack = [_]u8{0} ** 8; var input_stack_top: u8 = 0; /// What we're doing currently. var state: enum { passthru, seen_escape, task_switching, } = .passthru; /// This gets called by the PLIC handler in rupt/plic.zig pub fn handleInterrupt() void { const eql = std.mem.eql; const char = read().?; if (char == '\x1b') state = .seen_escape; switch (state) { .passthru => interpreter.notify(.{ .uart_data = char }), .seen_escape => { if (comptime debug) print("uart: seen escape, this char is {x}\n", .{char}); var maybe_found = false; input_stack[input_stack_top] = char; input_stack_top += 1; for (known_escapes) |seq| { if (input_stack_top > seq.len) continue; if (std.mem.eql(u8, seq[0..input_stack_top], input_stack[0..input_stack_top])) { maybe_found = true; if (seq.len == input_stack_top) { handleEscapeSequence(input_stack[0..input_stack_top]); } break; } } if (!maybe_found) { if (comptime debug) print("uart: this couldn't possibly be a known escape\n", .{}); for (input_stack[0..input_stack_top]) |ch| interpreter.notify(.{ .uart_data = ch }); input_stack_top = 0; } }, .task_switching => {}, } } /// What to do when we find any escape sequence. Called by handle_interrupt. fn handleEscapeSequence(data: []const u8) void { if (comptime debug) print("uart: handling escape sequence {x}\n", .{data}); switch (explainEscapeSequence(data).?) { .F1 => { print( \\ \\{} \\ heap: {}/{} pages used \\ tasks: {} \\ fg task: {} \\ , .{ ANSIFormat.SGR.render("Statistics", ANSIFormat.SGR.RenderOpts{ .bold = true }), heap.statistics(.pages_taken), heap.statistics(.pages_total), interpreter.statistics(.tasks_total), interpreter.shell.foreground_task.data.id, }, ); }, .F2 => { interpreter.shell.TaskSwitcher.activate(); }, .F9 => { @panic("you have no one to blame but yourself"); }, } input_stack_top = 0; state = .passthru; } /// All escape sequence variants we care about const known_escapes = [_][]const u8{ "\x1bOP", "\x1b[11~", "\x1bOw", "\x1b[20~", "\x1bOQ", "\x1b[12~", }; /// Turns out there are more than one representation for some sequences. Yay. /// This function takes a slice and checks if it is one that we care about, /// returning a self-descriptive enum variant or null if it just isn't. fn explainEscapeSequence(data: []const u8) ?enum { F1, F2, F9 } { const eql = std.mem.eql; if (eql(u8, data, "\x1bOP") or eql(u8, data, "\x1b[11~")) { return .F1; } else if (eql(u8, data, "\x1bOQ") or eql(u8, data, "\x1b[12~")) { return .F2; } else if (eql(u8, data, "\x1bOw") or eql(u8, data, "\x1b[20~")) { return .F9; } return null; }
src/uart.zig
const std = @import("std"); pub const ParseMode = struct { /// When pedantic is true, the parser will not allow data between /// records. pedantic: bool = true, }; /// An intel hex data record. /// Resembles a single line in the hex file. pub const Record = union(enum) { data: Data, end_of_file: void, extended_segment_address: ExtendedSegmentAddress, start_segment_address: StartSegmentAddress, extended_linear_address: ExtendedLinearAddress, start_linear_address: LinearStartAddress, /// A record that contains data. pub const Data = struct { /// Offset from the start of the current segment. offset: u16, /// Bytes in the segment data: []const u8, }; /// Contains the 8086 segment for the following data. pub const ExtendedSegmentAddress = struct { segment: u16, }; /// Contains the 8086 entry point for this file. pub const StartSegmentAddress = struct { /// The `CS` selector for the entry point. segment: u16, /// The `IP` register content for the entry point. offset: u16, }; /// Contains the linear offset for all following data. pub const ExtendedLinearAddress = struct { /// The upper 16 bit for the address. upperWord: u16, }; /// Contains the linear 32 bit entry point. pub const LinearStartAddress = struct { /// Linear entry point without segmentation. offset: u32, }; }; /// Parses intel hex records from the stream, using `mode` as parser configuration. /// For each record, `loader` is called with `context` as the first parameter. pub fn parseRaw(stream: anytype, mode: ParseMode, context: anytype, Errors: type, loader: fn (@TypeOf(context), record: Record) Errors!void) !void { while (true) { var b = stream.readByte() catch |err| { if (err == error.EndOfStream and !mode.pedantic) return; return err; }; if (b != ':') { if (b != '\n' and b != '\r' and mode.pedantic) { return error.InvalidCharacter; } else { continue; } } var line_buffer: [520]u8 = undefined; try stream.readNoEof(line_buffer[0..2]); const byte_count = std.fmt.parseInt(u8, line_buffer[0..2], 16) catch return error.InvalidRecord; const end_index = 10 + 2 * byte_count; try stream.readNoEof(line_buffer[2..end_index]); const line = line_buffer[0..end_index]; const address = std.fmt.parseInt(u16, line[2..6], 16) catch return error.InvalidRecord; const record_type = std.fmt.parseInt(u8, line[6..8], 16) catch return error.InvalidRecord; { var i: usize = 0; var checksum: u8 = 0; while (i < line.len) : (i += 2) { checksum +%= std.fmt.parseInt(u8, line[i .. i + 2], 16) catch return error.InvalidRecord; } if (checksum != 0) return error.InvalidChecksum; } switch (record_type) { 0x00 => { var temp_data: [255]u8 = undefined; for (temp_data[0..byte_count]) |*c, i| { c.* = std.fmt.parseInt(u8, line[8 + 2 * i .. 10 + 2 * i], 16) catch return error.InvalidRecord; } const data = Record.Data{ .offset = address, .data = temp_data[0..byte_count], }; try loader(context, Record{ .data = data }); }, 0x01 => { try loader(context, Record{ .end_of_file = {} }); return; }, 0x02 => { if (byte_count != 2) return error.InvalidRecord; const addr = Record.ExtendedSegmentAddress{ .segment = std.fmt.parseInt(u16, line[8..12], 16) catch return error.InvalidRecord, }; try loader(context, Record{ .extended_segment_address = addr }); }, 0x03 => { if (byte_count != 4) return error.InvalidRecord; const addr = Record.StartSegmentAddress{ .segment = std.fmt.parseInt(u16, line[8..12], 16) catch return error.InvalidRecord, .offset = std.fmt.parseInt(u16, line[12..16], 16) catch return error.InvalidRecord, }; try loader(context, Record{ .start_segment_address = addr }); }, 0x04 => { if (byte_count != 2) return error.InvalidRecord; const addr = Record.ExtendedLinearAddress{ .upperWord = std.fmt.parseInt(u16, line[8..12], 16) catch return error.InvalidRecord, }; try loader(context, Record{ .extended_linear_address = addr }); }, 0x05 => { if (byte_count != 4) return error.InvalidRecord; const addr = Record.LinearStartAddress{ .offset = std.fmt.parseInt(u32, line[8..16], 16) catch return error.InvalidRecord, }; try loader(context, Record{ .start_linear_address = addr }); }, else => return error.InvalidRecord, } } } /// Parses intel hex data segments from the stream, using `mode` as parser configuration. /// For each data record, `loader` is called with `context` as the first parameter. pub fn parseData(stream: anytype, mode: ParseMode, context: anytype, Errors: type, loader: fn (@TypeOf(context), offset: u32, record: []const u8) Errors!void) !?u32 { const Parser = struct { entry_point: ?u32, current_offset: u32, _context: @TypeOf(context), _loader: fn (@TypeOf(context), offset: u32, record: []const u8) Errors!void, fn load(parser: *@This(), record: Record) Errors!void { switch (record) { // Basic records .end_of_file => {}, .data => |data| try parser._loader(parser._context, parser.current_offset + data.offset, data.data), // Oldschool offsets .extended_segment_address => |addr| parser.current_offset = 16 * @as(u32, addr.segment), .start_segment_address => |addr| parser.entry_point = 16 * @as(u32, addr.segment) + @as(u32, addr.offset), // Newschool offsets .extended_linear_address => |addr| parser.current_offset = @as(u32, addr.upperWord) << 16, .start_linear_address => |addr| parser.entry_point = addr.offset, } } }; var parser = Parser{ .entry_point = null, .current_offset = 0, ._context = context, ._loader = loader, }; try parseRaw(stream, mode, &parser, Errors, Parser.load); return parser.entry_point; } const pedanticTestData = \\:0B0010006164647265737320676170A7 \\:020000021200EA \\:0400000300003800C1 \\:02000004FFFFFC \\:04000005000000CD2A \\:00000001FF \\ ; const laxTestData = \\ this is a comment! \\:0B0010006164647265737320676170A7 \\:020000021200EAi also allow stupid stuff here \\:0400000300003800C1 \\:02000004FFFFFC \\this is neither a comment \\:04000005000000CD2A \\34098302948092803284093284093284098320948s ; const TestVerifier = struct { index: usize = 0, fn process(verifier: *TestVerifier, record: Record) error{ TestUnexpectedResult, TestExpectedEqual }!void { switch (verifier.index) { 0 => { try std.testing.expectEqual(@as(u16, 16), record.data.offset); try std.testing.expectEqualSlices(u8, "address gap", record.data.data); }, 1 => try std.testing.expectEqual(@as(u16, 4608), record.extended_segment_address.segment), 2 => { try std.testing.expectEqual(@as(u16, 0), record.start_segment_address.segment); try std.testing.expectEqual(@as(u16, 14336), record.start_segment_address.offset); }, 3 => try std.testing.expectEqual(@as(u16, 65535), record.extended_linear_address.upperWord), 4 => try std.testing.expectEqual(@as(u32, 205), record.start_linear_address.offset), 5 => try std.testing.expect(record == .end_of_file), else => @panic("too many records!"), } verifier.index += 1; } }; test "ihex pedantic" { var stream = std.io.fixedBufferStream(pedanticTestData).reader(); var verifier = TestVerifier{}; try parseRaw(stream, ParseMode{ .pedantic = true }, &verifier, error{ TestUnexpectedResult, TestExpectedEqual }, TestVerifier.process); } test "ihex lax" { var stream = std.io.fixedBufferStream(laxTestData).reader(); var verifier = TestVerifier{}; try parseRaw(stream, ParseMode{ .pedantic = false }, &verifier, error{ TestUnexpectedResult, TestExpectedEqual }, TestVerifier.process); } test "huge file parseRaw" { var file = try std.fs.cwd().openFile("data/huge.ihex", .{ .read = true, .write = false }); defer file.close(); try parseRaw(file.reader(), ParseMode{ .pedantic = true }, {}, EmptyErrorSet, struct { fn parse(_: void, record: Record) EmptyErrorSet!void { _ = record; } }.parse); } const EmptyErrorSet = error{}; fn ignoreRecords(x: void, offset: u32, data: []const u8) EmptyErrorSet!void { _ = x; _ = offset; _ = data; } test "huge file parseData" { var file = try std.fs.cwd().openFile("data/huge.ihex", .{ .read = true, .write = false }); defer file.close(); _ = try parseData(file.reader(), ParseMode{ .pedantic = true }, {}, EmptyErrorSet, ignoreRecords); } test "parseData" { var stream = std.io.fixedBufferStream(pedanticTestData).reader(); const ep = try parseData(stream, ParseMode{ .pedantic = true }, {}, EmptyErrorSet, ignoreRecords); try std.testing.expectEqual(@as(u32, 205), ep.?); }
ihex.zig
const std = @import("std"); const ig = @import("imgui"); const cgltf = @import("cgltf"); const vk = @import("vk"); const gltf = @import("gltf_wrap.zig"); const engine = @import("engine.zig"); const autogui = @import("autogui.zig"); const Allocator = std.mem.Allocator; const warn = std.debug.warn; const assert = std.debug.assert; const Child = std.meta.Child; const heap_allocator = std.heap.c_allocator; const models = [_]ModelPath{ makePath("TriangleWithoutIndices"), makePath("Triangle"), makePath("AnimatedTriangle"), makePath("AnimatedMorphCube"), makePath("AnimatedMorphSphere"), }; const FIRST_MODEL = @as(usize, 0); var loadedModelIndex = FIRST_MODEL; var targetModelIndex = FIRST_MODEL; const ModelPath = struct { gltfFile: [*:0]const u8, directory: [*:0]const u8, }; fn makePath(comptime model: []const u8) ModelPath { const gen = struct { const path = "models/" ++ model ++ "/glTF/" ++ model ++ ".gltf"; const dir = "models/" ++ model ++ "/glTF/"; }; return ModelPath{ .gltfFile = gen.path, .directory = gen.dir }; } fn loadModel(index: usize) !*gltf.Data { const nextModel = &models[targetModelIndex]; std.debug.warn("Loading {s}\n", .{std.mem.spanZ(nextModel.gltfFile)}); const options = cgltf.Options{}; const data = try cgltf.parseFile(options, nextModel.gltfFile); errdefer cgltf.free(data); try cgltf.loadBuffers(options, data, nextModel.directory); // unload handled by cgltf.free const wrapped = try gltf.wrap(data, heap_allocator); errdefer gltf.free(wrapped); return wrapped; } fn uploadRenderingData(data: *gltf.Data, frame: *engine.render.Frame) !void { markUsageFlags(data); try uploadBuffers(data, frame); } fn markUsageFlags(data: *gltf.Data) void { for (data.buffer_views) |view| { if (view.raw.type == .vertices) view.buffer.usageFlags.vertexBuffer = true; if (view.raw.type == .indices) view.buffer.usageFlags.indexBuffer = true; } } fn uploadBuffers(data: *gltf.Data, frame: *engine.render.Frame) !void { assert(!data.renderingDataInitialized); var upload = try frame.beginUpload(); errdefer upload.abort(); errdefer unloadRenderingData(data); for (data.buffers) |*buffer, i| { buffer.gpuBuffer = try engine.render.createGpuBuffer(buffer.raw.size, buffer.usageFlags); const bufferData = @ptrCast([*]u8, buffer.raw.data.?)[0..buffer.raw.size]; try upload.setBufferData(&buffer.gpuBuffer.?, 0, bufferData); } upload.endAndWait(); data.renderingDataInitialized = true; } fn unloadRenderingData(data: *gltf.Data) void { const backend = engine.render.backend; assert(data.renderingDataInitialized); for (data.buffers) |*buffer| { if (buffer.gpuBuffer != null) { buffer.gpuBuffer.?.destroy(); buffer.gpuBuffer = null; } } } fn unloadModel(data: *gltf.Data) void { cgltf.free(data.raw); gltf.free(data); } var show_demo_window = false; var show_gltf_data = false; var clearColor = ig.Vec4{ .x = 0.2, .y = 0.2, .z = 0.2, .w = 1 }; pub fn main() !void { try engine.init("glTF Renderer", heap_allocator); defer engine.deinit(); // Our state var data = try loadModel(loadedModelIndex); defer unloadModel(data); assert(!data.renderingDataInitialized); // Main loop while (try engine.beginFrame()) : (engine.endFrame()) { // show the options window OPTIONS_WINDOW: { const open = ig.Begin("Control"); defer ig.End(); if (!open) break :OPTIONS_WINDOW; ig.Text("Current File (%lld/%lld): %s", loadedModelIndex + 1, models.len, models[loadedModelIndex].gltfFile); if (ig.Button("Load Previous File")) { targetModelIndex = (if (targetModelIndex == 0) models.len else targetModelIndex) - 1; } ig.SameLine(); if (ig.Button("Load Next File")) { targetModelIndex = if (targetModelIndex >= models.len - 1) 0 else (targetModelIndex + 1); } _ = ig.Checkbox("Show glTF Data", &show_gltf_data); _ = ig.Checkbox("Show ImGui Demo", &show_demo_window); if (ig.Button("Crash")) { @panic("Don't press the big shiny button!"); } } if (show_demo_window) ig.ShowDemoWindowExt(&show_demo_window); if (show_gltf_data) drawGltfUI(data, &show_gltf_data); if (targetModelIndex != loadedModelIndex) { unloadModel(data); data = try loadModel(targetModelIndex); loadedModelIndex = targetModelIndex; } // waits on frame ready semaphore var frame = try engine.render.beginRender(); defer frame.end(); if (data.renderingDataInitialized != true) { warn("Setting up rendering data...\n", .{}); try uploadRenderingData(data, &frame); assert(data.renderingDataInitialized); } // TODO: Make this beginRenderPass(colorPass) var colorRender = try frame.beginColorPass(clearColor); defer colorRender.end(); // rendering code here... try engine.render.renderImgui(&colorRender); } } fn drawGltfUI(data: *gltf.Data, show: *bool) void { const Static = struct {}; const showWindow = ig.BeginExt("glTF Data", show, .{}); defer ig.End(); // early out as an optimization if (!showWindow) return; ig.Columns(2); defer ig.Columns(1); ig.PushStyleVarVec2(ig.StyleVar.FramePadding, ig.Vec2{ .x = 2, .y = 2 }); defer ig.PopStyleVar(); ig.Separator(); autogui.draw(gltf.Data, data, heap_allocator); ig.Separator(); } pub export fn WinMain( hInstance: ?*c_void, hPrevInstance: ?*c_void, lpCmdLine: ?[*:0]const u8, nShowCmd: c_int, ) void { std.debug.maybeEnableSegfaultHandler(); main() catch |err| { std.log.err("{s}", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } std.os.exit(1); }; std.os.exit(0); }
src/main.zig
const std = @import("std"); const warn = std.debug.warn; const win = std.os.windows; usingnamespace @import("externs.zig"); //usage: ./injector process-id absolute-path-of-dll pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const mem = &arena.allocator; const args = try std.process.argsAlloc(mem); defer std.process.argsFree(mem, args); if (args.len != 3) return error.ExpectedTwoArgs; const path = try std.unicode.utf8ToUtf16LeWithNull(mem, args[2]); defer mem.free(path); const pid = try std.fmt.parseInt(u32, args[1], 10); //if we encounter a winapi error, print its exit code before exit errdefer { @setEvalBranchQuota(5000); const err = win.kernel32.GetLastError(); std.debug.warn("failed with code 0x{X}: {}\n", .{ @enumToInt(err), err }); } //open target process with VM_WRITE, CREATE_THREAD, VM_OPERATION const process = OpenProcess(0x20 | 0x2 | 0x8, 0, pid) orelse return error.OpenProcessFailed; defer std.os.windows.CloseHandle(process); //allocate memory for the dll's path string in the target process const target_path = VirtualAllocEx( process, null, path.len, win.MEM_RESERVE | win.MEM_COMMIT, win.PAGE_READWRITE, ) orelse return error.TargetPathAllocationFailed; defer _ = VirtualFreeEx(process, target_path, 0, win.MEM_RELEASE); //copy path string from injector to target process in the newly allocated memory if (WriteProcessMemory( process, target_path, path.ptr, (path.len + 1) * 2, null ) == 0) return error.WPMPathCopyFailed; // 1) get a handle to kernel32.dll in the injector's process // 2) get address of LoadLibraryW inside kernel32 // side note: kernel32 is loaded in the same place for all processes (of the same bitness), which is why this works // 3) create a thread in the target process starting in LoadLibraryW, with the path string as its argument const thread_handle = CreateRemoteThread( process, null, 0, @ptrCast( fn (win.LPVOID) callconv(.C) u32, win.kernel32.GetProcAddress( GetModuleHandleA("kernel32.dll") orelse unreachable, "LoadLibraryW", ) orelse unreachable, ), target_path, 0, null, ) orelse return error.ThreadCreationFailed; defer win.CloseHandle(thread_handle); try std.io.getStdOut().outStream().print("called LoadLibraryW\n", .{}); //wait for LoadLibraryW to return and the thread to exit //this is needed so we don't prematurely deallocate the path string memory _ = win.kernel32.WaitForSingleObject(thread_handle, win.INFINITE); try std.io.getStdOut().outStream().print("finished injecting\n", .{}); }
src/main.zig
const std = @import("std"); const c = @import("c"); const Buffer = @import("buffer.zig").Buffer; const Font = @import("font.zig").Font; const Face = @import("face.zig").Face; const SegmentProps = @import("buffer.zig").SegmentProps; const Feature = @import("common.zig").Feature; pub const ShapePlan = struct { handle: *c.hb_shape_plan_t, pub fn init(face: Face, props: SegmentProps, features: ?[]const Feature, shapers: []const []const u8) ShapePlan { return .{ .handle = hb_shape_plan_create( face.handle, &props.cast(), if (features) |f| f.ptr else null, if (features) |f| @intCast(c_uint, f.len) else 0, @ptrCast([*c]const [*c]const u8, shapers), ).? }; } pub fn initCached(face: Face, props: SegmentProps, features: ?[]const Feature, shapers: []const []const u8) ShapePlan { return .{ .handle = hb_shape_plan_create_cached( face.handle, &props.cast(), if (features) |f| f.ptr else null, if (features) |f| @intCast(c_uint, f.len) else 0, @ptrCast([*c]const [*c]const u8, shapers), ).? }; } pub fn init2(face: Face, props: SegmentProps, features: ?[]const Feature, cords: []const i32, shapers: []const []const u8) ShapePlan { return .{ .handle = hb_shape_plan_create2( face.handle, &props.cast(), if (features) |f| f.ptr else null, if (features) |f| @intCast(c_uint, f.len) else 0, cords.ptr, @intCast(c_uint, cords.len), @ptrCast([*c]const [*c]const u8, shapers), ).? }; } pub fn initCached2(face: Face, props: SegmentProps, features: ?[]const Feature, cords: []const i32, shapers: []const []const u8) ShapePlan { return .{ .handle = hb_shape_plan_create_cached2( face.handle, &props.cast(), if (features) |f| f.ptr else null, if (features) |f| @intCast(c_uint, f.len) else 0, cords.ptr, @intCast(c_uint, cords.len), @ptrCast([*c]const [*c]const u8, shapers), ).? }; } pub fn deinit(self: ShapePlan) void { c.hb_shape_plan_destroy(self.handle); } pub fn execute(self: ShapePlan, font: Font, buffer: Buffer, features: ?[]Feature) error{ShapingFailed}!void { if (hb_shape_plan_execute( self.handle, font.handle, buffer.handle, if (features) |f| f.ptr else null, if (features) |f| @intCast(c_uint, f.len) else 0, ) < 1) return error.ShapingFailed; } pub fn getShaper(self: ShapePlan) [:0]const u8 { return std.mem.span(c.hb_shape_plan_get_shaper(self.handle)); } }; pub extern fn hb_shape_plan_create(face: ?*c.hb_face_t, props: [*c]const c.hb_segment_properties_t, user_features: [*c]const Feature, num_user_features: c_uint, shaper_list: [*c]const [*c]const u8) ?*c.hb_shape_plan_t; pub extern fn hb_shape_plan_create_cached(face: ?*c.hb_face_t, props: [*c]const c.hb_segment_properties_t, user_features: [*c]const Feature, num_user_features: c_uint, shaper_list: [*c]const [*c]const u8) ?*c.hb_shape_plan_t; pub extern fn hb_shape_plan_create2(face: ?*c.hb_face_t, props: [*c]const c.hb_segment_properties_t, user_features: [*c]const Feature, num_user_features: c_uint, coords: [*c]const c_int, num_coords: c_uint, shaper_list: [*c]const [*c]const u8) ?*c.hb_shape_plan_t; pub extern fn hb_shape_plan_create_cached2(face: ?*c.hb_face_t, props: [*c]const c.hb_segment_properties_t, user_features: [*c]const Feature, num_user_features: c_uint, coords: [*c]const c_int, num_coords: c_uint, shaper_list: [*c]const [*c]const u8) ?*c.hb_shape_plan_t; pub extern fn hb_shape_plan_execute(shape_plan: ?*c.hb_shape_plan_t, font: ?*c.hb_font_t, buffer: ?*c.hb_buffer_t, features: [*c]const Feature, num_features: c_uint) u8;
freetype/src/harfbuzz/shape_plan.zig
const std = @import("std"); const ast = @import("ast.zig"); const Location = @import("location.zig").Location; const Scope = @import("scope.zig").Scope; const Diagnostics = @import("diagnostics.zig").Diagnostics; const CompileUnit = @import("../common/compile-unit.zig").CompileUnit; const CodeWriter = @import("code-writer.zig").CodeWriter; const Instruction = @import("../common/ir.zig").Instruction; const CodeGenError = error{ OutOfMemory, AlreadyDeclared, TooManyVariables, TooManyLabels, LabelAlreadyDefined, Overflow, NotInLoop, VariableNotFound, InvalidStoreTarget, }; /// Helper structure to emit debug symbols const DebugSyms = struct { const Self = @This(); writer: *CodeWriter, symbols: std.ArrayList(CompileUnit.DebugSymbol), fn push(self: *Self, location: Location) !void { try self.symbols.append(CompileUnit.DebugSymbol{ .offset = @intCast(u32, self.writer.code.items.len), .sourceLine = location.line, .sourceColumn = @intCast(u16, location.column), }); } }; fn emitStore(debug_symbols: *DebugSyms, scope: *Scope, writer: *CodeWriter, expression: ast.Expression) CodeGenError!void { try debug_symbols.push(expression.location); std.debug.assert(expression.isAssignable()); switch (expression.type) { .array_indexer => |indexer| { try emitExpression(debug_symbols, scope, writer, indexer.index.*); // load the index on the stack try emitExpression(debug_symbols, scope, writer, indexer.value.*); // load the array on the stack try writer.emitInstructionName(.array_store); try emitStore(debug_symbols, scope, writer, indexer.value.*); // now store back the value on the stack }, .variable_expr => |variable_name| { if (std.mem.eql(u8, variable_name, "true")) { return error.InvalidStoreTarget; } else if (std.mem.eql(u8, variable_name, "false")) { return error.InvalidStoreTarget; } else if (std.mem.eql(u8, variable_name, "void")) { return error.InvalidStoreTarget; } else { const v = scope.get(variable_name) orelse return error.VariableNotFound; switch (v.type) { .global => try writer.emitInstruction(Instruction{ .store_global_idx = .{ .value = v.storage_slot }, }), .local => try writer.emitInstruction(Instruction{ .store_local = .{ .value = v.storage_slot }, }), } } }, else => unreachable, } } fn emitExpression(debug_symbols: *DebugSyms, scope: *Scope, writer: *CodeWriter, expression: ast.Expression) CodeGenError!void { try debug_symbols.push(expression.location); switch (expression.type) { .array_indexer => |indexer| { try emitExpression(debug_symbols, scope, writer, indexer.index.*); try emitExpression(debug_symbols, scope, writer, indexer.value.*); try writer.emitInstructionName(.array_load); }, .variable_expr => |variable_name| { if (std.mem.eql(u8, variable_name, "true")) { try writer.emitInstruction(Instruction{ .push_true = .{}, }); } else if (std.mem.eql(u8, variable_name, "false")) { try writer.emitInstruction(Instruction{ .push_false = .{}, }); } else if (std.mem.eql(u8, variable_name, "void")) { try writer.emitInstruction(Instruction{ .push_void = .{}, }); } else { const v = scope.get(variable_name) orelse return error.VariableNotFound; switch (v.type) { .global => try writer.emitInstruction(Instruction{ .load_global_idx = .{ .value = v.storage_slot }, }), .local => try writer.emitInstruction(Instruction{ .load_local = .{ .value = v.storage_slot }, }), } } }, .array_literal => |array| { var i: usize = array.len; while (i > 0) { i -= 1; try emitExpression(debug_symbols, scope, writer, array[i]); } try writer.emitInstruction(Instruction{ .array_pack = .{ .value = @intCast(u16, array.len) }, }); }, .function_call => |call| { var i: usize = call.arguments.len; while (i > 0) { i -= 1; try emitExpression(debug_symbols, scope, writer, call.arguments[i]); } try writer.emitInstruction(Instruction{ .call_fn = .{ .function = call.function.type.variable_expr, .argc = @intCast(u8, call.arguments.len), }, }); }, .method_call => |call| { // TODO: Write code in compiler.lola that covers this path. var i: usize = call.arguments.len; while (i > 0) { i -= 1; try emitExpression(debug_symbols, scope, writer, call.arguments[i]); } try emitExpression(debug_symbols, scope, writer, call.object.*); try writer.emitInstruction(Instruction{ .call_obj = .{ .function = call.name, .argc = @intCast(u8, call.arguments.len), }, }); }, .number_literal => |literal| { try writer.emitInstruction(Instruction{ .push_num = .{ .value = literal }, }); }, .string_literal => |literal| { try writer.emitInstruction(Instruction{ .push_str = .{ .value = literal }, }); }, .unary_operator => |expr| { try emitExpression(debug_symbols, scope, writer, expr.value.*); try writer.emitInstructionName(switch (expr.operator) { .negate => .negate, .boolean_not => .bool_not, }); }, .binary_operator => |expr| { try emitExpression(debug_symbols, scope, writer, expr.lhs.*); try emitExpression(debug_symbols, scope, writer, expr.rhs.*); try writer.emitInstructionName(switch (expr.operator) { .add => .add, .subtract => .sub, .multiply => .mul, .divide => .div, .modulus => .mod, .boolean_or => .bool_or, .boolean_and => .bool_and, .less_than => .less, .greater_than => .greater, .greater_or_equal_than => .greater_eq, .less_or_equal_than => .less_eq, .equal => .eq, .different => .neq, }); }, } } fn emitStatement(debug_symbols: *DebugSyms, scope: *Scope, writer: *CodeWriter, stmt: ast.Statement) CodeGenError!void { try debug_symbols.push(stmt.location); switch (stmt.type) { .empty => { // trivial: do nothing! }, .assignment => |ass| { try emitExpression(debug_symbols, scope, writer, ass.value); try emitStore(debug_symbols, scope, writer, ass.target); }, .discard_value => |expr| { try emitExpression(debug_symbols, scope, writer, expr); try writer.emitInstruction(Instruction{ .pop = .{}, }); }, .return_void => { try writer.emitInstruction(Instruction{ .ret = .{}, }); }, .return_expr => |expr| { try emitExpression(debug_symbols, scope, writer, expr); try writer.emitInstruction(Instruction{ .retval = .{}, }); }, .while_loop => |loop| { const cont_lbl = try writer.createAndDefineLabel(); const break_lbl = try writer.createLabel(); try writer.pushLoop(break_lbl, cont_lbl); try emitExpression(debug_symbols, scope, writer, loop.condition); try writer.emitInstructionName(.jif); try writer.emitLabel(break_lbl); try emitStatement(debug_symbols, scope, writer, loop.body.*); try writer.emitInstructionName(.jmp); try writer.emitLabel(cont_lbl); try writer.defineLabel(break_lbl); writer.popLoop(); }, .for_loop => |loop| { try scope.enter(); try emitExpression(debug_symbols, scope, writer, loop.source); try writer.emitInstructionName(.iter_make); // Loop variable is a constant! try scope.declare(loop.variable, true); const loopvar = scope.get(loop.variable) orelse unreachable; std.debug.assert(loopvar.type == .local); const loop_start = try writer.createAndDefineLabel(); const loop_end = try writer.createLabel(); try writer.pushLoop(loop_end, loop_start); try writer.emitInstructionName(.iter_next); try writer.emitInstructionName(.jif); try writer.emitLabel(loop_end); try writer.emitInstruction(Instruction{ .store_local = .{ .value = loopvar.storage_slot, }, }); try emitStatement(debug_symbols, scope, writer, loop.body.*); try writer.emitInstructionName(.jmp); try writer.emitLabel(loop_start); try writer.defineLabel(loop_end); writer.popLoop(); // // erase the iterator from the stack try writer.emitInstructionName(.pop); try scope.leave(); }, .if_statement => |conditional| { const end_if = try writer.createLabel(); try emitExpression(debug_symbols, scope, writer, conditional.condition); if (conditional.false_body) |false_body| { const false_lbl = try writer.createLabel(); try writer.emitInstructionName(.jif); try writer.emitLabel(false_lbl); try emitStatement(debug_symbols, scope, writer, conditional.true_body.*); try writer.emitInstructionName(.jmp); try writer.emitLabel(end_if); try writer.defineLabel(false_lbl); try emitStatement(debug_symbols, scope, writer, false_body.*); } else { try writer.emitInstructionName(.jif); try writer.emitLabel(end_if); try emitStatement(debug_symbols, scope, writer, conditional.true_body.*); } try writer.defineLabel(end_if); }, .declaration => |decl| { try scope.declare(decl.variable, decl.is_const); if (decl.initial_value) |value| { try emitExpression(debug_symbols, scope, writer, value); const v = scope.get(decl.variable) orelse unreachable; switch (v.type) { .local => try writer.emitInstruction(Instruction{ .store_local = .{ .value = v.storage_slot, }, }), .global => try writer.emitInstruction(Instruction{ .store_global_idx = .{ .value = v.storage_slot, }, }), } } }, .block => |blk| { try scope.enter(); for (blk) |s| { try emitStatement(debug_symbols, scope, writer, s); } try scope.leave(); }, .@"break" => { try writer.emitBreak(); }, .@"continue" => { try writer.emitContinue(); }, } } /// Generates code for a given program. The program is assumed to be sane and checked with /// code analysis already. pub fn generateIR( allocator: *std.mem.Allocator, program: ast.Program, comment: []const u8, ) !CompileUnit { var arena = std.heap.ArenaAllocator.init(allocator); errdefer arena.deinit(); var writer = CodeWriter.init(allocator); defer writer.deinit(); var functions = std.ArrayList(CompileUnit.Function).init(allocator); defer functions.deinit(); var debug_symbols = DebugSyms{ .writer = &writer, .symbols = std.ArrayList(CompileUnit.DebugSymbol).init(allocator), }; defer debug_symbols.symbols.deinit(); var global_scope = Scope.init(allocator, null, true); defer global_scope.deinit(); for (program.root_script) |stmt| { try emitStatement(&debug_symbols, &global_scope, &writer, stmt); } // each script ends with a return try writer.emitInstruction(Instruction{ .ret = .{}, }); std.debug.assert(global_scope.return_point.items.len == 0); for (program.functions) |function, i| { const entry_point = @intCast(u32, writer.code.items.len); var local_scope = Scope.init(allocator, &global_scope, false); defer local_scope.deinit(); for (function.parameters) |param| { try local_scope.declare(param, true); } try emitStatement(&debug_symbols, &local_scope, &writer, function.body); // when no explicit return is given, we implicitly return void try writer.emitInstruction(Instruction{ .ret = .{}, }); try functions.append(CompileUnit.Function{ .name = try arena.allocator.dupe(u8, function.name), .entryPoint = entry_point, .localCount = @intCast(u16, local_scope.max_locals), }); } const code = try writer.finalize(); defer allocator.free(code); std.sort.sort(CompileUnit.DebugSymbol, debug_symbols.symbols.items, {}, struct { fn lessThan(v: void, lhs: CompileUnit.DebugSymbol, rhs: CompileUnit.DebugSymbol) bool { return lhs.offset < rhs.offset; } }.lessThan); var cu = CompileUnit{ .comment = try arena.allocator.dupe(u8, comment), .globalCount = @intCast(u16, global_scope.global_variables.items.len), .temporaryCount = @intCast(u16, global_scope.max_locals), .code = try arena.allocator.dupe(u8, code), .functions = try arena.allocator.dupe(CompileUnit.Function, functions.items), .debugSymbols = try arena.allocator.dupe(CompileUnit.DebugSymbol, debug_symbols.symbols.items), .arena = undefined, }; // this prevents miscompilation of undefined evaluation order in init statement. // we need to use the arena for allocation above, so we change it. cu.arena = arena; return cu; } test "code generation" { // For lack of a better idea: // Just run the analysis against the compiler test suite var diagnostics = Diagnostics.init(std.testing.allocator); defer diagnostics.deinit(); const seq = try @import("tokenizer.zig").tokenize(std.testing.allocator, &diagnostics, "src/test/compiler.lola", @embedFile("../../test/compiler.lola")); defer std.testing.allocator.free(seq); var pgm = try @import("parser.zig").parse(std.testing.allocator, &diagnostics, seq); defer pgm.deinit(); var compile_unit = try generateIR(std.testing.allocator, pgm, "test unit"); defer compile_unit.deinit(); std.testing.expectEqual(@as(usize, 0), diagnostics.messages.items.len); std.testing.expectEqualStrings("test unit", compile_unit.comment); }
src/library/compiler/codegen.zig
const color = @import("color.zig"); const t = @import("../util/index.zig"); const TestCase = struct { x: u32, y: u32, expect: u32, }; const test_cases = []TestCase{ TestCase{ .x = 0x0, .y = 0x0, .expect = 0x0 }, TestCase{ .x = 0x0, .y = 0x1, .expect = 0x0 }, TestCase{ .x = 0x0, .y = 0x2, .expect = 0x1 }, TestCase{ .x = 0x0, .y = 0xfffd, .expect = 0x3ffe8002 }, TestCase{ .x = 0x0, .y = 0xfffe, .expect = 0x3fff0001 }, TestCase{ .x = 0x0, .y = 0xffff, .expect = 0x3fff8000 }, TestCase{ .x = 0x0, .y = 0x10000, .expect = 0x0 }, TestCase{ .x = 0x0, .y = 0x10001, .expect = 0x8000 }, TestCase{ .x = 0x0, .y = 0x10002, .expect = 0x10001 }, TestCase{ .x = 0x0, .y = 0xfffffffd, .expect = 0x2 }, TestCase{ .x = 0x0, .y = 0xfffffffe, .expect = 0x1 }, TestCase{ .x = 0x0, .y = 0xffffffff, .expect = 0x0 }, TestCase{ .x = 0x1, .y = 0x0, .expect = 0x0 }, TestCase{ .x = 0x1, .y = 0x1, .expect = 0x0 }, TestCase{ .x = 0x1, .y = 0x2, .expect = 0x0 }, TestCase{ .x = 0x1, .y = 0xfffd, .expect = 0x3ffe0004 }, TestCase{ .x = 0x1, .y = 0xfffe, .expect = 0x3ffe8002 }, TestCase{ .x = 0x1, .y = 0xffff, .expect = 0x3fff0001 }, TestCase{ .x = 0x1, .y = 0x10000, .expect = 0x3fff8000 }, TestCase{ .x = 0x1, .y = 0x10001, .expect = 0x0 }, TestCase{ .x = 0x1, .y = 0x10002, .expect = 0x8000 }, TestCase{ .x = 0x1, .y = 0xfffffffd, .expect = 0x4 }, TestCase{ .x = 0x1, .y = 0xfffffffe, .expect = 0x2 }, TestCase{ .x = 0x1, .y = 0xffffffff, .expect = 0x1 }, TestCase{ .x = 0x2, .y = 0x0, .expect = 0x1 }, TestCase{ .x = 0x2, .y = 0x1, .expect = 0x0 }, TestCase{ .x = 0x2, .y = 0x2, .expect = 0x0 }, TestCase{ .x = 0x2, .y = 0xfffd, .expect = 0x3ffd8006 }, TestCase{ .x = 0x2, .y = 0xfffe, .expect = 0x3ffe0004 }, TestCase{ .x = 0x2, .y = 0xffff, .expect = 0x3ffe8002 }, TestCase{ .x = 0x2, .y = 0x10000, .expect = 0x3fff0001 }, TestCase{ .x = 0x2, .y = 0x10001, .expect = 0x3fff8000 }, TestCase{ .x = 0x2, .y = 0x10002, .expect = 0x0 }, TestCase{ .x = 0x2, .y = 0xfffffffd, .expect = 0x6 }, TestCase{ .x = 0x2, .y = 0xfffffffe, .expect = 0x4 }, TestCase{ .x = 0x2, .y = 0xffffffff, .expect = 0x2 }, TestCase{ .x = 0xfffd, .y = 0x0, .expect = 0x3ffe8002 }, TestCase{ .x = 0xfffd, .y = 0x1, .expect = 0x3ffe0004 }, TestCase{ .x = 0xfffd, .y = 0x2, .expect = 0x3ffd8006 }, TestCase{ .x = 0xfffd, .y = 0xfffd, .expect = 0x0 }, TestCase{ .x = 0xfffd, .y = 0xfffe, .expect = 0x0 }, TestCase{ .x = 0xfffd, .y = 0xffff, .expect = 0x1 }, TestCase{ .x = 0xfffd, .y = 0x10000, .expect = 0x2 }, TestCase{ .x = 0xfffd, .y = 0x10001, .expect = 0x4 }, TestCase{ .x = 0xfffd, .y = 0x10002, .expect = 0x6 }, TestCase{ .x = 0xfffd, .y = 0xfffffffd, .expect = 0x0 }, TestCase{ .x = 0xfffd, .y = 0xfffffffe, .expect = 0x3fff8000 }, TestCase{ .x = 0xfffd, .y = 0xffffffff, .expect = 0x3fff0001 }, TestCase{ .x = 0xfffe, .y = 0x0, .expect = 0x3fff0001 }, TestCase{ .x = 0xfffe, .y = 0x1, .expect = 0x3ffe8002 }, TestCase{ .x = 0xfffe, .y = 0x2, .expect = 0x3ffe0004 }, TestCase{ .x = 0xfffe, .y = 0xfffd, .expect = 0x0 }, TestCase{ .x = 0xfffe, .y = 0xfffe, .expect = 0x0 }, TestCase{ .x = 0xfffe, .y = 0xffff, .expect = 0x0 }, TestCase{ .x = 0xfffe, .y = 0x10000, .expect = 0x1 }, TestCase{ .x = 0xfffe, .y = 0x10001, .expect = 0x2 }, TestCase{ .x = 0xfffe, .y = 0x10002, .expect = 0x4 }, TestCase{ .x = 0xfffe, .y = 0xfffffffd, .expect = 0x8000 }, TestCase{ .x = 0xfffe, .y = 0xfffffffe, .expect = 0x0 }, TestCase{ .x = 0xfffe, .y = 0xffffffff, .expect = 0x3fff8000 }, TestCase{ .x = 0xffff, .y = 0x0, .expect = 0x3fff8000 }, TestCase{ .x = 0xffff, .y = 0x1, .expect = 0x3fff0001 }, TestCase{ .x = 0xffff, .y = 0x2, .expect = 0x3ffe8002 }, TestCase{ .x = 0xffff, .y = 0xfffd, .expect = 0x1 }, TestCase{ .x = 0xffff, .y = 0xfffe, .expect = 0x0 }, TestCase{ .x = 0xffff, .y = 0xffff, .expect = 0x0 }, TestCase{ .x = 0xffff, .y = 0x10000, .expect = 0x0 }, TestCase{ .x = 0xffff, .y = 0x10001, .expect = 0x1 }, TestCase{ .x = 0xffff, .y = 0x10002, .expect = 0x2 }, TestCase{ .x = 0xffff, .y = 0xfffffffd, .expect = 0x10001 }, TestCase{ .x = 0xffff, .y = 0xfffffffe, .expect = 0x8000 }, TestCase{ .x = 0xffff, .y = 0xffffffff, .expect = 0x0 }, TestCase{ .x = 0x10000, .y = 0x0, .expect = 0x0 }, TestCase{ .x = 0x10000, .y = 0x1, .expect = 0x3fff8000 }, TestCase{ .x = 0x10000, .y = 0x2, .expect = 0x3fff0001 }, TestCase{ .x = 0x10000, .y = 0xfffd, .expect = 0x2 }, TestCase{ .x = 0x10000, .y = 0xfffe, .expect = 0x1 }, TestCase{ .x = 0x10000, .y = 0xffff, .expect = 0x0 }, TestCase{ .x = 0x10000, .y = 0x10000, .expect = 0x0 }, TestCase{ .x = 0x10000, .y = 0x10001, .expect = 0x0 }, TestCase{ .x = 0x10000, .y = 0x10002, .expect = 0x1 }, TestCase{ .x = 0x10000, .y = 0xfffffffd, .expect = 0x18002 }, TestCase{ .x = 0x10000, .y = 0xfffffffe, .expect = 0x10001 }, TestCase{ .x = 0x10000, .y = 0xffffffff, .expect = 0x8000 }, TestCase{ .x = 0x10001, .y = 0x0, .expect = 0x8000 }, TestCase{ .x = 0x10001, .y = 0x1, .expect = 0x0 }, TestCase{ .x = 0x10001, .y = 0x2, .expect = 0x3fff8000 }, TestCase{ .x = 0x10001, .y = 0xfffd, .expect = 0x4 }, TestCase{ .x = 0x10001, .y = 0xfffe, .expect = 0x2 }, TestCase{ .x = 0x10001, .y = 0xffff, .expect = 0x1 }, TestCase{ .x = 0x10001, .y = 0x10000, .expect = 0x0 }, TestCase{ .x = 0x10001, .y = 0x10001, .expect = 0x0 }, TestCase{ .x = 0x10001, .y = 0x10002, .expect = 0x0 }, TestCase{ .x = 0x10001, .y = 0xfffffffd, .expect = 0x20004 }, TestCase{ .x = 0x10001, .y = 0xfffffffe, .expect = 0x18002 }, TestCase{ .x = 0x10001, .y = 0xffffffff, .expect = 0x10001 }, TestCase{ .x = 0x10002, .y = 0x0, .expect = 0x10001 }, TestCase{ .x = 0x10002, .y = 0x1, .expect = 0x8000 }, TestCase{ .x = 0x10002, .y = 0x2, .expect = 0x0 }, TestCase{ .x = 0x10002, .y = 0xfffd, .expect = 0x6 }, TestCase{ .x = 0x10002, .y = 0xfffe, .expect = 0x4 }, TestCase{ .x = 0x10002, .y = 0xffff, .expect = 0x2 }, TestCase{ .x = 0x10002, .y = 0x10000, .expect = 0x1 }, TestCase{ .x = 0x10002, .y = 0x10001, .expect = 0x0 }, TestCase{ .x = 0x10002, .y = 0x10002, .expect = 0x0 }, TestCase{ .x = 0x10002, .y = 0xfffffffd, .expect = 0x28006 }, TestCase{ .x = 0x10002, .y = 0xfffffffe, .expect = 0x20004 }, TestCase{ .x = 0x10002, .y = 0xffffffff, .expect = 0x18002 }, TestCase{ .x = 0xfffffffd, .y = 0x0, .expect = 0x2 }, TestCase{ .x = 0xfffffffd, .y = 0x1, .expect = 0x4 }, TestCase{ .x = 0xfffffffd, .y = 0x2, .expect = 0x6 }, TestCase{ .x = 0xfffffffd, .y = 0xfffd, .expect = 0x0 }, TestCase{ .x = 0xfffffffd, .y = 0xfffe, .expect = 0x8000 }, TestCase{ .x = 0xfffffffd, .y = 0xffff, .expect = 0x10001 }, TestCase{ .x = 0xfffffffd, .y = 0x10000, .expect = 0x18002 }, TestCase{ .x = 0xfffffffd, .y = 0x10001, .expect = 0x20004 }, TestCase{ .x = 0xfffffffd, .y = 0x10002, .expect = 0x28006 }, TestCase{ .x = 0xfffffffd, .y = 0xfffffffd, .expect = 0x0 }, TestCase{ .x = 0xfffffffd, .y = 0xfffffffe, .expect = 0x0 }, TestCase{ .x = 0xfffffffd, .y = 0xffffffff, .expect = 0x1 }, TestCase{ .x = 0xfffffffe, .y = 0x0, .expect = 0x1 }, TestCase{ .x = 0xfffffffe, .y = 0x1, .expect = 0x2 }, TestCase{ .x = 0xfffffffe, .y = 0x2, .expect = 0x4 }, TestCase{ .x = 0xfffffffe, .y = 0xfffd, .expect = 0x3fff8000 }, TestCase{ .x = 0xfffffffe, .y = 0xfffe, .expect = 0x0 }, TestCase{ .x = 0xfffffffe, .y = 0xffff, .expect = 0x8000 }, TestCase{ .x = 0xfffffffe, .y = 0x10000, .expect = 0x10001 }, TestCase{ .x = 0xfffffffe, .y = 0x10001, .expect = 0x18002 }, TestCase{ .x = 0xfffffffe, .y = 0x10002, .expect = 0x20004 }, TestCase{ .x = 0xfffffffe, .y = 0xfffffffd, .expect = 0x0 }, TestCase{ .x = 0xfffffffe, .y = 0xfffffffe, .expect = 0x0 }, TestCase{ .x = 0xfffffffe, .y = 0xffffffff, .expect = 0x0 }, TestCase{ .x = 0xffffffff, .y = 0x0, .expect = 0x0 }, TestCase{ .x = 0xffffffff, .y = 0x1, .expect = 0x1 }, TestCase{ .x = 0xffffffff, .y = 0x2, .expect = 0x2 }, TestCase{ .x = 0xffffffff, .y = 0xfffd, .expect = 0x3fff0001 }, TestCase{ .x = 0xffffffff, .y = 0xfffe, .expect = 0x3fff8000 }, TestCase{ .x = 0xffffffff, .y = 0xffff, .expect = 0x0 }, TestCase{ .x = 0xffffffff, .y = 0x10000, .expect = 0x8000 }, TestCase{ .x = 0xffffffff, .y = 0x10001, .expect = 0x10001 }, TestCase{ .x = 0xffffffff, .y = 0x10002, .expect = 0x18002 }, TestCase{ .x = 0xffffffff, .y = 0xfffffffd, .expect = 0x1 }, TestCase{ .x = 0xffffffff, .y = 0xfffffffe, .expect = 0x0 }, TestCase{ .x = 0xffffffff, .y = 0xffffffff, .expect = 0x0 }, }; test "sqdiff" { for (test_cases) |v, idx| { const got = color.sqdiff(v.x, v.y); if (got != v.expect) { try t.terrorf("#{} want 0{x} got 0x{x}", idx, v.expect, got); } } }
src/color/color_test.zig
const std = @import("std"); pub const Command = struct { pub const Arg = struct { name: []const u8, takes_value: bool = true, }; name: []const u8, takes_arg: bool, }; const ArgvIterator = struct { argv: []const [:0]const u8, current_index: usize, next_index: usize, pub fn init(argv: []const [:0]const u8) ArgvIterator { return .{ .argv = argv, .current_index = 0, .next_index = 0, }; } pub fn next(self: *ArgvIterator) ?[:0]const u8 { if (self.next_index >= self.argv.len) return null; self.current_index = self.next_index; self.next_index += 1; return self.argv[self.current_index]; } pub fn rest(self: *ArgvIterator) ?[]const [:0]const u8 { if (self.next_index >= self.argv.len) return null; return self.argv[self.next_index..]; } }; pub const ArgsParser = struct { argv: []const [:0]const u8, pub fn parse(self: *const ArgsParser, comptime args: []const Command.Arg) !ArgsParserResult(args) { const ParseResult = ArgsParserResult(args); var result = ParseResult{}; var argv_iter = ArgvIterator.init(self.argv); while (argv_iter.next()) |current_arg| { var current_arg_ctx = extractKeyAndValue(current_arg); inline for (args) |arg, arg_idx| { if (std.mem.eql(u8, arg.name, current_arg_ctx.key)) { if (arg.takes_value) { if (current_arg_ctx.value == null) return error.MissingArgValue; result.args_data[arg_idx].value.some = current_arg_ctx.value; } else { result.args_data[arg_idx].value.none = true; } } } } return result; } }; pub fn parse(argv: []const [:0]const u8, comptime commands: []const Command) !CmdParserResult(commands) { const ParseResult = CmdParserResult(commands); var result = ParseResult{}; var argv_iter = ArgvIterator.init(argv); var cmd_name = argv_iter.next() orelse return error.ExpectedACommand; inline for (commands) |cmd, cmd_idx| { if (std.mem.eql(u8, cmd.name, cmd_name)) { switch (cmd.takes_arg) { true => { result.cmds_data[cmd_idx].args.value = argv_iter.rest() orelse return error.MissingCommandArgs; return result; }, false => { result.cmds_data[cmd_idx].args.none = true; return result; }, } } } return error.UnknownCommand; } pub fn CmdParserResult(comptime commands: []const Command) type { return struct { const Self = @This(); pub const CommandData = struct { name: []const u8, args: union { value: ?[]const [:0]const u8, none: bool, }, }; cmds_data: [commands.len]CommandData = blk: { var data: [commands.len]CommandData = undefined; inline for (commands) |command, idx| { data[idx] = switch (command.takes_arg) { true => .{ .name = command.name, .args = .{ .value = null }, }, false => .{ .name = command.name, .args = .{ .none = false }, }, }; } break :blk data; }, pub fn matches(self: *Self, name: []const u8) bool { for (self.cmds_data) |cmd| { if (std.mem.eql(u8, cmd.name, name)) return cmd.args.none; } return false; } pub fn argsOf(self: *Self, name: []const u8) ?ArgsParser { for (self.cmds_data) |cmd| { if (std.mem.eql(u8, cmd.name, name) and cmd.args.value != null) return ArgsParser{ .argv = cmd.args.value.? }; } return null; } }; } pub fn ArgsParserResult(comptime args: []const Command.Arg) type { return struct { const Self = @This(); pub const ArgData = struct { key: []const u8, value: union { some: ?[]const u8, none: bool, }, }; args_data: [args.len]ArgData = blk: { var data: [args.len]ArgData = undefined; inline for (args) |arg, idx| { data[idx] = switch (arg.takes_value) { true => .{ .key = arg.name, .value = .{ .some = null }, }, false => .{ .key = arg.name, .value = .{ .none = false }, }, }; } break :blk data; }, pub fn matches(self: *Self, name: []const u8) bool { for (self.args_data) |arg| { if (std.mem.eql(u8, arg.key, name)) return arg.value.none; } return false; } pub fn valueOf(self: *Self, name: []const u8) ?[]const u8 { for (self.args_data) |arg| { if (std.mem.eql(u8, arg.key, name)) return arg.value.some; } return null; } }; } const ArgContext = struct { key: []const u8, value: ?[]const u8, }; fn extractKeyAndValue(arg: [:0]const u8) ArgContext { var arg_token_it = std.mem.tokenize(u8, arg, "="); var ret = ArgContext{ .key = arg_token_it.next() orelse arg, .value = null, }; var value = arg_token_it.rest(); if (value.len > 0) ret.value = value; return ret; } test "parser" { var cmds_mock: []const [:0]const u8 = &.{ "build", "release", "src_dir=test/sources", }; var parsed_cmds = try parse(cmds_mock[0..], &[_]Command{ .{ .name = "help", .takes_arg = false }, .{ .name = "clean", .takes_arg = false }, .{ .name = "run", .takes_arg = false }, .{ .name = "build", .takes_arg = true }, }); try std.testing.expectEqual(false, parsed_cmds.matches("clean")); if (parsed_cmds.argsOf("build")) |args_parser| { var args = try args_parser.parse(&[_]Command.Arg{ .{ .name = "src_dir" }, .{ .name = "config_file" }, .{ .name = "debug", .takes_value = false }, .{ .name = "release", .takes_value = false }, }); try std.testing.expectEqualSlices(u8, "test/sources", args.valueOf("src_dir").?); try std.testing.expectEqual(true, args.matches("release")); try std.testing.expectEqual(false, args.matches("debug")); } }
src/command.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/day16.txt"); // const data = @embedFile("../data/day16-tst.txt"); pub fn main() !void { var message = tokenize(u8, data, "\r\n").next().?; var bits = try gpa.alloc(u8, message.len * 4); var buffer_index: usize = 0; for (message) |c| { _ = try std.fmt.bufPrint(bits[buffer_index .. buffer_index + 4], "{b:0>4}", .{try std.fmt.charToDigit(c, 16)}); buffer_index += 4; } var offset: usize = 0; var version: usize = 0; var value = readPacket(bits, &offset, &version); print("{} {}\n", .{ version, value }); } fn readPacket(bits: []u8, offset: *usize, version: *usize) usize { version.* += parseInt(usize, bits[offset.* .. offset.* + 3], 2) catch unreachable; var typeid = parseInt(u8, bits[offset.* + 3 .. offset.* + 6], 2) catch unreachable; switch (typeid) { 4 => _ = return readValue(bits, offset), else => return readOperator(typeid, bits, offset, version), } } fn readValue(bits: []u8, offset: *usize) usize { var start_offset = offset.* + 6; var curr_offset = start_offset; var done = false; var num = List(u8).init(gpa); defer num.deinit(); while (!done) { // For now, just skip bits if (bits[curr_offset] == '0') done = true; num.appendSlice(bits[curr_offset + 1 .. curr_offset + 5]) catch unreachable; curr_offset += 5; } var value = parseInt(u64, num.items, 2) catch 0; offset.* = curr_offset; return value; } fn readOperator(typeid: u8, bits: []u8, offset: *usize, version: *usize) usize { var start_offset = offset.* + 6; var curr_offset = start_offset; var mode: u1 = if (bits[curr_offset] == '0') 0 else 1; var length_bits: u8 = if (mode == 1) 11 else 15; curr_offset += 1; var nb_subpackets = parseInt(u16, bits[curr_offset .. curr_offset + length_bits], 2) catch unreachable; curr_offset += length_bits; offset.* = curr_offset; var operands = List(usize).init(gpa); defer operands.deinit(); if (mode == 0) { while (offset.* < curr_offset + nb_subpackets) { operands.append(readPacket(bits, offset, version)) catch unreachable; } } else { for (util.range(nb_subpackets)) |_| { operands.append(readPacket(bits, offset, version)) catch unreachable; } } switch (typeid) { 0 => return sum(operands.items), 1 => return prod(operands.items), 2 => return min(operands.items), 3 => return max(operands.items), 5 => return gt(operands.items), 6 => return lt(operands.items), 7 => return eq(operands.items), else => unreachable, } } fn sum(ops: []usize) usize { var result: usize = 0; for (ops) |op| { result += op; } return result; } fn prod(ops: []usize) usize { var result: usize = 1; for (ops) |op| { result *= op; } return result; } fn min(ops: []usize) usize { var result: usize = std.math.maxInt(usize); for (ops) |op| { result = std.math.min(op, result); } return result; } fn max(ops: []usize) usize { var result: usize = 0; for (ops) |op| { result = std.math.max(op, result); } return result; } fn gt(ops: []usize) usize { var result: usize = if (ops[0] > ops[1]) 1 else 0; return result; } fn lt(ops: []usize) usize { var result: usize = if (ops[0] < ops[1]) 1 else 0; return result; } fn eq(ops: []usize) usize { var result: usize = if (ops[0] == ops[1]) 1 else 0; return result; } // 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 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/day16.zig
const std = @import("std"); const assert = std.debug.assert; pub const Fabric = struct { pub const Pos = struct { x: usize, y: usize, pub fn init(x: usize, y: usize) Pos { return Pos{ .x = x, .y = y, }; } }; pub const Cut = struct { pmin: Pos, pmax: Pos, pub fn init(pmin: Pos, pmax: Pos) Cut { return Cut{ .pmin = pmin, .pmax = pmax, }; } }; cells: std.AutoHashMap(Pos, usize), cuts: std.AutoHashMap(usize, Cut), pmin: Pos, pmax: Pos, imin: usize, imax: usize, pub fn init() Fabric { const allocator = std.heap.direct_allocator; return Fabric{ .cells = std.AutoHashMap(Pos, usize).init(allocator), .cuts = std.AutoHashMap(usize, Cut).init(allocator), .pmin = Pos.init(std.math.maxInt(usize), std.math.maxInt(usize)), .pmax = Pos.init(0, 0), .imin = 0, .imax = 0, }; } pub fn deinit(self: *Fabric) void { self.cuts.deinit(); self.cells.deinit(); } pub fn add_cut(self: *Fabric, line: []const u8) void { // std.debug.warn("CUT [{}]\n", line); var cut: Cut = undefined; var id: usize = 0; var r: usize = 0; var itc = std.mem.separate(line, " "); while (itc.next()) |piece| { r += 1; if (r == 1) { id = std.fmt.parseInt(usize, piece[1..], 10) catch 0; if (self.imin > id) self.imin = id; if (self.imax < id) self.imax = id; continue; } if (r == 3) { var q: usize = 0; var itp = std.mem.separate(piece[0 .. piece.len - 1], ","); while (itp.next()) |str| { q += 1; const v = std.fmt.parseInt(usize, str, 10) catch 0; if (q == 1) { cut.pmin.x = v; if (self.pmin.x > cut.pmin.x) self.pmin.x = cut.pmin.x; continue; } if (q == 2) { cut.pmin.y = v; if (self.pmin.y > cut.pmin.y) self.pmin.y = cut.pmin.y; continue; } } } if (r == 4) { var q: usize = 0; var itp = std.mem.separate(piece, "x"); while (itp.next()) |str| { q += 1; const v = std.fmt.parseInt(usize, str, 10) catch 0; if (q == 1) { cut.pmax.x = cut.pmin.x + v - 1; if (self.pmax.x < cut.pmax.x) self.pmax.x = cut.pmax.x; continue; } if (q == 2) { cut.pmax.y = cut.pmin.y + v - 1; if (self.pmax.y < cut.pmax.y) self.pmax.y = cut.pmax.y; continue; } } } } _ = self.cuts.put(id, cut) catch unreachable; // std.debug.warn("CUT => {} {} {} {} {}\n", id, cut.pmin.x, cut.pmin.y, cut.pmax.x, cut.pmax.y); var x: usize = cut.pmin.x; while (x <= cut.pmax.x) : (x += 1) { var y: usize = cut.pmin.y; while (y <= cut.pmax.y) : (y += 1) { var c: usize = 0; const p = Pos.init(x, y); if (self.cells.contains(p)) { c = self.cells.get(p).?.value; } c += 1; _ = self.cells.put(p, c) catch unreachable; } } } pub fn count_overlaps(self: *Fabric) usize { // std.debug.warn("BOARD => {} {} {} {}\n", self.pmin.x, self.pmin.y, self.pmax.x, self.pmax.y); var count: usize = 0; var x: usize = self.pmin.x; while (x <= self.pmax.x) : (x += 1) { var y: usize = self.pmin.y; while (y <= self.pmax.y) : (y += 1) { const p = Pos.init(x, y); if (!self.cells.contains(p)) continue; var c = self.cells.get(p).?.value; if (c > 1) count += 1; } } return count; } pub fn find_non_overlapping(self: *Fabric) usize { const allocator = std.heap.direct_allocator; var bad = std.AutoHashMap(usize, void).init(allocator); defer bad.deinit(); var id: usize = 0; var j: usize = self.imin; while (j <= self.imax) : (j += 1) { if (!self.cuts.contains(j)) continue; if (bad.contains(j)) continue; const c0 = self.cuts.get(j).?.value; var ok: bool = true; var k: usize = 0; while (k <= self.imax) : (k += 1) { if (j == k) continue; if (!self.cuts.contains(k)) continue; const c1 = self.cuts.get(k).?.value; if ((c0.pmin.x > c1.pmax.x) or (c0.pmax.x < c1.pmin.x) or (c0.pmin.y > c1.pmax.y) or (c0.pmax.y < c1.pmin.y)) { continue; } // std.debug.warn("OVERLAP {} {}\n", j, k); ok = false; _ = bad.put(k, {}) catch unreachable; break; } if (!ok) { continue; } // std.debug.warn("FOUND {}: {} {} {} {}\n", j, c0.pmin.x, c0.pmin.y, c0.pmax.y, c0.pmax.y); id = j; } return id; } }; test "simple cuts" { const data = \\#1 @ 1,3: 4x4 \\#2 @ 3,1: 4x4 \\#3 @ 5,5: 2x2 ; var fabric = Fabric.init(); defer fabric.deinit(); var it = std.mem.separate(data, "\n"); while (it.next()) |line| { fabric.add_cut(line); } const output = fabric.count_overlaps(); assert(output == 4); } test "simple non-overlapping" { const data = \\#1 @ 1,3: 4x4 \\#2 @ 3,1: 4x4 \\#3 @ 5,5: 2x2 ; var fabric = Fabric.init(); defer fabric.deinit(); var it = std.mem.separate(data, "\n"); while (it.next()) |line| { fabric.add_cut(line); } const output = fabric.find_non_overlapping(); assert(output == 3); }
2018/p03/fabric.zig
const std = @import("std"); const with_trace = true; const assert = std.debug.assert; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } pub fn main() anyerror!void { const stdout = std.io.getStdOut().writer(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const limit = 1 * 1024 * 1024 * 1024; const text = try std.fs.cwd().readFileAlloc(allocator, "day4.txt", limit); defer allocator.free(text); var totalvalidroomid: u32 = 0; { var it = std.mem.tokenize(u8, text, "\n"); while (it.next()) |line_full| { const line = std.mem.trim(u8, line_full, " \n\r\t"); if (line.len == 0) continue; var room_id: u32 = 0; const LetterFreq = struct { freq: u8, letter: u8, fn lessthan(a: @This(), b: @This()) bool { if (a.freq > b.freq) return true; if (a.freq == b.freq and a.letter < b.letter) return true; return false; } }; const checksum = line[line.len - 6 .. line.len - 1]; var letters: [26]LetterFreq = [1]LetterFreq{.{ .letter = 0, .freq = 0 }} ** 26; for (line[0 .. line.len - 7]) |c| { if (c >= 'a' and c <= 'z') { letters[c - 'a'].letter = c; letters[c - 'a'].freq += 1; } else if (c >= '0' and c <= '9') { room_id = (10 * room_id) + (c - '0'); } else if (c == '-') { continue; } else { unreachable; } } std.sort.sort(LetterFreq, &letters, LetterFreq.lessthan); var valid = true; for (checksum) |c, i| { if (letters[i].letter != c) valid = false; } if (valid) { totalvalidroomid += room_id; var decrypt: [100]u8 = undefined; for (line[0 .. line.len - 7]) |c, i| { if (c >= 'a' and c <= 'z') { decrypt[i] = 'a' + @intCast(u8, (@intCast(u32, c - 'a') + room_id) % 26); } else if (c == '-') { decrypt[i] = ' '; } else { decrypt[i] = c; } } const north = std.mem.indexOf(u8, &decrypt, "north") != null; const prefix = if (north) "############ " else " "; try stdout.print("{}{}\n", .{ prefix, decrypt[0 .. line.len - 7] }); } //trace("letters=", .{}); //for (letters) |l| { // trace("{}, ", .{l}); //} //trace("\n checksum = {}, valid={}, room_id={}\n", .{ checksum, valid, room_id }); } } try stdout.print("num={}\n", .{totalvalidroomid}); // return error.SolutionNotFound; }
2016/day4.zig
const std = @import("std"); pub const FlagRegister = packed union { raw: u8, flags: Flags, symbols: FlagsSymbol, }; pub const FlagsSymbol = packed struct { C: bool, N: bool, V: bool, dummmy1: bool, H: bool, dummy2: bool, Z: bool, S: bool, }; pub const Flags = packed struct { carry: bool, is_sub: bool, overflow: bool, dummy1: bool, half_carry: bool, dummy2: bool, zero: bool, sign: bool, }; const AF = packed union { raw: u16, pair: packed struct { F: FlagRegister, A: u8, }, }; const BC = packed union { raw: u16, pair: packed struct { C: u8, B: u8, }, }; const DE = packed union { raw: u16, pair: packed struct { E: u8, D: u8, }, }; const HL = packed union { raw: u16, pair: packed struct { L: u8, H: u8, }, }; pub const GeneralRegisters = packed struct { af: AF, bc: BC, de: DE, hl: HL, const Self = @This(); pub fn init() Self { return Self{ .af = AF{ .raw = 0 }, .bc = BC{ .raw = 0 }, .de = DE{ .raw = 0 }, .hl = HL{ .raw = 0 }, }; } }; pub const Z80Registers = struct { main: GeneralRegisters, alternate: GeneralRegisters, ix: u16 = 0, iy: u16 = 0, sp: u16 = 0, pc: u16 = 0, interrupt_vector: u8 = 0, dram_refresh: u8 = 0, interrupt_enable1: bool = false, interrupt_enable2: bool = false, const Self = @This(); pub fn init() Self { return Self{ .main = GeneralRegisters.init(), .alternate = GeneralRegisters.init(), }; } }; pub const Z80Bus = struct { read8: Read8Fn, write8: Write8Fn, pub const Read8Fn = fn (bus: *Z80Bus, address: u16) u8; pub const Write8Fn = fn (bus: *Z80Bus, address: u16, data: u8) void; }; pub const InterruptMode = packed enum(u2) { Mode0, Mode1, Mode2, }; const Timings = @import("z80/timings.zig").Timings; const InstructionMask = struct { pub const Load_Register_Register = 0b01000000; pub const Load_Register_Immediate = 0b00000110; pub const Load_Register_IndirectHL = 0b01000110; pub const Load_IndirectHL_Register = 0b01110000; }; const RegisterMask = enum(u3) { A = 0b111, B = 0b000, C = 0b001, D = 0b010, E = 0b011, H = 0b100, L = 0b101, }; pub const Z80 = struct { registers: Z80Registers, interrupt_mode: InterruptMode = .Mode0, is_halted: bool = false, wait: bool = false, total_t_cycles: u64 = 0, total_m_cycles: u64 = 0, current_cycles: []const u8 = undefined, current_t: u8 = 0, current_m: u8 = 0, current_instruction_storage: [3]u8 = undefined, current_instruction: []const u8 = undefined, bus: *Z80Bus = undefined, temp_pointer: u16 = 0, const Self = @This(); pub fn init(bus: *Z80Bus) Self { var result = Self{ .registers = Z80Registers.init(), .bus = bus, }; result.reset(); return result; } pub fn interuptRequest(self: *Self) void { // Interrupt requested from an external device } pub fn nmiRequest(self: *Self) void { // Non Maskable Interrupt // Set PC to 0x0066 } pub fn reset(self: *Self) void { // RESET signal self.registers.pc = 0; self.registers.interrupt_vector = 0; self.registers.dram_refresh = 0; self.registers.interrupt_enable1 = false; self.registers.interrupt_enable2 = false; self.current_t = 0; self.current_m = 0; self.total_t_cycles = 0; self.total_m_cycles = 0; } // BUSREQ ? pub fn tick(self: *Self) void { if (self.current_t == 0 and self.current_m == 0) { // When halted, do NOP if (self.is_halted) { self.current_instruction_storage[0] = 0; self.current_instruction = self.current_instruction_storage[0..1]; } else { // Read instruction from memory self.current_instruction_storage[0] = self.bus.read8(self.bus, self.registers.pc); self.registers.pc += 1; self.current_instruction = self.current_instruction_storage[0..1]; } self.current_cycles = Timings[self.current_instruction[0]]; self.current_m = 0; self.current_t = self.current_cycles[self.current_m]; } const current_opcode = self.current_instruction[0]; var executed: bool = false; // NOP if (current_opcode == 0x00) { executed = true; } // LD r,r' inline for (std.meta.fields(RegisterMask)) |destination_field| { const destination_register = comptime @intToEnum(RegisterMask, destination_field.value); inline for (std.meta.fields(RegisterMask)) |source_field| { const source_register = comptime @intToEnum(RegisterMask, source_field.value); const ld_reg_reg_opcode = InstructionMask.Load_Register_Register | @as(u8, @enumToInt(source_register)) | (@as(u8, @enumToInt(destination_register)) << 3); if (current_opcode == ld_reg_reg_opcode) { const dest_fn = comptime dest_reg_fn(destination_register); const source_fn = comptime source_reg_fn(source_register); self.LD(dest_fn, source_fn); executed = true; } } } // LD r,n inline for (std.meta.fields(RegisterMask)) |destination_field| { const destination_register = comptime @intToEnum(RegisterMask, destination_field.value); const ld_reg_imm_opcode = InstructionMask.Load_Register_Immediate | (@as(u8, @enumToInt(destination_register)) << 3); if (current_opcode == ld_reg_imm_opcode) { const dest_fn = comptime dest_reg_fn(destination_register); self.LD(dest_fn, source_imm8); executed = true; } } // LD r, (HL) inline for (std.meta.fields(RegisterMask)) |destination_field| { const destination_register = comptime @intToEnum(RegisterMask, destination_field.value); const ld_reg_indirect_hl_opcode = InstructionMask.Load_Register_IndirectHL | (@as(u8, @enumToInt(destination_register)) << 3); if (current_opcode == ld_reg_indirect_hl_opcode) { const dest_fn = comptime dest_reg_fn(destination_register); self.LD(dest_fn, source_indirect_hl); executed = true; } } // LD (HL), r inline for (std.meta.fields(RegisterMask)) |source_field| { const source_register = comptime @intToEnum(RegisterMask, source_field.value); const ld_indirecthl_reg_opcode = InstructionMask.Load_IndirectHL_Register | @as(u8, @enumToInt(source_register)); if (current_opcode == ld_indirecthl_reg_opcode) { const source_fn = comptime source_reg_fn(source_register); self.LD(dest_indirect_hl, source_fn); executed = true; } } if (!executed) { std.debug.panic("Opcode 0x0{x} not implemented!\n", .{current_opcode}); } if (Timings[current_opcode].len == 0) { std.debug.panic("Opcode 0x0{x} does not have timing!\n", .{current_opcode}); } if (self.current_t != 0) { self.current_t -= 1; if (self.current_t == 0) { self.current_m += 1; self.total_m_cycles += 1; if (self.current_m < self.current_cycles.len) { self.current_t = self.current_cycles[self.current_m]; } else { self.current_m = 0; self.current_t = 0; } } } self.total_t_cycles += 1; } const DestinationFn = fn (self: *Self, data: u16) void; const SourceFn = fn (self: *Self) ?u16; inline fn LD(self: *Self, comptime destinationFn: DestinationFn, comptime sourceFn: SourceFn) void { const readData = sourceFn(self); if (readData) |data| { destinationFn(self, data); } } inline fn dest_reg_fn(comptime register: RegisterMask) DestinationFn { return switch (register) { .A => return dest_reg_A, .B => return dest_reg_B, .C => return dest_reg_C, .D => return dest_reg_D, .E => return dest_reg_E, .H => return dest_reg_H, .L => return dest_reg_L, }; } inline fn source_reg_fn(comptime register: RegisterMask) SourceFn { return switch (register) { .A => return source_reg_A, .B => return source_reg_B, .C => return source_reg_C, .D => return source_reg_D, .E => return source_reg_E, .H => return source_reg_H, .L => return source_reg_L, }; } fn dest_reg_A(self: *Self, data: u16) void { self.registers.main.af.pair.A = @truncate(u8, data); } fn source_reg_A(self: *Self) ?u16 { if (self.current_m == 0 and self.current_t == 3) { return self.registers.main.af.pair.A; } return null; } fn dest_reg_F(self: *Self, data: u16) void { self.registers.main.af.pair.F = @truncate(u8, data); } fn source_reg_F(self: *Self) ?u16 { if (self.current_m == 0 and self.current_t == 3) { return self.registers.main.af.pair.F; } return null; } fn dest_reg_B(self: *Self, data: u16) void { self.registers.main.bc.pair.B = @truncate(u8, data); } fn source_reg_B(self: *Self) ?u16 { if (self.current_m == 0 and self.current_t == 3) { return self.registers.main.bc.pair.B; } return null; } fn dest_reg_C(self: *Self, data: u16) void { self.registers.main.bc.pair.C = @truncate(u8, data); } fn source_reg_C(self: *Self) ?u16 { if (self.current_m == 0 and self.current_t == 3) { return self.registers.main.bc.pair.C; } return null; } fn dest_reg_D(self: *Self, data: u16) void { self.registers.main.de.pair.D = @truncate(u8, data); } fn source_reg_D(self: *Self) ?u16 { if (self.current_m == 0 and self.current_t == 3) { return self.registers.main.de.pair.D; } return null; } fn dest_reg_E(self: *Self, data: u16) void { self.registers.main.de.pair.E = @truncate(u8, data); } fn source_reg_E(self: *Self) ?u16 { if (self.current_m == 0 and self.current_t == 3) { return self.registers.main.de.pair.E; } return null; } fn dest_reg_H(self: *Self, data: u16) void { self.registers.main.hl.pair.H = @truncate(u8, data); } fn source_reg_H(self: *Self) ?u16 { if (self.current_m == 0 and self.current_t == 3) { return self.registers.main.hl.pair.H; } return null; } fn dest_reg_L(self: *Self, data: u16) void { self.registers.main.hl.pair.L = @truncate(u8, data); } fn source_reg_L(self: *Self) ?u16 { if (self.current_m == 0 and self.current_t == 3) { return self.registers.main.hl.pair.L; } return null; } fn source_imm8(self: *Self) ?u16 { if (self.current_m == 1 and self.current_t == 3) { const result: u16 = self.bus.read8(self.bus, self.registers.pc); self.registers.pc += 1; return result; } return null; } fn dest_indirect_hl(self: *Self, data: u16) void { if (self.current_m == 0 and self.current_t == 3) { const pointer = self.registers.main.hl.raw; self.bus.write8(self.bus, pointer, @truncate(u8, data)); } } fn source_indirect_hl(self: *Self) ?u16 { if (self.current_m == 0 and self.current_t == 2) { self.temp_pointer = self.registers.main.hl.raw; } else if (self.current_m == 1 and self.current_t == 3) { const result: u16 = self.bus.read8(self.bus, self.temp_pointer); return result; } return null; } };
lib/cpu/z80.zig
const std = @import("std"); const assert = std.debug.assert; const warn = std.debug.warn; const ModelData = @import("../ModelFiles/ModelFiles.zig").ModelData; const VertexAttributeType = ModelData.VertexAttributeType; const Buffer = @import("../WindowGraphicsInput/WindowGraphicsInput.zig").Buffer; const VertexMeta = @import("../WindowGraphicsInput/WindowGraphicsInput.zig").VertexMeta; const ShaderInstance = @import("Shader.zig").ShaderInstance; const Matrix = @import("../Mathematics/Mathematics.zig").Matrix; const wgi = @import("../WindowGraphicsInput/WindowGraphicsInput.zig"); const Texture2D = @import("Texture2D.zig").Texture2D; const Animation = @import("Animation.zig").Animation; const rtrenderengine = @import("RTRenderEngine.zig"); const getSettings = rtrenderengine.getSettings; const min = std.math.min; const ReferenceCounter = @import("../RefCount.zig").ReferenceCounter; const Asset = @import("../Assets/Assets.zig").Asset; pub const Mesh = struct { ref_count: ReferenceCounter = ReferenceCounter{}, asset: ?*Asset = null, vertex_data_buffer: Buffer, index_data_buffer: ?Buffer, modifiable: bool, model: *ModelData, pub fn initFromAsset(asset: *Asset, modifiable: bool) !Mesh { if (asset.asset_type != Asset.AssetType.Model) { return error.InvalidAssetType; } if (asset.state != Asset.AssetState.Ready) { return error.InvalidAssetState; } var m = try init(&asset.model.?, modifiable); m.asset = asset; asset.ref_count.inc(); return m; } // model object must remain valid for as long as this mesh object is valid // model.data can be freed however. That data will not be used again. // when_unused is caleld when the mesh is no longer being used by any mesh renderer pub fn init(model: *ModelData, modifiable: bool) !Mesh { VertexMeta.unbind(); var vbuf: Buffer = try Buffer.init(); errdefer vbuf.free(); try vbuf.upload(Buffer.BufferType.VertexData, std.mem.sliceAsBytes(model.vertex_data.?), modifiable); var ibuf: ?Buffer = null; if (model.*.index_count > 0) { ibuf = try Buffer.init(); errdefer ibuf.?.free(); if (model.indices_u16 != null) { try ibuf.?.upload(Buffer.BufferType.IndexData, std.mem.sliceAsBytes(model.indices_u16.?), modifiable); } else { try ibuf.?.upload(Buffer.BufferType.IndexData, std.mem.sliceAsBytes(model.indices_u32.?), modifiable); } } return Mesh{ .vertex_data_buffer = vbuf, .index_data_buffer = ibuf, .modifiable = modifiable, .model = model, }; } pub fn uploadVertexData(self: *Mesh, offset: u32, data: []const u8) !void { if (!self.modifiable) { return error.ReadOnlyMesh; } try self.vertex_data_buffer.uploadRegion(Buffer.BufferType.VertexData, data, offset, true); } pub fn uploadIndexData(self: *Mesh, offset: u32, data: []const u8) !void { if (!self.modifiable) { return error.ReadOnlyMesh; } if (self.index_data_buffer == null) { return error.NoIndices; } try self.index_data_buffer.?.uploadRegion(Buffer.BufferType.IndexData, data, offset, true); } fn free_(self: *Mesh) void { self.ref_count.deinit(); self.vertex_data_buffer.free(); if (self.index_data_buffer != null) { self.index_data_buffer.?.free(); } } // Does not delete the model pub fn free(self: *Mesh) void { self.free_(); self.asset = null; } pub fn freeIfUnused(self: *Mesh) void { if (self.asset != null and self.ref_count.n == 0) { self.ref_count.deinit(); self.free_(); self.asset.?.ref_count.dec(); if (self.asset.?.ref_count.n == 0) { self.asset.?.free(false); } self.asset = null; } } };
src/RTRenderEngine/Mesh.zig
pub usingnamespace @import("std").os.windows; // General pub const KEY_EVENT = 0x0001; pub const MOUSE_EVENT = 0x0002; pub const WINDOW_BUFFER_SIZE_EVENT = 0x0004; pub const MENU_EVENT = 0x0008; pub const FOCUS_EVENT = 0x0010; pub extern fn GetConsoleOutputCP() c_uint; pub extern fn SetConsoleOutputCP(wCodePageID: c_uint) BOOL; pub extern fn SetConsoleMode(hConsoleHandle: HANDLE, dwMode: DWORD) BOOL; pub extern fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) BOOL; pub extern fn WriteConsoleW( hConsoleOutput: HANDLE, lpBuffer: [*]const u16, nNumberOfCharsToWrite: DWORD, lpNumberOfCharsWritten: ?*DWORD, lpReserved: ?*c_void ) BOOL; // Events const union_unnamed_248 = extern union { UnicodeChar: WCHAR, AsciiChar: CHAR, }; pub const KEY_EVENT_RECORD = extern struct { bKeyDown: BOOL, wRepeatCount: WORD, wVirtualKeyCode: WORD, wVirtualScanCode: WORD, uChar: union_unnamed_248, dwControlKeyState: DWORD, }; pub const PKEY_EVENT_RECORD = *KEY_EVENT_RECORD; pub const MOUSE_EVENT_RECORD = extern struct { dwMousePosition: COORD, dwButtonState: DWORD, dwControlKeyState: DWORD, dwEventFlags: DWORD, }; pub const PMOUSE_EVENT_RECORD = *MOUSE_EVENT_RECORD; pub const WINDOW_BUFFER_SIZE_RECORD = extern struct { dwSize: COORD, }; pub const PWINDOW_BUFFER_SIZE_RECORD = *WINDOW_BUFFER_SIZE_RECORD; pub const MENU_EVENT_RECORD = extern struct { dwCommandId: UINT, }; pub const PMENU_EVENT_RECORD = *MENU_EVENT_RECORD; pub const FOCUS_EVENT_RECORD = extern struct { bSetFocus: BOOL, }; pub const PFOCUS_EVENT_RECORD = *FOCUS_EVENT_RECORD; const union_unnamed_249 = extern union { KeyEvent: KEY_EVENT_RECORD, MouseEvent: MOUSE_EVENT_RECORD, WindowBufferSizeEvent: WINDOW_BUFFER_SIZE_RECORD, MenuEvent: MENU_EVENT_RECORD, FocusEvent: FOCUS_EVENT_RECORD, }; pub const INPUT_RECORD = extern struct { EventType: WORD, Event: union_unnamed_249, }; pub const PINPUT_RECORD = *INPUT_RECORD; pub extern "kernel32" fn ReadConsoleInputW( hConsoleInput: HANDLE, lpBuffer: PINPUT_RECORD, nLength: DWORD, lpNumberOfEventsRead: LPDWORD ) BOOL;
src/c/c.zig
const std = @import("std"); const spu = @import("spu-mk2"); const common = @import("shared.zig"); var emulator: spu.SpuMk2(common.WasmDemoMachine) = undefined; const bootrom = @embedFile("../../zig-out/firmware/wasm.bin"); pub fn dumpState(emu: *spu.SpuMk2) !void { _ = emu; } pub fn dumpTrace(emu: *spu.SpuMk2, ip: u16, instruction: spu.Instruction, input0: u16, input1: u16, output: u16) !void { _ = emu; _ = ip; _ = instruction; _ = input0; _ = input1; _ = output; } export fn init() void { // serialWrite("a", 1); emulator = spu.SpuMk2(common.WasmDemoMachine).init(.{}); // serialWrite("b", 1); std.mem.copy(u8, &emulator.memory.memory, bootrom[0..std.math.min(emulator.memory.memory.len, bootrom.len)]); // serialWrite("c", 1); } export fn run(steps: u32) u32 { emulator.runBatch(steps) catch |err| { // halting is similar to debugging if (err != error.CpuHalted) emulator.reset(); switch (err) { error.BadInstruction => return 1, error.UnalignedAccess => return 2, error.BusError => return 3, error.DebugBreak => return 4, error.CpuHalted => return 5, } }; return 0; } export fn resetCpu() void { emulator.triggerInterrupt(.reset); } export fn invokeNmi() void { emulator.triggerInterrupt(.nmi); } export fn getMemoryPtr() [*]u8 { return &emulator.memory.memory; } extern fn invokeJsPanic() noreturn; extern fn serialRead(data: [*]u8, len: u32) u32; extern fn serialWrite(data: [*]const u8, len: u32) void; pub const SerialEmulator = struct { pub fn read() !u16 { var value: [1]u8 = undefined; if (serialRead(&value, 1) == 1) { return @as(u16, value[0]); } else { return 0xFFFF; } } pub fn write(value: u16) !void { serialWrite(&[_]u8{@truncate(u8, value)}, 1); } }; pub fn panic(message: []const u8, stackTrace: ?*std.builtin.StackTrace) noreturn { serialWrite(message.ptr, message.len); _ = stackTrace; invokeJsPanic(); } pub fn log(level: anytype, comptime fmt: []const u8, args: anytype) void { _ = level; _ = fmt; _ = args; // }
tools/emulator/web-main.zig
usingnamespace @import("root").preamble; const log = lib.output.log.scoped(.{ .prefix = "APIC", .filter = .info, }).write; const regs = @import("regs.zig"); const builtin = @import("builtin"); const interrupts = @import("interrupts.zig"); // LAPIC fn lapic_ptr() ?*volatile [0x100]u32 { if (os.platform.thread.get_current_cpu().platform_data.lapic) |ptr| { return ptr.get_writeback(); } return null; } fn x2apic_msr(comptime register: u10) comptime_int { return @as(u32, 0x800) + @truncate(u8, register >> 2); } fn write_x2apic(comptime T: type, comptime register: u10, value: T) void { regs.MSR(T, x2apic_msr(register)).write(value); } fn read_x2apic(comptime T: type, comptime register: u10) T { return regs.MSR(T, x2apic_msr(register)).read(); } pub fn enable() void { const spur_reg = @as(u32, 0x100) | interrupts.spurious_vector; const cpu = os.platform.thread.get_current_cpu(); const raw = IA32_APIC_BASE.read(); if (raw & 0x400 != 0) { // X2APIC cpu.platform_data.lapic = null; write_x2apic(u32, SPURIOUS, spur_reg); cpu.platform_data.lapic_id = read_x2apic(u32, LAPIC_ID); return; } const phy = raw & 0xFFFFF000; // ignore flags const lapic = os.platform.phys_ptr(*volatile [0x100]u32).from_int(phy); cpu.platform_data.lapic = lapic; const lapic_wb = lapic.get_writeback(); lapic_wb[SPURIOUS] = spur_reg; cpu.platform_data.lapic_id = lapic_wb[LAPIC_ID]; } pub fn eoi() void { if (lapic_ptr()) |lapic| { lapic[EOI] = 0; } else { write_x2apic(u32, EOI, 0); } } pub fn timer(ticks: u32, div: u32, vec: u32) void { if (lapic_ptr()) |lapic| { lapic[LVT_TIMER] = vec | TIMER_MODE_PERIODIC; lapic[TIMER_DIV] = div; lapic[TIMER_INITCNT] = ticks; } else { @panic("X2APIC timer NYI"); } } pub fn ipi(apic_id: u32, vector: u8) void { if (lapic_ptr()) |lapic| { lapic[ICR_HIGH] = apic_id; lapic[ICR_LOW] = @as(u32, vector); } else { write_x2apic(u64, ICR_LOW, (@as(u64, apic_id) << 32) | (@as(u64, vector))); } } // ACPI information fn handle_processor(apic_id: u32) void {} const Override = struct { gsi: u32, flags: u16, ioapic_id: u8, }; var source_overrides = [1]?Override{null} ** 0x100; /// Routes the legacy irq to given lapic vector /// Returns the GSI in case you want to disable it later pub fn route_irq(lapic_id: u32, irq: u8, vector: u8) u32 { const gsi_mapping = map_irq_to_gsi(irq); route_gsi_ioapic(gsi_mapping.ioapic_id, lapic_id, vector, gsi_mapping.gsi, gsi_mapping.flags); return gsi_mapping.gsi; } /// Route a GSI to the given lapic vector pub fn route_gsi(lapic_id: u32, vector: u8, gsi: u32, flags: u16) void { route_gsi_ioapic(gsi_to_ioapic(gsi), lapic_id, vector, gsi, flags); } fn route_gsi_ioapic(ioapic_id: u8, lapic_id: u32, vector: u8, gsi: u32, flags: u16) void { const value = 0 | (@as(u64, vector) << 0) | (@as(u64, flags & 0b1010) << 12) | (@as(u64, lapic_id) << 56); const ioapic = ioapics[ioapic_id].?; const gsi_offset = (gsi - ioapic.gsi_base) * 2 + 0x10; ioapic.write(gsi_offset + 0, @truncate(u32, value)); ioapic.write(gsi_offset + 1, @truncate(u32, value >> 32)); } fn map_irq_to_gsi(irq: u8) Override { return source_overrides[irq] orelse Override{ .gsi = @as(u32, irq), .flags = 0, .ioapic_id = gsi_to_ioapic(irq), }; } const IOAPIC = struct { phys: usize, gsi_base: u32, fn reg(self: *const @This(), offset: usize) *volatile u32 { return os.platform.phys_ptr(*volatile u32).from_int(self.phys + offset).get_uncached(); } fn write(self: *const @This(), offset: u32, value: u32) void { self.reg(0x00).* = offset; self.reg(0x10).* = value; } fn read(self: *const @This(), offset: u32) u32 { self.reg(0x00).* = offset; return self.reg(0x10).*; } fn gsi_count(self: *const @This()) u32 { return (self.read(1) >> 16) & 0xFF; } }; fn gsi_to_ioapic(gsi: u32) u8 { for (ioapics) |ioa_o, idx| { if (ioa_o) |ioa| { const gsi_count = ioa.gsi_count(); if (ioa.gsi_base <= gsi and gsi < ioa.gsi_base + gsi_count) return @intCast(u8, idx); } } log(null, "GSI: {d}", .{gsi}); @panic("Can't find ioapic for gsi!"); } var ioapics = [1]?IOAPIC{null} ** config.kernel.x86_64.max_ioapics; pub fn handle_madt(madt: []u8) void { log(.debug, "Got MADT (size={X})", .{madt.len}); var offset: u64 = 0x2C; while (offset + 2 <= madt.len) { const kind = madt[offset + 0]; const size = madt[offset + 1]; const data = madt[offset .. offset + size]; if (offset + size >= madt.len) break; switch (kind) { 0x00 => { const apic_id = data[3]; const flags = std.mem.readIntNative(u32, data[4..8]); if (flags & 0x3 != 0) handle_processor(@as(u32, apic_id)); }, 0x01 => { const ioapic_id = data[2]; ioapics[ioapic_id] = .{ .phys = std.mem.readIntNative(u32, data[4..8]), .gsi_base = std.mem.readIntNative(u32, data[8..12]), }; }, 0x02 => { // We can probably filter away overrides where irq == gsi and flags == 0 // Until we have a reason to do so, let's not. const irq = data[3]; source_overrides[irq] = .{ .gsi = std.mem.readIntNative(u32, data[4..8]), .flags = std.mem.readIntNative(u16, data[8..10]), .ioapic_id = data[2], }; }, 0x03 => { std.debug.assert(size >= 8); log(.warn, "TODO: NMI source", .{}); }, 0x04 => { std.debug.assert(size >= 6); log(.warn, "TODO: LAPIC Non-maskable interrupt", .{}); }, 0x05 => { std.debug.assert(size >= 12); log(.warn, "TODO: LAPIC addr override", .{}); }, 0x06 => { std.debug.assert(size >= 16); log(.warn, "TODO: I/O SAPIC", .{}); }, 0x07 => { std.debug.assert(size >= 17); log(.warn, "TODO: Local SAPIC", .{}); }, 0x08 => { std.debug.assert(size >= 16); log(.warn, "TODO: Platform interrupt sources", .{}); }, 0x09 => { const flags = std.mem.readIntNative(u32, data[8..12]); const apic_id = std.mem.readIntNative(u32, data[12..16]); if (flags & 0x3 != 0) handle_processor(apic_id); }, 0x0A => { std.debug.assert(size >= 12); log(.warn, "TODO: LX2APIC NMI", .{}); }, else => { log(.err, "Unknown MADT entry: 0x{X}", .{kind}); }, } offset += size; } } const IA32_APIC_BASE = @import("regs.zig").MSR(u64, 0x0000001B); const LAPIC_ID = 0x20 / 4; const ICR_LOW = 0x300 / 4; const ICR_HIGH = 0x310 / 4; const TIMER_MODE_PERIODIC = 1 << 17; const TIMER_DIV = 0x3E0 / 4; const TIMER_INITCNT = 0x380 / 4; const SPURIOUS = 0xF0 / 4; const EOI = 0xB0 / 4;
subprojects/flork/src/platform/x86_64/apic.zig
const std = @import("std"); //const filters = @import("filters"); const build_options = @import("build_options"); const debugDisp = build_options.debugDisp; const debugLoop = build_options.debugLoop; const debugStageTypes = build_options.debugStageTypes; const debugCmd = build_options.debugCmd; const debugStart = build_options.debugStart; // will later exploit usingnamespace to allow users to add stages to library of stages const State = enum(u4) { peekTo, readTo, output, call, start, run, done, sever, eos, anyinput, commit, dummy, }; const stageError = error{ ok, finished, active, endOfStream, noInStream, noOutStream, outOfBounds, pipeStall, }; const Message = enum(u2) { ok, data, sever, severed, }; pub fn ReturnOf(comptime func: anytype) type { return switch (@typeInfo(@TypeOf(func))) { .Fn, .BoundFn => |fn_info| fn_info.return_type.?, else => unreachable, }; } // we use TypeUnion to store the values passed between stages. We define the Stage by passing a tuple of types with // the types valid to use in the pipe's TypeUnion(s). We use Filters to create non generic versions of the filter functions // with specific types, validating that the types are valid for the Stage. pub fn TypeUnion(comptime list: anytype) type { // list is atuple of the types in this typeUnion const info = @typeInfo(@TypeOf(list)); // validate list is a tuple if (info != .Struct) @compileError("Expected struct type"); if (!info.Struct.is_tuple) @compileError("Struct type must be a tuple type"); // define the typedUnion's enum (ESet) based on std.meta.FieldEnum comptime var s = 0; comptime var a = 0; comptime var enumFields: [list.len]std.builtin.TypeInfo.EnumField = undefined; comptime var decls = [_]std.builtin.TypeInfo.Declaration{}; inline for (list) |T, i| { std.debug.assert(@TypeOf(T) == type); // validate list entry is a type enumFields[i].name = @typeName(T); enumFields[i].value = i; if (@sizeOf(T) > s) s = @sizeOf(T); // track size and alignment needed to store the value if (@alignOf(T) > a) a = @alignOf(T); } const TSet = @Type(.{ .Enum = .{ // create the enum type .layout = .Auto, .tag_type = std.math.IntFittingRange(0, list.len - 1), .fields = &enumFields, .decls = &decls, .is_exhaustive = true, }, }); return struct { pub const TU = @This(); // create buffer for the value with correct alignment and size for the included types value: [s]u8 align(a) = [_]u8{undefined} ** s, type: TSet = undefined, // convert an ESet literal to the corresponding type (if t is runtime we get an error) pub fn TypeOf(comptime e: TSet) type { return list[@enumToInt(e)]; } pub fn getType(self: *TU) @TypeOf(._) { return self.type; } pub fn put(self: *TU, v: anytype) void { if (@TypeOf(v) == TU) { std.mem.copy(u8, &self.value, &v.value); self.type = v.type; return; } inline for (list) |T, i| { if (T == @TypeOf(v)) { @ptrCast(*T, &self.value).* = v; self.type = @intToEnum(TSet, i); return; } } std.debug.print("put: type {} not in TypeUnion {}\n", .{ @TypeOf(v), TU }); unreachable; } // return the value of typeUnion - validate that stored and requested types match. pub fn get(self: *TU, comptime T: type) T { if (T == TU) return self.*; inline for (list) |U, i| { if (i == @enumToInt(self.type)) { if (T == U) return @ptrCast(*T, &self.value).*; std.debug.print("get: Union {} expected type {} found {}\n", .{ list, U, T }); unreachable; } } std.debug.print("get: Union {} instance not initialized\n", .{list}); unreachable; } // test if type is in typeUnion pub fn inUnion(comptime T: type) bool { inline for (list) |U| { if (T == U) return true; } return false; } // check if the typeUnion contains a value of type pub fn typeIs(self: TU, comptime T: type) bool { inline for (list) |U, i| { if (i == @enumToInt(self.type)) { if (T == U) return true; } } return false; } // create a typeUnion via allocator and set its value //fn init(allocator: *std.mem.Allocator) TU { // var self: *TU = allocator.create(TU) catch unreachable; // return self.*; //} pub fn list(alloc: *std.mem.Allocator, T: anytype, v: anytype) []TU { const inf = @typeInfo(@TypeOf(v)); // validate v is a tuple if (inf != .Struct) @compileError("Expected struct type"); if (!inf.Struct.is_tuple) @compileError("Struct type must be a tuple type"); const tuArray = [v.len]TU; var self: *tuArray = alloc.create(tuArray) catch unreachable; for (self) | *tu, i | { comptime var j = 0; inline while (j<v.len) : (j+=1) { if (i==j) tu.put(@as(T[j],v[j])); } } return self; } }; } // This is used to define the connections between stages (and pipes) pub fn ConnType(comptime S: type, comptime TU: type) type { return struct { pub const Conn = @This(); data: TU = undefined, in: Message = undefined, src: *S = undefined, // used by output from: usize = 0, sout: usize = 0, dst: *S = undefined, // used by input to: usize = 0, sin: usize = 0, //next: ?*Conn = null, // unused but removing it causes stalls (WHY?) fn set(self: *Conn, p: []S, f: usize, o: usize, t: usize, s: usize) void { self.from = f; // only used when building connectons (to be removed) self.src = &p[f]; // stage output self.sout = o; // stream number self.to = t; // only used when building connectons (to be removed) self.dst = &p[t]; // stage input self.sin = s; // stream number } }; } // Used to create a type for stages that can be used with any of the types in the list, which needs to be a tuple of types. // A stage is defined as a filter, its args and connections pub fn _Stage(comptime Make:*Z, list: anytype) type { return struct { pub const StageType = @This(); pub const TU = TypeUnion(list); pub const Conn = ConnType(StageType, TU); outC: ?*Conn = null, // output conn inC: ?*Conn = null, // input conn fwdC: ?*Conn = null, bwdC: ?*Conn = null, state: State = undefined, commit: isize = -90909090, i: usize = undefined, frame: anyframe = undefined, err: stageError = error.ok, n: []Conn = undefined, // connections used by this stage (might be removable) name: ?[]const u8 = null, // name of the stage, may dissapear as we get it via questionable hack end: bool = false, allocator: *std.mem.Allocator = undefined, // allocator in use for this pipe pipeAddr:usize = 0, // Use Make.getPT() and PTIdx to get a pointer to the parent pipe PTIdx:usize = undefined, pub fn call(self: *StageType, ctx:anytype, tup:anytype) !void { const PT = Make.getPT(); inline for (PT) | T, i | { if (i == self.PTIdx) { const parent = @intToPtr(*T,self.pipeAddr); // parent pipe so we can adjust nodes _ = parent; const CallPipe = Make.Mint(tup); //std.debug.print("call {any}\n",.{CallPipe.pipe}); var callpipe = CallPipe.init(self.allocator); // create callpipe instance //var save = Conn{}; if (self.outC == null and callpipe.outIdx < 255) return error.noOutStream; if (self.inC == null and callpipe.inIdx < 255) return error.noInStream; //if (callpipe.outIdx < 255) { // save.src = self.outC.?.src; // save.from = self.outC.?.from; // callpipe.p[callpipe.outIdx].outC = self.outC; // self.outC.?.src = &callpipe.p[callpipe.outIdx]; // self.outC.?.from = callpipe.outIdx; //} //if (callpipe.inIdx < 255) { // save.dst = self.inC.?.dst; // save.to = self.inC.?.to; // callpipe.p[callpipe.inIdx].inC = self.inC; // self.inC.?.dst = &callpipe.p[callpipe.inIdx]; // self.inC.?.to = callpipe.inIdx; //} try callpipe.run(ctx); //if (callpipe.outIdx < 255) { // restore output // self.outC.?.src = save.src; // self.outC.?.from = save.from; // } //if (callpipe.inIdx < 255) { //restore input // self.inC.?.dst = save.dst; // self.inC.?.to = save.to; //} _ = parent; } } //suspend { // self.state = .call; // tell dispatcher to run the pipe // self.frame = @frame(); //} self.state = .done; } pub fn inStream(self: *StageType) !usize { if (self.inC) |c| return c.sin; return error.noInStream; } pub fn outStream(self: *StageType) !usize { if (self.outC) |c| return c.sout; return error.noOutStream; } pub fn typeIs(self: *StageType, comptime T: type) !bool { if (debugCmd) std.log.info("peekTo {*} inC {*}\n", .{ self, self.inC }); if (self.inC) |c| { if (debugCmd) std.log.info("peekTo {*} in {} {}\n", .{ c, c.in, c.data }); while (c.in == .ok) { suspend { //self.fwdC = c; self.state = .peekTo; self.frame = @frame(); } } } self.state = .done; if (self.inC) |c| { if (debugCmd) std.log.info("peekTo {}_{s} {} in {} {}\n", .{ self.i, self.name, c.sout, c.in, c.data }); if (c.in == .data) { return c.data.typeIs(T); } else { self.err = error.endOfStream; return self.err; } } self.err = error.noInStream; return self.err; } pub fn peekTo(self: *StageType, comptime T: type) !T { if (debugCmd) std.log.info("peekTo {*} inC {*}\n", .{ self, self.inC }); if (self.inC) |c| { if (debugCmd) std.log.info("peekTo {*} in {} {}\n", .{ c, c.in, c.data }); while (c.in == .ok) { suspend { self.state = .peekTo; self.frame = @frame(); } } } self.state = .done; if (self.inC) |c| { if (debugCmd) std.log.info("peekTo {}_{s} {} in {} {}\n", .{ self.i, self.name, c.sout, c.in, c.data }); if (c.in == .data) { return c.data.get(T); } else { self.err = error.endOfStream; return self.err; } } self.err = error.noInStream; return self.err; } pub fn readTo(self: *StageType, comptime T: type) !T { if (self.inC) |c| { while (c.in == .ok) { suspend { self.state = .readTo; self.frame = @frame(); } } } self.state = .done; if (self.inC) |c| { if (c.in == .data) { self.bwdC = c; c.in = .ok; return c.data.get(T); } else { self.err = error.endOfStream; return self.err; } } self.err = error.noInStream; return self.err; } pub fn output(self: *StageType, v: anytype) !void { if (self.outC) |c| { while (c.in == .data) { suspend { self.state = .output; self.frame = @frame(); if (debugCmd) std.log.info("output {}_{s} {} in {} {}\n", .{ self.i, self.name, c.sout, c.in, v }); } } } self.state = .done; if (self.outC) |c| { if (debugCmd) std.log.info("output {*} {} in {} {}\n", .{ c, c.sout, c.in, v }); if (c.in == .ok) { self.fwdC = c; c.in = .data; c.data.put(v); return; } else { self.err = error.endOfStream; return self.err; } } self.err = error.noOutStream; return self.err; } pub fn selectOutput(self: *StageType, o: usize) !void { return self.setoutC(o); } pub fn severOutput(self: *StageType) !void { if (self.outC) |c| { self.fwdC = c; self.outC = null; self.state = .sever; } else { self.err = error.noOutStream; return self.err; } } pub fn severInput(self: *StageType) !void { if (self.inC) |c| { self.bwdC = c; self.inC = null; self.state = .sever; } else { self.err = error.noInStream; return self.err; } } pub fn selectInput(self: *StageType, i: usize) !void { return self.setinC(i); } pub fn selectAnyInput(self: *StageType) !usize { // std.log.info("anyin {*} inC {*}\n",.{self, self.inC}); if (countInstreams(self) > 0) { // std.log.info("anyin {*}", .{self.inC}); if (self.inC) |c| { if (debugCmd) std.log.info("anyin pre {}_{s} in {} {}\n", .{ self.i, self.name, c.in, c.data }); if (c.in == .ok) { suspend { self.state = .anyinput; self.frame = @frame(); } } } self.state = .done; if (self.inC) |c| { if (c.in == .data) { return c.sin; } } } self.err = error.noInStream; return self.err; } pub fn endStage(self: *StageType) void { if (debugCmd) std.debug.print("end: {s}\n",.{self.name}); for (self.n) |*c| { if (c.dst == self) { if (c.in == .data) { c.in = .sever; } if (self.inC == c) { c.src.fwdC = c; self.inC = null; } } if (c.src == self) { if (c.in == .ok) { c.in = .sever; } if (self.outC == c) { c.dst.bwdC = c; self.outC = null; } } self.state = .eos; } const PT = Make.getPT(); inline for (PT) | T, i | { if (i == self.PTIdx) { const parent = @intToPtr(*T,self.pipeAddr); // parent pipe so we can track pipe.rc if (@errorToInt(self.err) > @errorToInt(parent.rc)) parent.rc = self.err; } } self.commit = 90909090; return; } pub fn ok(self: *StageType) !void { return if (self.err == error.ok or self.err == error.endOfStream or self.err == error.noInStream) .{} else self.err; } fn setinC(self: *StageType, i: usize) !void { for (self.n) |*c| { if (c.dst == self and c.sin == i) { self.inC = c; return; } } self.inC = null; self.err = error.noInStream; return self.err; } pub fn countInstreams(self: *StageType) usize { var count: usize = 0; for (self.n) |c| { if (c.dst == self and (c.in == .data or c.src.outC != null)) count += 1; } return count; } fn setoutC(self: *StageType, o: usize) !void { for (self.n) |*c| { if (c.src == self and c.sout == o) { self.outC = c; return; } } self.outC = null; self.err = error.noOutStream; return self.err; } }; } pub fn _run(comptime Make: *Z, comptime context:type, pp:anytype) !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; const thisPipe = Make.Mint(pp).init(allocator); return thisPipe.run(context); } // In filters and the Stage struct we sometimes need to find the PipeType and instance that created the stage. // Since PipeTypes and instances are created after Stages/Filters Type we have a small problem. This comptime struct // front ends PipeType creations so we get extract them in Stages. When a Stage is created we use @prtToInto to save // the instance pointer so we later can use getPT and an inline for to find the PipeType and @intToPtr to get the // pipe's instance. pub const Z = struct { PT: []const type = &[_]type{}, pub fn Mint(comptime self:*Z, pp:anytype) type { // @compileLog("recursive"); const Pipe = _Mint(self,pp,self.PT.len); self.PT = &[_]type{Pipe} ++ self.PT; return Pipe; } pub fn Stage(comptime self:*Z, list:anytype) type { return _Stage(self, list); } pub fn run(comptime self:*Z, comptime context:type, pp:anytype) !void { return try _run(self, context, pp); } pub fn getPT(comptime self:*Z) []const type { return self.PT; } }; // Once we have defined the Stage & Filters types, we need to create a pipeType using Mint. The PipeType // is used to set the args for a pipe using struct(s) as context blocks. Any required args are set, // the run funcion should be called to execute the pipe. // Mint creates a tuple, arg_set, of stage arguement types, sets up some label mapping, and returns a PipeType. // init creates a PipeType using an allocator, then connects the stages using connectors and the label mapping. // run uses arg_set to create a tuple of values for the pipe stages arguements, fills in the values, and runs the pipe fn _Mint(comptime Make:*Z, pp:anytype, pN:usize) type { _ = Make; comptime var lmap = [_]?u8{null} ** pp.len; // mapping for stg to label comptime var nodesLen = pp.len; // number of nodes for the pipe comptime var labels: std.meta.Tuple( // list of enum literals type for labels list: { comptime var l: []const type = &[_]type{}; inline for (pp) |stg| { if (@typeInfo(@TypeOf(stg[0])) == .EnumLiteral and @tagName(stg[0])[0] != '_' and stg.len > 1 and @typeInfo(@TypeOf(stg[1])) != .EnumLiteral) { l = l ++ &[_]type{@TypeOf(stg[0])}; } } break :list l; // return tuple of enum literal types, to create labels tuple }) = undefined; { // context block - we want to use k later in runtime comptime var k = 0; // save enum literals in the labels tuple inline for (pp) |stg, i| { if (@typeInfo(@TypeOf(stg[0])) == .EnumLiteral and @tagName(stg[0])[0] != '_' and stg.len > 1 and @typeInfo(@TypeOf(stg[1])) != .EnumLiteral) { labels[k] = stg[0]; k += 1; } // nodesLen may need adjustment with addpipe/callpipe inline for (stg) |elem, j| { if (@typeInfo(@TypeOf(elem)) == .EnumLiteral) { switch (elem) { ._ => { if (j > 0) nodesLen -= 1 else unreachable; }, // end must follow a label or filter ._i => { if (j == 0 and i < pp.len-1) nodesLen -= 1 else unreachable; }, // bad in connector ._o => { if (j == 0 and i > 0) nodesLen -= 1 else unreachable; }, // bad out connector else => {}, // extend when .add method added } } } } // map stage to label inline for (pp) |stg, i| { if (@typeInfo(@TypeOf(stg[0])) == .EnumLiteral and @tagName(stg[0])[0] != '_' ) { // ignore ._{x} for (labels) |lbl, j| { if (stg[0] == lbl) lmap[i] = j; // save the mapping } } } } // inline for (pp) |_, i| { // if (lmap[i]) |l| { // @compileLog(i); // @compileLog(labels[l]); // } // } comptime var ST:?type = null; // get the StageType from one of the Filter function calls comptime var arg_set: []const type = &[_]type{}; // build tuple of types for stage Fn and Args inline for (pp) |stg, i| { // fill in the args types comptime var flag: bool = true; inline for (stg) |elem| { const E = @typeInfo(@TypeOf(elem)); switch (E) { .Fn, .BoundFn => { if (debugStart) std.debug.print("fn {} {}\n", .{ i, elem }); arg_set = arg_set ++ &[_]type{std.meta.Tuple(&[_]type{ @TypeOf(elem), std.meta.ArgsTuple(@TypeOf(elem)) })}; flag = false; if (ST == null) { // get StageType from a Filter fn's first arg type which must be *StageType std.debug.assert(!E.Fn.is_generic); ST = @typeInfo(E.Fn.args[0].arg_type.?).Pointer.child; } }, else => {}, } } if (flag) arg_set = arg_set ++ &[_]type{std.meta.Tuple(&[_]type{void})}; } std.debug.assert(ST != null); return struct { // return an instance of ThisPipe const StageType = ST.?; // The StageType as extracted from a Filter function const Conn = StageType.Conn; // list of connections const ThisPipe = @This(); // this pipe's type const pipe = pp; // the pipe source tuple const pNum = pN; // stages/filter of the pipe p: [pipe.len]StageType = [_]StageType{undefined} ** pipe.len, // connection nodes nodes: [nodesLen]Conn = [_]StageType.Conn{undefined} ** nodesLen, // callpipe input and output connector numbers (255 when no connection) inIdx:u8 = 255, outIdx:u8 = 255, // commit level of pipe commit: isize = -90909090, severed: u32 = 0, // the pipes last error (or void) rc: anyerror = error.ok, // the pipes args for this run (see fn args) theArgs: std.meta.Tuple(arg_set) = undefined, pub fn init(allocator: *std.mem.Allocator) *ThisPipe { var self: *ThisPipe = allocator.create(ThisPipe) catch unreachable; //self.parent = Parent; var p = self.p[0..]; // simipify life using slices var nodes = self.nodes[0..]; self.outIdx = 255; self.inIdx = 255; //@compileLog(p.len); inline for (pipe) |stg, i| { p[i] = StageType{ .i=i, .allocator=allocator, .PTIdx = pNum, .pipeAddr = @ptrToInt(self) }; inline for (stg) |elem| { // parse the pipe switch (@typeInfo(@TypeOf(elem))) { .Fn, .BoundFn => { // fn.... var name = @typeName(@TypeOf(elem)); //std.debug.print("{s}\n",.{name}); const end = std.mem.indexOfPos(u8, name, 0, ")).Fn.return_type").?; const start = std.mem.lastIndexOf(u8,name[0..end],".").? + 1; p[i].name = name[start..end]; if (debugStart) std.debug.print("stg {} {s}\n", .{ i, p[i].name }); }, .EnumLiteral => { // label (.any) or end (._) switch (elem) { // position of EnumLiteral in stage tuple already verified in Mint comptime ._ => { p[i].end = true; }, ._i => { if (i==0 or (i>0 and p[i-1].end)) self.inIdx = if (self.inIdx==255) i+1 else unreachable // dup input connnector else unreachable; // illegal input connector }, ._o => { if (!p[i-1].end) // i>0 known from Mint comptime self.outIdx = if (self.outIdx==255) i-1 else unreachable // dup output connnector else unreachable; // illegal output connector }, else => {}, // not interested in labels here } //std.debug.print("Idx {} {} {}\n",.{self.outIdx,self.inIdx, nodesLen}); }, else => {}, } } } // var buffer: [@sizeOf(@TypeOf(nodes)) + 1000]u8 = undefined; // const buffalloc = &std.heap.FixedBufferAllocator.init(&buffer).allocator; // var map = std.hash_map.StringHashMap(Conn).init(buffalloc); // defer map.deinit(); //@compileLog(nodes.len); var map: [nodesLen]?Conn = .{null} ** nodesLen; // create the pipe's nodes - all Conn{} fields are initialized by .set or in .run so var j: u32 = 0; for (p) |item, i| { const stg = if (item.name) |_| true else false; if (stg and !item.end and i != self.outIdx) { // add nodes when not end of stream and no out connection nodes[j].set(p, i, 0, i + 1, 0); j += 1; } if (lmap[i]) |lbl| { // get the label index of this pp step if (map[lbl]) |*k| { if (!stg) { if (item.end) { if (i == 0 or !p[i-1].end) { // if previous item did not have an end of stream if (p[i-1].name == null) { var n = map[lmap[i-1].?].?; nodes[j - 1].set(p, n.from, n.sout-1, k.to, k.sin); k.set(p, k.from, k.sout, k.to, k.sin + 1); n.set(p, n.from, n.sout + 1, n.to, n.sin); } else { nodes[j - 1].set(p, i - 1, 0, k.to, k.sin); k.set(p, k.from, k.sout, k.to, k.sin + 1); } } else { // this is a null output stream k.set(p, k.from, k.sout+1, k.to, k.sin); } } else { nodes[j].set(p, k.from, k.sout, i + 1, 0); j += 1; //if (i > 0 and p[i-1].name != null) { k.set(p, k.from, k.sout + 1, k.to, k.sin); //} } } else { if (item.end) { nodes[j].set(p, k.from, k.sout, i, k.sin); j += 1; k.set(p, k.from, k.sout + 1, k.to, k.sin + 1); } } } else { map[lbl] = Conn{}; map[lbl].?.set(p, i, 1, i, 1); } } if (debugStart) std.debug.print("{} {}\n", .{ i, j }); } // save the node slice in the stages; for (p) |_, i| { p[i].n = self.nodes[0..j]; } // debug if (debugStart) { for (self.nodes[0..j]) |c, k| { std.debug.print("{} {}_{s} {} -> {}_{s} {}\n", .{ k, c.from, p[c.from].name, c.sout, c.to, p[c.to].name, c.sin }); } } //@compileLog("done"); //std.debug.print("{*}\n{*}\n",.{p,nodes}); return self; } // associate the args with the stage's filters and a context struct. Returns an arg_tuple fn args(self: *ThisPipe, context: anytype) std.meta.Tuple(arg_set) { //tuple for calling fn(s) allong with the arguement tuples reguired var tuple = self.theArgs; // fill in the args tuple adding the fn(s) and argument values, using the passed contect structure block inline for (pipe) |stg, i| { comptime var flag: bool = true; inline for (stg) |elem, j| { switch (@typeInfo(@TypeOf(elem))) { .Fn, .BoundFn => { // fn.... tuple[i][0] = elem; tuple[i][1][0] = &self.p[i]; flag = false; }, .EnumLiteral => { // label continue; }, .Struct => { // struct we have found the tuple with the args... inline for (elem) |arg, k| { //@compileLog(i); //@compileLog(@typeInfo(@TypeOf(tuple[i][1][k+1]))); //@compileLog(arg); switch (@typeInfo(@TypeOf(arg))) { .Int, .Float, .ComptimeInt, .ComptimeFloat, .EnumLiteral => { // constants if (debugStart) std.debug.print("Int {} {}\n", .{ j, arg }); tuple[i][1][k+1] = arg; }, .Null => { tuple[i][1][k+1] = null; }, .Pointer => { // string with a var, var.field or (use a slice, not an array) if (debugStart) std.debug.print("Ptr {} {s}\n", .{ j, arg }); // this would be much simpiler if runtime vars worked in nested tuples... if (@TypeOf(tuple[i][1][k+1]) == []const u8 and arg[0] == '\'') { // expect a string tuple[i][1][k+1] = arg[1..]; continue; } if (context == void) continue; comptime { var t = @typeInfo(@TypeOf(tuple[i][1][k+1])); // base type from args tuple if (t == .Optional) { t = @typeInfo(t.Optional.child); // type of the optional } switch (t) { // decide what to do with the arg using type in args tuple .Int, .Float => { tuple[i][1][k+1] = if (std.mem.indexOfPos(u8,arg,0,".")) |dot| @field(@field(context, arg[0..dot]), arg[dot+1..]) else @field(context, arg); }, .Pointer => |p| { if (p.size == .Slice) { // slices are implied pointers tuple[i][1][k+1] = if (std.mem.indexOfPos(u8,arg,0,".")) |dot| @field(@field(context, arg[0..dot]), arg[dot+1..]) else @field(context, arg); } else { // pointer to something else (non slice) switch (@typeInfo(p.child)) { .Int, .Float, .Struct, .Pointer => { tuple[i][1][k+1] = if (std.mem.indexOfPos(u8,arg,0,".")) |dot| &@field(@field(context, arg[0..dot]), arg[dot+1..]) else &@field(context, arg); }, else => { @compileLog(p.child); @compileLog(@typeInfo(p.child)); }, } } }, else => { @compileLog(@TypeOf(tuple[i][1][k+1])); // unsupported arg type }, } } }, // more types will be needed, depending on additional stages else => { @compileLog(@TypeOf(arg)); // unsupported arg type }, } } }, else => {}, } } if (flag) tuple[i][0] = .{}; } if (debugStart) { comptime var i = 0; inline while (i < tuple.len) : (i += 1) { std.debug.print("{} {s}\n", .{ i, tuple[i][0] }); if (@TypeOf(tuple[i][0]) != void) { std.debug.print(" {*}\n", .{tuple[i][1][0]}); } } } return tuple; } // run the pipe, you can repeat runs with different arg_tuple(s) without redoing setup. pub fn run(self: *ThisPipe, context: anytype) !void { const what:enum{prep,call,all} = .all; var p = self.p[0..]; // use slices for easier to read code var nodes = self.p[0].n; const allocator = p[0].allocator; // use the same allocator used to allocate ThisPipe if (what == .prep or what == .all) { self.theArgs = self.args(context); //var arena3 = std.heap.ArenaAllocator.init(std.heap.page_allocator); //defer arena3.deinit(); self.severed = 0; self.rc = error.ok; // set starting input/output streams to lowest connected streams (usually 0 - but NOT always) for (nodes) |*n| { if (n.src.outC) |c| { if (n.sout < c.sout) n.src.outC = n; } else n.src.outC = n; if (n.dst.inC) |c| { if (n.sin < c.sin) n.dst.inC = n; } else n.dst.inC = n; n.in = .ok; } // set stages to starting State for (p) |*s| { if (s.name) |_| { //s.commit = -@intCast(isize, (i + 100)); s.commit = -1; s.state = .start; //s.rc = error.active; s.err = error.ok; } } // main dispatch loop self.commit = -1; self.severed = 0; } const cList = std.ArrayList(*Conn); // type for dispatch lists var fwdList = cList.init(allocator); //defer fwdList.deinit(); // using arena var bwdList = cList.init(allocator); //defer bwdList.deinit(); // using arena var list:*cList = &fwdList; var count:usize = 0; running: while (self.severed < nodes.len or bwdList.items.len >0) { var temp: isize = 90909090; count += 1; if (fwdList.items.len > 0) { list = &fwdList; //std.debug.print(">",.{}); } else { if (bwdList.items.len > 0) { list = &bwdList; //std.debug.print("<",.{}); } } while (list.items.len>0) { const c = list.swapRemove(list.items.len-1); // dispatch a pending peekTo or readTo if (c == c.dst.inC and (c.dst.state == .peekTo or c.dst.state == .readTo) and c.in != .ok and c.dst.commit == self.commit) { resume c.dst.frame; if (c.dst.fwdC) |n| { try fwdList.append(n); c.dst.fwdC = null; } if (c.dst.bwdC) |n| { try bwdList.append(n); c.dst.bwdC = null; } continue :running; } // dispatch a pending anyinput if (c.dst.state == .anyinput and c.in == .data and c.dst.commit == self.commit) { c.dst.inC = c; resume c.dst.frame; if (c.dst.fwdC) |n| { try fwdList.append(n); c.dst.fwdC = null; } if (c.dst.bwdC) |n| { try bwdList.append(n); c.dst.bwdC = null; } continue :running; } // dispatch a pending output if (c == c.src.outC and c.src.state == .output and c.in != .data and c.src.commit == self.commit) { resume c.src.frame; if (c.src.fwdC) |n| { try fwdList.append(n); c.src.fwdC = null; } if (c.src.bwdC) |n| { try bwdList.append(n); c.src.bwdC = null; } continue :running; } // compete a sever after any data in the node is consumed if ((c.in == .sever or c.in == .ok) and (c.src.state == .sever or c.src.state == .eos or c.dst.state == .sever or c.dst.state == .eos)) { c.in = .severed; if (c.dst.state == .anyinput and c.dst.countInstreams() == 0) { // wakeup anyinput if required resume c.dst.frame; std.debug.assert(c.dst.state != .anyinput); } if (c.dst.state == .peekTo) { resume c.dst.frame; std.debug.assert(c.dst.state != .peekTo); } if (c.dst.fwdC) |n| { try fwdList.append(n); c.dst.fwdC = null; } if (c.dst.bwdC) |n| { try bwdList.append(n); c.dst.bwdC = null; } self.severed += 1; continue :running; } } if (fwdList.items.len>0 or bwdList.items.len>0) continue :running; // std.debug.print(":",.{}); // var i = nodes.len; // if (loop<10) while (i>0) { // (nodes) |*c| { // i -= 1; // var c = &nodes[i]; for (nodes) |*c| { // std.debug.print(":",.{}); // dispatch a pending peekTo or readTo if (c == c.dst.inC and (c.dst.state == .peekTo or c.dst.state == .readTo) and c.in != .ok and c.dst.commit == self.commit) { //std.debug.print("{c}",.{@tagName(c.dst.state)[0]}); try bwdList.append(c); continue :running; } // dispatch a pending anyinput if (c.dst.state == .anyinput and c.in == .data and c.dst.commit == self.commit) { try bwdList.append(c); continue :running; } // dispatch a pending output if (c == c.src.outC and c.src.state == .output and c.in != .data and c.src.commit == self.commit) { try fwdList.append(c); continue :running; } // compete a sever after any data in the node is consumed if ((c.in == .sever or c.in == .ok) and (c.src.state == .sever or c.src.state == .eos or c.dst.state == .sever or c.dst.state == .eos)) { try fwdList.append(c); continue :running; } //std.debug.print(".call dst {} {}\n src {} {} - {} {}\n",.{c.dst.state, c.dst.commit, c.src.state, c.src.commit, self.commit, c.in}); if ((c.dst.state == .call or c.src.state == .call) and c.in != .sever ) { const stage = if (c.dst.state == .call) c.dst else c.src; if (stage.commit == self.commit) { resume stage.frame; if (stage.fwdC) |n| { try fwdList.append(n); stage.fwdC = null; } if (c.dst.fwdC) |n| { try bwdList.append(n); c.dst.fwdC = null; } continue :running; } } // start a stage fliter from connection destination if (c.dst.state == .start and c.dst.commit == self.commit) { c.dst.state = .run; c.dst.commit = 0; comptime var j = 0; inline while (j < p.len) : (j += 1) { if (@TypeOf(self.theArgs[j][0]) != void) { // prevent inline from generating void calls if (c.dst.i == j) { const f = pipe[j][if (@typeInfo(@TypeOf(pipe[j][0])) == .EnumLiteral) 1 else 0]; // @frameSize can be buggy... _ = @asyncCall(allocator.alignedAlloc(u8, 16, @sizeOf(@Frame(f))) catch unreachable, {}, f, self.theArgs[j][1]); } } } if (c.dst.fwdC) |n| { try fwdList.append(n); c.dst.fwdC = null; } if (c.dst.bwdC) |n| { try bwdList.append(n); c.dst.bwdC = null; } continue :running; } // start a stage filter from connection source if (c.src.state == .start and c.src.commit == self.commit) { c.src.state = .run; c.src.commit = 0; comptime var j = 0; inline while (j < p.len) : (j += 1) { if (@TypeOf(self.theArgs[j][0]) != void) { // prevent inline from generating void calls if (c.src.i == j) { const f = pipe[j][if (@typeInfo(@TypeOf(pipe[j][0])) == .EnumLiteral) 1 else 0]; // @frameSize can be buggy... _ = @asyncCall(allocator.alignedAlloc(u8, 16, @sizeOf(@Frame(f))) catch unreachable, {}, f, self.theArgs[j][1]); } } } if (c.src.fwdC) |n| { try fwdList.append(n); c.src.fwdC = null; } if (c.src.bwdC) |n| { try bwdList.append(n); c.src.bwdC = null; } continue :running; } // track commit levels if (c.dst.commit < temp) temp = c.dst.commit; if (c.src.commit < temp) temp = c.src.commit; } if (fwdList.items.len>0 or bwdList.items.len>0) continue :running; // is it time to commit to a higher level? if (debugDisp) std.debug.print("commit {} {}\n", .{ self.commit, temp }); if (temp > self.commit) { self.commit = temp; if (what == .prep and self.commit >= 0) return; continue :running; } if (self.severed == nodes.len) break :running; // when/if we use os threads in stages we will need to wait for them here. // detect stalls for (p) |*s| { if (debugDisp) std.log.info("{s} {}", .{ s.name, s.rc}); if (s.err != error.ok) { if (s.err == error.endOfStream or s.commit == -90909090) { continue; } else if (self.severed < nodes.len) { std.debug.print("\nStalled! {s} rc {} {}/{}\n", .{ s.name, s.err, nodes.len, self.severed}); for (nodes) |*c| { std.debug.print("src {}_{s} {} {} {} dst {}_{s} {} {} {} in {} {}\n", .{ c.src.i, c.src.name, c.sout, c.src.state, c.src.commit, c.dst.i, c.dst.name, c.sin, c.dst.state, c.dst.commit, c.in, c.data.type }); } self.commit = 90909090; self.rc = error.pipeStall; return self.rc; } } } break :running; } if (true) { // safety checking const flag = for (nodes) |c| { if (c.in != .severed or c.src.state != .eos or c.dst.state != .eos) break true; } else false; if (flag) { std.debug.print(" -- {} {}/{} {} {}\n",.{count, nodes.len, self.severed, fwdList.items.len, bwdList.items.len}); for (nodes) |*c| { std.debug.print("src {}_{s} {} {} {} dst {}_{s} {} {} {} in {} {}\n", .{ c.src.i, c.src.name, c.sout, c.src.state, c.src.commit, c.dst.i, c.dst.name, c.sin, c.dst.state, c.dst.commit, c.in, c.data.type }); } } } self.commit = 90909090; return; } }; }
pipes.zig
const std = @import("std"); const mem = std.mem; const testing = std.testing; const Metric = @import("metric.zig").Metric; pub fn GaugeCallFnType(comptime StateType: type) type { const CallFnArgType = switch (@typeInfo(StateType)) { .Pointer => StateType, .Optional => |opt| opt.child, else => *StateType, }; return fn (state: CallFnArgType) f64; } pub fn Gauge(comptime StateType: type) type { const CallFnType = GaugeCallFnType(StateType); return struct { const Self = @This(); metric: Metric = .{ .getResultFn = getResult, }, callFn: CallFnType = undefined, state: StateType = undefined, pub fn init(allocator: mem.Allocator, comptime callFn: CallFnType, state: StateType) !*Self { const self = try allocator.create(Self); self.* = .{}; self.callFn = callFn; self.state = state; return self; } pub fn get(self: *Self) f64 { const TypeInfo = @typeInfo(StateType); switch (TypeInfo) { .Pointer => { return self.callFn(self.state); }, .Optional => { if (self.state) |state| { return self.callFn(state); } else { return 0.0; } }, else => { return self.callFn(&self.state); }, } } fn getResult(metric: *Metric, allocator: mem.Allocator) Metric.Error!Metric.Result { _ = allocator; const self = @fieldParentPtr(Self, "metric", metric); return Metric.Result{ .gauge = self.get() }; } }; } test "gauge: get" { const State = struct { value: f64, }; var state = State{ .value = 20.0 }; var gauge = try Gauge(*State).init( testing.allocator, struct { fn get(s: *State) f64 { return s.value + 1.0; } }.get, &state, ); defer testing.allocator.destroy(gauge); try testing.expectEqual(@as(f64, 21.0), gauge.get()); } test "gauge: optional state" { const State = struct { value: f64, }; var state = State{ .value = 20.0 }; var gauge = try Gauge(?*State).init( testing.allocator, struct { fn get(s: *State) f64 { return s.value + 1.0; } }.get, &state, ); defer testing.allocator.destroy(gauge); try testing.expectEqual(@as(f64, 21.0), gauge.get()); } test "gauge: non-pointer state" { var gauge = try Gauge(f64).init( testing.allocator, struct { fn get(s: *f64) f64 { s.* += 1.0; return s.*; } }.get, 0.0, ); defer testing.allocator.destroy(gauge); try testing.expectEqual(@as(f64, 1.0), gauge.get()); } test "gauge: shared state" { const State = struct { mutex: std.Thread.Mutex = .{}, items: std.ArrayList(usize) = std.ArrayList(usize).init(testing.allocator), }; var shared_state = State{}; defer shared_state.items.deinit(); var gauge = try Gauge(*State).init( testing.allocator, struct { fn get(state: *State) f64 { return @intToFloat(f64, state.items.items.len); } }.get, &shared_state, ); defer testing.allocator.destroy(gauge); var threads: [4]std.Thread = undefined; for (threads) |*thread, thread_index| { thread.* = try std.Thread.spawn( .{}, struct { fn run(thread_idx: usize, state: *State) !void { var i: usize = 0; while (i < 4) : (i += 1) { state.mutex.lock(); defer state.mutex.unlock(); try state.items.append(thread_idx + i); } } }.run, .{ thread_index, &shared_state }, ); } for (threads) |*thread| thread.join(); try testing.expectEqual(@as(usize, 16), @floatToInt(usize, gauge.get())); } test "gauge: write" { var gauge = try Gauge(usize).init( testing.allocator, struct { fn get(state: *usize) f64 { state.* += 340; return @intToFloat(f64, state.*); } }.get, @as(usize, 0), ); defer testing.allocator.destroy(gauge); var buffer = std.ArrayList(u8).init(testing.allocator); defer buffer.deinit(); var metric = &gauge.metric; try metric.write(testing.allocator, buffer.writer(), "mygauge"); try testing.expectEqualStrings("mygauge 340.000000\n", buffer.items); }
src/Gauge.zig
const std = @import("std"); const zap = @import("zap"); const hyperia = @import("hyperia.zig"); const mem = std.mem; const mpsc = hyperia.mpsc; const builtin = std.builtin; const testing = std.testing; const assert = std.debug.assert; pub const cache_line_length = switch (builtin.cpu.arch) { .x86_64, .aarch64, .powerpc64 => 128, .arm, .mips, .mips64, .riscv64 => 32, .s390x => 256, else => 64, }; pub fn AsyncQueue(comptime T: type, comptime capacity: comptime_int) type { return struct { const Self = @This(); queue: Queue(T, capacity) = .{}, closed: bool = false, producer_event: mpsc.AsyncAutoResetEvent(void) = .{}, consumer_event: mpsc.AsyncAutoResetEvent(void) = .{}, pub fn close(self: *Self) void { @atomicStore(bool, &self.closed, true, .Monotonic); while (true) { var batch: zap.Pool.Batch = .{}; batch.push(self.producer_event.set()); batch.push(self.consumer_event.set()); if (batch.isEmpty()) break; hyperia.pool.schedule(.{}, batch); } } pub fn push(self: *Self, item: T) bool { while (!@atomicLoad(bool, &self.closed, .Monotonic)) { if (self.queue.push(item)) { if (self.consumer_event.set()) |runnable| { hyperia.pool.schedule(.{}, runnable); } return true; } self.producer_event.wait(); } return false; } pub fn pop(self: *Self) ?T { while (!@atomicLoad(bool, &self.closed, .Monotonic)) { if (self.queue.pop()) |item| { if (self.producer_event.set()) |runnable| { hyperia.pool.schedule(.{}, runnable); } return item; } self.consumer_event.wait(); } return null; } }; } pub fn Queue(comptime T: type, comptime capacity: comptime_int) type { return struct { const Self = @This(); entries: [capacity]T align(cache_line_length) = undefined, enqueue_pos: usize align(cache_line_length) = 0, dequeue_pos: usize align(cache_line_length) = 0, pub fn push(self: *Self, item: T) bool { const head = self.enqueue_pos; const tail = @atomicLoad(usize, &self.dequeue_pos, .Acquire); if (head +% 1 -% tail > capacity) { return false; } self.entries[head & (capacity - 1)] = item; @atomicStore(usize, &self.enqueue_pos, head +% 1, .Release); return true; } pub fn pop(self: *Self) ?T { const tail = self.dequeue_pos; const head = @atomicLoad(usize, &self.enqueue_pos, .Acquire); if (tail -% head == 0) { return null; } const popped = self.entries[tail & (capacity - 1)]; @atomicStore(usize, &self.dequeue_pos, tail +% 1, .Release); return popped; } }; } test { testing.refAllDecls(Queue(u64, 4)); testing.refAllDecls(AsyncQueue(u64, 4)); } test "queue" { var queue: Queue(u64, 4) = .{}; var i: usize = 0; while (i < 4) : (i += 1) testing.expect(queue.push(i)); testing.expect(!queue.push(5)); testing.expect(!queue.push(6)); testing.expect(!queue.push(7)); testing.expect(!queue.push(8)); var j: usize = 0; while (j < 4) : (j += 1) testing.expect(queue.pop().? == j); testing.expect(queue.pop() == null); testing.expect(queue.pop() == null); testing.expect(queue.pop() == null); testing.expect(queue.pop() == null); }
spsc.zig
const sf = struct { pub usingnamespace @import("../sfml.zig"); pub usingnamespace sf.network; }; const UdpSocket = @This(); // Constructor/destructor /// Creates a new udp socket pub fn create() !UdpSocket { var sock = sf.c.sfUdpSocket_create(); if (sock) |s| { return UdpSocket{ ._ptr = s }; } else return sf.Error.nullptrUnknownReason; } /// Destroys this socket pub fn destroy(self: *UdpSocket) void { sf.c.sfUdpSocket_destroy(self._ptr); } // Methods /// Enables or disables blocking mode (true for blocking) /// In blocking mode, receive waits for data pub fn setBlocking(self: *UdpSocket, blocking: bool) void { sf.c.sfUdpSocket_setBlocking(self._ptr, @boolToInt(blocking)); } /// Tells whether or not the socket is in blocking mode pub fn isBlocking(self: UdpSocket) bool { return sf.c.sfUdpSocket_isBlocking(self._ptr) != 0; } /// Gets the port this socket is bound to (null for no port) pub fn getLocalPort(self: UdpSocket) ?u16 { const port = sf.c.sfUdpSocket_getLocalPort(self._ptr); return if (port == 0) null else port; } /// Binds the socket to a specified port and ip /// port: the port to bind to (null to let the os choose) /// ip: the interface to bind to (null for any interface) pub fn bind(self: *UdpSocket, port: ?u16, ip: ?sf.IpAddress) sf.Socket.Error!void { const p = port orelse 0; const i = ip orelse sf.IpAddress.any(); const code = sf.c.sfUdpSocket_bind(self._ptr, p, i._ip); try sf.Socket._codeToErr(code); } /// Unbinds the socket from the port it's bound to pub fn unbind(self: *UdpSocket) void { sf.c.sfUdpSocket_unbind(self._ptr); } /// Sends raw data to a recipient pub fn send(self: *UdpSocket, data: []const u8, remote: sf.IpAndPort) sf.Socket.Error!void { const code = sf.c.sfUdpSocket_send(self._ptr, data.ptr, data.len, remote.ip._ip, remote.port); try sf.Socket._codeToErr(code); } /// Sends a packet to a recipient pub fn sendPacket(self: *UdpSocket, packet: sf.Packet, remote: sf.IpAndPort) sf.Socket.Error!void { const code = sf.c.sfUdpSocket_sendPacket(self._ptr, packet._ptr, remote.ip._ip, remote.port); try sf.Socket._codeToErr(code); } /// Represents received data and a remote ip and port pub const ReceivedRaw = struct { data: []const u8, sender: sf.IpAndPort }; /// Receives raw data from a recipient /// Pass in a buffer large enough /// Returns the slice of the received data and the sender ip and port pub fn receive(self: *UdpSocket, buf: []u8) sf.Socket.Error!ReceivedRaw { var size: usize = undefined; var remote: sf.IpAndPort = undefined; const code = sf.c.sfUdpSocket_receive(self._ptr, buf.ptr, buf.len, &size, &remote.ip._ip, &remote.port); try sf.Socket._codeToErr(code); return ReceivedRaw{ .data = buf[0..size], .sender = remote }; } // TODO: consider receiveAlloc ? // TODO: should this return its own new packet? /// Receives a packet from a recipient /// Pass the packet to fill with the data /// Returns the sender ip and port pub fn receivePacket(self: *UdpSocket, packet: *sf.Packet) sf.Socket.Error!sf.IpAndPort { var remote: sf.IpAndPort = undefined; const code = sf.c.sfUdpSocket_receivePacket(self._ptr, packet._ptr, &remote.ip._ip, &remote.port); try sf.Socket._codeToErr(code); return remote; } /// Gets the max datagram size you can send pub fn getMaxDatagramSize() c_uint { return sf.c.sfUdpSocket_maxDatagramSize(); } /// Pointer to the csfml structure _ptr: *sf.c.sfUdpSocket, test "udp socket: dumb test" { const tst = @import("std").testing; var buf: [1024]u8 = undefined; var pack = try sf.Packet.create(); defer pack.destroy(); var sock = try UdpSocket.create(); defer sock.destroy(); sock.setBlocking(false); try tst.expect(!sock.isBlocking()); try sock.bind(null, null); const port = sock.getLocalPort().?; try tst.expect(port >= 49152); try tst.expectError(error.notReady, sock.receive(&buf)); sock.unbind(); try tst.expect(sock.getLocalPort() == null); try tst.expectError(error.otherError, sock.receivePacket(&pack)); const target = sf.IpAndPort{ .port = 1, .ip = sf.IpAddress.none() }; try tst.expectError(error.otherError, sock.sendPacket(pack, target)); try tst.expectError(error.otherError, sock.send(buf[0..10], target)); }
src/sfml/network/UdpSocket.zig
const gllparser = @import("../gllparser/gllparser.zig"); const Error = gllparser.Error; const Parser = gllparser.Parser; const ParserContext = gllparser.Context; const Result = gllparser.Result; const NodeName = gllparser.NodeName; const std = @import("std"); const testing = std.testing; const mem = std.mem; pub const Void = struct { pub fn deinit(self: *const @This(), allocator: mem.Allocator) void { _ = self; _ = allocator; } }; /// If the result is not `null`, its `.offset` value will be updated to reflect the current parse /// position before Always returns it. pub fn Context(comptime Value: type) type { return ?Result(Value); } /// Always yields the input value (once/unambiguously), or no value (if the input value is null). /// /// The `input` value is taken ownership of by the parser, and deinitialized once the parser is. pub fn Always(comptime Payload: type, comptime Value: type) type { return struct { parser: Parser(Payload, Value) = Parser(Payload, Value).init(parse, nodeName, deinit, null), input: Context(Value), const Self = @This(); pub fn init(allocator: mem.Allocator, input: Context(Value)) !*Parser(Payload, Value) { const self = Self{ .input = input }; return try self.parser.heapAlloc(allocator, self); } pub fn initStack(input: Context(Value)) Self { return Self{ .input = input }; } pub fn deinit(parser: *Parser(Payload, Value), allocator: mem.Allocator, freed: ?*std.AutoHashMap(usize, void)) void { _ = freed; const self = @fieldParentPtr(Self, "parser", parser); if (self.input) |input| input.deinit(allocator); } pub fn nodeName(parser: *const Parser(Payload, Value), node_name_cache: *std.AutoHashMap(usize, NodeName)) Error!u64 { _ = node_name_cache; const self = @fieldParentPtr(Self, "parser", parser); var v = std.hash_map.hashString("Always"); v +%= std.hash_map.getAutoHashFn(?Result(Value), void)({}, self.input); return v; } pub fn parse(parser: *const Parser(Payload, Value), in_ctx: *const ParserContext(Payload, Value)) callconv(.Async) Error!void { const self = @fieldParentPtr(Self, "parser", parser); var ctx = in_ctx.with(self.input); defer ctx.results.close(); if (self.input) |input| { var tmp = input.toUnowned(); tmp.offset = ctx.offset; try ctx.results.add(tmp); } } }; } test "always" { nosuspend { const allocator = testing.allocator; const Payload = void; const ctx = try ParserContext(Payload, Void).init(allocator, "hello world", {}); defer ctx.deinit(); const noop = try Always(Payload, Void).init(allocator, null); defer noop.deinit(allocator, null); try noop.parse(&ctx); var sub = ctx.subscribe(); try testing.expect(sub.next() == null); } }
src/combn/combinator/always.zig
const builtin = @import("builtin"); const std = @import("std"); const c = @import("c.zig"); const examples = @import("scene/examples.zig"); const Debounce = @import("debounce.zig").Debounce; const Options = @import("options.zig").Options; const Renderer = @import("renderer.zig").Renderer; const Scene = @import("scene.zig").Scene; const Gui = @import("gui.zig").Gui; pub const Window = struct { const Self = @This(); alloc: *std.mem.Allocator, window: *c.GLFWwindow, // WGPU handles device: c.WGPUDeviceId, queue: c.WGPUQueueId, surface: c.WGPUSurfaceId, swap_chain: c.WGPUSwapChainId, // Subsystems renderer: Renderer, gui: Gui, debounce: Debounce, focused: bool, show_editor: bool, show_gui_demo: bool, total_samples: ?u32, pub fn init(alloc: *std.mem.Allocator, options_: Options, name: [*c]const u8) !*Self { const window = c.glfwCreateWindow( @intCast(c_int, options_.width), @intCast(c_int, options_.height), name, null, null, ) orelse { var err_str: [*c]u8 = null; const err = c.glfwGetError(&err_str); std.debug.panic("Failed to open window: {} ({})", .{ err, err_str }); }; var width_: c_int = undefined; var height_: c_int = undefined; c.glfwGetFramebufferSize(window, &width_, &height_); var options = options_; options.width = @intCast(u32, width_); options.height = @intCast(u32, height_); // Extract the WGPU Surface from the platform-specific window const platform = builtin.os.tag; const surface = if (platform == .macos) surf: { // Time to do hilarious Objective-C runtime hacks, equivalent to // [ns_window.contentView setWantsLayer:YES]; // id metal_layer = [CAMetalLayer layer]; // [ns_window.contentView setLayer:metal_layer]; const objc = @import("objc.zig"); const darwin = @import("darwin.zig"); const cocoa_window = darwin.glfwGetCocoaWindow(window); const ns_window = @ptrCast(c.id, @alignCast(8, cocoa_window)); const cv = objc.call(ns_window, "contentView"); _ = objc.call_(cv, "setWantsLayer:", true); const ca_metal = objc.class("CAMetalLayer"); const metal_layer = objc.call(ca_metal, "layer"); _ = objc.call_(cv, "setLayer:", metal_layer); break :surf c.wgpu_create_surface_from_metal_layer(metal_layer); } else { std.debug.panic("Unimplemented on platform {}", .{platform}); }; //////////////////////////////////////////////////////////////////////////// // WGPU initial setup var adapter: c.WGPUAdapterId = 0; c.wgpu_request_adapter_async(&(c.WGPURequestAdapterOptions){ .power_preference = c.WGPUPowerPreference._HighPerformance, .compatible_surface = surface, }, 2 | 4 | 8, adapter_cb, &adapter); const device = c.wgpu_adapter_request_device( adapter, &(c.WGPUDeviceDescriptor){ .label = "", .features = 0, .limits = (c.WGPULimits){ .max_bind_groups = 1, }, .trace_path = null, }, ); var out = try alloc.create(Self); // Attach the Window handle to the window so we can extract it _ = c.glfwSetWindowUserPointer(window, out); _ = c.glfwSetFramebufferSizeCallback(window, size_cb); _ = c.glfwSetWindowFocusCallback(window, focus_cb); const scene = try examples.new_cornell_box(alloc); out.* = .{ .alloc = alloc, .window = window, .device = device, .queue = c.wgpu_device_get_default_queue(device), .surface = surface, .swap_chain = undefined, .renderer = try Renderer.init(alloc, scene, options, device), .gui = try Gui.init(alloc, window, device), .debounce = Debounce.init(), .show_editor = false, .show_gui_demo = false, .total_samples = options.total_samples, .focused = false, }; out.resize_swap_chain(options.width, options.height); // Trigger a compilation of an optimized shader immediately try out.debounce.update(0); return out; } pub fn deinit(self: *Self) void { c.glfwDestroyWindow(self.window); self.renderer.deinit(); self.gui.deinit(); self.alloc.destroy(self); } pub fn should_close(self: *const Self) bool { return c.glfwWindowShouldClose(self.window) != 0; } fn draw(self: *Self) !void { if (self.debounce.check()) { // Try to kick off an async build of a scene-specific shader. // // If this fails (because we've already got shaderc running), // then poke the debounce system to retrigger. var scene = try self.renderer.scene.clone(); if (!try self.renderer.build_opt(scene)) { try self.debounce.update(10); scene.deinit(); } } const next_texture_view = c.wgpu_swap_chain_get_current_texture_view(self.swap_chain); if (next_texture_view == 0) { std.debug.panic("Cannot acquire next swap chain texture", .{}); } const cmd_encoder = c.wgpu_device_create_command_encoder( self.device, &(c.WGPUCommandEncoderDescriptor){ .label = "main encoder" }, ); self.gui.new_frame(); var menu_width: f32 = 0; var menu_height: f32 = 0; var save_img = false; if (c.igBeginMainMenuBar()) { if (c.igBeginMenu("Scene", true)) { var new_scene_fn: ?fn (alloc: *std.mem.Allocator) anyerror!Scene = null; if (c.igMenuItemBool("Simple", "", false, true)) { new_scene_fn = examples.new_simple_scene; } if (c.igMenuItemBool("Cornell Spheres", "", false, true)) { new_scene_fn = examples.new_cornell_balls; } if (c.igMenuItemBool("Cornell Box", "", false, true)) { new_scene_fn = examples.new_cornell_box; } if (c.igMenuItemBool("Ray Tracing in One Weekend", "", false, true)) { new_scene_fn = examples.new_rtiow; } if (c.igMenuItemBool("Prism", "", false, true)) { new_scene_fn = examples.new_prism; } if (c.igMenuItemBool("THE ORB", "", false, true)) { new_scene_fn = examples.new_orb_scene; } if (c.igMenuItemBool("Golden spheres", "", false, true)) { new_scene_fn = examples.new_hex_box; } if (c.igMenuItemBool("Chromatic aberration test", "", false, true)) { new_scene_fn = examples.new_cornell_aberration; } if (c.igMenuItemBool("Caffeine", "", false, true)) { new_scene_fn = examples.new_caffeine; } if (c.igMenuItemBool("Riboflavin", "", false, true)) { new_scene_fn = examples.new_riboflavin; } if (new_scene_fn) |f| { const options = self.renderer.get_options(); self.renderer.deinit(); const scene = try f(self.alloc); self.renderer = try Renderer.init(self.alloc, scene, options, self.device); try self.debounce.update(0); // Trigger optimized shader compilation } c.igEndMenu(); } if (c.igBeginMenu("Edit", true)) { _ = c.igMenuItemBoolPtr("Show editor", "", &self.show_editor, true); _ = c.igMenuItemBoolPtr("Show GUI demo", "", &self.show_gui_demo, true); _ = c.igMenuItemBoolPtr("Save out.png", "", &save_img, true); c.igEndMenu(); } menu_height = c.igGetWindowHeight() - 1; const stats = try self.renderer.stats(self.alloc); defer self.alloc.free(stats); var text_size: c.ImVec2 = undefined; c.igCalcTextSize(&text_size, stats.ptr, null, false, -1); c.igSetCursorPosX(c.igGetWindowWidth() - text_size.x - 10); c.igTextUnformatted(stats.ptr, null); c.igEndMainMenuBar(); } // If the scene is changed through the editor, then poke the debounce // timer to build the optimized shader once things stop changing if (self.show_editor) { if (try self.renderer.draw_gui(menu_height, &menu_width)) { try self.debounce.update(1000); } } if (self.show_gui_demo) { c.igShowDemoWindow(&self.show_gui_demo); } const io = c.igGetIO() orelse std.debug.panic("Could not get io\n", .{}); const pixel_density = io.*.DisplayFramebufferScale.x; const window_width = io.*.DisplaySize.x; const window_height = io.*.DisplaySize.y; try self.renderer.draw( .{ .width = (window_width - menu_width) * pixel_density, .height = (window_height - menu_height) * pixel_density, .x = menu_width * pixel_density, .y = menu_height * pixel_density, }, next_texture_view, cmd_encoder, ); // Draw the GUI, which has been building render lists until now self.gui.draw(next_texture_view, cmd_encoder); const cmd_buf = c.wgpu_command_encoder_finish(cmd_encoder, null); c.wgpu_queue_submit(self.queue, &cmd_buf, 1); _ = c.wgpu_swap_chain_present(self.swap_chain); if (save_img) { try self.renderer.save_png(); } } pub fn run(self: *Self) !void { while (!self.should_close()) { try self.draw(); if (self.total_samples) |n| { if (self.renderer.uniforms.samples >= n) { return self.renderer.save_png(); } } if (self.focused) { c.glfwPollEvents(); } else { c.glfwWaitEvents(); } } } fn update_size(self: *Self, width_: c_int, height_: c_int) void { const width = @intCast(u32, width_); const height = @intCast(u32, height_); self.renderer.update_size(width, height); self.resize_swap_chain(width, height); } fn resize_swap_chain(self: *Self, width: u32, height: u32) void { self.swap_chain = c.wgpu_device_create_swap_chain( self.device, self.surface, &(c.WGPUSwapChainDescriptor){ .usage = c.WGPUTextureUsage_RENDER_ATTACHMENT, .format = c.WGPUTextureFormat._Bgra8Unorm, .width = width, .height = height, .present_mode = c.WGPUPresentMode._Fifo, }, ); } fn update_focus(self: *Self, focused: bool) void { self.focused = focused; } }; export fn size_cb(w: ?*c.GLFWwindow, width: c_int, height: c_int) void { const ptr = c.glfwGetWindowUserPointer(w) orelse std.debug.panic("Missing user pointer", .{}); var r = @ptrCast(*Window, @alignCast(8, ptr)); r.update_size(width, height); } export fn focus_cb(w: ?*c.GLFWwindow, focused: c_int) void { const ptr = c.glfwGetWindowUserPointer(w) orelse std.debug.panic("Missing user pointer", .{}); var r = @ptrCast(*Window, @alignCast(8, ptr)); r.update_focus(focused == c.GLFW_TRUE); } export fn adapter_cb(received: c.WGPUAdapterId, data: ?*c_void) void { @ptrCast(*c.WGPUAdapterId, @alignCast(8, data)).* = received; }
src/window.zig
const std = @import("std"); const Scope = @import("Scope.zig"); const value = @import("value.zig"); const Value = value.Value; const p2z = @import("pcre2zig"); const ScopeStack = @This(); allocator: std.mem.Allocator, columns: Value = value.val_nil, value_cache: std.StringHashMap(Value), func_memo: std.AutoHashMap(u64, Value), global_scope: std.StringHashMap(Value), headers: std.StringArrayHashMap(usize), mdata_cache: std.StringHashMap(?p2z.MatchData), regex_cache: std.StringHashMap(p2z.CompiledCode), stack: std.ArrayList(Scope), // Current data filename file: Value = value.val_nil, // Record numbering frnum: usize = 0, rnum: usize = 0, // Current record rec_buf: [1024 * 64]u8 = undefined, record: Value = value.val_nil, // Record ranges rec_ranges: std.AutoHashMap(u8, void) = undefined, // Delimiters ics: Value = value.strToValue(","), irs: Value = value.strToValue("\n"), ocs: Value = value.strToValue(","), ors: Value = value.strToValue("\n"), // Column headers header_row: ?usize = null, const builtins = std.ComptimeStringMap(void, .{ .{ "atan2", {} }, .{ "chars", {} }, .{ "col", {} }, .{ "contains", {} }, .{ "cos", {} }, .{ "each", {} }, .{ "endsWith", {} }, .{ "exp", {} }, .{ "filter", {} }, .{ "int", {} }, .{ "indexOf", {} }, .{ "join", {} }, .{ "keys", {} }, .{ "keysByValueAsc", {} }, .{ "keysByValueDesc", {} }, .{ "lastIndexOf", {} }, .{ "len", {} }, .{ "log", {} }, .{ "map", {} }, .{ "max", {} }, .{ "mean", {} }, .{ "median", {} }, .{ "memo", {} }, .{ "min", {} }, .{ "mode", {} }, .{ "print", {} }, .{ "pop", {} }, .{ "push", {} }, .{ "rand", {} }, .{ "reduce", {} }, .{ "replace", {} }, .{ "reverse", {} }, .{ "sin", {} }, .{ "sortAsc", {} }, .{ "sortDesc", {} }, .{ "split", {} }, .{ "sqrt", {} }, .{ "startsWith", {} }, .{ "stdev", {} }, .{ "toLower", {} }, .{ "toUpper", {} }, .{ "unique", {} }, .{ "values", {} }, }); const globals = std.ComptimeStringMap(void, .{ .{ "@cols", {} }, .{ "@file", {} }, .{ "@frnum", {} }, .{ "@head", {} }, .{ "@ics", {} }, .{ "@irs", {} }, .{ "@ocs", {} }, .{ "@ors", {} }, .{ "@rec", {} }, .{ "@rnum", {} }, }); pub fn init(allocator: std.mem.Allocator) ScopeStack { return ScopeStack{ .allocator = allocator, .value_cache = std.StringHashMap(Value).init(allocator), .func_memo = std.AutoHashMap(u64, Value).init(allocator), .global_scope = std.StringHashMap(Value).init(allocator), .headers = std.StringArrayHashMap(usize).init(allocator), .mdata_cache = std.StringHashMap(?p2z.MatchData).init(allocator), .rec_ranges = std.AutoHashMap(u8, void).init(allocator), .regex_cache = std.StringHashMap(p2z.CompiledCode).init(allocator), .stack = std.ArrayList(Scope).init(allocator), }; } pub fn deinit(self: *ScopeStack) void { var code_iter = self.regex_cache.valueIterator(); while (code_iter.next()) |code_ptr| code_ptr.deinit(); var value_iter = self.value_cache.valueIterator(); while (value_iter.next()) |v| { if (value.asMatcher(v.*)) |obj_ptr| obj_ptr.matcher.data.deinit(); } } pub fn push(self: *ScopeStack, scope: Scope) !void { try self.stack.append(scope); } pub fn pop(self: *ScopeStack) Scope { std.debug.assert(self.stack.items.len > 0); return self.stack.pop(); } pub fn isDefined(self: ScopeStack, key: []const u8) bool { if (builtins.has(key)) return true; if (globals.has(key)) return true; const len = self.stack.items.len; var i: usize = 1; while (i <= len) : (i += 1) { if (self.stack.items[len - i].map.contains(key)) return true; //if (self.stack.items[len - i].ty == .function) return self.stack.items[0].isDefined(key); } return self.global_scope.contains(key); } pub fn load(self: ScopeStack, key: []const u8) ?Value { const len = self.stack.items.len; var i: usize = 1; while (i <= len) : (i += 1) { if (self.stack.items[len - i].map.get(key)) |v| return v; //if (self.stack.items[len - i].ty == .function) return self.stack.items[0].load(key); } return self.global_scope.get(key); } pub fn store(self: *ScopeStack, key: []const u8, v: Value) !void { if (self.stack.items.len > 0) { try self.stack.items[self.stack.items.len - 1].map.put(key, v); } else { const key_copy = try self.allocator.dupe(u8, key); try self.global_scope.put(key_copy, try value.copy(v, self.allocator)); } } pub fn update(self: *ScopeStack, key: []const u8, v: Value) !void { const len = self.stack.items.len; var i: usize = 1; while (i <= len) : (i += 1) { if (self.stack.items[len - i].map.contains(key)) return self.stack.items[len - i].map.put(key, v); //if (self.stack.items[len - i].ty == .function) return self.stack.items[0].update(key, value); } try self.global_scope.put(key, try value.copy(v, self.allocator)); } // Debug pub fn dump(self: ScopeStack) void { std.debug.print("\n*** ScopeStack Dump Begin ***\n", .{}); for (self.stack.items) |scope, i| { std.debug.print("*** Scope #{} Dump Begin ***\n", .{i}); scope.dump(); std.debug.print("*** Scope #{} Dump End ***\n", .{i}); } std.debug.print("*** Global Scope Dump Begin ***\n", .{}); var iter = self.global_scope.iterator(); while (iter.next()) |entry| std.debug.print("\t{s}: {}\n", .{ entry.key_ptr.*, entry.value_ptr.* }); std.debug.print("*** Global Scope Dump End ***\n", .{}); std.debug.print("*** ScopeStack Dump End ***\n", .{}); }
src/ScopeStack.zig
const std = @import("std"); const aoc = @import("aoc-lib.zig"); fn parts(alloc: std.mem.Allocator, inp: []const u8) ![2]u16 { var si = std.mem.indexOfScalar(u8, inp, @as(u8, '\n')) orelse unreachable; var calls = try aoc.Ints(alloc, u8, inp[0..si]); defer alloc.free(calls); var rounds: [100]u8 = @splat(100, @as(u8, 101)); for (calls) |v, i| { rounds[v] = @intCast(u8, i); } var res = [2]u16{ 0, 0 }; var first: u8 = 255; var last: u8 = 0; var boardInts = try aoc.Ints(alloc, u8, inp[si + 2 ..]); defer alloc.free(boardInts); var boardI: usize = 0; while (boardI < boardInts.len) : (boardI += 25) { var board = boardInts[boardI .. boardI + 25]; var rl = [10]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; for (board) |v, i| { var round = rounds[v]; var r = i % 5; var c = @divFloor(i, 5); if (rl[r] < round) { rl[r] = round; } if (rl[c + 5] < round) { rl[c + 5] = round; } } var min = std.mem.min(u8, rl[0..]); var sc: u16 = 0; for (board) |v| { if (rounds[v] > min) { sc += @as(u16, v); } } if (first > min) { first = min; res[0] = calls[min] * sc; } if (last < min) { last = min; res[1] = calls[min] * sc; } } return res; } test "parts" { var t = try parts(aoc.talloc, aoc.test1file); try aoc.assertEq(@as(u16, 4512), t[0]); try aoc.assertEq(@as(u16, 1924), t[1]); t = try parts(aoc.talloc, aoc.inputfile); try aoc.assertEq(@as(u16, 63552), t[0]); try aoc.assertEq(@as(u16, 9020), t[1]); } fn day04(inp: []const u8, bench: bool) anyerror!void { var p = try parts(aoc.halloc, inp); if (!bench) { try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p[0], p[1] }); } } pub fn main() anyerror!void { try aoc.benchme(aoc.input(), day04); }
2021/04/aoc.zig
usingnamespace @import("../engine/engine.zig"); const Literal = @import("../parser/literal.zig").Literal; const LiteralValue = @import("../parser/literal.zig").LiteralValue; const std = @import("std"); const testing = std.testing; const mem = std.mem; pub fn OneOfContext(comptime Payload: type, comptime Value: type) type { return []const *Parser(Payload, Value); } /// Represents values from one parse path. /// /// In the case of a non-ambiguous `OneOf` grammar of `Parser1 | Parser2`, the combinator will /// yield: /// /// ``` /// stream(OneOfValue(Parser1Value)) /// ``` /// /// Or: /// /// ``` /// stream(OneOfValue(Parser2Value)) /// ``` /// /// In the case of an ambiguous grammar `Parser1 | Parser2` where either parser can produce three /// different parse paths, it will always yield the first successful path. pub fn OneOfValue(comptime Value: type) type { return Value; } /// Matches one of the given `input` parsers, matching the first parse path. If ambiguous grammar /// matching is desired, see `OneOfAmbiguous`. /// /// The `input` parsers must remain alive for as long as the `OneOf` parser will be used. pub fn OneOf(comptime Payload: type, comptime Value: type) type { return struct { parser: Parser(Payload, OneOfValue(Value)) = Parser(Payload, OneOfValue(Value)).init(parse, nodeName, deinit), input: OneOfContext(Payload, Value), const Self = @This(); pub fn init(input: OneOfContext(Payload, Value)) Self { return Self{ .input = input }; } pub fn deinit(parser: *Parser(Payload, Value), allocator: *mem.Allocator) void { const self = @fieldParentPtr(Self, "parser", parser); for (self.input) |in_parser| { in_parser.deinit(allocator); } } pub fn nodeName(parser: *const Parser(Payload, Value), node_name_cache: *std.AutoHashMap(usize, ParserNodeName)) Error!u64 { const self = @fieldParentPtr(Self, "parser", parser); var v = std.hash_map.hashString("OneOf"); for (self.input) |in_parser| { v +%= try in_parser.nodeName(node_name_cache); } return v; } pub fn parse(parser: *const Parser(Payload, Value), in_ctx: *const Context(Payload, Value)) callconv(.Async) !void { const self = @fieldParentPtr(Self, "parser", parser); var ctx = in_ctx.with(self.input); defer ctx.results.close(); var gotValues: usize = 0; for (self.input) |in_parser| { const child_node_name = try in_parser.nodeName(&in_ctx.memoizer.node_name_cache); var child_ctx = try in_ctx.initChild(Value, child_node_name, ctx.offset); defer child_ctx.deinitChild(); if (!child_ctx.existing_results) try in_parser.parse(&child_ctx); var sub = child_ctx.subscribe(); while (sub.next()) |next| { switch (next.result) { .err => {}, else => { // TODO(slimsag): need path committal functionality if (gotValues == 0) try ctx.results.add(next.toUnowned()); gotValues += 1; }, } } } if (gotValues == 0) { // All parse paths failed, so return a nice error. // // TODO(slimsag): include names of expected input parsers // // TODO(slimsag): collect and return the furthest error if a parse path made // progress and failed. try ctx.results.add(Result(OneOfValue(Value)).initError(ctx.offset, "expected OneOf")); } } }; } // Confirms that the following grammar works as expected: // // ```ebnf // Grammar = "ello" | "world" ; // ``` // test "oneof" { nosuspend { const allocator = testing.allocator; const Payload = void; const ctx = try Context(Payload, OneOfValue(LiteralValue)).init(allocator, "elloworld", {}); defer ctx.deinit(); const parsers: []*Parser(Payload, LiteralValue) = &.{ (&Literal(Payload).init("ello").parser).ref(), (&Literal(Payload).init("world").parser).ref(), }; var helloOrWorld = OneOf(Payload, LiteralValue).init(parsers); try helloOrWorld.parser.parse(&ctx); var sub = ctx.subscribe(); var r1 = sub.next().?; try testing.expectEqual(@as(usize, 4), r1.offset); try testing.expectEqualStrings("ello", r1.result.value.value); try testing.expect(sub.next() == null); // stream closed } } // Confirms behavior of the following grammar, which is ambiguous and should use OneOfAmbiguous // instead of OneOf: // // ```ebnf // Grammar = "ello" | "elloworld" ; // ``` // test "oneof_ambiguous_first" { nosuspend { const allocator = testing.allocator; const Payload = void; const ctx = try Context(Payload, OneOfValue(LiteralValue)).init(allocator, "elloworld", {}); defer ctx.deinit(); const parsers: []*Parser(Payload, LiteralValue) = &.{ (&Literal(Payload).init("ello").parser).ref(), (&Literal(Payload).init("elloworld").parser).ref(), }; var helloOrWorld = OneOf(Payload, LiteralValue).init(parsers); try helloOrWorld.parser.parse(&ctx); var sub = ctx.subscribe(); var r1 = sub.next().?; try testing.expectEqual(@as(usize, 4), r1.offset); try testing.expectEqualStrings("ello", r1.result.value.value); try testing.expect(sub.next() == null); // stream closed } }
src/combn/combinator/oneof.zig
const zang = @import("zang"); const common = @import("common.zig"); const c = @import("common/c.zig"); pub const AUDIO_FORMAT: zang.AudioFormat = .signed16_lsb; pub const AUDIO_SAMPLE_RATE = 48000; pub const AUDIO_BUFFER_SIZE = 1024; pub const DESCRIPTION = \\example_curve \\ \\Trigger a weird sound effect with the keyboard. The \\sound is defined using a curve, and scales with the \\frequency of the key you press. ; const carrier_curve = [_]zang.CurveNode{ .{ .t = 0.0, .value = 440.0 }, .{ .t = 0.5, .value = 880.0 }, .{ .t = 1.0, .value = 110.0 }, .{ .t = 1.5, .value = 660.0 }, .{ .t = 2.0, .value = 330.0 }, .{ .t = 3.9, .value = 20.0 }, }; const modulator_curve = [_]zang.CurveNode{ .{ .t = 0.0, .value = 110.0 }, .{ .t = 1.5, .value = 55.0 }, .{ .t = 3.0, .value = 220.0 }, }; const CurvePlayer = struct { pub const num_outputs = 2; pub const num_temps = 2; pub const Params = struct { sample_rate: f32, rel_freq: f32, }; carrier_curve: zang.Curve, carrier: zang.SineOsc, modulator_curve: zang.Curve, modulator: zang.SineOsc, fn init() CurvePlayer { return .{ .carrier_curve = zang.Curve.init(), .carrier = zang.SineOsc.init(), .modulator_curve = zang.Curve.init(), .modulator = zang.SineOsc.init(), }; } fn paint( self: *CurvePlayer, span: zang.Span, outputs: [num_outputs][]f32, temps: [num_temps][]f32, note_id_changed: bool, params: Params, ) void { const freq_mul = params.rel_freq; zang.zero(span, temps[0]); self.modulator_curve.paint(span, .{temps[0]}, .{}, note_id_changed, .{ .sample_rate = params.sample_rate, .function = .smoothstep, .curve = &modulator_curve, }); zang.multiplyWithScalar(span, temps[0], freq_mul); zang.zero(span, temps[1]); self.modulator.paint(span, .{temps[1]}, .{}, note_id_changed, .{ .sample_rate = params.sample_rate, .freq = zang.buffer(temps[0]), .phase = zang.constant(0.0), }); zang.zero(span, temps[0]); self.carrier_curve.paint(span, .{temps[0]}, .{}, note_id_changed, .{ .sample_rate = params.sample_rate, .function = .smoothstep, .curve = &carrier_curve, }); zang.multiplyWithScalar(span, temps[0], freq_mul); self.carrier.paint(span, .{outputs[0]}, .{}, note_id_changed, .{ .sample_rate = params.sample_rate, .freq = zang.buffer(temps[0]), .phase = zang.buffer(temps[1]), }); zang.addInto(span, outputs[1], temps[0]); } }; pub const MainModule = struct { pub const num_outputs = 2; pub const num_temps = 2; pub const output_audio = common.AudioOut{ .mono = 0 }; pub const output_visualize = 0; pub const output_sync_oscilloscope = 1; iq: zang.Notes(CurvePlayer.Params).ImpulseQueue, idgen: zang.IdGenerator, player: CurvePlayer, trigger: zang.Trigger(CurvePlayer.Params), pub fn init() MainModule { return .{ .iq = zang.Notes(CurvePlayer.Params).ImpulseQueue.init(), .idgen = zang.IdGenerator.init(), .player = CurvePlayer.init(), .trigger = zang.Trigger(CurvePlayer.Params).init(), }; } pub fn paint( self: *MainModule, span: zang.Span, outputs: [num_outputs][]f32, temps: [num_temps][]f32, ) void { var ctr = self.trigger.counter(span, self.iq.consume()); while (self.trigger.next(&ctr)) |result| { self.player.paint(result.span, outputs, temps, result.note_id_changed, result.params); } } pub fn keyEvent(self: *MainModule, key: i32, down: bool, impulse_frame: usize) bool { if (common.getKeyRelFreq(key)) |rel_freq| { if (down) { self.iq.push(impulse_frame, self.idgen.nextId(), .{ .sample_rate = AUDIO_SAMPLE_RATE, .rel_freq = rel_freq, }); } return true; } return false; } };
examples/example_curve.zig
/// Listen address for the server. pub const address = "127.0.0.1:6667"; /// Word bank for use by local bots. pub const word_bank = [_][]const u8{ "lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod", "tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "ut", "enim", "ad", "minim", "veniam", "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "ut", "aliquip", "ex", "ea", "commodo", "consequat", "duis", "aute", "irure", "dolor", "in", "reprehenderit", "in", "voluptate", "velit", "esse", "cillum", "dolore", "eu", "fugiat", "nulla", "pariatur", "excepteur", "sint", "occaecat", "cupidatat", "non", "proident", "sunt", "in", "culpa", "qui", "officia", "deserunt", "mollit", "anim", "id", "est", "laborum", }; /// Pre-defined channels. pub const channels = [_][]const u8{ "#chess", "#future", "#games", "#movies", "#music", "#nature", "#news", "#study", }; /// Artificial local users. pub const local_bots = [_][]const u8{ "Abigail", "Albert", "Alice", "Anna", "Arthur", "Austin", "Bella", "Bobby", "Charlie", "Charlotte", "Clara", "Daisy", "Daniel", "David", "Eliza", "Ella", "Elliot", "Emma", "Ethan", "Finn", "George", "Hannah", "Harry", "Henry", "Holly", "Isabella", "Jack", "Jackson", "Jacob", "Jake", "James", "Jasmine", "Jessica", "John", "Joseph", "Lily", "Lucas", "Max", "Nathan", "Olivia", "Phoebe", "Sarah", "Scarlett", "Sophie", "Summer", "Tyler", "Violet", "William", "Zara", "Zoe", }; pub fn Range(comptime T: type) type { return struct { min: T, max: T, }; } /// Number of channels that a bot should try to be in. pub const bot_channels_target = Range(u8){ .min = 2, .max = 5 }; /// Probability that a bot leaves a channel at each tick. pub const bot_channels_leave_rate = Range(f32){ .min = 0.0005, .max = 0.0010 }; /// Number of sent messages per each tick in every joined channel. pub const bot_message_rate = Range(f32){ .min = 0.002, .max = 0.010 }; /// Average message length. pub const bot_message_length = Range(u8){ .min = 10, .max = 20 };
src/config.zig
const std = @import("std"); const zlm = @import("zlm"); const Vec3 = zlm.Vec3; const Allocator = std.mem.Allocator; const graphics = @import("didot-graphics"); const objects = @import("didot-objects"); const models = @import("didot-models"); const bmp = @import("didot-image").bmp; const obj = models.obj; const Application = @import("didot-app").Application; const Texture = graphics.Texture; const Input = graphics.Input; const Window = graphics.Window; const ShaderProgram = graphics.ShaderProgram; const Material = graphics.Material; const GameObject = objects.GameObject; const Scene = objects.Scene; const Camera = objects.Camera; const PointLight = objects.PointLight; var input: *Input = undefined; var airplane: ?*GameObject = undefined; fn cameraUpdate(allocator: *Allocator, gameObject: *GameObject, delta: f32) !void { if (airplane) |plane| { gameObject.position = plane.position.add(zlm.Vec3.new( -9.0, 3.0, 0.0, )); //gameObject.lookAt(plane.position, zlm.Vec3.new(0, 1, 0)); gameObject.rotation = zlm.Vec3.new(0, 0, -15).toRadians(); } } fn planeInput(allocator: *Allocator, gameObject: *GameObject, delta: f32) !void { const speed: f32 = 0.1 * delta; const forward = gameObject.getForward(); const left = gameObject.getLeft(); airplane = gameObject; // if (input.isMouseButtonDown(.Left)) { // input.setMouseInputMode(.Grabbed); // } else if (input.isKeyDown(Input.KEY_ESCAPE)) { // input.setMouseInputMode(.Normal); // } // if (input.getMouseInputMode() == .Grabbed) { // gameObject.rotation.x -= (input.mouseDelta.x / 300.0) * delta; // gameObject.rotation.y -= (input.mouseDelta.y / 300.0) * delta; // } if (input.getJoystick(0)) |joystick| { const axes = joystick.getRawAxes(); var fw = axes[1]; // forward var r = axes[0]; // right var thrust = (axes[3] - 1.0) * -0.5; const threshold = 0.2; if (r < threshold and r > 0) r = 0; if (r > -threshold and r < 0) r = 0; if (fw < threshold and fw > 0) fw = 0; if (fw > -threshold and fw < 0) fw = 0; gameObject.position = gameObject.position.add(forward.scale(thrust*speed)); gameObject.rotation.x -= (r / 50.0) * delta; gameObject.rotation.y -= (fw / 50.0) * delta; } } fn testLight(allocator: *Allocator, gameObject: *GameObject, delta: f32) !void { const time = @intToFloat(f64, std.time.milliTimestamp()); const rad = @floatCast(f32, @mod((time/1000.0), std.math.pi*2.0)); gameObject.position = Vec3.new(std.math.sin(rad)*10+5, 3, std.math.cos(rad)*10-10); } fn init(allocator: *Allocator, app: *Application) !void { input = &app.window.input; var shader = try ShaderProgram.create(@embedFile("vert.glsl"), @embedFile("frag.glsl")); const scene = app.scene; var grassImage = try bmp.read_bmp(allocator, "grass.bmp"); var texture = Texture.create2D(grassImage); grassImage.deinit(); // it's now uploaded to the GPU, so we can free the image. var grassMaterial = Material { .texture = texture }; var camera = try Camera.create(allocator, shader); camera.gameObject.position = Vec3.new(1.5, 1.5, -0.5); camera.gameObject.rotation = Vec3.new(-120.0, -15.0, 0).toRadians(); camera.gameObject.updateFn = cameraUpdate; try scene.add(camera.gameObject); var airplaneMesh = try obj.read_obj(allocator, "res/f15.obj"); var plane = GameObject.createObject(allocator, airplaneMesh); plane.position = Vec3.new(-1.2, 1.95, -3); plane.updateFn = planeInput; try scene.add(plane); // var light = try PointLight.create(allocator); // light.gameObject.position = Vec3.new(1, 5, -5); // light.gameObject.updateFn = testLight; // light.gameObject.mesh = objects.PrimitiveCubeMesh; // light.gameObject.material.ambient = Vec3.one; // try scene.add(light.gameObject); } var gp: std.heap.GeneralPurposeAllocator(.{}) = undefined; pub fn main() !void { gp = .{}; defer { _ = gp.deinit(); } const allocator = &gp.allocator; var scene = try Scene.create(allocator); var app = Application { .title = "Flight Test", .initFn = init }; try app.start(allocator, scene); }
examples/flight-test/flight-sim.zig
const ImageInStream = zigimg.ImageInStream; const ImageSeekStream = zigimg.ImageSeekStream; const PixelFormat = zigimg.PixelFormat; const assert = std.debug.assert; const color = zigimg.color; const errors = zigimg.errors; const pcx = zigimg.pcx; const std = @import("std"); const testing = std.testing; const zigimg = @import("zigimg"); usingnamespace @import("helpers.zig"); test "PCX bpp1 (linear)" { const file = try testOpenFile(testing.allocator, "tests/fixtures/pcx/test-bpp1.pcx"); defer file.close(); var fileInStream = file.inStream(); var fileSeekStream = file.seekableStream(); var pcxFile = pcx.PCX{}; const pixels = try pcxFile.read(testing.allocator, @ptrCast(*ImageInStream, &fileInStream.stream), @ptrCast(*ImageSeekStream, &fileSeekStream.stream)); defer pixels.deinit(testing.allocator); expectEq(pcxFile.width, 27); expectEq(pcxFile.height, 27); expectEq(pcxFile.pixel_format, PixelFormat.Bpp1); testing.expect(pixels == .Bpp1); expectEq(pixels.Bpp1.indices[0], 0); expectEq(pixels.Bpp1.indices[15], 1); expectEq(pixels.Bpp1.indices[18], 1); expectEq(pixels.Bpp1.indices[19], 1); expectEq(pixels.Bpp1.indices[20], 1); expectEq(pixels.Bpp1.indices[22 * 27 + 11], 1); expectEq(pixels.Bpp1.palette[0].R, 102); expectEq(pixels.Bpp1.palette[0].G, 90); expectEq(pixels.Bpp1.palette[0].B, 155); expectEq(pixels.Bpp1.palette[1].R, 115); expectEq(pixels.Bpp1.palette[1].G, 137); expectEq(pixels.Bpp1.palette[1].B, 106); } test "PCX bpp4 (linear)" { const file = try testOpenFile(testing.allocator, "tests/fixtures/pcx/test-bpp4.pcx"); defer file.close(); var fileInStream = file.inStream(); var fileSeekStream = file.seekableStream(); var pcxFile = pcx.PCX{}; const pixels = try pcxFile.read(testing.allocator, @ptrCast(*ImageInStream, &fileInStream.stream), @ptrCast(*ImageSeekStream, &fileSeekStream.stream)); defer pixels.deinit(testing.allocator); expectEq(pcxFile.width, 27); expectEq(pcxFile.height, 27); expectEq(pcxFile.pixel_format, PixelFormat.Bpp4); testing.expect(pixels == .Bpp4); expectEq(pixels.Bpp4.indices[0], 1); expectEq(pixels.Bpp4.indices[1], 9); expectEq(pixels.Bpp4.indices[2], 0); expectEq(pixels.Bpp4.indices[3], 0); expectEq(pixels.Bpp4.indices[4], 4); expectEq(pixels.Bpp4.indices[14 * 27 + 9], 6); expectEq(pixels.Bpp4.indices[25 * 27 + 25], 7); expectEq(pixels.Bpp4.palette[0].R, 0x5e); expectEq(pixels.Bpp4.palette[0].G, 0x37); expectEq(pixels.Bpp4.palette[0].B, 0x97); expectEq(pixels.Bpp4.palette[15].R, 0x60); expectEq(pixels.Bpp4.palette[15].G, 0xb5); expectEq(pixels.Bpp4.palette[15].B, 0x68); } test "PCX bpp8 (linear)" { const file = try testOpenFile(testing.allocator, "tests/fixtures/pcx/test-bpp8.pcx"); defer file.close(); var fileInStream = file.inStream(); var fileSeekStream = file.seekableStream(); var pcxFile = pcx.PCX{}; const pixels = try pcxFile.read(testing.allocator, @ptrCast(*ImageInStream, &fileInStream.stream), @ptrCast(*ImageSeekStream, &fileSeekStream.stream)); defer pixels.deinit(testing.allocator); expectEq(pcxFile.width, 27); expectEq(pcxFile.height, 27); expectEq(pcxFile.pixel_format, PixelFormat.Bpp8); testing.expect(pixels == .Bpp8); expectEq(pixels.Bpp8.indices[0], 37); expectEq(pixels.Bpp8.indices[3 * 27 + 15], 60); expectEq(pixels.Bpp8.indices[26 * 27 + 26], 254); expectEq(pixels.Bpp8.palette[0].R, 0x46); expectEq(pixels.Bpp8.palette[0].G, 0x1c); expectEq(pixels.Bpp8.palette[0].B, 0x71); expectEq(pixels.Bpp8.palette[15].R, 0x41); expectEq(pixels.Bpp8.palette[15].G, 0x49); expectEq(pixels.Bpp8.palette[15].B, 0x30); expectEq(pixels.Bpp8.palette[219].R, 0x61); expectEq(pixels.Bpp8.palette[219].G, 0x8e); expectEq(pixels.Bpp8.palette[219].B, 0xc3); } test "PCX bpp24 (planar)" { const file = try testOpenFile(testing.allocator, "tests/fixtures/pcx/test-bpp24.pcx"); defer file.close(); var fileInStream = file.inStream(); var fileSeekStream = file.seekableStream(); var pcxFile = pcx.PCX{}; const pixels = try pcxFile.read(testing.allocator, @ptrCast(*ImageInStream, &fileInStream.stream), @ptrCast(*ImageSeekStream, &fileSeekStream.stream)); defer pixels.deinit(testing.allocator); expectEq(pcxFile.header.planes, 3); expectEq(pcxFile.header.bpp, 8); expectEq(pcxFile.width, 27); expectEq(pcxFile.height, 27); expectEq(pcxFile.pixel_format, PixelFormat.Rgb24); testing.expect(pixels == .Rgb24); expectEq(pixels.Rgb24[0].R, 0x34); expectEq(pixels.Rgb24[0].G, 0x53); expectEq(pixels.Rgb24[0].B, 0x9f); expectEq(pixels.Rgb24[1].R, 0x32); expectEq(pixels.Rgb24[1].G, 0x5b); expectEq(pixels.Rgb24[1].B, 0x96); expectEq(pixels.Rgb24[26].R, 0xa8); expectEq(pixels.Rgb24[26].G, 0x5a); expectEq(pixels.Rgb24[26].B, 0x78); expectEq(pixels.Rgb24[27].R, 0x2e); expectEq(pixels.Rgb24[27].G, 0x54); expectEq(pixels.Rgb24[27].B, 0x99); expectEq(pixels.Rgb24[26 * 27 + 26].R, 0x88); expectEq(pixels.Rgb24[26 * 27 + 26].G, 0xb7); expectEq(pixels.Rgb24[26 * 27 + 26].B, 0x55); }
tests/pcx_test.zig
const std = @import("std"); const assert = std.debug.assert; const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const ExecError = error{ InvalidOpcode, InvalidParamMode, }; fn opcode(ins: i32) i32 { return @rem(ins, 100); } test "opcode extraction" { assert(opcode(1002) == 2); } fn paramMode(ins: i32, pos: i32) i32 { var div: i32 = 100; // Mode of parameter 0 is in digit 3 var i: i32 = 0; while (i < pos) : (i += 1) { div *= 10; } return @rem(@divTrunc(ins, div), 10); } test "param mode extraction" { assert(paramMode(1002, 0) == 0); assert(paramMode(1002, 1) == 1); assert(paramMode(1002, 2) == 0); } pub const Intcode = []i32; pub const IntcodeComputer = struct { mem: []i32, pc: usize, state: State, input: ?i32, output: ?i32, const Self = @This(); pub const State = enum { Stopped, Running, AwaitingInput, AwaitingOutput, }; pub fn init(intcode: []i32) Self { return Self{ .mem = intcode, .pc = 0, .state = State.Running, .input = null, .output = null, }; } fn getParam(self: Self, n: usize, mode: i32) !i32 { return switch (mode) { 0 => self.mem[@intCast(usize, self.mem[self.pc + 1 + n])], 1 => self.mem[self.pc + 1 + n], else => return error.InvalidParamMode, }; } pub fn exec(self: *Self) !void { const instr = self.mem[self.pc]; switch (opcode(instr)) { 99 => self.state = State.Stopped, 1 => { const val_x = try self.getParam(0, paramMode(instr, 0)); const val_y = try self.getParam(1, paramMode(instr, 1)); const pos_result = @intCast(usize, self.mem[self.pc + 3]); self.mem[pos_result] = val_x + val_y; self.pc += 4; }, 2 => { const val_x = try self.getParam(0, paramMode(instr, 0)); const val_y = try self.getParam(1, paramMode(instr, 1)); const pos_result = @intCast(usize, self.mem[self.pc + 3]); self.mem[pos_result] = val_x * val_y; self.pc += 4; }, 3 => { const pos_x = @intCast(usize, self.mem[self.pc + 1]); var buf: [1024]u8 = undefined; if (self.input) |val| { self.mem[pos_x] = val; self.pc += 2; self.input = null; } else { self.state = State.AwaitingInput; } }, 4 => { const val_x = try self.getParam(0, paramMode(instr, 0)); if (self.output) |_| { self.state = State.AwaitingOutput; } else { self.output = val_x; self.pc += 2; } }, 5 => { const val_x = try self.getParam(0, paramMode(instr, 0)); if (val_x != 0) { const val_y = try self.getParam(1, paramMode(instr, 1)); self.pc = @intCast(usize, val_y); } else { self.pc += 3; } }, 6 => { const val_x = try self.getParam(0, paramMode(instr, 0)); if (val_x == 0) { const val_y = try self.getParam(1, paramMode(instr, 1)); self.pc = @intCast(usize, val_y); } else { self.pc += 3; } }, 7 => { const val_x = try self.getParam(0, paramMode(instr, 0)); const val_y = try self.getParam(1, paramMode(instr, 1)); const pos_result = @intCast(usize, self.mem[self.pc + 3]); self.mem[pos_result] = if (val_x < val_y) 1 else 0; self.pc += 4; }, 8 => { const val_x = try self.getParam(0, paramMode(instr, 0)); const val_y = try self.getParam(1, paramMode(instr, 1)); const pos_result = @intCast(usize, self.mem[self.pc + 3]); self.mem[pos_result] = if (val_x == val_y) 1 else 0; self.pc += 4; }, else => { std.debug.warn("pos: {}, instr: {}\n", .{ self.pc, instr }); return error.InvalidOpcode; }, } } pub fn execUntilHalt(self: *Self) !void { // try to jump-start the computer if it was waiting for I/O if (self.state != State.Stopped) self.state = State.Running; while (self.state == State.Running) try self.exec(); } }; test "test exec 1" { var intcode = [_]i32{ 1, 0, 0, 0, 99 }; var comp = IntcodeComputer.init(&intcode); try comp.execUntilHalt(); assert(intcode[0] == 2); } test "test exec 2" { var intcode = [_]i32{ 2, 3, 0, 3, 99 }; var comp = IntcodeComputer.init(&intcode); try comp.execUntilHalt(); assert(intcode[3] == 6); } test "test exec 3" { var intcode = [_]i32{ 2, 4, 4, 5, 99, 0 }; var comp = IntcodeComputer.init(&intcode); try comp.execUntilHalt(); assert(intcode[5] == 9801); } test "test exec with different param mode" { var intcode = [_]i32{ 1002, 4, 3, 4, 33 }; var comp = IntcodeComputer.init(&intcode); try comp.execUntilHalt(); assert(intcode[4] == 99); } test "test exec with negative integers" { var intcode = [_]i32{ 1101, 100, -1, 4, 0 }; var comp = IntcodeComputer.init(&intcode); try comp.execUntilHalt(); assert(intcode[4] == 99); } test "test equal 1" { var intcode = [_]i32{ 3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8 }; var comp = IntcodeComputer.init(&intcode); comp.input = 8; try comp.execUntilHalt(); assert(comp.output.? == 1); } test "test equal 2" { var intcode = [_]i32{ 3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8 }; var comp = IntcodeComputer.init(&intcode); comp.input = 13; try comp.execUntilHalt(); assert(comp.output.? == 0); } test "test less than 1" { var intcode = [_]i32{ 3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8 }; var comp = IntcodeComputer.init(&intcode); comp.input = 5; try comp.execUntilHalt(); assert(comp.output.? == 1); } test "test less than 2" { var intcode = [_]i32{ 3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8 }; var comp = IntcodeComputer.init(&intcode); comp.input = 20; try comp.execUntilHalt(); assert(comp.output.? == 0); } test "test equal immediate" { var intcode = [_]i32{ 3, 3, 1108, -1, 8, 3, 4, 3, 99 }; var comp = IntcodeComputer.init(&intcode); comp.input = 8; try comp.execUntilHalt(); assert(comp.output.? == 1); } test "test less than immediate" { var intcode = [_]i32{ 3, 3, 1107, -1, 8, 3, 4, 3, 99 }; var comp = IntcodeComputer.init(&intcode); comp.input = 3; try comp.execUntilHalt(); assert(comp.output.? == 1); } fn runAmp(amp: *IntcodeComputer, phase: i32, input: i32) !i32 { amp.input = phase; try amp.execUntilHalt(); amp.input = input; try amp.execUntilHalt(); defer amp.output = null; return amp.output orelse error.NoOutput; } fn runAmpNoPhase(amp: *IntcodeComputer, input: i32) !i32 { amp.input = input; try amp.execUntilHalt(); defer amp.output = null; return amp.output orelse error.NoOutput; } fn runAmps(amps: []IntcodeComputer, phase_sequence: []i32) !i32 { var x: i32 = 0; for (amps) |*amp, i| { x = try runAmp(amp, phase_sequence[i], x); } while (amps[0].state != .Stopped) { for (amps) |*amp| { x = try runAmpNoPhase(amp, x); } } return x; } test "run amps" { const amp = [_]i32{ 3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0 }; var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); var amps: [5]IntcodeComputer = undefined; for (amps) |*a| { a.* = IntcodeComputer.init(try std.mem.dupe(allocator, i32, &amp)); } var phase_sequence = [_]i32{ 4, 3, 2, 1, 0 }; const expected: i32 = 43210; expectEqual(expected, try runAmps(&amps, &phase_sequence)); } test "run amps with feedback" { const amp = [_]i32{ 3, 26, 1001, 26, -4, 26, 3, 27, 1002, 27, 2, 27, 1, 27, 26, 27, 4, 27, 1001, 28, -1, 28, 1005, 28, 6, 99, 0, 0, 5, }; var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); var amps: [5]IntcodeComputer = undefined; for (amps) |*a| { a.* = IntcodeComputer.init(try std.mem.dupe(allocator, i32, &amp)); } var phase_sequence = [_]i32{ 9, 8, 7, 6, 5 }; const expected: i32 = 139629729; expectEqual(expected, try runAmps(&amps, &phase_sequence)); } const PermutationError = std.mem.Allocator.Error; fn permutations(comptime T: type, alloc: *Allocator, options: []T) PermutationError!ArrayList(ArrayList(T)) { var result = ArrayList(ArrayList(T)).init(alloc); if (options.len < 1) try result.append(ArrayList(T).init(alloc)); for (options) |opt, i| { var cp = try std.mem.dupe(alloc, T, options); var remaining = ArrayList(T).fromOwnedSlice(alloc, cp); _ = remaining.orderedRemove(i); for ((try permutations(T, alloc, remaining.items)).items) |*p| { try p.insert(0, opt); try result.append(p.*); } } return result; } test "empty permutation" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); var options = [_]u8{}; const perm = try permutations(u8, allocator, &options); assert(perm.items.len == 1); } test "permutation with 2 elements" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); var options = [_]u8{ 0, 1 }; const perm = try permutations(u8, allocator, &options); assert(perm.items.len == 2); } test "permutation with 4 elements" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); var options = [_]u8{ 0, 1, 2, 3 }; const perm = try permutations(u8, allocator, &options); assert(perm.items.len == 24); } fn findMaxOutput(alloc: *Allocator, amps_orig: []const Intcode) !i32 { // Duplicate the amps var amps = try alloc.alloc(IntcodeComputer, amps_orig.len); for (amps) |*a, i| { a.* = IntcodeComputer.init(try std.mem.dupe(alloc, i32, amps_orig[i])); } // free the duplicates later defer { for (amps) |a| alloc.free(a.mem); alloc.free(amps); } // Iterate through permutations var phases = [_]i32{ 5, 6, 7, 8, 9 }; var max_perm: ?[]i32 = null; var max_output: ?i32 = null; for ((try permutations(i32, alloc, &phases)).items) |perm| { // reset amps intcode for (amps) |*a, i| { std.mem.copy(i32, a.mem, amps_orig[i]); a.* = IntcodeComputer.init(a.mem); } // run const output = try runAmps(amps, perm.items); if (max_output) |max| { if (output > max) { max_perm = perm.items; max_output = output; } } else { max_perm = perm.items; max_output = output; } } return max_output orelse return error.NoPermutations; } test "max output 1" { const amp = [_]i32{ 3, 26, 1001, 26, -4, 26, 3, 27, 1002, 27, 2, 27, 1, 27, 26, 27, 4, 27, 1001, 28, -1, 28, 1005, 28, 6, 99, 0, 0, 5, }; var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); var amps: [5]Intcode = undefined; for (amps) |*a| { a.* = try std.mem.dupe(allocator, i32, &amp); } const output = try findMaxOutput(allocator, &amps); const expected_output: i32 = 139629729; expectEqual(expected_output, output); } test "max output 2" { const amp = [_]i32{ 3, 52, 1001, 52, -5, 52, 3, 53, 1, 52, 56, 54, 1007, 54, 5, 55, 1005, 55, 26, 1001, 54, -5, 54, 1105, 1, 12, 1, 53, 54, 53, 1008, 54, 0, 55, 1001, 55, 1, 55, 2, 53, 55, 53, 4, 53, 1001, 56, -1, 56, 1005, 56, 6, 99, 0, 0, 0, 0, 10, }; var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); var amps: [5]Intcode = undefined; for (amps) |*a| { a.* = try std.mem.dupe(allocator, i32, &amp); } const output = try findMaxOutput(allocator, &amps); const expected_output: i32 = 18216; expectEqual(expected_output, output); } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); const input_file = try std.fs.cwd().openFile("input07.txt", .{}); var input_stream = input_file.reader(); var buf: [1024]u8 = undefined; var ints = std.ArrayList(i32).init(allocator); // read amp intcode into an int arraylist while (try input_stream.readUntilDelimiterOrEof(&buf, ',')) |item| { // add an empty element to the input file because I don't want to modify // this to discard newlines try ints.append(std.fmt.parseInt(i32, item, 10) catch -1); } // duplicate amps 5 times var amps: [5]Intcode = undefined; for (amps) |*a| { a.* = try std.mem.dupe(allocator, i32, ints.items); } // try combinations of phase sequences std.debug.warn("max achievable output: {}\n", .{try findMaxOutput(allocator, &amps)}); }
zig/07_2.zig
const std = @import("std"); const grail = @import("grailsort.zig"); const testing = std.testing; const print = std.debug.print; const tracy = @import("tracy.zig"); var gpa_storage = std.heap.GeneralPurposeAllocator(.{}){}; const gpa = &gpa_storage.allocator; const verify_sorted = true; var test_words: []const [:0]const u8 = &[_][:0]const u8{}; pub fn main() void { tracy.InitThread(); tracy.SetThreadName("main"); readTestData(); doStringTests(); //doFloatTests(f64); //doFloatTests(f32); //doIntTests(u8); //doIntTests(u32); //doIntTests(u64); //doIntTests(i32); } fn doIntTests(comptime T: type) void { //doAllKeyCases("std.sort" , "unique", T, std.sort.sort, comptime std.sort.asc(T) , comptime doIntCast(T)); doAllKeyCases("grailsort", "unique", T, grail.sort , comptime std.sort.asc(T) , comptime doIntCast(T)); //doAllKeyCases("std.sort" , "x2" , T, std.sort.sort, comptime removeBits(T, 1), comptime doIntCast(T)); //doAllKeyCases("grailsort", "x2" , T, grail.sort , comptime removeBits(T, 1), comptime doIntCast(T)); //doAllKeyCases("std.sort" , "x8" , T, std.sort.sort, comptime removeBits(T, 3), comptime doIntCast(T)); //doAllKeyCases("grailsort", "x8" , T, grail.sort , comptime removeBits(T, 3), comptime doIntCast(T)); //doAllKeyCases("std.sort" , "x32" , T, std.sort.sort, comptime removeBits(T, 5), comptime doIntCast(T)); doAllKeyCases("grailsort", "x32" , T, grail.sort , comptime removeBits(T, 5), comptime doIntCast(T)); } fn doFloatTests(comptime T: type) void { //doAllKeyCases("std.sort" , "unique", T, std.sort.sort, comptime std.sort.asc(T) , comptime genFloats(T, 1)); doAllKeyCases("grailsort", "unique", T, grail.sort , comptime std.sort.asc(T) , comptime genFloats(T, 1)); //doAllKeyCases("std.sort" , "x2" , T, std.sort.sort, comptime std.sort.asc(T), comptime genFloats(T, 2)); //doAllKeyCases("grailsort", "x2" , T, grail.sort , comptime std.sort.asc(T), comptime genFloats(T, 2)); //doAllKeyCases("std.sort" , "x8" , T, std.sort.sort, comptime std.sort.asc(T), comptime genFloats(T, 8)); //doAllKeyCases("grailsort", "x8" , T, grail.sort , comptime std.sort.asc(T), comptime genFloats(T, 8)); //doAllKeyCases("std.sort" , "x32" , T, std.sort.sort, comptime std.sort.asc(T), comptime genFloats(T, 32)); doAllKeyCases("grailsort", "x32" , T, grail.sort , comptime std.sort.asc(T), comptime genFloats(T, 32)); } fn doStringTests() void { const gen = struct { pub fn lessSlice(_: void, lhs: []const u8, rhs: []const u8) bool { return std.mem.lessThan(u8, lhs, rhs); } pub fn sliceAt(idx: usize) []const u8 { return test_words[idx % test_words.len]; } pub fn lessPtr(_: void, lhs: [*:0]const u8, rhs: [*:0]const u8) bool { var a = lhs; var b = rhs; while (true) { if (a[0] != b[0]) return a[0] < b[0]; if (a[0] == 0) return false; a += 1; b += 1; } } pub fn ptrAt(idx: usize) [*:0]const u8 { return test_words[idx % test_words.len].ptr; } }; doAllKeyCases("grailsort", "unique", []const u8, grail.sort, gen.lessSlice, gen.sliceAt); doAllKeyCases("grailsort", "unique", [*:0]const u8, grail.sort, gen.lessPtr, gen.ptrAt); doAllKeyCases("grailsort", "x32", []const u8, grail.sort, gen.lessSlice, comptime repeat([]const u8, gen.sliceAt, 32)); doAllKeyCases("grailsort", "x32", [*:0]const u8, grail.sort, gen.lessPtr, comptime repeat([*:0]const u8, gen.ptrAt, 32)); } fn doAllKeyCases(comptime sort: []const u8, comptime benchmark: []const u8, comptime T: type, comptime sortFn: anytype, comptime lessThan: fn(void, T, T) bool, comptime fromInt: fn(usize) T) void { const ctx = tracy.ZoneN(@src(), sort ++ " " ++ @typeName(T) ++ " " ++ benchmark); defer ctx.End(); const max_len = 10_000_000; const array = gpa.alloc(T, max_len) catch unreachable; const golden = gpa.alloc(T, max_len) catch unreachable; defer gpa.free(array); defer gpa.free(golden); var extern_array = gpa.alloc(T, grail.findOptimalBufferLength(max_len)); var seed_rnd = std.rand.DefaultPrng.init(42); for (golden) |*v, i| v.* = fromInt(i); //checkSorted(T, golden, lessThan); print(" --------------- {: >9} {} {} ---------------- \n", .{sort, @typeName(T), benchmark}); print(" Items : ns / item | ms avg | ms max | ms min\n", .{}); var block_size: usize = 4; var array_len: usize = block_size * block_size + (block_size/2-1); while (array_len <= max_len) : ({block_size *= 2; array_len = block_size * block_size + (block_size/2-1);}) { for ([_]bool{true, false}) |randomized| { const len_zone = tracy.ZoneN(@src(), "len"); defer len_zone.End(); len_zone.Value(array_len); var runs = 10_000_000 / array_len; if (runs > 100) runs = 100; if (runs < 10) runs = 10; var run_rnd = std.rand.DefaultPrng.init(seed_rnd.random.int(u64)); tracy.PlotU("Array Size", array_len); var min_time: u64 = ~@as(u64, 0); var max_time: u64 = 0; var total_time: u64 = 0; var total_cycles: u64 = 0; var run_id: usize = 0; while (run_id < runs) : (run_id += 1) { const seed = run_rnd.random.int(u64); const part = array[0..array_len]; if (randomized) { setRandom(T, part, golden[0..array_len], seed); } else { std.mem.copy(T, part, golden[0..array_len]); } var time = std.time.Timer.start() catch unreachable; sortFn(T, part, {}, lessThan); const elapsed = time.read(); checkSorted(T, part, lessThan); if (elapsed < min_time) min_time = elapsed; if (elapsed > max_time) max_time = elapsed; total_time += elapsed; } const avg_time = total_time / runs; print("{: >9} : {d: >9.3} | {d: >9.3} | {d: >9.3} | {d: >9.3} | random={}\n", .{ array_len, @intToFloat(f64, avg_time) / @intToFloat(f64, array_len), millis(avg_time), millis(max_time), millis(min_time), randomized }); } } } fn millis(nanos: u64) f64 { return @intToFloat(f64, nanos) / 1_000_000.0; } fn checkSorted(comptime T: type, array: []T, comptime lessThan: fn(void, T, T) bool) void { if (verify_sorted) { for (array[1..]) |v, i| { testing.expect(!lessThan({}, v, array[i])); } } else { // clobber the memory asm volatile("" : : [g]"r"(array.ptr) : "memory"); } } fn setRandom(comptime T: type, array: []T, golden: []const T, seed: u64) void { std.mem.copy(T, array, golden); var rnd = std.rand.DefaultPrng.init(seed); rnd.random.shuffle(T, array); } fn doIntCast(comptime T: type) fn(usize) T { return struct { fn doCast(v: usize) T { if (T == u8) { return @truncate(T, v); } else { return @intCast(T, v); } } }.doCast; } fn genFloats(comptime T: type, comptime repeats: comptime_int) fn(usize) T { return struct { fn genFloat(v: usize) T { return @intToFloat(T, v / repeats); } }.genFloat; } fn repeat(comptime T: type, comptime inner: fn(usize)T, comptime repeats: comptime_int) fn(usize)T { return struct { inline fn gen(v: usize) T { return inner(v / repeats); } }.gen; } fn removeBits(comptime T: type, comptime bits: comptime_int) fn(void, T, T) bool { return struct { fn shiftLess(_: void, a: T, b: T) bool { return (a >> bits) < (b >> bits); } }.shiftLess; } /// This function converts a time in nanoseconds to /// the equivalent value that would have been returned /// from rdtsc to get that duration. fn nanosToCycles(nanos: u64) u64 { // The RDTSC instruction does not actually count // processor cycles or retired instructions. It // counts real time relative to an arbitrary clock. // The speed of this clock is hardware dependent. // You can find the values here: // https://github.com/torvalds/linux/blob/master/tools/power/x86/turbostat/turbostat.c#L5172-L5184 // (search for 24000000 if they have moved) // For the purposes of this function, we will // assume that we're running on a skylake processor or similar, // which updates at 24 MHz return nanos * 24 / 1000; } fn readTestData() void { const file = std.fs.cwd().openFile("data\\words.txt", .{}) catch unreachable; const bytes = file.readToEndAlloc(gpa, 10 * 1024 * 1024) catch unreachable; var words_array = std.ArrayList([:0]const u8).init(gpa); // don't free this list, we will keep pointers into it // for the entire lifetime of the program. var total_len: usize = 0; words_array.ensureCapacity(500_000) catch unreachable; var words = std.mem.tokenize(bytes, &[_]u8{ '\n', '\r', 0 }); while (words.next()) |word| { // the file must end with a newline, or this won't work. const mut_word = @intToPtr([*]u8, @ptrToInt(word.ptr)); mut_word[word.len] = 0; total_len += word.len; words_array.append(mut_word[0..word.len :0]) catch unreachable; } // save the slice to our test list. test_words = words_array.toOwnedSlice(); print("avg word len: {}\n", .{@intToFloat(f64, total_len) / @intToFloat(f64, test_words.len)}); }
src/benchmark.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const print = std.debug.print; const data = @embedFile("../data/day02.txt"); const Verb = enum { Forward, Down, Up, }; const Command = struct { verb: Verb, amount: u32, pub fn from(line: []const u8) !Command { var splitter = std.mem.tokenize(line, " "); var verbString = splitter.next().?; var amountString = splitter.next().?; var verb = switch (verbString[0]) { 'f' => Verb.Forward, 'd' => Verb.Down, 'u' => Verb.Up, else => @panic("Oops! Wrong verb?"), }; var amount = try std.fmt.parseUnsigned(u32, amountString, 10); return Command{ .verb = verb, .amount = amount, }; } }; fn part1() !void { var lineTokenizer = std.mem.tokenize(data, "\r\n"); var horizontal: u32 = 0; var depth: u32 = 0; while (lineTokenizer.next()) |line| { var command = try Command.from(line); switch (command.verb) { .Forward => horizontal += command.amount, .Down => depth += command.amount, .Up => depth -= command.amount, } } print("Part1: Horizontal: {d}, vertical: {d} => Product: {d}\n", .{ horizontal, depth, horizontal * depth }); } fn part2() !void { var lineTokenizer = std.mem.tokenize(data, "\r\n"); var aim: u32 = 0; var horizontal: u32 = 0; var depth: u32 = 0; while (lineTokenizer.next()) |line| { var command = try Command.from(line); switch (command.verb) { .Forward => { horizontal += command.amount; depth += command.amount * aim; }, .Down => aim += command.amount, .Up => aim -= command.amount, } } print("Part2: Horizontal: {d}, vertical: {d} => Product: {d}\n", .{ horizontal, depth, horizontal * depth }); } pub fn main() !void { try part1(); try part2(); }
src/day02.zig
pub const ArrayError = error{CapacityError}; pub fn ArrayVec(comptime T: type, comptime SIZE: usize) type { return struct { array: [SIZE]T, length: usize, const Self = @This(); fn set_len(self: *Self, new_len: usize) void { self.length = new_len; } /// Returns a new, empty ArrayVec. pub fn new() Self { return Self{ .array = undefined, .length = @as(usize, 0), }; } /// Returns the length of the ArrayVec pub fn len(self: *const Self) usize { return self.length; } /// Returns the capacity of the ArrayVec pub fn capacity(self: *const Self) usize { return SIZE; } /// Returns a boolean indicating whether /// the ArrayVec is full pub fn isFull(self: *const Self) bool { return self.len() == self.capacity(); } /// Returns a boolean indicating whether /// the ArrayVec is empty pub fn isEmpty(self: *const Self) bool { return self.len() == 0; } /// Returns the remaing capacity of the ArrayVec. /// This is the number of elements remaing untill /// the ArrayVec is full. pub fn remainingCapacity(self: *const Self) usize { return self.capacity() - self.len(); } /// Returns a const slice to the underlying memory pub fn asConstSlice(self: *const Self) []const T { return self.array[0..self.len()]; } /// Returns a (mutable) slice to the underlying /// memory. pub fn asSlice(self: *Self) []T { return self.array[0..self.len()]; } /// Truncates the ArrayVec to the new length. It is /// the programmers responsability to deallocate any /// truncated elements if nessecary. /// Notice that truncate is lazy, and doesn't touch /// any truncated elements. pub fn truncate(self: *Self, new_len: usize) void { if (new_len < self.len()) { self.set_len(new_len); } } /// Clears the entire ArrayVec. It is /// the programmers responsability to deallocate the /// cleared items if nessecary. /// Notice that clear is lazy, and doesn't touch any /// cleared items. pub fn clear(self: *Self) void { self.truncate(0); } pub fn push(self: *Self, element: T) !void { if (self.len() < self.capacity()) { self.push_unchecked(element); } else { return ArrayError.CapacityError; } } pub fn push_unchecked(self: *Self, element: T) void { @setRuntimeSafety(false); const self_len = self.len(); self.array[self_len] = element; self.set_len(self_len + 1); } pub fn pop(self: *Self) ?T { if (!self.isEmpty()) { return self.pop_unchecked(); } else { return null; } } pub fn pop_unchecked(self: *Self) T { @setRuntimeSafety(false); const new_len = self.len() - 1; self.set_len(new_len); return self.array[new_len]; } pub fn extend_from_slice(self: *Self, other: []const T) !void { if (self.remainingCapacity() >= other.len) { self.extend_from_slice_unchecked(other); } else { return ArrayError.CapacityError; } } pub fn extend_from_slice_unchecked(self: *Self, other: []const T) void { @setRuntimeSafety(false); const mem = @import("std").mem; mem.copy(T, self.array[self.length..], other); self.set_len(self.length + other.len); } }; } const testing = if (@import("builtin").is_test) struct { fn expectEqual(x: anytype, y: anytype) void { @import("std").debug.assert(x == y); } } else void; test "test new" { comptime { var array = ArrayVec(i32, 10).new(); } } test "test len, cap, empty" { const CAP: usize = 20; comptime { var array = ArrayVec(i32, CAP).new(); testing.expectEqual(array.isEmpty(), true); testing.expectEqual(array.len(), 0); testing.expectEqual(array.capacity(), CAP); testing.expectEqual(array.remainingCapacity(), CAP); } } test "try push" { const CAP: usize = 10; comptime { var array = ArrayVec(i32, CAP).new(); comptime var i = 0; inline while (i < CAP) { i += 1; try array.push(i); testing.expectEqual(array.len(), i); testing.expectEqual(array.remainingCapacity(), CAP - i); } testing.expectEqual(array.isFull(), true); } } test "try pop" { const CAP: usize = 10; comptime { var array = ArrayVec(i32, CAP).new(); comptime var i = 0; { inline while (i < CAP) { i += 1; try array.push(i); defer if (array.pop()) |elem| testing.expectEqual(elem, i) else @panic("Failed to pop"); } } testing.expectEqual(array.isEmpty(), true); } } test "extend from slice" { const CAP: usize = 10; const SLICE = &[_]i32{ 1, 2, 3, 4, 5, 6 }; comptime { var array = ArrayVec(i32, CAP).new(); try array.extend_from_slice(SLICE); testing.expectEqual(array.len(), SLICE.len); for (array.asConstSlice()) |elem, idx| { testing.expectEqual(elem, SLICE[idx]); } } }
src/array.zig
pub const uart = @import("hw/uart.zig"); pub const psci = @import("hw/psci.zig"); pub const entry_uart = @import("hw/entry_uart.zig"); pub const syscon = @import("hw/syscon.zig"); const std = @import("std"); const fb = @import("console/fb.zig"); const printf = fb.printf; const dtblib = @import("dtb"); const SysconConf = struct { regmap: void = {}, // XXX we need to use the full DTB parser here folks. phandle. assume 0x100000 (~+0x1000) for now value: ?u32 = null, offset: ?u32 = null, }; pub fn init(dtb: []const u8) !void { printf("dtb at {*:0>16} (0x{x} bytes)\n", .{ dtb.ptr, dtb.len }); var traverser: dtblib.Traverser = undefined; try traverser.init(dtb); var depth: usize = 1; var compatible: enum { Unknown, Psci, Syscon, SysconReboot, SysconPoweroff } = .Unknown; var address_cells: ?u32 = null; var psci_method: ?[]const u8 = null; var reg: ?[]const u8 = null; var syscon_conf: SysconConf = .{}; var ev = try traverser.next(); while (ev != .End) : (ev = try traverser.next()) { switch (ev) { .BeginNode => { depth += 1; }, .EndNode => { depth -= 1; defer { compatible = .Unknown; psci_method = null; reg = null; syscon_conf = .{}; } if (compatible == .Psci and psci_method != null) { if (std.mem.eql(u8, psci_method.?, "hvc\x00")) { psci.method = .Hvc; continue; } else if (std.mem.eql(u8, psci_method.?, "smc\x00")) { psci.method = .Smc; continue; } else { printf("unknown psci method: {s}\n", .{psci_method.?}); continue; } } switch (compatible) { .Syscon => { syscon.init(readCells(address_cells orelse continue, reg orelse continue)); continue; }, .SysconReboot => { const value = syscon_conf.value orelse continue; const offset = syscon_conf.offset orelse continue; syscon.initReboot(offset, value); continue; }, .SysconPoweroff => { const value = syscon_conf.value orelse continue; const offset = syscon_conf.offset orelse continue; syscon.initPoweroff(offset, value); continue; }, else => {}, } }, .Prop => |prop| { if (compatible == .Unknown and std.mem.eql(u8, prop.name, "compatible")) { if (std.mem.indexOf(u8, prop.value, "arm,psci") != null) { compatible = .Psci; } else if (std.mem.indexOf(u8, prop.value, "syscon\x00") != null) { compatible = .Syscon; } else if (std.mem.indexOf(u8, prop.value, "syscon-poweroff\x00") != null) { compatible = .SysconPoweroff; } else if (std.mem.indexOf(u8, prop.value, "syscon-reboot\x00") != null) { compatible = .SysconReboot; } } else if (std.mem.eql(u8, prop.name, "#address-cells")) { if (address_cells == null) { address_cells = readU32(prop.value); } } else if (std.mem.eql(u8, prop.name, "reg")) { reg = prop.value; } else if (std.mem.eql(u8, prop.name, "method")) { psci_method = prop.value; } else if (std.mem.eql(u8, prop.name, "value")) { syscon_conf.value = readU32(prop.value); } else if (std.mem.eql(u8, prop.name, "offset")) { syscon_conf.offset = readU32(prop.value); } }, .End => {}, } } } // XXX these things are copied everywhere lol fn readU32(value: []const u8) u32 { return std.mem.bigToNative(u32, @ptrCast(*const u32, @alignCast(@alignOf(u32), value.ptr)).*); } fn readU64(value: []const u8) u64 { return (@as(u64, readU32(value[0..4])) << 32) | readU32(value[4..8]); } fn readCells(cell_count: u32, value: []const u8) u64 { if (cell_count == 1) { if (value.len < @sizeOf(u32)) @panic("readCells: cell_count = 1, bad len"); return readU32(value); } if (cell_count == 2) { if (value.len < @sizeOf(u64)) @panic("readCells: cell_count = 2, bad len"); return readU64(value); } @panic("readCells: cell_count unk"); }
dainkrnl/src/hw.zig
const std = @import("std"); const gl = @import("zgl"); const glfw = @import("glfw"); const nvg = @import("nanovg"); /// An unsigned int that can be losslessly converted to an f32 pub const I = u24; /// A 2-vector of unsigned integers that can be losslessly converted to f32 pub const Vec2 = std.meta.Vector(2, I); /// A 2-vector of optional unsigned integers that can be losslessly converted to f32 pub const OptVec2 = [2]?I; /// A layout direction (row or column) pub const Direction = enum { row, col }; /// Root window pub const Window = struct { child: *Widget, size: Vec2, win: glfw.Window, ctx: *nvg.Context, pub fn init(title: [*:0]const u8, size: Vec2, child: *Widget) !Window { const win = try glfw.Window.create(size[0], size[1], title, null, null, .{ .context_version_major = 3, .context_version_minor = 3, .opengl_profile = .opengl_core_profile, }); errdefer win.destroy(); try glfw.makeContextCurrent(win); const ctx = nvg.Context.createGl3(.{}); errdefer ctx.deleteGl3(); return Window{ .child = child, .size = size, .win = win, .ctx = ctx, }; } pub fn deinit(self: *Window) void { try glfw.makeContextCurrent(win); self.ctx.deleteGl3(); self.win.destroy(); } pub fn draw(self: *Window) !void { try glfw.makeContextCurrent(self.win); const fb_size = try self.win.getFramebufferSize(); gl.viewport(0, 0, fb_size.width, fb_size.height); gl.clearColor(0, 0, 0, 0); gl.clear(.{ .color = true }); self.ctx.beginFrame( @intToFloat(f32, self.size[0]), @intToFloat(f32, self.size[1]), @intToFloat(f32, fb_size.width) / @intToFloat(f32, self.size[0]), ); // Offset by 1 here because nvg doesn't render pixels at 0 coords self.child.draw(self.ctx, .{ 1, 1 }); self.ctx.endFrame(); try self.win.swapBuffers(); } pub fn layout(self: *Window) void { // TODO: do this with a callback instead of every frame if (self.win.getSize()) |size| { self.size = .{ @intCast(I, size.width), @intCast(I, size.height), }; } else |_| {} self.child.pos = .{ 0, 0 }; self.child.layoutMin(); // Subtract 1 here because nvg doesn't render pixels at 0 coords self.child.layoutFull(self.size - Vec2{ 1, 1 }); } }; /// Generic widget interface for layout, input, and rendering pub const Widget = struct { /// Widget position relative to parent pos: Vec2 = Vec2{ 0, 0 }, /// Widget size size: Vec2 = Vec2{ 0, 0 }, min_size: OptVec2 = .{ null, null }, max_size: OptVec2 = .{ null, null }, /// How much to grow compared to siblings. 0 = no growth /// 360 is a highly composite number; good for lots of nice ratios growth: u16 = 360, /// Whether or not to fill the box in the cross direction expand: bool = true, funcs: struct { draw: fn (*Widget, *nvg.Context, offset: Vec2) void, layoutMin: fn (*Widget) void, layoutFull: fn (*Widget, container_size: Vec2) void, }, fn draw(self: *Widget, ctx: *nvg.Context, offset: Vec2) void { self.funcs.draw(self, ctx, offset); } fn layoutMin(self: *Widget) void { self.funcs.layoutMin(self); self.size = clamp(self.size, self.min_size, self.max_size); } fn layoutFull(self: *Widget, container_size: Vec2) void { self.funcs.layoutFull(self, container_size); self.size = clamp(self.size, self.min_size, self.max_size); } }; fn clamp(vec: Vec2, min: OptVec2, max: OptVec2) Vec2 { const min_v = Vec2{ min[0] orelse 0, min[1] orelse 0, }; const max_i = std.math.maxInt(I); const max_v = Vec2{ max[0] orelse max_i, max[1] orelse max_i, }; return @maximum(@minimum(vec, max_v), min_v); } /// A nested box for layout purposes pub const Box = struct { w: Widget = .{ .funcs = .{ .draw = draw, .layoutMin = layoutMin, .layoutFull = layoutFull, } }, /// Direction in which to layout children direction: Direction = .row, children: std.ArrayListUnmanaged(Child) = .{}, const Child = struct { w: *Widget, new_size: Vec2 = undefined, new_clamped: Vec2 = undefined, frozen: bool = false, }; pub fn init(opts: anytype) Box { var self = Box{}; inline for (comptime std.meta.fieldNames(@TypeOf(opts))) |field| { if (comptime std.mem.eql(u8, field, "direction")) { self.direction = opts.direction; } else { @field(self.w, field) = @field(opts, field); } } return self; } fn layoutMin(widget: *Widget) void { const self = @fieldParentPtr(Box, "w", widget); const dim = @enumToInt(self.direction); self.w.size = .{ 0, 0 }; for (self.children.items) |child| { child.w.layoutMin(); self.w.size[dim] += child.w.size[dim]; } } fn layoutFull(widget: *Widget, total: Vec2) void { const self = @fieldParentPtr(Box, "w", widget); const dim = @enumToInt(self.direction); while (true) { var extra = total[dim]; var total_growth: I = 0; for (self.children.items) |child| { if (child.frozen) { extra -|= child.new_clamped[dim]; } else { extra -|= child.w.size[dim]; total_growth += child.w.growth; } } var violation: i25 = 0; for (self.children.items) |*child| { if (child.frozen) continue; child.new_size = child.w.size; if (total_growth > 0 and child.w.growth > 0) { child.new_size[dim] += extra * child.w.growth / total_growth; } child.new_clamped = clamp(child.new_size, child.w.min_size, child.w.max_size); violation += @as(i25, child.new_clamped[dim]) - child.new_size[dim]; } const vord = std.math.order(violation, 0); if (vord == .eq) break; var all_frozen = true; for (self.children.items) |*child| { if (child.frozen) continue; const child_violation = @as(i25, child.new_clamped[dim]) - child.new_size[dim]; const cvord = std.math.order(child_violation, 0); if (cvord == vord) { child.frozen = true; } else { all_frozen = false; } } if (all_frozen) break; } var pos = Vec2{ 0, 0 }; for (self.children.items) |*child| { child.frozen = false; if (child.w.expand) { child.new_size[1 - dim] = @maximum(child.new_size[1 - dim], total[1 - dim]); } child.w.pos = pos; child.w.layoutFull(child.new_size); pos[dim] += child.w.size[dim]; } self.w.size = @maximum(self.w.size, total); self.w.size = clamp(self.w.size, self.w.min_size, self.w.max_size); } pub fn addChild(self: *Box, allocator: std.mem.Allocator, child: *Widget) !void { try self.children.append(allocator, .{ .w = child }); } fn draw(widget: *Widget, ctx: *nvg.Context, offset: Vec2) void { const self = @fieldParentPtr(Box, "w", widget); var rng = std.rand.DefaultPrng.init(@ptrToInt(self)); var color = randRgb(rng.random(), 0.05); ctx.beginPath(); ctx.roundedRect( @intToFloat(f32, self.w.pos[0] + offset[0]), @intToFloat(f32, self.w.pos[1] + offset[1]), @intToFloat(f32, self.w.size[0]), @intToFloat(f32, self.w.size[1]), 40, ); ctx.fillColor(color); ctx.fill(); color.a = 1.0; ctx.strokeColor(color); ctx.strokeWidth(4); ctx.stroke(); for (self.children.items) |child| { child.w.draw(ctx, offset + self.w.pos); } } fn randRgb(rand: std.rand.Random, alpha: f32) nvg.Color { var vec = std.meta.Vector(3, f32){ rand.floatNorm(f32), rand.floatNorm(f32), rand.floatNorm(f32), }; vec = @fabs(vec); const fac = 1 / @reduce(.Max, vec); vec *= @splat(3, fac); return nvg.Color.rgbaf(vec[0], vec[1], vec[2], alpha); } };
src/ui.zig
const std = @import("std"); /// State transition errors pub const StateError = error{ /// Invalid transition Invalid, /// A state transition was canceled Canceled, /// A trigger or state transition has already been defined AlreadyDefined, }; /// Transition handlers must return whether the transition should complete or be canceled. /// This can be used for state transition guards, as well as logging and debugging. pub const HandlerResult = enum { /// Continue with the transition Continue, /// Cancel the transition by returning StateError.Canceled Cancel, /// Cancel the transition without error CancelNoError, }; /// A transition, and optional trigger pub fn Transition(comptime StateType: type, comptime TriggerType: ?type) type { return struct { trigger: if (TriggerType) |T| ?T else ?void = null, from: StateType, to: StateType, }; } /// Construct a state machine type given a state enum and an optional trigger enum. /// Add states and triggers using the member functions. pub fn StateMachine(comptime StateType: type, comptime TriggerType: ?type, initial_state: StateType) type { return StateMachineFromTable(StateType, TriggerType, &[0]Transition(StateType, TriggerType){}, initial_state, &[0]StateType{}); } /// Construct a state machine type given a state enum, an optional trigger enum, a transition table, initial state and end states (which can be empty) /// If you want to add transitions and end states using the member methods, you can use `StateMachine(...)` as a shorthand. pub fn StateMachineFromTable(comptime StateType: type, comptime TriggerType: ?type, transitions: []const Transition(StateType, TriggerType), initial_state: StateType, final_states: []const StateType) type { const StateTriggerSelector = enum { state, trigger }; const TriggerTypeArg = if (TriggerType) |T| T else void; const StateTriggerUnion = union(StateTriggerSelector) { state: StateType, trigger: if (TriggerType) |T| T else void, }; const state_type_count = comptime std.meta.fields(StateType).len; const trigger_type_count = comptime if (TriggerType) |T| std.meta.fields(T).len else 0; const TransitionBitSet = std.StaticBitSet(state_type_count * state_type_count); const state_enum_bits = std.math.log2_int_ceil(usize, state_type_count); const trigger_enum_bits = if (trigger_type_count > 0) std.math.log2_int_ceil(usize, trigger_type_count) else 0; // Add 1 to bit_count because zero is used to indicates absence of transition (no target state defined for a source state/trigger combination) // Cell values must thus be adjusted accordingly when added or queried. const CellType = std.meta.Int(.unsigned, std.math.max(state_enum_bits, trigger_enum_bits) + 1); const TriggerPackedIntArray = if (TriggerType != null) std.PackedIntArray(CellType, state_type_count * std.math.max(trigger_type_count, 1)) else void; const FinalStatesType = std.StaticBitSet(state_type_count); return struct { internal: struct { start_state: StateType, current_state: StateType, state_map: TransitionBitSet, final_states: FinalStatesType, transition_handlers: []*Handler, triggers: TriggerPackedIntArray, } = undefined, pub const StateEnum = StateType; pub const TriggerEnum = if (TriggerType) |T| T else void; const Self = @This(); /// Transition handler interface pub const Handler = struct { onTransition: fn (self: *Handler, trigger: ?TriggerTypeArg, from: StateType, to: StateType) HandlerResult, }; /// Returns a new state machine instance pub fn init() Self { var instance: Self = .{}; instance.internal.start_state = initial_state; instance.internal.current_state = initial_state; instance.internal.final_states = FinalStatesType.initEmpty(); instance.internal.transition_handlers = &.{}; instance.internal.state_map = TransitionBitSet.initEmpty(); if (comptime TriggerType != null) instance.internal.triggers = TriggerPackedIntArray.initAllTo(0); for (transitions) |t| { var offset = (@enumToInt(t.from) * state_type_count) + @enumToInt(t.to); instance.internal.state_map.setValue(offset, true); if (comptime TriggerType != null) { if (t.trigger) |trigger| { const slot = computeTriggerSlot(trigger, t.from); instance.internal.triggers.set(slot, @enumToInt(t.to) + @as(CellType, 1)); } } } for (final_states) |f| { instance.internal.final_states.setValue(@enumToInt(f), true); } return instance; } /// Returns the current state pub fn currentState(self: *Self) StateType { return self.internal.current_state; } /// Sets the start state. This becomes the new `currentState()`. pub fn setStartState(self: *Self, start_state: StateType) void { self.internal.start_state = start_state; self.internal.current_state = start_state; } /// Unconditionally restart the state machine. /// This sets the current state back to the initial start state. pub fn restart(self: *Self) void { self.internal.current_state = self.internal.start_state; } /// Same as `restart` but fails if the state machine is currently neither in a final state, /// nor in the initial start state. pub fn safeRestart(self: *Self) StateError!void { if (!self.isInFinalState() and !self.isInStartState()) return StateError.Invalid; self.internal.current_state = self.internal.start_state; } /// Returns true if the current state is the start state pub fn isInStartState(self: *Self) bool { return self.internal.current_state == self.internal.start_state; } /// Final states are optional. Note that it's possible, and common, for transitions /// to exit final states during execution. It's up to the library user to check for /// any final state conditions, using `isInFinalState()` or comparing with `currentState()` /// Returns `StateError.Invalid` if the final state is already added. pub fn addFinalState(self: *Self, final_state: StateType) !void { if (self.isFinalState(final_state)) return StateError.Invalid; self.internal.final_states.setValue(@enumToInt(final_state), true); } /// Returns true if the state machine is in a final state pub fn isInFinalState(self: *Self) bool { return self.internal.final_states.isSet(@enumToInt(self.currentState())); } /// Returns true if the argument is a final state pub fn isFinalState(self: *Self, state: StateType) bool { return self.internal.final_states.isSet(@enumToInt(state)); } /// Invoke all `handlers` when a state transition happens pub fn setTransitionHandlers(self: *Self, handlers: []*Handler) void { self.internal.transition_handlers = handlers; } /// Add the transition `from` -> `to` if missing, and define a trigger for the transition pub fn addTriggerAndTransition(self: *Self, trigger: TriggerTypeArg, from: StateType, to: StateType) !void { if (comptime TriggerType != null) { if (!self.canTransitionFromTo(from, to)) try self.addTransition(from, to); try self.addTrigger(trigger, from, to); } } fn computeTriggerSlot(trigger: TriggerTypeArg, from: StateType) usize { return @intCast(usize, @enumToInt(from)) * trigger_type_count + @enumToInt(trigger); } /// Check if the transition `from` -> `to` is valid and add the trigger for this transition pub fn addTrigger(self: *Self, trigger: TriggerTypeArg, from: StateType, to: StateType) !void { if (comptime TriggerType != null) { if (self.canTransitionFromTo(from, to)) { var slot = computeTriggerSlot(trigger, from); if (self.internal.triggers.get(slot) != 0) return StateError.AlreadyDefined; self.internal.triggers.set(slot, @intCast(CellType, @enumToInt(to)) + 1); } else return StateError.Invalid; } } /// Trigger a transition /// Returns `StateError.Invalid` if the trigger is not defined for the current state pub fn activateTrigger(self: *Self, trigger: TriggerTypeArg) !void { if (comptime TriggerType != null) { var slot = computeTriggerSlot(trigger, self.internal.current_state); var to_state = self.internal.triggers.get(slot); if (to_state != 0) { try self.transitionToInternal(trigger, @intToEnum(StateType, to_state - 1)); } else { return StateError.Invalid; } } } /// Add a valid state transition /// Returns `StateError.AlreadyDefined` if the transition is already defined pub fn addTransition(self: *Self, from: StateType, to: StateType) !void { const offset: usize = (@intCast(usize, @enumToInt(from)) * state_type_count) + @enumToInt(to); if (self.internal.state_map.isSet(offset)) return StateError.AlreadyDefined; self.internal.state_map.setValue(offset, true); } /// Returns true if the current state is equal to `requested_state` pub fn isCurrently(self: *Self, requested_state: StateType) bool { return self.internal.current_state == requested_state; } /// Returns true if the transition is possible pub fn canTransitionTo(self: *Self, new_state: StateType) bool { const offset: usize = (@intCast(usize, @enumToInt(self.currentState())) * state_type_count) + @enumToInt(new_state); return self.internal.state_map.isSet(offset); } /// Returns true if the transition `from` -> `to` is possible pub fn canTransitionFromTo(self: *Self, from: StateType, to: StateType) bool { const offset: usize = (@intCast(usize, @enumToInt(from)) * state_type_count) + @enumToInt(to); return self.internal.state_map.isSet(offset); } /// If possible, transition from current state to `new_state` /// Returns `StateError.Invalid` if the transition is not allowed pub fn transitionTo(self: *Self, new_state: StateType) StateError!void { return self.transitionToInternal(null, new_state); } fn transitionToInternal(self: *Self, trigger: ?TriggerTypeArg, new_state: StateType) StateError!void { if (!self.canTransitionTo(new_state)) { return StateError.Invalid; } for (self.internal.transition_handlers) |handler| { switch (handler.onTransition(handler, trigger, self.currentState(), new_state)) { .Cancel => return StateError.Canceled, .CancelNoError => return, else => {}, } } self.internal.current_state = new_state; } /// Transition initiated by state or trigger /// Returns `StateError.Invalid` if the transition is not allowed pub fn apply(self: *Self, state_or_trigger: StateTriggerUnion) !void { if (state_or_trigger == StateTriggerSelector.state) { try self.transitionTo(state_or_trigger.state); } else if (TriggerType) |_| { try self.activateTrigger(state_or_trigger.trigger); } } /// An iterator that returns the next possible states pub const PossibleNextStateIterator = struct { fsm: *Self, index: usize = 0, /// Next valid state, or null if no more valid states are available pub fn next(self: *@This()) ?StateEnum { inline for (std.meta.fields(StateType)) |field, i| { if (i == self.index) { self.index += 1; if (self.fsm.canTransitionTo(@intToEnum(StateType, field.value))) { return @intToEnum(StateType, field.value); } } } return null; } /// Restarts the iterator pub fn reset(self: *@This()) void { self.index = 0; } }; /// Returns an iterator for the next possible states from the current state pub fn validNextStatesIterator(self: *Self) PossibleNextStateIterator { return .{ .fsm = self }; } /// Graphviz export options pub const ExportOptions = struct { rankdir: []const u8 = "LR", layout: ?[]const u8 = null, shape: []const u8 = "circle", shape_final_state: []const u8 = "doublecircle", fixed_shape_size: bool = false, show_triggers: bool = true, show_initial_state: bool = false, }; /// Exports a Graphviz directed graph to the given writer pub fn exportGraphviz(self: *Self, title: []const u8, writer: anytype, options: ExportOptions) !void { try writer.print("digraph {s} {{\n", .{title}); try writer.print(" rankdir=LR;\n", .{}); if (options.layout) |layout| try writer.print(" layout={s};\n", .{layout}); if (options.show_initial_state) try writer.print(" node [shape = point ]; \"start:\";\n", .{}); // Style for final states if (self.internal.final_states.count() > 0) { try writer.print(" node [shape = {s} fixedsize = {}];", .{ options.shape_final_state, options.fixed_shape_size }); var final_it = self.internal.final_states.iterator(.{ .kind = .set, .direction = .forward }); while (final_it.next()) |index| { try writer.print(" \"{s}\" ", .{@tagName(@intToEnum(StateType, index))}); } try writer.print(";\n", .{}); } // Default style try writer.print(" node [shape = {s} fixedsize = {}];\n", .{ options.shape, options.fixed_shape_size }); if (options.show_initial_state) { try writer.print(" \"start:\" -> \"{s}\";\n", .{@tagName(self.internal.start_state)}); } var it = self.internal.state_map.iterator(.{ .kind = .set, .direction = .forward }); while (it.next()) |index| { const from = @intToEnum(StateType, index / state_type_count); const to = @intToEnum(StateType, index % state_type_count); try writer.print(" \"{s}\" -> \"{s}\"", .{ @tagName(from), @tagName(to) }); if (TriggerType) |T| { if (options.show_triggers) { var triggers_start_offset = @intCast(usize, @enumToInt(from)) * trigger_type_count; var transition_name_buf: [4096]u8 = undefined; var transition_name = std.io.fixedBufferStream(&transition_name_buf); var trigger_index: usize = 0; while (trigger_index < trigger_type_count) : (trigger_index += 1) { const slot_val = self.internal.triggers.get(triggers_start_offset + trigger_index); if (slot_val > 0 and (slot_val - 1) == @enumToInt(to)) { if ((try transition_name.getPos()) == 0) { try writer.print(" [label = \"", .{}); } if ((try transition_name.getPos()) > 0) { try transition_name.writer().print(" || ", .{}); } try transition_name.writer().print("{s}", .{@tagName(@intToEnum(T, trigger_index))}); } } if ((try transition_name.getPos()) > 0) { try writer.print("{s}\"]", .{transition_name.getWritten()}); } } } try writer.print(";\n", .{}); } try writer.print("}}\n", .{}); } /// Reads a state machine from a buffer containing Graphviz or libfsm text. /// Any currently existing transitions are preserved. /// Parsing is supported at both comptime and runtime. /// /// Lines of the following forms are considered during parsing: /// /// a -> b /// "a" -> "b" /// a -> b [label="someevent"] /// a -> b [label="event1 || event2"] /// a -> b "event1" /// "a" -> "b" "event1"; /// a -> b 'event1' /// 'a' -> 'b' 'event1' /// 'a' -> 'b' 'event1 || event2' /// start: a; /// start: -> "a"; /// end: "abc" a2 a3 a4; /// end: -> "X" Y 'ZZZ'; /// end: -> event1, e2, 'ZZZ'; /// /// The purpose of this parser is to support a simple text format for defining state machines, /// not to be a full .gv parser. pub fn importText(self: *Self, input: []const u8) !void { // Might as well use a state machine to implement importing textual state machines. // After an input event, we'll end up in one of these states: const LineState = enum { ready, source, target, trigger, await_start_state, startstate, await_end_states, endstates }; const Input = enum { identifier, startcolon, endcolon, newline }; const transition_table = [_]Transition(LineState, Input){ .{ .trigger = .identifier, .from = .ready, .to = .source }, .{ .trigger = .identifier, .from = .target, .to = .trigger }, .{ .trigger = .identifier, .from = .trigger, .to = .trigger }, .{ .trigger = .identifier, .from = .await_start_state, .to = .startstate }, .{ .trigger = .identifier, .from = .await_end_states, .to = .endstates }, .{ .trigger = .identifier, .from = .endstates, .to = .endstates }, .{ .trigger = .identifier, .from = .source, .to = .target }, .{ .trigger = .startcolon, .from = .ready, .to = .await_start_state }, .{ .trigger = .endcolon, .from = .ready, .to = .await_end_states }, .{ .trigger = .newline, .from = .ready, .to = .ready }, .{ .trigger = .newline, .from = .startstate, .to = .ready }, .{ .trigger = .newline, .from = .endstates, .to = .ready }, .{ .trigger = .newline, .from = .target, .to = .ready }, .{ .trigger = .newline, .from = .trigger, .to = .ready }, }; const FSM = StateMachineFromTable(LineState, Input, transition_table[0..], .ready, &.{}); var fsm = FSM.init(); const ParseHandler = struct { handler: FSM.Handler, fsm: *Self, from: ?StateType = null, to: ?StateType = null, current_identifer: []const u8 = "", pub fn init(fsmptr: *Self) @This() { return .{ .handler = Interface.make(FSM.Handler, @This()), .fsm = fsmptr, }; } pub fn onTransition(handler: *FSM.Handler, trigger: ?Input, from: LineState, to: LineState) HandlerResult { const parse_handler = Interface.downcast(@This(), handler); _ = from; _ = trigger; if (to == .startstate) { const start_enum = std.meta.stringToEnum(StateType, parse_handler.current_identifer); if (start_enum) |e| parse_handler.fsm.setStartState(e); } else if (to == .endstates) { const end_enum = std.meta.stringToEnum(StateType, parse_handler.current_identifer); if (end_enum) |e| parse_handler.fsm.addFinalState(e) catch return HandlerResult.Cancel; } else if (to == .source) { const from_enum = std.meta.stringToEnum(StateType, parse_handler.current_identifer); parse_handler.from = from_enum; } else if (to == .target) { const to_enum = std.meta.stringToEnum(StateType, parse_handler.current_identifer); parse_handler.to = to_enum; if (parse_handler.from != null and parse_handler.to != null) { parse_handler.fsm.addTransition(parse_handler.from.?, parse_handler.to.?) catch |e| { if (e != StateError.AlreadyDefined) return HandlerResult.Cancel; }; } } else if (to == .trigger) { if (TriggerType != null) { const trigger_enum = std.meta.stringToEnum(TriggerType.?, parse_handler.current_identifer); if (trigger_enum) |te| { parse_handler.fsm.addTrigger(te, parse_handler.from.?, parse_handler.to.?) catch { return HandlerResult.Cancel; }; } } else { return HandlerResult.Cancel; } } return HandlerResult.Continue; } }; var parse_handler = ParseHandler.init(self); var handlers: [1]*FSM.Handler = .{&parse_handler.handler}; fsm.setTransitionHandlers(&handlers); var line_no: usize = 1; var lines = std.mem.split(u8, input, "\n"); while (lines.next()) |line| { if (std.mem.indexOf(u8, line, "->") == null and std.mem.indexOf(u8, line, "start:") == null and std.mem.indexOf(u8, line, "end:") == null) continue; var parts = std.mem.tokenize(u8, line, " \t='\";,"); while (parts.next()) |part| { if (anyStringsEqual(&.{ "->", "[label", "]", "||" }, part)) { continue; } else if (std.mem.eql(u8, part, "start:")) { try fsm.activateTrigger(.startcolon); } else if (std.mem.eql(u8, part, "end:")) { try fsm.activateTrigger(.endcolon); } else { parse_handler.current_identifer = part; try fsm.activateTrigger(.identifier); } } try fsm.activateTrigger(.newline); line_no += 1; } try fsm.activateTrigger(.newline); } }; } /// Helper that returns true if any of the slices are equal to the item fn anyStringsEqual(slices: []const []const u8, item: []const u8) bool { for (slices) |slice| { if (std.mem.eql(u8, slice, item)) return true; } return false; } /// Helper type to make it easier to deal with polymorphic types pub const Interface = struct { /// We establish the convention that the implementation type has the interface as the /// first field, allowing a slightly less verbose interface idiom. This will not compile /// if there's a mismatch. When this convention doesn't work, use @fieldParentPtr directly. pub fn downcast(comptime Implementer: type, interface_ref: anytype) *Implementer { const field_name = comptime std.meta.fieldNames(Implementer).*[0]; return @fieldParentPtr(Implementer, field_name, interface_ref); } /// Instantiates an interface type and populates its function pointers to point to /// proper functions in the given implementer type. pub fn make(comptime InterfaceType: type, comptime Implementer: type) InterfaceType { var instance: InterfaceType = undefined; inline for (std.meta.fields(InterfaceType)) |f| { if (comptime std.meta.trait.hasFn(f.name[0..f.name.len])(Implementer)) { @field(instance, f.name) = @field(Implementer, f.name[0..f.name.len]); } } return instance; } }; /// An enum generator useful for testing, as well as state machines with sequenced states or triggers. /// If `prefix` is an empty string, use @"0", @"1", etc to refer to the enum field. pub fn GenerateConsecutiveEnum(prefix: []const u8, element_count: usize) type { const EnumField = std.builtin.TypeInfo.EnumField; var fields: []const EnumField = &[_]EnumField{}; var i: usize = 0; while (i < element_count) : (i += 1) { comptime var tmp_buf: [128]u8 = undefined; const field_name = comptime try std.fmt.bufPrint(&tmp_buf, "{s}{d}", .{ prefix, i }); fields = fields ++ &[_]EnumField{.{ .name = field_name, .value = i, }}; } return @Type(.{ .Enum = .{ .layout = .Auto, .fields = fields, .tag_type = std.math.IntFittingRange(0, element_count), .decls = &[_]std.builtin.TypeInfo.Declaration{}, .is_exhaustive = false, } }); } const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const expectEqualSlices = std.testing.expectEqualSlices; const expectError = std.testing.expectError; test "generate state enums" { const State = GenerateConsecutiveEnum("S", 100); var fsm = StateMachine(State, null, .S0).init(); try fsm.addTransition(.S0, .S1); try fsm.transitionTo(.S1); try expectEqual(fsm.currentState(), .S1); } test "minimal without trigger" { const State = enum { on, off }; var fsm = StateMachine(State, null, .off).init(); try fsm.addTransition(.on, .off); try fsm.addTransition(.off, .on); try fsm.transitionTo(.on); try expectEqual(fsm.currentState(), .on); } test "comptime minimal without trigger" { comptime { const State = enum { on, off }; var fsm = StateMachine(State, null, .off).init(); try fsm.addTransition(.on, .off); try fsm.addTransition(.off, .on); try fsm.transitionTo(.on); try expectEqual(fsm.currentState(), .on); } } test "minimal with trigger" { const State = enum { on, off }; const Trigger = enum { click }; var fsm = StateMachine(State, Trigger, .off).init(); try fsm.addTransition(.on, .off); try fsm.addTransition(.off, .on); try fsm.addTrigger(.click, .on, .off); try fsm.addTrigger(.click, .off, .on); // Transition manually try fsm.transitionTo(.on); try expectEqual(fsm.currentState(), .on); // Transition through a trigger (event) try fsm.activateTrigger(.click); try expectEqual(fsm.currentState(), .off); } test "minimal with trigger defined using a table" { const State = enum { on, off }; const Trigger = enum { click }; const definition = [_]Transition(State, Trigger){ .{ .trigger = .click, .from = .on, .to = .off }, .{ .trigger = .click, .from = .off, .to = .on }, }; var fsm = StateMachineFromTable(State, Trigger, &definition, .off, &.{}).init(); // Transition manually try fsm.transitionTo(.on); try expectEqual(fsm.currentState(), .on); // Transition through a trigger (event) try fsm.activateTrigger(.click); try expectEqual(fsm.currentState(), .off); } test "check state" { const State = enum { start, stop }; const FSM = StateMachine(State, null, .start); var fsm = FSM.init(); try fsm.addTransition(.start, .stop); try fsm.addFinalState(.stop); try expect(fsm.isFinalState(.stop)); try expect(fsm.isInStartState()); try expect(fsm.isCurrently(.start)); try expect(!fsm.isInFinalState()); try fsm.transitionTo(.stop); try expect(fsm.isCurrently(.stop)); try expectEqual(fsm.currentState(), .stop); try expect(fsm.isInFinalState()); } // Simple CSV parser based on the state model in https://ppolv.wordpress.com/2008/02/25/parsing-csv-in-erlang // The main idea is that we classify incoming characters as InputEvent's. When a character arrives, we // simply trigger the event. If the input is well-formed, we automatically move to the appropriate state. // To actually extract CSV fields, we use a transition handler to keep track of where field slices starts and ends. // If the input is incorrect we have detailed information about where it happens, and why based on states and triggers. test "csv parser" { const State = enum { field_start, unquoted, quoted, post_quoted, done }; const InputEvent = enum { char, quote, whitespace, comma, newline, anything_not_quote, eof }; // Intentionally badly formatted csv to exercise corner cases const csv_input = \\"first",second,"third",4 \\ "more", right, here, 5 \\ 1,,b,c ; const FSM = StateMachine(State, InputEvent, .field_start); const Parser = struct { handler: FSM.Handler, fsm: *FSM, csv: []const u8, cur_field_start: usize, cur_index: usize, line: usize = 0, col: usize = 0, const expected_parse_result: [3][4][]const u8 = .{ .{ "\"first\"", "second", "\"third\"", "4" }, .{ "\"more\"", "right", "here", "5" }, .{ "1", "", "b", "c" }, }; pub fn parse(fsm: *FSM, csv: []const u8) !void { var instance: @This() = .{ .handler = Interface.make(FSM.Handler, @This()), .fsm = fsm, .csv = csv, .cur_field_start = 0, .cur_index = 0, .line = 0, .col = 0, }; instance.fsm.setTransitionHandlers(&.{&instance.handler}); try instance.read(); } /// Feeds the input stream through the state machine fn read(self: *@This()) !void { var reader = std.io.fixedBufferStream(self.csv).reader(); while (true) : (self.cur_index += 1) { var input = reader.readByte() catch { // An example of how to handle parsing errors self.fsm.activateTrigger(.eof) catch { try std.io.getStdErr().writer().print("Unexpected end of stream\n", .{}); }; return; }; // The order of checks is important to classify input correctly if (self.fsm.isCurrently(.quoted) and input != '"') { try self.fsm.activateTrigger(.anything_not_quote); } else if (input == '\n') { try self.fsm.activateTrigger(.newline); } else if (std.ascii.isSpace(input)) { try self.fsm.activateTrigger(.whitespace); } else if (input == ',') { try self.fsm.activateTrigger(.comma); } else if (input == '"') { try self.fsm.activateTrigger(.quote); } else if (std.ascii.isPrint(input)) { try self.fsm.activateTrigger(.char); } } } /// We use state transitions to extract CSV field slices, and we're not using any extra memory. /// Note that the transition handler must be public. pub fn onTransition(handler: *FSM.Handler, trigger: ?InputEvent, from: State, to: State) HandlerResult { const self = Interface.downcast(@This(), handler); const fields_per_row = 4; // Start of a field if (from == .field_start) { self.cur_field_start = self.cur_index; } // End of a field if (to != from and (from == .unquoted or from == .post_quoted)) { const found_field = std.mem.trim(u8, self.csv[self.cur_field_start..self.cur_index], " "); std.testing.expectEqualSlices(u8, found_field, expected_parse_result[self.line][self.col]) catch unreachable; self.col = (self.col + 1) % fields_per_row; } // Empty field if (trigger.? == .comma and self.cur_field_start == self.cur_index) { self.col = (self.col + 1) % fields_per_row; } if (trigger.? == .newline) { self.line += 1; } return HandlerResult.Continue; } }; var fsm = FSM.init(); try fsm.addTriggerAndTransition(.whitespace, .field_start, .field_start); try fsm.addTriggerAndTransition(.whitespace, .unquoted, .unquoted); try fsm.addTriggerAndTransition(.whitespace, .post_quoted, .post_quoted); try fsm.addTriggerAndTransition(.char, .field_start, .unquoted); try fsm.addTriggerAndTransition(.char, .unquoted, .unquoted); try fsm.addTriggerAndTransition(.quote, .field_start, .quoted); try fsm.addTriggerAndTransition(.quote, .quoted, .post_quoted); try fsm.addTriggerAndTransition(.anything_not_quote, .quoted, .quoted); try fsm.addTriggerAndTransition(.comma, .post_quoted, .field_start); try fsm.addTriggerAndTransition(.comma, .unquoted, .field_start); try fsm.addTriggerAndTransition(.comma, .field_start, .field_start); try fsm.addTriggerAndTransition(.newline, .post_quoted, .field_start); try fsm.addTriggerAndTransition(.newline, .unquoted, .field_start); try fsm.addTriggerAndTransition(.eof, .unquoted, .done); try fsm.addTriggerAndTransition(.eof, .quoted, .done); try fsm.addFinalState(.done); try Parser.parse(&fsm, csv_input); try expect(fsm.isInFinalState()); // Uncomment to generate a Graphviz diagram // try fsm.exportGraphviz("csv", std.io.getStdOut().writer(), .{.shape = "box", .shape_final_state = "doublecircle", .show_initial_state=true}); } // Demonstrates that triggering a single "click" event can perpetually cycle through intensity states. test "moore machine: three-level intensity light" { // Here we use anonymous state/trigger enums, Zig will still allow us to reference these var fsm = StateMachine(enum { off, dim, medium, bright }, enum { click }, .off).init(); try fsm.addTriggerAndTransition(.click, .off, .dim); try fsm.addTriggerAndTransition(.click, .dim, .medium); try fsm.addTriggerAndTransition(.click, .medium, .bright); try fsm.addTriggerAndTransition(.click, .bright, .off); // Trigger a full cycle of off -> dim -> medium -> bright -> off try expect(fsm.isCurrently(.off)); try fsm.activateTrigger(.click); try expect(fsm.isCurrently(.dim)); try fsm.activateTrigger(.click); try expect(fsm.isCurrently(.medium)); try fsm.activateTrigger(.click); try expect(fsm.isCurrently(.bright)); try fsm.activateTrigger(.click); try expect(fsm.isCurrently(.off)); try expect(fsm.canTransitionTo(.dim)); try expect(!fsm.canTransitionTo(.medium)); try expect(!fsm.canTransitionTo(.bright)); try expect(!fsm.canTransitionTo(.off)); // Uncomment to generate a Graphviz diagram // try fsm.exportGraphviz("lights", std.io.getStdOut().writer(), .{.layout = "circo", .shape = "box"}); } test "handler that cancels" { const State = enum { on, off }; const Trigger = enum { click }; const FSM = StateMachine(State, Trigger, .off); var fsm = FSM.init(); // Demonstrates how to manage extra state (in this case a simple counter) while reacting // to transitions. Once the counter reaches 3, it cancels any further transitions. Real-world // handlers typically check from/to states and perhaps even which trigger (if any) caused the // transition. const CountingHandler = struct { handler: FSM.Handler, counter: usize, pub fn init() @This() { return .{ .handler = Interface.make(FSM.Handler, @This()), .counter = 0, }; } pub fn onTransition(handler: *FSM.Handler, trigger: ?Trigger, from: State, to: State) HandlerResult { _ = &.{ from, to, trigger }; const self = Interface.downcast(@This(), handler); self.counter += 1; return if (self.counter < 3) HandlerResult.Continue else HandlerResult.Cancel; } }; var countingHandler = CountingHandler.init(); fsm.setTransitionHandlers(&.{&countingHandler.handler}); try fsm.addTriggerAndTransition(.click, .on, .off); try fsm.addTriggerAndTransition(.click, .off, .on); try fsm.activateTrigger(.click); try fsm.activateTrigger(.click); // Third time will fail try expectError(StateError.Canceled, fsm.activateTrigger(.click)); } // Implements https://en.wikipedia.org/wiki/Deterministic_finite_automaton#Example test "comptime dfa: binary alphabet, require even number of zeros in input" { // Comptime use of triggers is commented out until this is fixed: https://github.com/ziglang/zig/issues/10694 //comptime { @setEvalBranchQuota(10_000); // Note that both "start: S1;" and "start: -> S1;" syntaxes work, same with end: const input = \\ S1 -> S2 [label = "0"]; \\ S2 -> S1 [label = "0"]; \\ S1 -> S1 [label = "1"]; \\ S2 -> S2 [label = "1"]; \\ start: S1; \\ end: S1; ; const State = enum { S1, S2 }; const Bit = enum { @"0", @"1" }; var fsm = StateMachine(State, Bit, .S1).init(); try fsm.importText(input); // With valid input, we wil end up in the final state const valid_input: []const Bit = &.{ .@"0", .@"0", .@"1", .@"1" }; for (valid_input) |bit| try fsm.activateTrigger(bit); try expect(fsm.isInFinalState()); // With invalid input, we will not end up in the final state const invalid_input: []const Bit = &.{ .@"0", .@"0", .@"0", .@"1" }; for (invalid_input) |bit| try fsm.activateTrigger(bit); try expect(!fsm.isInFinalState()); } } test "import: graphviz" { const input = \\digraph parser_example { \\ rankdir=LR; \\ node [shape = doublecircle fixedsize = false]; 3 4 8 ; \\ node [shape = circle fixedsize = false]; \\ start: -> 0; \\ 0 -> 2 [label = "SS(B)"]; \\ 0 -> 1 [label = "SS(S)"]; \\ 1 -> 3 [label = "S($end)"]; \\ 2 -> 6 [label = "SS(b)"]; \\ 2 -> 5 [label = "SS(a)"]; \\ 2 -> 4 [label = "S(A)"]; \\ 5 -> 7 [label = "S(b)"]; \\ 5 -> 5 [label = "S(a)"]; \\ 6 -> 6 [label = "S(b)"]; \\ 6 -> 5 [label = "S(a)"]; \\ 7 -> 8 [label = "S(b)"]; \\ 7 -> 5 [label = "S(a)"]; \\ 8 -> 6 [label = "S(b)"]; \\ 8 -> 5 [label = "S(a) || extra"]; \\} ; var outbuf = std.ArrayList(u8).init(std.testing.allocator); defer outbuf.deinit(); const State = enum { @"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8" }; const Trigger = enum { @"SS(B)", @"SS(S)", @"S($end)", @"SS(b)", @"SS(a)", @"S(A)", @"S(b)", @"S(a)", extra }; var fsm = StateMachine(State, Trigger, .@"0").init(); try fsm.importText(input); try fsm.apply(.{ .trigger = .@"SS(B)" }); try expectEqual(fsm.currentState(), .@"2"); try fsm.transitionTo(.@"6"); try expectEqual(fsm.currentState(), .@"6"); // Self-transition try fsm.activateTrigger(.@"S(b)"); try expectEqual(fsm.currentState(), .@"6"); } test "import: libfsm text" { const input = \\ 1 -> 2 "a"; \\ 2 -> 3 "a"; \\ 3 -> 4 "b"; \\ 4 -> 5 "b"; \\ 5 -> 1 'c'; \\ "1" -> "3" 'c'; \\ 3 -> 5 'c'; \\ start: 1; \\ end: 3, 4, 5; ; var outbuf = std.ArrayList(u8).init(std.testing.allocator); defer outbuf.deinit(); const State = enum { @"0", @"1", @"2", @"3", @"4", @"5" }; const Trigger = enum { a, b, c }; var fsm = StateMachine(State, Trigger, .@"0").init(); try fsm.importText(input); try expectEqual(fsm.currentState(), .@"1"); try fsm.transitionTo(.@"2"); try expectEqual(fsm.currentState(), .@"2"); try fsm.activateTrigger(.a); try expectEqual(fsm.currentState(), .@"3"); try expect(fsm.isInFinalState()); } // Implements the state diagram example from the Graphviz docs test "export: graphviz export of finite automaton sample" { const State = enum { @"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8" }; const Trigger = enum { @"SS(B)", @"SS(S)", @"S($end)", @"SS(b)", @"SS(a)", @"S(A)", @"S(b)", @"S(a)", extra }; var fsm = StateMachine(State, Trigger, .@"0").init(); try fsm.addTransition(State.@"0", State.@"2"); try fsm.addTransition(State.@"0", State.@"1"); try fsm.addTransition(State.@"1", State.@"3"); try fsm.addTransition(State.@"2", State.@"6"); try fsm.addTransition(State.@"2", State.@"5"); try fsm.addTransition(State.@"2", State.@"4"); try fsm.addTransition(State.@"5", State.@"7"); try fsm.addTransition(State.@"5", State.@"5"); try fsm.addTransition(State.@"6", State.@"6"); try fsm.addTransition(State.@"6", State.@"5"); try fsm.addTransition(State.@"7", State.@"8"); try fsm.addTransition(State.@"7", State.@"5"); try fsm.addTransition(State.@"8", State.@"6"); try fsm.addTransition(State.@"8", State.@"5"); try fsm.addFinalState(State.@"3"); try fsm.addFinalState(State.@"4"); try fsm.addFinalState(State.@"8"); try fsm.addTrigger(.@"SS(B)", .@"0", .@"2"); try fsm.addTrigger(.@"SS(S)", .@"0", .@"1"); try fsm.addTrigger(.@"S($end)", .@"1", .@"3"); try fsm.addTrigger(.@"SS(b)", .@"2", .@"6"); try fsm.addTrigger(.@"SS(a)", .@"2", .@"5"); try fsm.addTrigger(.@"S(A)", .@"2", .@"4"); try fsm.addTrigger(.@"S(b)", .@"5", .@"7"); try fsm.addTrigger(.@"S(a)", .@"5", .@"5"); try fsm.addTrigger(.@"S(b)", .@"6", .@"6"); try fsm.addTrigger(.@"S(a)", .@"6", .@"5"); try fsm.addTrigger(.@"S(b)", .@"7", .@"8"); try fsm.addTrigger(.@"S(a)", .@"7", .@"5"); try fsm.addTrigger(.@"S(b)", .@"8", .@"6"); try fsm.addTrigger(.@"S(a)", .@"8", .@"5"); // This demonstrates that multiple triggers on the same transition are concatenated with || try fsm.addTrigger(.extra, .@"8", .@"5"); var outbuf = std.ArrayList(u8).init(std.testing.allocator); defer outbuf.deinit(); try fsm.exportGraphviz("parser_example", outbuf.writer(), .{}); const target = \\digraph parser_example { \\ rankdir=LR; \\ node [shape = doublecircle fixedsize = false]; "3" "4" "8" ; \\ node [shape = circle fixedsize = false]; \\ "0" -> "1" [label = "SS(S)"]; \\ "0" -> "2" [label = "SS(B)"]; \\ "1" -> "3" [label = "S($end)"]; \\ "2" -> "4" [label = "S(A)"]; \\ "2" -> "5" [label = "SS(a)"]; \\ "2" -> "6" [label = "SS(b)"]; \\ "5" -> "5" [label = "S(a)"]; \\ "5" -> "7" [label = "S(b)"]; \\ "6" -> "5" [label = "S(a)"]; \\ "6" -> "6" [label = "S(b)"]; \\ "7" -> "5" [label = "S(a)"]; \\ "7" -> "8" [label = "S(b)"]; \\ "8" -> "5" [label = "S(a) || extra"]; \\ "8" -> "6" [label = "S(b)"]; \\} \\ ; try expectEqualSlices(u8, target[0..], outbuf.items[0..]); } test "finite state automaton for accepting a 25p car park charge (from Computers Without Memory - Computerphile)" { const state_machine = \\ sum0 -> sum5 p5 \\ sum0 -> sum10 p10 \\ sum0 -> sum20 p20 \\ sum5 -> sum10 p5 \\ sum5 -> sum15 p10 \\ sum5 -> sum25 p20 \\ sum10 -> sum15 p5 \\ sum10 -> sum20 p10 \\ sum15 -> sum20 p5 \\ sum15 -> sum25 p10 \\ sum20 -> sum25 p5 \\ start: sum0 \\ end: sum25 ; const Sum = enum { sum0, sum5, sum10, sum15, sum20, sum25 }; const Coin = enum { p5, p10, p20 }; var fsm = StateMachine(Sum, Coin, .sum0).init(); try fsm.importText(state_machine); // Add 5p, 10p and 10p coins try fsm.activateTrigger(.p5); try fsm.activateTrigger(.p10); try fsm.activateTrigger(.p10); // Car park charge reached try expect(fsm.isInFinalState()); // Verify that we're unable to accept more coins try expectError(StateError.Invalid, fsm.activateTrigger(.p10)); // Restart the state machine and try a different combination to reach 25p fsm.restart(); try fsm.activateTrigger(.p20); try fsm.activateTrigger(.p5); try expect(fsm.isInFinalState()); // Same as restart(), but makes sure we're currently in the start state or a final state try fsm.safeRestart(); try fsm.activateTrigger(.p10); try expectError(StateError.Invalid, fsm.safeRestart()); try fsm.activateTrigger(.p5); try fsm.activateTrigger(.p5); try fsm.activateTrigger(.p5); try expect(fsm.isInFinalState()); } test "iterate next valid states" { const state_machine = \\ sum0 -> sum5 p5 \\ sum0 -> sum10 p10 \\ sum0 -> sum20 p20 \\ sum5 -> sum10 p5 \\ sum5 -> sum15 p10 \\ sum5 -> sum25 p20 \\ sum10 -> sum15 p5 \\ sum10 -> sum20 p10 \\ sum15 -> sum20 p5 \\ sum15 -> sum25 p10 \\ sum20 -> sum25 p5 \\ start: sum0 \\ end: sum25 ; const Sum = enum { sum0, sum5, sum10, sum15, sum20, sum25 }; const Coin = enum { p5, p10, p20 }; var fsm = StateMachine(Sum, Coin, .sum0).init(); try fsm.importText(state_machine); var next_valid_iterator = fsm.validNextStatesIterator(); try expectEqual(Sum.sum5, next_valid_iterator.next().?); try expectEqual(Sum.sum10, next_valid_iterator.next().?); try expectEqual(Sum.sum20, next_valid_iterator.next().?); try expectEqual(next_valid_iterator.next(), null); } /// An elevator state machine const ElevatorTest = struct { const Elevator = enum { doors_opened, doors_closed, moving, exit_light_blinking }; const ElevatorActions = enum { open, close, alarm }; pub fn init() !StateMachine(Elevator, ElevatorActions, .doors_opened) { var fsm = StateMachine(Elevator, ElevatorActions, .doors_opened).init(); try fsm.addTransition(.doors_opened, .doors_closed); try fsm.addTransition(.doors_closed, .moving); try fsm.addTransition(.moving, .moving); try fsm.addTransition(.doors_opened, .exit_light_blinking); try fsm.addTransition(.doors_closed, .doors_opened); try fsm.addTransition(.exit_light_blinking, .doors_opened); return fsm; } }; test "elevator: redefine transition should fail" { var fsm = try ElevatorTest.init(); try expectError(StateError.AlreadyDefined, fsm.addTransition(.doors_opened, .doors_closed)); } test "elevator: apply" { var fsm = try ElevatorTest.init(); try fsm.addTrigger(.alarm, .doors_opened, .exit_light_blinking); try fsm.apply(.{ .state = ElevatorTest.Elevator.doors_closed }); try fsm.apply(.{ .state = ElevatorTest.Elevator.doors_opened }); try fsm.apply(.{ .trigger = ElevatorTest.ElevatorActions.alarm }); try expect(fsm.isCurrently(.exit_light_blinking)); } test "elevator: transition success" { var fsm = try ElevatorTest.init(); try fsm.transitionTo(.doors_closed); try expectEqual(fsm.currentState(), .doors_closed); } test "elevator: add a trigger and active it" { var fsm = try ElevatorTest.init(); // The same trigger can be invoked for multiple state transitions try fsm.addTrigger(.alarm, .doors_opened, .exit_light_blinking); try expectEqual(fsm.currentState(), .doors_opened); try fsm.activateTrigger(.alarm); try expectEqual(fsm.currentState(), .exit_light_blinking); } test "statemachine from transition array" { const Elevator = enum { doors_opened, doors_closed, exit_light_blinking, moving }; const Events = enum { open, close, alarm, notused1, notused2 }; const defs = [_]Transition(Elevator, Events){ .{ .trigger = .open, .from = .doors_closed, .to = .doors_opened }, .{ .trigger = .open, .from = .doors_opened, .to = .doors_opened }, .{ .trigger = .close, .from = .doors_opened, .to = .doors_closed }, .{ .trigger = .close, .from = .doors_closed, .to = .doors_closed }, .{ .trigger = .alarm, .from = .doors_closed, .to = .doors_opened }, .{ .trigger = .alarm, .from = .doors_opened, .to = .exit_light_blinking }, .{ .from = .doors_closed, .to = .moving }, .{ .from = .moving, .to = .moving }, .{ .from = .moving, .to = .doors_closed }, }; const final_states = [_]Elevator{}; const FSM = StateMachineFromTable(Elevator, Events, defs[0..], .doors_closed, final_states[0..]); var fsm = FSM.init(); try fsm.transitionTo(.doors_opened); try fsm.transitionTo(.doors_opened); if (!fsm.canTransitionTo(.moving)) { fsm.transitionTo(.moving) catch {}; try fsm.transitionTo(.doors_closed); if (fsm.canTransitionTo(.moving)) try fsm.transitionTo(.moving); try fsm.transitionTo(.doors_closed); } }
src/main.zig
pub const Message = struct { sender: MailboxId, receiver: MailboxId, type: usize, payload: usize, pub fn from(mailbox_id: *const MailboxId) Message { return Message{ .sender = MailboxId.Undefined, .receiver = *mailbox_id, .type = 0, .payload = 0, }; } pub fn to(mailbox_id: *const MailboxId, msg_type: usize) Message { return Message{ .sender = MailboxId.This, .receiver = *mailbox_id, .type = msg_type, .payload = 0, }; } pub fn withData(mailbox_id: *const MailboxId, msg_type: usize, payload: usize) Message { return Message{ .sender = MailboxId.This, .receiver = *mailbox_id, .type = msg_type, .payload = payload, }; } }; pub const MailboxId = union(enum) { Undefined, This, Kernel, Port: u16, Thread: u16, }; ////////////////////////////////////// //// Ports reserved for servers //// ////////////////////////////////////// pub const Server = struct { pub const Keyboard = MailboxId{ .Port = 0 }; pub const Terminal = MailboxId{ .Port = 1 }; }; //////////////////////// //// POSIX things //// //////////////////////// // Standard streams. pub const STDIN_FILENO = 0; pub const STDOUT_FILENO = 1; pub const STDERR_FILENO = 2; // FIXME: let's borrow Linux's error numbers for now. pub const getErrno = @import("linux/index.zig").getErrno; use @import("linux/errno.zig"); // TODO: implement this correctly. pub fn read(fd: i32, buf: *u8, count: usize) usize { switch (fd) { STDIN_FILENO => { var i: usize = 0; while (i < count) : (i += 1) { send(Message.to(Server.Keyboard, 0)); var message = Message.from(MailboxId.This); receive(*message); buf[i] = u8(message.payload); } }, else => unreachable, } return count; } // TODO: implement this correctly. pub fn write(fd: i32, buf: *const u8, count: usize) usize { switch (fd) { STDOUT_FILENO, STDERR_FILENO => { var i: usize = 0; while (i < count) : (i += 1) { send(Message.withData(Server.Terminal, 1, buf[i])); } }, else => unreachable, } return count; } /////////////////////////// //// Syscall numbers //// /////////////////////////// pub const Syscall = enum(usize) { exit = 0, createPort = 1, send = 2, receive = 3, subscribeIRQ = 4, inb = 5, map = 6, createThread = 7, createProcess = 8, wait = 9, portReady = 10, }; //////////////////// //// Syscalls //// //////////////////// pub fn exit(status: i32) noreturn { _ = syscall1(Syscall.exit, @bitCast(usize, isize(status))); unreachable; } pub fn createPort(mailbox_id: *const MailboxId) void { _ = switch (*mailbox_id) { MailboxId.Port => |id| syscall1(Syscall.createPort, id), else => unreachable, }; } pub fn send(message: *const Message) void { _ = syscall1(Syscall.send, @ptrToInt(message)); } pub fn receive(destination: *Message) void { _ = syscall1(Syscall.receive, @ptrToInt(destination)); } pub fn subscribeIRQ(irq: u8, mailbox_id: *const MailboxId) void { _ = syscall2(Syscall.subscribeIRQ, irq, @ptrToInt(mailbox_id)); } pub fn inb(port: u16) u8 { return u8(syscall1(Syscall.inb, port)); } pub fn map(v_addr: usize, p_addr: usize, size: usize, writable: bool) bool { return syscall4(Syscall.map, v_addr, p_addr, size, usize(writable)) != 0; } pub fn createThread(function: fn () void) u16 { return u16(syscall1(Syscall.createThread, @ptrToInt(function))); } pub fn createProcess(elf_addr: usize) u16 { return u16(syscall1(Syscall.createProcess, elf_addr)); } pub fn wait(tid: u16) void { _ = syscall1(Syscall.wait, tid); } pub fn portReady(port: u16) bool { return syscall1(Syscall.portReady, port) != 0; } ///////////////////////// //// Syscall stubs //// ///////////////////////// inline fn syscall0(number: Syscall) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number) ); } inline fn syscall1(number: Syscall, arg1: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), [arg1] "{ecx}" (arg1) ); } inline fn syscall2(number: Syscall, arg1: usize, arg2: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), [arg1] "{ecx}" (arg1), [arg2] "{edx}" (arg2) ); } inline fn syscall3(number: Syscall, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), [arg1] "{ecx}" (arg1), [arg2] "{edx}" (arg2), [arg3] "{ebx}" (arg3) ); } inline fn syscall4(number: Syscall, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), [arg1] "{ecx}" (arg1), [arg2] "{edx}" (arg2), [arg3] "{ebx}" (arg3), [arg4] "{esi}" (arg4) ); } inline fn syscall5( number: Syscall, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize, ) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), [arg1] "{ecx}" (arg1), [arg2] "{edx}" (arg2), [arg3] "{ebx}" (arg3), [arg4] "{esi}" (arg4), [arg5] "{edi}" (arg5) ); } inline fn syscall6( number: Syscall, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize, arg6: usize, ) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), [arg1] "{ecx}" (arg1), [arg2] "{edx}" (arg2), [arg3] "{ebx}" (arg3), [arg4] "{esi}" (arg4), [arg5] "{edi}" (arg5), [arg6] "{ebp}" (arg6) ); }
std/os/zen.zig
const std = @import("std"); const builtin = @import("builtin"); const native_endian = builtin.target.cpu.arch.endian(); const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const expectEqualSlices = std.testing.expectEqualSlices; const maxInt = std.math.maxInt; top_level_field: i32, test "top level fields" { if (builtin.zig_backend == .stage2_x86_64 or builtin.zig_backend == .stage2_arm) return error.SkipZigTest; var instance = @This(){ .top_level_field = 1234, }; instance.top_level_field += 1; try expect(@as(i32, 1235) == instance.top_level_field); } const StructWithFields = struct { a: u8, b: u32, c: u64, d: u32, fn first(self: *const StructWithFields) u8 { return self.a; } fn second(self: *const StructWithFields) u32 { return self.b; } fn third(self: *const StructWithFields) u64 { return self.c; } fn fourth(self: *const StructWithFields) u32 { return self.d; } }; test "non-packed struct has fields padded out to the required alignment" { if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const foo = StructWithFields{ .a = 5, .b = 1, .c = 10, .d = 2 }; try expect(foo.first() == 5); try expect(foo.second() == 1); try expect(foo.third() == 10); try expect(foo.fourth() == 2); } const StructWithNoFields = struct { fn add(a: i32, b: i32) i32 { return a + b; } }; const StructFoo = struct { a: i32, b: bool, c: f32, }; test "structs" { if (builtin.zig_backend == .stage2_x86_64 or builtin.zig_backend == .stage2_arm) return error.SkipZigTest; var foo: StructFoo = undefined; @memset(@ptrCast([*]u8, &foo), 0, @sizeOf(StructFoo)); foo.a += 1; foo.b = foo.a == 1; try testFoo(foo); testMutation(&foo); try expect(foo.c == 100); } fn testFoo(foo: StructFoo) !void { try expect(foo.b); } fn testMutation(foo: *StructFoo) void { foo.c = 100; } test "struct byval assign" { if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; var foo1: StructFoo = undefined; var foo2: StructFoo = undefined; foo1.a = 1234; foo2.a = 0; try expect(foo2.a == 0); foo2 = foo1; try expect(foo2.a == 1234); } test "call struct static method" { if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const result = StructWithNoFields.add(3, 4); try expect(result == 7); } const should_be_11 = StructWithNoFields.add(5, 6); test "invoke static method in global scope" { try expect(should_be_11 == 11); } const empty_global_instance = StructWithNoFields{}; test "return empty struct instance" { _ = returnEmptyStructInstance(); } fn returnEmptyStructInstance() StructWithNoFields { return empty_global_instance; } const Node = struct { val: Val, next: *Node, }; const Val = struct { x: i32, }; test "fn call of struct field" { if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const Foo = struct { ptr: fn () i32, }; const S = struct { fn aFunc() i32 { return 13; } fn callStructField(foo: Foo) i32 { return foo.ptr(); } }; try expect(S.callStructField(Foo{ .ptr = S.aFunc }) == 13); } test "struct initializer" { const val = Val{ .x = 42 }; try expect(val.x == 42); } const MemberFnTestFoo = struct { x: i32, fn member(foo: MemberFnTestFoo) i32 { return foo.x; } }; test "call member function directly" { if (builtin.zig_backend == .stage2_x86_64 or builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const instance = MemberFnTestFoo{ .x = 1234 }; const result = MemberFnTestFoo.member(instance); try expect(result == 1234); } test "store member function in variable" { if (builtin.zig_backend == .stage2_x86_64 or builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const instance = MemberFnTestFoo{ .x = 1234 }; const memberFn = MemberFnTestFoo.member; const result = memberFn(instance); try expect(result == 1234); } test "member functions" { if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const r = MemberFnRand{ .seed = 1234 }; try expect(r.getSeed() == 1234); } const MemberFnRand = struct { seed: u32, pub fn getSeed(r: *const MemberFnRand) u32 { return r.seed; } }; test "return struct byval from function" { if (builtin.zig_backend == .stage2_x86_64 or builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const bar = makeBar2(1234, 5678); try expect(bar.y == 5678); } const Bar = struct { x: i32, y: i32, }; fn makeBar2(x: i32, y: i32) Bar { return Bar{ .x = x, .y = y, }; } test "call method with mutable reference to struct with no fields" { if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const S = struct { fn doC(s: *const @This()) bool { _ = s; return true; } fn do(s: *@This()) bool { _ = s; return true; } }; var s = S{}; try expect(S.doC(&s)); try expect(s.doC()); try expect(S.do(&s)); try expect(s.do()); } test "usingnamespace within struct scope" { if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const S = struct { usingnamespace struct { pub fn inner() i32 { return 42; } }; }; try expect(@as(i32, 42) == S.inner()); } test "struct field init with catch" { if (builtin.zig_backend == .stage2_x86_64 or builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const S = struct { fn doTheTest() !void { var x: anyerror!isize = 1; var req = Foo{ .field = x catch undefined, }; try expect(req.field == 1); } pub const Foo = extern struct { field: isize, }; }; try S.doTheTest(); comptime try S.doTheTest(); } test "packed struct field alignment" { if (builtin.object_format == .c) return error.SkipZigTest; const Stage1 = struct { var baz: packed struct { a: u32, b: u32, } = undefined; }; const Stage2 = struct { var baz: packed struct { a: u32, b: u32 align(1), } = undefined; }; const S = if (builtin.zig_backend != .stage1) Stage2 else Stage1; try expect(@TypeOf(&S.baz.b) == *align(1) u32); } const blah: packed struct { a: u3, b: u3, c: u2, } = undefined; test "bit field alignment" { try expect(@TypeOf(&blah.b) == *align(1:3:1) const u3); }
test/behavior/struct.zig
/// Authenticated Encryption with Associated Data pub const aead = struct { pub const aegis = struct { pub const Aegis128L = @import("crypto/aegis.zig").Aegis128L; pub const Aegis256 = @import("crypto/aegis.zig").Aegis256; }; pub const aes_gcm = struct { pub const Aes128Gcm = @import("crypto/aes_gcm.zig").Aes128Gcm; pub const Aes256Gcm = @import("crypto/aes_gcm.zig").Aes256Gcm; }; pub const Gimli = @import("crypto/gimli.zig").Aead; pub const chacha_poly = struct { pub const ChaCha20Poly1305 = @import("crypto/chacha20.zig").Chacha20Poly1305; pub const XChaCha20Poly1305 = @import("crypto/chacha20.zig").XChacha20Poly1305; }; pub const salsa_poly = struct { pub const XSalsa20Poly1305 = @import("crypto/salsa20.zig").XSalsa20Poly1305; }; }; /// Authentication (MAC) functions. pub const auth = struct { pub const hmac = @import("crypto/hmac.zig"); pub const siphash = @import("crypto/siphash.zig"); }; /// Core functions, that should rarely be used directly by applications. pub const core = struct { pub const aes = @import("crypto/aes.zig"); pub const Gimli = @import("crypto/gimli.zig").State; /// Modes are generic compositions to construct encryption/decryption functions from block ciphers and permutations. /// /// These modes are designed to be building blocks for higher-level constructions, and should generally not be used directly by applications, as they may not provide the expected properties and security guarantees. /// /// Most applications may want to use AEADs instead. pub const modes = @import("crypto/modes.zig"); }; /// Diffie-Hellman key exchange functions. pub const dh = struct { pub const X25519 = @import("crypto/25519/x25519.zig").X25519; }; /// Elliptic-curve arithmetic. pub const ecc = struct { pub const Curve25519 = @import("crypto/25519/curve25519.zig").Curve25519; pub const Edwards25519 = @import("crypto/25519/edwards25519.zig").Edwards25519; pub const Ristretto255 = @import("crypto/25519/ristretto255.zig").Ristretto255; }; /// Hash functions. pub const hash = struct { pub const blake2 = @import("crypto/blake2.zig"); pub const Blake3 = @import("crypto/blake3.zig").Blake3; pub const Gimli = @import("crypto/gimli.zig").Hash; pub const Md5 = @import("crypto/md5.zig").Md5; pub const Sha1 = @import("crypto/sha1.zig").Sha1; pub const sha2 = @import("crypto/sha2.zig"); pub const sha3 = @import("crypto/sha3.zig"); }; /// Key derivation functions. pub const kdf = struct { pub const hkdf = @import("crypto/hkdf.zig"); }; /// MAC functions requiring single-use secret keys. pub const onetimeauth = struct { pub const Ghash = @import("crypto/ghash.zig").Ghash; pub const Poly1305 = @import("crypto/poly1305.zig").Poly1305; }; /// A password hashing function derives a uniform key from low-entropy input material such as passwords. /// It is intentionally slow or expensive. /// /// With the standard definition of a key derivation function, if a key space is small, an exhaustive search may be practical. /// Password hashing functions make exhaustive searches way slower or way more expensive, even when implemented on GPUs and ASICs, by using different, optionally combined strategies: /// /// - Requiring a lot of computation cycles to complete /// - Requiring a lot of memory to complete /// - Requiring multiple CPU cores to complete /// - Requiring cache-local data to complete in reasonable time /// - Requiring large static tables /// - Avoiding precomputations and time/memory tradeoffs /// - Requiring multi-party computations /// - Combining the input material with random per-entry data (salts), application-specific contexts and keys /// /// Password hashing functions must be used whenever sensitive data has to be directly derived from a password. pub const pwhash = struct { pub const bcrypt = @import("crypto/bcrypt.zig"); pub const pbkdf2 = @import("crypto/pbkdf2.zig").pbkdf2; }; /// Digital signature functions. pub const sign = struct { pub const Ed25519 = @import("crypto/25519/ed25519.zig").Ed25519; }; /// Stream ciphers. These do not provide any kind of authentication. /// Most applications should be using AEAD constructions instead of stream ciphers directly. pub const stream = struct { pub const chacha = struct { pub const ChaCha20IETF = @import("crypto/chacha20.zig").ChaCha20IETF; pub const ChaCha20With64BitNonce = @import("crypto/chacha20.zig").ChaCha20With64BitNonce; pub const XChaCha20IETF = @import("crypto/chacha20.zig").XChaCha20IETF; }; pub const salsa = struct { pub const Salsa20 = @import("crypto/salsa20.zig").Salsa20; pub const XSalsa20 = @import("crypto/salsa20.zig").XSalsa20; }; }; pub const nacl = struct { const salsa20 = @import("crypto/salsa20.zig"); pub const Box = salsa20.Box; pub const SecretBox = salsa20.SecretBox; pub const SealedBox = salsa20.SealedBox; }; const std = @import("std.zig"); pub const randomBytes = std.os.getrandom; test "crypto" { inline for (std.meta.declarations(@This())) |decl| { switch (decl.data) { .Type => |t| { std.testing.refAllDecls(t); }, .Var => |v| { _ = v; }, .Fn => |f| { _ = f; }, } } _ = @import("crypto/aes.zig"); _ = @import("crypto/bcrypt.zig"); _ = @import("crypto/blake2.zig"); _ = @import("crypto/blake3.zig"); _ = @import("crypto/chacha20.zig"); _ = @import("crypto/gimli.zig"); _ = @import("crypto/hmac.zig"); _ = @import("crypto/md5.zig"); _ = @import("crypto/modes.zig"); _ = @import("crypto/pbkdf2.zig"); _ = @import("crypto/poly1305.zig"); _ = @import("crypto/sha1.zig"); _ = @import("crypto/sha2.zig"); _ = @import("crypto/sha3.zig"); _ = @import("crypto/salsa20.zig"); _ = @import("crypto/siphash.zig"); _ = @import("crypto/25519/curve25519.zig"); _ = @import("crypto/25519/ed25519.zig"); _ = @import("crypto/25519/edwards25519.zig"); _ = @import("crypto/25519/field.zig"); _ = @import("crypto/25519/scalar.zig"); _ = @import("crypto/25519/x25519.zig"); _ = @import("crypto/25519/ristretto255.zig"); } test "issue #4532: no index out of bounds" { const types = [_]type{ hash.Md5, hash.Sha1, hash.sha2.Sha224, hash.sha2.Sha256, hash.sha2.Sha384, hash.sha2.Sha512, hash.sha3.Sha3_224, hash.sha3.Sha3_256, hash.sha3.Sha3_384, hash.sha3.Sha3_512, hash.blake2.Blake2s128, hash.blake2.Blake2s224, hash.blake2.Blake2s256, hash.blake2.Blake2b128, hash.blake2.Blake2b256, hash.blake2.Blake2b384, hash.blake2.Blake2b512, hash.Gimli, }; inline for (types) |Hasher| { var block = [_]u8{'#'} ** Hasher.block_length; var out1: [Hasher.digest_length]u8 = undefined; var out2: [Hasher.digest_length]u8 = undefined; const h0 = Hasher.init(.{}); var h = h0; h.update(block[0..]); h.final(&out1); h = h0; h.update(block[0..1]); h.update(block[1..]); h.final(&out2); std.testing.expectEqual(out1, out2); } }
lib/std/crypto.zig
const std = @import("std"); const liu = @import("./liu/lib.zig"); // This file stores the specifications of created assets and the code to // re-generate them from valid data, where the valid data is easier to reason // about than the produced asset files. Ideally the valid data is human-readable. const assert = std.debug.assert; const Allocator = std.mem.Allocator; pub const kilordle = struct { pub const Spec = struct { words: [5][]const u8, wordles: [5][]const u8, }; fn soa_translation(alloc: Allocator, data: []const u8) ![5][]const u8 { const count = data.len / 6; const out: [5][]u8 = .{ try alloc.alloc(u8, count), try alloc.alloc(u8, count), try alloc.alloc(u8, count), try alloc.alloc(u8, count), try alloc.alloc(u8, count), }; var index: u32 = 0; while (index < count) : (index += 1) { const wordle_data = data[(index * 6)..][0..5]; out[0][index] = wordle_data[0]; out[1][index] = wordle_data[1]; out[2][index] = wordle_data[2]; out[3][index] = wordle_data[3]; out[4][index] = wordle_data[4]; } return out; } pub fn generate() !void { const cwd = std.fs.cwd(); const words = try cwd.readFileAllocOptions( liu.Temp, "src/routes/kilordle/wordle-words.txt", 4096 * 4096, null, 8, null, ); const wordles = try cwd.readFileAllocOptions( liu.Temp, "src/routes/kilordle/wordles.txt", 4096 * 4096, null, 8, null, ); { var wordle_array_data = @ptrCast([][6]u8, wordles); wordle_array_data.len /= 6; std.sort.sort([6]u8, wordle_array_data, {}, struct { fn cmp(_: void, lhs: [6]u8, rhs: [6]u8) bool { return std.mem.lessThan(u8, &lhs, &rhs); } }.cmp); } const words_out = try soa_translation(liu.Temp, words); const wordles_out = try soa_translation(liu.Temp, wordles); const out_data = Spec{ .words = words_out, .wordles = wordles_out, }; const encoded = try liu.packed_asset.tempEncode(out_data, null); const out_bytes = try encoded.copyContiguous(liu.Temp); try cwd.writeFile("static/kilordle/data.rtf", out_bytes); } };
src/assets.zig
const std = @import("std"); const builtin = std.builtin; const linkage: builtin.GlobalLinkage = if (builtin.is_test) .Internal else .Weak; // This parameter is true iff the target architecture supports the bare minimum // to implement the atomic load/store intrinsics. // Some architectures support atomic load/stores but no CAS, but we ignore this // detail to keep the export logic clean and because we need some kind of CAS to // implement the spinlocks. const supports_atomic_ops = switch (builtin.arch) { .msp430, .avr => false, .arm, .armeb, .thumb, .thumbeb => // The ARM v6m ISA has no ldrex/strex and so it's impossible to do CAS // operations (unless we're targeting Linux, the kernel provides a way to // perform CAS operations). // XXX: The Linux code path is not implemented yet. !std.Target.arm.featureSetHas(std.Target.current.cpu.features, .has_v6m), else => true, }; // The size (in bytes) of the biggest object that the architecture can // load/store atomically. // Objects bigger than this threshold require the use of a lock. const largest_atomic_size = switch (builtin.arch) { // XXX: On x86/x86_64 we could check the presence of cmpxchg8b/cmpxchg16b // and set this parameter accordingly. else => @sizeOf(usize), }; const cache_line_size = 64; const SpinlockTable = struct { // Allocate ~4096 bytes of memory for the spinlock table const max_spinlocks = 64; const Spinlock = struct { // Prevent false sharing by providing enough padding between two // consecutive spinlock elements v: enum(usize) { Unlocked = 0, Locked } align(cache_line_size) = .Unlocked, fn acquire(self: *@This()) void { while (true) { switch (@atomicRmw(@TypeOf(self.v), &self.v, .Xchg, .Locked, .Acquire)) { .Unlocked => break, .Locked => {}, } } } fn release(self: *@This()) void { @atomicStore(@TypeOf(self.v), &self.v, .Unlocked, .Release); } }; list: [max_spinlocks]Spinlock = [_]Spinlock{.{}} ** max_spinlocks, // The spinlock table behaves as a really simple hash table, mapping // addresses to spinlocks. The mapping is not unique but that's only a // performance problem as the lock will be contended by more than a pair of // threads. fn get(self: *@This(), address: usize) *Spinlock { var sl = &self.list[(address >> 3) % max_spinlocks]; sl.acquire(); return sl; } }; var spinlocks: SpinlockTable = SpinlockTable{}; // The following builtins do not respect the specified memory model and instead // uses seq_cst, the strongest one, for simplicity sake. // Generic version of GCC atomic builtin functions. // Those work on any object no matter the pointer alignment nor its size. fn __atomic_load(size: u32, src: [*]u8, dest: [*]u8, model: i32) callconv(.C) void { var sl = spinlocks.get(@ptrToInt(src)); defer sl.release(); @memcpy(dest, src, size); } fn __atomic_store(size: u32, dest: [*]u8, src: [*]u8, model: i32) callconv(.C) void { var sl = spinlocks.get(@ptrToInt(dest)); defer sl.release(); @memcpy(dest, src, size); } fn __atomic_exchange(size: u32, ptr: [*]u8, val: [*]u8, old: [*]u8, model: i32) callconv(.C) void { var sl = spinlocks.get(@ptrToInt(ptr)); defer sl.release(); @memcpy(old, ptr, size); @memcpy(ptr, val, size); } fn __atomic_compare_exchange( size: u32, ptr: [*]u8, expected: [*]u8, desired: [*]u8, success: i32, failure: i32, ) callconv(.C) i32 { var sl = spinlocks.get(@ptrToInt(ptr)); defer sl.release(); for (ptr[0..size]) |b, i| { if (expected[i] != b) break; } else { // The two objects, ptr and expected, are equal @memcpy(ptr, desired, size); return 1; } @memcpy(expected, ptr, size); return 0; } comptime { if (supports_atomic_ops) { @export(__atomic_load, .{ .name = "__atomic_load", .linkage = linkage }); @export(__atomic_store, .{ .name = "__atomic_store", .linkage = linkage }); @export(__atomic_exchange, .{ .name = "__atomic_exchange", .linkage = linkage }); @export(__atomic_compare_exchange, .{ .name = "__atomic_compare_exchange", .linkage = linkage }); } } // Specialized versions of the GCC atomic builtin functions. // LLVM emits those iff the object size is known and the pointers are correctly // aligned. fn atomicLoadFn(comptime T: type) fn (*T, i32) callconv(.C) T { return struct { fn atomic_load_N(src: *T, model: i32) callconv(.C) T { if (@sizeOf(T) > largest_atomic_size) { var sl = spinlocks.get(@ptrToInt(src)); defer sl.release(); return src.*; } else { return @atomicLoad(T, src, .SeqCst); } } }.atomic_load_N; } comptime { if (supports_atomic_ops) { @export(atomicLoadFn(u8), .{ .name = "__atomic_load_1", .linkage = linkage }); @export(atomicLoadFn(u16), .{ .name = "__atomic_load_2", .linkage = linkage }); @export(atomicLoadFn(u32), .{ .name = "__atomic_load_4", .linkage = linkage }); @export(atomicLoadFn(u64), .{ .name = "__atomic_load_8", .linkage = linkage }); } } fn atomicStoreFn(comptime T: type) fn (*T, T, i32) callconv(.C) void { return struct { fn atomic_store_N(dst: *T, value: T, model: i32) callconv(.C) void { if (@sizeOf(T) > largest_atomic_size) { var sl = spinlocks.get(@ptrToInt(dst)); defer sl.release(); dst.* = value; } else { @atomicStore(T, dst, value, .SeqCst); } } }.atomic_store_N; } comptime { if (supports_atomic_ops) { @export(atomicStoreFn(u8), .{ .name = "__atomic_store_1", .linkage = linkage }); @export(atomicStoreFn(u16), .{ .name = "__atomic_store_2", .linkage = linkage }); @export(atomicStoreFn(u32), .{ .name = "__atomic_store_4", .linkage = linkage }); @export(atomicStoreFn(u64), .{ .name = "__atomic_store_8", .linkage = linkage }); } } fn atomicExchangeFn(comptime T: type) fn (*T, T, i32) callconv(.C) T { return struct { fn atomic_exchange_N(ptr: *T, val: T, model: i32) callconv(.C) T { if (@sizeOf(T) > largest_atomic_size) { var sl = spinlocks.get(@ptrToInt(ptr)); defer sl.release(); const value = ptr.*; ptr.* = val; return value; } else { return @atomicRmw(T, ptr, .Xchg, val, .SeqCst); } } }.atomic_exchange_N; } comptime { if (supports_atomic_ops) { @export(atomicExchangeFn(u8), .{ .name = "__atomic_exchange_1", .linkage = linkage }); @export(atomicExchangeFn(u16), .{ .name = "__atomic_exchange_2", .linkage = linkage }); @export(atomicExchangeFn(u32), .{ .name = "__atomic_exchange_4", .linkage = linkage }); @export(atomicExchangeFn(u64), .{ .name = "__atomic_exchange_8", .linkage = linkage }); } } fn atomicCompareExchangeFn(comptime T: type) fn (*T, *T, T, i32, i32) callconv(.C) i32 { return struct { fn atomic_compare_exchange_N(ptr: *T, expected: *T, desired: T, success: i32, failure: i32) callconv(.C) i32 { if (@sizeOf(T) > largest_atomic_size) { var sl = spinlocks.get(@ptrToInt(ptr)); defer sl.release(); const value = ptr.*; if (value == expected.*) { ptr.* = desired; return 1; } expected.* = value; return 0; } else { if (@cmpxchgStrong(T, ptr, expected.*, desired, .SeqCst, .SeqCst)) |old_value| { expected.* = old_value; return 0; } return 1; } } }.atomic_compare_exchange_N; } comptime { if (supports_atomic_ops) { @export(atomicCompareExchangeFn(u8), .{ .name = "__atomic_compare_exchange_1", .linkage = linkage }); @export(atomicCompareExchangeFn(u16), .{ .name = "__atomic_compare_exchange_2", .linkage = linkage }); @export(atomicCompareExchangeFn(u32), .{ .name = "__atomic_compare_exchange_4", .linkage = linkage }); @export(atomicCompareExchangeFn(u64), .{ .name = "__atomic_compare_exchange_8", .linkage = linkage }); } } fn fetchFn(comptime T: type, comptime op: builtin.AtomicRmwOp) fn (*T, T, i32) callconv(.C) T { return struct { pub fn fetch_op_N(ptr: *T, val: T, model: i32) callconv(.C) T { if (@sizeOf(T) > largest_atomic_size) { var sl = spinlocks.get(@ptrToInt(ptr)); defer sl.release(); const value = ptr.*; ptr.* = switch (op) { .Add => value +% val, .Sub => value -% val, .And => value & val, .Nand => ~(value & val), .Or => value | val, .Xor => value ^ val, else => @compileError("unsupported atomic op"), }; return value; } return @atomicRmw(T, ptr, op, val, .SeqCst); } }.fetch_op_N; } comptime { if (supports_atomic_ops) { @export(fetchFn(u8, .Add), .{ .name = "__atomic_fetch_add_1", .linkage = linkage }); @export(fetchFn(u16, .Add), .{ .name = "__atomic_fetch_add_2", .linkage = linkage }); @export(fetchFn(u32, .Add), .{ .name = "__atomic_fetch_add_4", .linkage = linkage }); @export(fetchFn(u64, .Add), .{ .name = "__atomic_fetch_add_8", .linkage = linkage }); @export(fetchFn(u8, .Sub), .{ .name = "__atomic_fetch_sub_1", .linkage = linkage }); @export(fetchFn(u16, .Sub), .{ .name = "__atomic_fetch_sub_2", .linkage = linkage }); @export(fetchFn(u32, .Sub), .{ .name = "__atomic_fetch_sub_4", .linkage = linkage }); @export(fetchFn(u64, .Sub), .{ .name = "__atomic_fetch_sub_8", .linkage = linkage }); @export(fetchFn(u8, .And), .{ .name = "__atomic_fetch_and_1", .linkage = linkage }); @export(fetchFn(u16, .And), .{ .name = "__atomic_fetch_and_2", .linkage = linkage }); @export(fetchFn(u32, .And), .{ .name = "__atomic_fetch_and_4", .linkage = linkage }); @export(fetchFn(u64, .And), .{ .name = "__atomic_fetch_and_8", .linkage = linkage }); @export(fetchFn(u8, .Or), .{ .name = "__atomic_fetch_or_1", .linkage = linkage }); @export(fetchFn(u16, .Or), .{ .name = "__atomic_fetch_or_2", .linkage = linkage }); @export(fetchFn(u32, .Or), .{ .name = "__atomic_fetch_or_4", .linkage = linkage }); @export(fetchFn(u64, .Or), .{ .name = "__atomic_fetch_or_8", .linkage = linkage }); @export(fetchFn(u8, .Xor), .{ .name = "__atomic_fetch_xor_1", .linkage = linkage }); @export(fetchFn(u16, .Xor), .{ .name = "__atomic_fetch_xor_2", .linkage = linkage }); @export(fetchFn(u32, .Xor), .{ .name = "__atomic_fetch_xor_4", .linkage = linkage }); @export(fetchFn(u64, .Xor), .{ .name = "__atomic_fetch_xor_8", .linkage = linkage }); @export(fetchFn(u8, .Nand), .{ .name = "__atomic_fetch_nand_1", .linkage = linkage }); @export(fetchFn(u16, .Nand), .{ .name = "__atomic_fetch_nand_2", .linkage = linkage }); @export(fetchFn(u32, .Nand), .{ .name = "__atomic_fetch_nand_4", .linkage = linkage }); @export(fetchFn(u64, .Nand), .{ .name = "__atomic_fetch_nand_8", .linkage = linkage }); } }
lib/std/special/compiler_rt/atomics.zig
const std = @import("std"); const ast = @import("ast.zig"); const Location = @import("location.zig").Location; const Scope = @import("scope.zig").Scope; const Diagnostics = @import("diagnostics.zig").Diagnostics; const Type = @import("typeset.zig").Type; const TypeSet = @import("typeset.zig").TypeSet; const AnalysisState = struct { /// Depth of nested loops (while, for) loop_nesting: usize, /// Depth of nested conditionally executed scopes (if, while, for) conditional_scope_depth: usize, /// Only `true` when not analyzing a function is_root_script: bool, }; const ValidationError = error{OutOfMemory}; const array_or_string = TypeSet.init(.{ .array, .string }); fn expressionTypeToString(src: ast.Expression.Type) []const u8 { return switch (src) { .array_indexer => "array indexer", .variable_expr => "variable", .array_literal => "array literal", .function_call => "function call", .method_call => "method call", .number_literal => "number literal", .string_literal => "string literal", .unary_operator => "unary operator application", .binary_operator => "binary operator application", }; } fn emitTooManyVariables(diagnostics: *Diagnostics, location: Location) !void { try diagnostics.emit(.@"error", location, "Too many variables declared! The maximum allowed number of variables is 35535.", .{}); } fn performTypeCheck(diagnostics: *Diagnostics, location: Location, expected: TypeSet, actual: TypeSet) !void { if (expected.intersection(actual).isEmpty()) { try diagnostics.emit(.warning, location, "Possible type mismatch detected: Expected {}, found {}", .{ expected, actual, }); } } /// Validates a expression and returns a set of possible result types. fn validateExpression(state: *AnalysisState, diagnostics: *Diagnostics, scope: *Scope, expression: ast.Expression) ValidationError!TypeSet { // we're happy for now with expressions... switch (expression.type) { .array_indexer => |indexer| { const array_type = try validateExpression(state, diagnostics, scope, indexer.value.*); const index_type = try validateExpression(state, diagnostics, scope, indexer.index.*); try performTypeCheck(diagnostics, indexer.value.location, array_or_string, array_type); try performTypeCheck(diagnostics, indexer.index.location, TypeSet.from(.number), index_type); if (array_type.contains(.array)) { // when we're possibly indexing an array, // we return a value of type `any` return TypeSet.any; } else if (array_type.contains(.string)) { // when we are not an array, but a string, // we can only return a number. return TypeSet.from(.number); } else { return TypeSet.empty; } }, .variable_expr => |variable_name| { // Check reserved names if (std.mem.eql(u8, variable_name, "true")) { return TypeSet.from(.boolean); } else if (std.mem.eql(u8, variable_name, "false")) { return TypeSet.from(.boolean); } else if (std.mem.eql(u8, variable_name, "void")) { return TypeSet.from(.void); } const variable = scope.get(variable_name) orelse { try diagnostics.emit(.@"error", expression.location, "Use of undeclared variable {}", .{ variable_name, }); return TypeSet.any; }; return variable.possible_types; }, .array_literal => |array| { for (array) |item| { _ = try validateExpression(state, diagnostics, scope, item); } return TypeSet.from(.array); }, .function_call => |call| { if (call.function.type != .variable_expr) { try diagnostics.emit(.@"error", expression.location, "Function name expected", .{}); } if (call.arguments.len >= 256) { try diagnostics.emit(.@"error", expression.location, "Function argument list exceeds 255 arguments!", .{}); } for (call.arguments) |item| { _ = try validateExpression(state, diagnostics, scope, item); } return TypeSet.any; }, .method_call => |call| { _ = try validateExpression(state, diagnostics, scope, call.object.*); for (call.arguments) |item| { _ = try validateExpression(state, diagnostics, scope, item); } return TypeSet.any; }, .number_literal => |expr| { // these are always ok return TypeSet.from(.number); }, .string_literal => |literal| { return TypeSet.from(.string); }, .unary_operator => |expr| { const result = try validateExpression(state, diagnostics, scope, expr.value.*); const expected = switch (expr.operator) { .negate => Type.number, .boolean_not => Type.boolean, }; try performTypeCheck(diagnostics, expression.location, TypeSet.from(expected), result); return result; }, .binary_operator => |expr| { const lhs = try validateExpression(state, diagnostics, scope, expr.lhs.*); const rhs = try validateExpression(state, diagnostics, scope, expr.rhs.*); const accepted_set = switch (expr.operator) { .add => TypeSet.init(.{ .string, .number, .array }), .subtract, .multiply, .divide, .modulus => TypeSet.from(.number), .boolean_or, .boolean_and => TypeSet.from(.boolean), .equal, .different => TypeSet.any, .less_than, .greater_than, .greater_or_equal_than, .less_or_equal_than => TypeSet.init(.{ .string, .number, .array }), }; try performTypeCheck(diagnostics, expr.lhs.location, accepted_set, lhs); try performTypeCheck(diagnostics, expr.rhs.location, accepted_set, rhs); if (!TypeSet.areCompatible(lhs, rhs)) { try diagnostics.emit(.warning, expression.location, "Possible type mismatch detected. {} and {} are not compatible.\n", .{ lhs, rhs, }); return TypeSet.empty; } return switch (expr.operator) { .add => TypeSet.intersection(lhs, rhs), .subtract, .multiply, .divide, .modulus => TypeSet.from(.number), .boolean_or, .boolean_and => TypeSet.from(.boolean), .less_than, .greater_than, .greater_or_equal_than, .less_or_equal_than, .equal, .different => TypeSet.from(.boolean), }; }, } return .void; } fn validateStore(state: *AnalysisState, diagnostics: *Diagnostics, scope: *Scope, expression: ast.Expression, type_hint: TypeSet) ValidationError!void { if (!expression.isAssignable()) { try diagnostics.emit(.@"error", expression.location, "Expected array indexer or a variable, got {}", .{ expressionTypeToString(expression.type), }); return; } switch (expression.type) { .array_indexer => |indexer| { const array_val = try validateExpression(state, diagnostics, scope, indexer.value.*); const index_val = try validateExpression(state, diagnostics, scope, indexer.index.*); try performTypeCheck(diagnostics, indexer.value.location, array_or_string, array_val); try performTypeCheck(diagnostics, indexer.index.location, TypeSet.from(.number), index_val); if (array_val.contains(.string) and !array_val.contains(.array)) { // when we are sure we write into a string, but definitly not an array // check if we're writing a number. try performTypeCheck(diagnostics, expression.location, TypeSet.from(.number), type_hint); } // now propagate the store validation back to the lvalue. // Note that we can assume that the lvalue _is_ a array, as it would be a type mismatch otherwise. try validateStore(state, diagnostics, scope, indexer.value.*, array_or_string.intersection(array_val)); }, .variable_expr => |variable_name| { if (std.mem.eql(u8, variable_name, "true") or std.mem.eql(u8, variable_name, "false") or std.mem.eql(u8, variable_name, "void")) { try diagnostics.emit(.@"error", expression.location, "Expected array indexer or a variable, got {}", .{ variable_name, }); } else if (scope.get(variable_name)) |variable| { if (variable.is_const) { try diagnostics.emit(.@"error", expression.location, "Assignment to constant {} not allowed.", .{ variable_name, }); } const previous = variable.possible_types; if (state.conditional_scope_depth > 0) { variable.possible_types = variable.possible_types.@"union"(type_hint); } else { variable.possible_types = type_hint; } // std.debug.warn("mutate {} from {} into {} applying {}\n", .{ // variable_name, // previous, // variable.possible_types, // type_hint, // }); } }, else => unreachable, } } fn validateStatement(state: *AnalysisState, diagnostics: *Diagnostics, scope: *Scope, stmt: ast.Statement) ValidationError!void { switch (stmt.type) { .empty => { // trivial: do nothing! }, .assignment => |ass| { const value_type = try validateExpression(state, diagnostics, scope, ass.value); if (ass.target.isAssignable()) { try validateStore(state, diagnostics, scope, ass.target, value_type); } else { try diagnostics.emit(.@"error", ass.target.location, "Expected either a array indexer or a variable, got {}", .{ @tagName(@as(ast.Expression.Type, ass.target.type)), }); } }, .discard_value => |expr| { _ = try validateExpression(state, diagnostics, scope, expr); }, .return_void => { // this is always ok }, .return_expr => |expr| { // this is ok when the expr is ok _ = try validateExpression(state, diagnostics, scope, expr); // and when we are not on the root script. if (state.is_root_script) { try diagnostics.emit(.@"error", stmt.location, "Returning a value from global scope is not allowed.", .{}); } }, .while_loop => |loop| { state.loop_nesting += 1; defer state.loop_nesting -= 1; state.conditional_scope_depth += 1; defer state.conditional_scope_depth -= 1; const condition_type = try validateExpression(state, diagnostics, scope, loop.condition); try validateStatement(state, diagnostics, scope, loop.body.*); try performTypeCheck(diagnostics, stmt.location, TypeSet.from(.boolean), condition_type); }, .for_loop => |loop| { state.loop_nesting += 1; defer state.loop_nesting -= 1; state.conditional_scope_depth += 1; defer state.conditional_scope_depth -= 1; try scope.enter(); scope.declare(loop.variable, true) catch |err| switch (err) { error.AlreadyDeclared => unreachable, // not possible for locals error.TooManyVariables => try emitTooManyVariables(diagnostics, stmt.location), else => |e| return e, }; const array_type = try validateExpression(state, diagnostics, scope, loop.source); try validateStatement(state, diagnostics, scope, loop.body.*); try performTypeCheck(diagnostics, stmt.location, TypeSet.from(.array), array_type); try scope.leave(); }, .if_statement => |conditional| { state.conditional_scope_depth += 1; defer state.conditional_scope_depth -= 1; const conditional_type = try validateExpression(state, diagnostics, scope, conditional.condition); try validateStatement(state, diagnostics, scope, conditional.true_body.*); if (conditional.false_body) |body| { try validateStatement(state, diagnostics, scope, body.*); } try performTypeCheck(diagnostics, stmt.location, TypeSet.from(.boolean), conditional_type); }, .declaration => |decl| { // evaluate expression before so we can safely reference up-variables: // var a = a * 2; const initial_value = if (decl.initial_value) |init_val| try validateExpression(state, diagnostics, scope, init_val) else null; scope.declare(decl.variable, decl.is_const) catch |err| switch (err) { error.AlreadyDeclared => try diagnostics.emit(.@"error", stmt.location, "Global variable {} is already declared!", .{decl.variable}), error.TooManyVariables => try emitTooManyVariables(diagnostics, stmt.location), else => |e| return e, }; if (initial_value) |init_val| scope.get(decl.variable).?.possible_types = init_val; if (decl.is_const and decl.initial_value == null) { try diagnostics.emit(.@"error", stmt.location, "Constant {} must be initialized!", .{ decl.variable, }); } }, .block => |blk| { try scope.enter(); for (blk) |sub_stmt| { try validateStatement(state, diagnostics, scope, sub_stmt); } try scope.leave(); }, .@"break" => { if (state.loop_nesting == 0) { try diagnostics.emit(.@"error", stmt.location, "break outside of loop!", .{}); } }, .@"continue" => { if (state.loop_nesting == 0) { try diagnostics.emit(.@"error", stmt.location, "continue outside of loop!", .{}); } }, } } fn getErrorCount(diagnostics: *const Diagnostics) usize { var res: usize = 0; for (diagnostics.messages.items) |msg| { if (msg.kind == .@"error") res += 1; } return res; } /// Validates the `program` against programming mistakes and filles `diagnostics` with the findings. /// Note that the function will always succeed when no `OutOfMemory` happens. To see if the program /// is semantically sound, check `diagnostics` for error messages. pub fn validate(allocator: *std.mem.Allocator, diagnostics: *Diagnostics, program: ast.Program) ValidationError!bool { var global_scope = Scope.init(allocator, null, true); defer global_scope.deinit(); const initial_errc = getErrorCount(diagnostics); for (program.root_script) |stmt| { var state = AnalysisState{ .loop_nesting = 0, .is_root_script = true, .conditional_scope_depth = 0, }; try validateStatement(&state, diagnostics, &global_scope, stmt); } std.debug.assert(global_scope.return_point.items.len == 0); for (program.functions) |function, i| { for (program.functions[0..i]) |other_fn| { if (std.mem.eql(u8, function.name, other_fn.name)) { try diagnostics.emit(.@"error", function.location, "A function with the name {} was already declared!", .{function.name}); break; } } var local_scope = Scope.init(allocator, &global_scope, false); defer local_scope.deinit(); for (function.parameters) |param| { local_scope.declare(param, true) catch |err| switch (err) { error.AlreadyDeclared => try diagnostics.emit(.@"error", function.location, "A parameter {} is already declared!", .{param}), error.TooManyVariables => try emitTooManyVariables(diagnostics, function.location), else => |e| return e, }; } var state = AnalysisState{ .loop_nesting = 0, .is_root_script = false, .conditional_scope_depth = 0, }; try validateStatement(&state, diagnostics, &local_scope, function.body); } return (getErrorCount(diagnostics) == initial_errc); } test "validate correct program" { // For lack of a better idea: // Just run the analysis against the compiler test suite var diagnostics = Diagnostics.init(std.testing.allocator); defer diagnostics.deinit(); const seq = try @import("tokenizer.zig").tokenize(std.testing.allocator, &diagnostics, "src/test/compiler.lola", @embedFile("../../test/compiler.lola")); defer std.testing.allocator.free(seq); var pgm = try @import("parser.zig").parse(std.testing.allocator, &diagnostics, seq); defer pgm.deinit(); std.testing.expectEqual(true, try validate(std.testing.allocator, &diagnostics, pgm)); for (diagnostics.messages.items) |msg| { std.debug.warn("{}\n", .{msg}); } std.testing.expectEqual(@as(usize, 0), diagnostics.messages.items.len); } fn expectAnalysisErrors(source: []const u8, expected_messages: []const []const u8) !void { // For lack of a better idea: // Just run the analysis against the compiler test suite var diagnostics = Diagnostics.init(std.testing.allocator); defer diagnostics.deinit(); const seq = try @import("tokenizer.zig").tokenize(std.testing.allocator, &diagnostics, "", source); defer std.testing.allocator.free(seq); var pgm = try @import("parser.zig").parse(std.testing.allocator, &diagnostics, seq); defer pgm.deinit(); std.testing.expectEqual(false, try validate(std.testing.allocator, &diagnostics, pgm)); std.testing.expectEqual(expected_messages.len, diagnostics.messages.items.len); for (expected_messages) |expected, i| { std.testing.expectEqualStrings(expected, diagnostics.messages.items[i].message); } } test "detect return from root script" { try expectAnalysisErrors("return 10;", &[_][]const u8{ "Returning a value from global scope is not allowed.", }); } test "detect const without init" { try expectAnalysisErrors("const a;", &[_][]const u8{ "Constant a must be initialized!", }); } test "detect assignment to const" { try expectAnalysisErrors("const a = 5; a = 10;", &[_][]const u8{ "Assignment to constant a not allowed.", }); } test "detect doubly-declared global variables" { try expectAnalysisErrors("var a; var a;", &[_][]const u8{ "Global variable a is already declared!", }); } test "detect assignment to const parameter" { try expectAnalysisErrors("function f(x) { x = void; }", &[_][]const u8{ "Assignment to constant x not allowed.", }); }
src/library/compiler/analysis.zig
const builtin = @import("builtin"); const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the hyperbolic arc-cosine of x. /// /// Special cases: /// - acosh(x) = snan if x < 1 /// - acosh(nan) = nan pub fn acosh(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => acosh32(x), f64 => acosh64(x), else => @compileError("acosh not implemented for " ++ @typeName(T)), }; } // acosh(x) = log(x + sqrt(x * x - 1)) fn acosh32(x: f32) f32 { const u = @bitCast(u32, x); const i = u & 0x7FFFFFFF; // |x| < 2, invalid if x < 1 or nan if (i < 0x3F800000 + (1 << 23)) { return math.log1p(x - 1 + math.sqrt((x - 1) * (x - 1) + 2 * (x - 1))); } // |x| < 0x1p12 else if (i < 0x3F800000 + (12 << 23)) { return math.ln(2 * x - 1 / (x + math.sqrt(x * x - 1))); } // |x| >= 0x1p12 else { return math.ln(x) + 0.693147180559945309417232121458176568; } } fn acosh64(x: f64) f64 { const u = @bitCast(u64, x); const e = (u >> 52) & 0x7FF; // |x| < 2, invalid if x < 1 or nan if (e < 0x3FF + 1) { return math.log1p(x - 1 + math.sqrt((x - 1) * (x - 1) + 2 * (x - 1))); } // |x| < 0x1p26 else if (e < 0x3FF + 26) { return math.ln(2 * x - 1 / (x + math.sqrt(x * x - 1))); } // |x| >= 0x1p26 or nan else { return math.ln(x) + 0.693147180559945309417232121458176568; } } test "math.acosh" { try expect(acosh(@as(f32, 1.5)) == acosh32(1.5)); try expect(acosh(@as(f64, 1.5)) == acosh64(1.5)); } test "math.acosh32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, acosh32(1.5), 0.962424, epsilon)); try expect(math.approxEqAbs(f32, acosh32(37.45), 4.315976, epsilon)); try expect(math.approxEqAbs(f32, acosh32(89.123), 5.183133, epsilon)); try expect(math.approxEqAbs(f32, acosh32(123123.234375), 12.414088, epsilon)); } test "math.acosh64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, acosh64(1.5), 0.962424, epsilon)); try expect(math.approxEqAbs(f64, acosh64(37.45), 4.315976, epsilon)); try expect(math.approxEqAbs(f64, acosh64(89.123), 5.183133, epsilon)); try expect(math.approxEqAbs(f64, acosh64(123123.234375), 12.414088, epsilon)); } test "math.acosh32.special" { try expect(math.isNan(acosh32(math.nan(f32)))); try expect(math.isSignalNan(acosh32(0.5))); } test "math.acosh64.special" { try expect(math.isNan(acosh64(math.nan(f64)))); try expect(math.isSignalNan(acosh64(0.5))); }
lib/std/math/acosh.zig
const aoc = @import("../aoc.zig"); const std = @import("std"); const HappinessTable = aoc.StringTable(i16); const HappinessPermutator = aoc.Permutator([]const u8); pub fn run(problem: *aoc.Problem) !aoc.Solution { var happiness = HappinessTable.init(problem.allocator); while (problem.line()) |line| { var tokens = std.mem.tokenize(u8, line, " "); const p1 = tokens.next().?; _ = tokens.next().?; const factor: i8 = if (std.mem.eql(u8, tokens.next().?, "gain")) 1 else -1; const amount = try std.fmt.parseInt(i8, tokens.next().?, 10); _ = tokens.next().?; _ = tokens.next().?; _ = tokens.next().?; _ = tokens.next().?; _ = tokens.next().?; _ = tokens.next().?; const p2_dot = tokens.next().?; try happiness.put(p1, p2_dot[0..p2_dot.len-1], factor * amount); } var permutator = try HappinessPermutator.fromHashMapKeys(problem.allocator, HappinessTable, happiness); defer permutator.deinit(); const excluded = get_max_happiness(&permutator, happiness); const me = "__ME__"; permutator.reset(); for (permutator.elements.items) |person| { try happiness.put(person, me, 0); try happiness.put(me, person, 0); } try permutator.elements.append(me); const included = get_max_happiness(&permutator, happiness); return problem.solution(excluded, included); } fn get_max_happiness(permutator: *HappinessPermutator, happiness: HappinessTable) u16 { var max_happiness: i16 = 0; while (permutator.next()) |seating| { var this_happiness: i16 = happiness.get(seating[0], seating[seating.len - 1]).? + happiness.get(seating[seating.len - 1], seating[0]).?; for (seating[0..seating.len - 1]) |p1, idx| { const p2 = seating[idx + 1]; this_happiness += happiness.get(p1, p2).? + happiness.get(p2, p1).?; } max_happiness = std.math.max(max_happiness, this_happiness); } return @intCast(u16, max_happiness); }
src/main/zig/2015/day13.zig
const std = @import("std"); const mc = @import("mc.zig"); const color = @import("color.zig"); const tracy = @import("tracy.zig"); const audio = @import("audio-extractor.zig"); const FrameProcessor = @import("frame-processor.zig").FrameProcessor; usingnamespace @import("threadpool"); const sdl = @cImport({ @cInclude("SDL.h"); }); // 8K resolution - used to testing under extreme circumstances and forcing bottleneck onto CPU execution const WINDOW_WIDTH = 7680; const WINDOW_HEIGHT = 4320; const ColorTranslationPool = ThreadPool(translateColors, null); const SDLFrameProcessor = FrameProcessor(*SDLWindow); var running: bool = true; const SDLWindow = struct { // the only two functions that you can set this without breaking is SDL_BlitSurface and SDL_BlitScaled // note: if you use SDL_BlitScaled, there is a _massive_ performance penalty, obviously due to scaling const BlitFunction = sdl.SDL_BlitSurface; const Self = @This(); window: *sdl.SDL_Window, surface: *sdl.SDL_Surface, pub fn create(width: u16, height: u16) Self { return Self{ .window = sdl.SDL_CreateWindow( "Vidmap MC Viewer", sdl.SDL_WINDOWPOS_CENTERED, sdl.SDL_WINDOWPOS_CENTERED, width, height, sdl.SDL_WINDOW_MAXIMIZED, ).?, .surface = makeSurface(width, height), }; } pub fn updateWindow(self: *Self, data: [*]const u8) void { self.surface.*.pixels = @intToPtr([*]u8, @ptrToInt(data)); // tracy start _ = BlitFunction(self.surface, null, sdl.SDL_GetWindowSurface(self.window), null); // tracy end _ = sdl.SDL_UpdateWindowSurface(self.window); } pub fn processInput(self: *Self) bool { _ = self; var event: sdl.SDL_Event = undefined; _ = sdl.SDL_PollEvent(&event); return event.@"type" != sdl.SDL_QUIT; } pub fn exit(self: *Self) void { _ = self; sdl.SDL_Quit(); } fn makeSurface(width: u16, height: u16) *sdl.SDL_Surface { var surface = sdl.SDL_CreateRGBSurfaceWithFormat(0, 0, 0, 16, sdl.SDL_PIXELFORMAT_RGB444); surface.*.flags |= sdl.SDL_PREALLOC; surface.*.w = width; surface.*.h = height; surface.*.pitch = width * 2; return surface; } }; const allocator = std.testing.allocator; var threadPool: *ColorTranslationPool = undefined; pub fn main() !void { const target = parseTarget(allocator); std.debug.print("Opening {s}\n", .{target}); if (sdl.SDL_Init(sdl.SDL_INIT_VIDEO | sdl.SDL_INIT_TIMER) != 0) { @panic("Failed to init sdl.SDL"); } try audio.extractAudio(target, "audio.ogg"); var window = SDLWindow.create(WINDOW_WIDTH, WINDOW_HEIGHT); threadPool = try ColorTranslationPool.init(allocator, 4); var processor = try allocator.create(SDLFrameProcessor); processor.* = .{ .userData = &window, .callback = updateSDLWindow, }; const frameDelay = @floatToInt(u32, try processor.open(target, WINDOW_WIDTH, WINDOW_HEIGHT)); const timer = sdl.SDL_AddTimer(frameDelay, stepNextFrame, processor); while (running and window.processInput()) { sdl.SDL_Delay(frameDelay); } _ = sdl.SDL_RemoveTimer(timer); } fn parseTarget(alloc: *std.mem.Allocator) [:0]const u8 { const default = "video.mp4"[0..]; var argsIter = std.process.args(); // skip own exe path _ = argsIter.skip(); return (argsIter.next(alloc) orelse default) catch default; } fn translateColors(pixelData: [*]u16, srcOff: usize, len: usize) void { for (pixelData[srcOff .. srcOff + len]) |*pixel| { pixel.* = color.toU16RGB(mc.ColorLookupTable[pixel.*]); } } fn updateSDLWindow(rawData: [*c]const u8, window: ?*SDLWindow) void { const pixelCount = WINDOW_WIDTH * WINDOW_HEIGHT; // first we force zig to accept alignment, because right now it doesn't know it's already aligned const realigned = @ptrCast([*]const u16, @alignCast(@alignOf(u16), rawData))[0..pixelCount]; // and then we do hacky stuff to interpret this as mutable RGBA4444 short data, since we actually // want to write back to this (as we have to display it via SDL_Surface) const pixelData = @intToPtr([*]u16, @ptrToInt(&realigned[0]))[0..pixelCount]; const tracy_colorTranslate = tracy.ZoneN(@src(), "Color Translation"); // figure out how big each workload should be const partition = (pixelCount * @sizeOf(u16)) / ((std.Thread.getCpuCount() catch 2) / 2); var index: usize = 0; while (index < pixelCount) : (index += partition) { threadPool.submitTask(.{ pixelData, index, partition, }) catch @panic("Failed to submit color translation task"); } threadPool.awaitTermination() catch return; tracy_colorTranslate.End(); const tracy_updateWindow = tracy.ZoneN(@src(), "Update SDL Window"); window.?.updateWindow(rawData); tracy_updateWindow.End(); } fn stepNextFrame(interval: u32, processorPtr: ?*c_void) callconv(.C) u32 { defer tracy.FrameMark(); var processor = @ptrCast(*SDLFrameProcessor, @alignCast(8, processorPtr.?)).*; const tracy_frameProcess = tracy.ZoneN(@src(), "Frame Processing"); defer tracy_frameProcess.End(); if (!processor.processNextFrame()) { running = false; return 0; } return interval; }
nativemap/src/sdl-app.zig
const FILE = @import("std").c.FILE; pub fn ErrUnion(comptime t: type) type { return union(enum) { err: status, ok: t, pub fn init(result: t, stat: status) @This() { return if (stat == .OK) .{ .ok = result } else .{ .err = stat }; } }; } pub const Oom = error{OutOfMemory}; pub const zone = opaque { extern fn ldns_zone_new_frm_fp_l(z: ?**zone, fp: *FILE, origin: ?*const rdf, ttl: u32, c: rr_class, line_nr: *c_int) status; pub const NewFrmFpDiagnostic = struct { code: status, line: c_int, }; pub const NewFrmFpResult = union(enum) { err: NewFrmFpDiagnostic, ok: *zone, }; pub fn new_frm_fp(fp: *FILE, origin: ?*const rdf, ttl: u32, c: rr_class) NewFrmFpResult { var z: *zone = undefined; var line: c_int = 0; const stat = ldns_zone_new_frm_fp_l(&z, fp, origin, ttl, c, &line); if (stat == .OK) { return .{ .ok = z }; } else { return .{ .err = .{ .code = stat, .line = line } }; } } extern fn ldns_zone_soa(z: *const zone) ?*rr; pub const soa = ldns_zone_soa; extern fn ldns_zone_rrs(z: *const zone) *rr_list; pub const rrs = ldns_zone_rrs; extern fn ldns_zone_deep_free(zone: *zone) void; pub const deep_free = ldns_zone_deep_free; }; pub const rr = opaque { extern fn ldns_rr_owner(row: *const rr) *rdf; pub const owner = ldns_rr_owner; extern fn ldns_rr_ttl(row: *const rr) u32; pub const ttl = ldns_rr_ttl; extern fn ldns_rr_get_type(row: *const rr) rr_type; pub const get_type = ldns_rr_get_type; extern fn ldns_rr_rd_count(row: *const rr) usize; pub const rd_count = ldns_rr_rd_count; extern fn ldns_rr_rdf(row: *const rr, nr: usize) ?*rdf; pub fn rdf(row: *const rr, nr: usize) *rdf { return row.ldns_rr_rdf(nr).?; // null on out of bounds } extern fn ldns_rr_new_frm_str(n: ?**rr, str: [*:0]const u8, default_ttl: u32, origin: ?*const rdf, prev: ?*?*rdf) status; pub fn new_frm_str(str: [*:0]const u8, default_ttl: u32, origin: ?*const rdf, prev: ?*?*rdf) ErrUnion(*rr){ var row: *rr = undefined; const stat = ldns_rr_new_frm_str(&row, str, default_ttl, origin, null); return ErrUnion(*rr).init(row, stat); } extern fn ldns_rr_free(row: *rr) void; pub const free = ldns_rr_free; }; pub const rr_list = opaque { extern fn ldns_rr_list_rr_count(list: *const rr_list) usize; pub const rr_count = ldns_rr_list_rr_count; extern fn ldns_rr_list_rr(list: *const rr_list, nr: usize) ?*rr; pub fn rr(list: *const rr_list, nr: usize) *rr { return list.ldns_rr_list_rr(nr).?; // null on out of bounds } }; pub const rdf = opaque { extern fn ldns_rdf_get_type(rd: *const rdf) rdf_type; pub const get_type = ldns_rdf_get_type; extern fn ldns_rdf2buffer_str(output: *buffer, rdf: *const rdf) status; pub fn appendStr(rd: *const rdf, output: *buffer) status { return ldns_rdf2buffer_str(output, rd); } extern fn ldns_rdf2native_int8(rd: *const rdf) u8; pub const int8 = ldns_rdf2native_int8; extern fn ldns_rdf2native_int16(rd: *const rdf) u16; pub const int16 = ldns_rdf2native_int16; extern fn ldns_rdf2native_int32(rd: *const rdf) u32; pub const int32 = ldns_rdf2native_int32; extern fn ldns_rdf_new_frm_str(type_: rdf_type, str: [*:0]const u8) ?*rdf; pub const new_frm_str = ldns_rdf_new_frm_str; extern fn ldns_rdf_deep_free(rd: *rdf) void; pub const deep_free = ldns_rdf_deep_free; }; pub const buffer = opaque { extern fn ldns_buffer_new(capacity: usize) ?*buffer; pub fn new(capacity: usize) Oom!*buffer { return ldns_buffer_new(capacity) orelse error.OutOfMemory; } extern fn ldns_buffer_free(buffer: *buffer) void; pub const free = ldns_buffer_free; pub fn clear(buf: *buffer) void { const casted = @ptrCast(*buffer_struct, @alignCast(@alignOf(buffer_struct), buf)); casted._position = 0; casted._limit = casted._capacity; } pub fn data(buf: *buffer) []u8 { const casted = @ptrCast(*buffer_struct, @alignCast(@alignOf(buffer_struct), buf)); return casted._data[0..casted._position]; } }; // TODO when zig translate-c supports bitfields fix this const buffer_struct = extern struct { // The current position used for reading/writing _position: usize, // The read/write limit _limit: usize, // The amount of data the buffer can contain _capacity: usize, // The data contained in the buffer _data: [*]u8, // If the buffer is fixed it cannot be resized //unsigned _fixed : 1; // The current state of the buffer. If writing to the buffer fails // for any reason, this value is changed. This way, you can perform // multiple writes in sequence and check for success afterwards. //status _status; }; pub const rr_class = extern enum(c_int) { IN = 1, CH = 3, HS = 4, NONE = 254, ANY = 255, FIRST = 0, LAST = 65535, COUNT = 65536, _, }; pub const rr_type = extern enum(c_int) { A = 1, NS = 2, MD = 3, MF = 4, CNAME = 5, SOA = 6, MB = 7, MG = 8, MR = 9, NULL = 10, WKS = 11, PTR = 12, HINFO = 13, MINFO = 14, MX = 15, TXT = 16, RP = 17, AFSDB = 18, X25 = 19, ISDN = 20, RT = 21, NSAP = 22, NSAP_PTR = 23, SIG = 24, KEY = 25, PX = 26, GPOS = 27, AAAA = 28, LOC = 29, NXT = 30, EID = 31, NIMLOC = 32, SRV = 33, ATMA = 34, NAPTR = 35, KX = 36, CERT = 37, A6 = 38, DNAME = 39, SINK = 40, OPT = 41, APL = 42, DS = 43, SSHFP = 44, IPSECKEY = 45, RRSIG = 46, NSEC = 47, DNSKEY = 48, DHCID = 49, NSEC3 = 50, NSEC3PARAM = 51, NSEC3PARAMS = 51, TLSA = 52, SMIMEA = 53, HIP = 55, NINFO = 56, RKEY = 57, TALINK = 58, CDS = 59, CDNSKEY = 60, OPENPGPKEY = 61, CSYNC = 62, ZONEMD = 63, SPF = 99, UINFO = 100, UID = 101, GID = 102, UNSPEC = 103, NID = 104, L32 = 105, L64 = 106, LP = 107, EUI48 = 108, EUI64 = 109, TKEY = 249, TSIG = 250, IXFR = 251, AXFR = 252, MAILB = 253, MAILA = 254, ANY = 255, URI = 256, CAA = 257, AVC = 258, DOA = 259, AMTRELAY = 260, TA = 32768, DLV = 32769, FIRST = 0, LAST = 65535, COUNT = 65536, _, extern fn ldns_rr_type2buffer_str(output: *buffer, type_: rr_type) status; pub fn appendStr(type_: rr_type, output: *buffer) status { return ldns_rr_type2buffer_str(output, type_); } }; pub const rdf_type = extern enum(c_int) { NONE = 0, DNAME = 1, INT8 = 2, INT16 = 3, INT32 = 4, A = 5, AAAA = 6, STR = 7, APL = 8, B32_EXT = 9, B64 = 10, HEX = 11, NSEC = 12, TYPE = 13, CLASS = 14, CERT_ALG = 15, ALG = 16, UNKNOWN = 17, TIME = 18, PERIOD = 19, TSIGTIME = 20, HIP = 21, INT16_DATA = 22, SERVICE = 23, LOC = 24, WKS = 25, NSAP = 26, ATMA = 27, IPSECKEY = 28, NSEC3_SALT = 29, NSEC3_NEXT_OWNER = 30, ILNP64 = 31, EUI48 = 32, EUI64 = 33, TAG = 34, LONG_STR = 35, CERTIFICATE_USAGE = 36, SELECTOR = 37, MATCHING_TYPE = 38, AMTRELAY = 39, BITMAP = 12, _, }; pub const status = extern enum(c_int) { OK, EMPTY_LABEL, LABEL_OVERFLOW, DOMAINNAME_OVERFLOW, DOMAINNAME_UNDERFLOW, DDD_OVERFLOW, PACKET_OVERFLOW, INVALID_POINTER, MEM_ERR, INTERNAL_ERR, SSL_ERR, ERR, INVALID_INT, INVALID_IP4, INVALID_IP6, INVALID_STR, INVALID_B32_EXT, INVALID_B64, INVALID_HEX, INVALID_TIME, NETWORK_ERR, ADDRESS_ERR, FILE_ERR, UNKNOWN_INET, NOT_IMPL, NULL, CRYPTO_UNKNOWN_ALGO, CRYPTO_ALGO_NOT_IMPL, CRYPTO_NO_RRSIG, CRYPTO_NO_DNSKEY, CRYPTO_NO_TRUSTED_DNSKEY, CRYPTO_NO_DS, CRYPTO_NO_TRUSTED_DS, CRYPTO_NO_MATCHING_KEYTAG_DNSKEY, CRYPTO_VALIDATED, CRYPTO_BOGUS, CRYPTO_SIG_EXPIRED, CRYPTO_SIG_NOT_INCEPTED, CRYPTO_TSIG_BOGUS, CRYPTO_TSIG_ERR, CRYPTO_EXPIRATION_BEFORE_INCEPTION, CRYPTO_TYPE_COVERED_ERR, ENGINE_KEY_NOT_LOADED, NSEC3_ERR, RES_NO_NS, RES_QUERY, WIRE_INCOMPLETE_HEADER, WIRE_INCOMPLETE_QUESTION, WIRE_INCOMPLETE_ANSWER, WIRE_INCOMPLETE_AUTHORITY, WIRE_INCOMPLETE_ADDITIONAL, NO_DATA, CERT_BAD_ALGORITHM, SYNTAX_TYPE_ERR, SYNTAX_CLASS_ERR, SYNTAX_TTL_ERR, SYNTAX_INCLUDE_ERR_NOTIMPL, SYNTAX_RDATA_ERR, SYNTAX_DNAME_ERR, SYNTAX_VERSION_ERR, SYNTAX_ALG_ERR, SYNTAX_KEYWORD_ERR, SYNTAX_TTL, SYNTAX_ORIGIN, SYNTAX_INCLUDE, SYNTAX_EMPTY, SYNTAX_ITERATIONS_OVERFLOW, SYNTAX_MISSING_VALUE_ERR, SYNTAX_INTEGER_OVERFLOW, SYNTAX_BAD_ESCAPE, SOCKET_ERROR, SYNTAX_ERR, DNSSEC_EXISTENCE_DENIED, DNSSEC_NSEC_RR_NOT_COVERED, DNSSEC_NSEC_WILDCARD_NOT_COVERED, DNSSEC_NSEC3_ORIGINAL_NOT_FOUND, MISSING_RDATA_FIELDS_RRSIG, MISSING_RDATA_FIELDS_KEY, CRYPTO_SIG_EXPIRED_WITHIN_MARGIN, CRYPTO_SIG_NOT_INCEPTED_WITHIN_MARGIN, DANE_STATUS_MESSAGES, DANE_UNKNOWN_CERTIFICATE_USAGE, DANE_UNKNOWN_SELECTOR, DANE_UNKNOWN_MATCHING_TYPE, DANE_UNKNOWN_PROTOCOL, DANE_UNKNOWN_TRANSPORT, DANE_MISSING_EXTRA_CERTS, DANE_EXTRA_CERTS_NOT_USED, DANE_OFFSET_OUT_OF_RANGE, DANE_INSECURE, DANE_BOGUS, DANE_TLSA_DID_NOT_MATCH, DANE_NON_CA_CERTIFICATE, DANE_PKIX_DID_NOT_VALIDATE, DANE_PKIX_NO_SELF_SIGNED_TRUST_ANCHOR, EXISTS_ERR, INVALID_ILNP64, INVALID_EUI48, INVALID_EUI64, WIRE_RDATA_ERR, INVALID_TAG, TYPE_NOT_IN_BITMAP, INVALID_RDF_TYPE, RDATA_OVERFLOW, SYNTAX_SUPERFLUOUS_TEXT_ERR, NSEC3_DOMAINNAME_OVERFLOW, DANE_NEED_OPENSSL_GE_1_1_FOR_DANE_TA, _, extern fn ldns_get_errorstr_by_id(err: status) ?[*:0]const u8; pub fn get_errorstr(err: status) [*:0]const u8 { return ldns_get_errorstr_by_id(err).?; // null on invalid } };
src/zdns.zig
pub const SQLITE_VERSION_NUMBER = @as(u32, 3029000); pub const SQLITE_OK = @as(u32, 0); pub const SQLITE_ERROR = @as(u32, 1); pub const SQLITE_INTERNAL = @as(u32, 2); pub const SQLITE_PERM = @as(u32, 3); pub const SQLITE_ABORT = @as(u32, 4); pub const SQLITE_BUSY = @as(u32, 5); pub const SQLITE_LOCKED = @as(u32, 6); pub const SQLITE_NOMEM = @as(u32, 7); pub const SQLITE_READONLY = @as(u32, 8); pub const SQLITE_INTERRUPT = @as(u32, 9); pub const SQLITE_IOERR = @as(u32, 10); pub const SQLITE_CORRUPT = @as(u32, 11); pub const SQLITE_NOTFOUND = @as(u32, 12); pub const SQLITE_FULL = @as(u32, 13); pub const SQLITE_CANTOPEN = @as(u32, 14); pub const SQLITE_PROTOCOL = @as(u32, 15); pub const SQLITE_EMPTY = @as(u32, 16); pub const SQLITE_SCHEMA = @as(u32, 17); pub const SQLITE_TOOBIG = @as(u32, 18); pub const SQLITE_CONSTRAINT = @as(u32, 19); pub const SQLITE_MISMATCH = @as(u32, 20); pub const SQLITE_MISUSE = @as(u32, 21); pub const SQLITE_NOLFS = @as(u32, 22); pub const SQLITE_AUTH = @as(u32, 23); pub const SQLITE_FORMAT = @as(u32, 24); pub const SQLITE_RANGE = @as(u32, 25); pub const SQLITE_NOTADB = @as(u32, 26); pub const SQLITE_NOTICE = @as(u32, 27); pub const SQLITE_WARNING = @as(u32, 28); pub const SQLITE_ROW = @as(u32, 100); pub const SQLITE_DONE = @as(u32, 101); pub const SQLITE_OPEN_READONLY = @as(u32, 1); pub const SQLITE_OPEN_READWRITE = @as(u32, 2); pub const SQLITE_OPEN_CREATE = @as(u32, 4); pub const SQLITE_OPEN_DELETEONCLOSE = @as(u32, 8); pub const SQLITE_OPEN_EXCLUSIVE = @as(u32, 16); pub const SQLITE_OPEN_AUTOPROXY = @as(u32, 32); pub const SQLITE_OPEN_URI = @as(u32, 64); pub const SQLITE_OPEN_MEMORY = @as(u32, 128); pub const SQLITE_OPEN_MAIN_DB = @as(u32, 256); pub const SQLITE_OPEN_TEMP_DB = @as(u32, 512); pub const SQLITE_OPEN_TRANSIENT_DB = @as(u32, 1024); pub const SQLITE_OPEN_MAIN_JOURNAL = @as(u32, 2048); pub const SQLITE_OPEN_TEMP_JOURNAL = @as(u32, 4096); pub const SQLITE_OPEN_SUBJOURNAL = @as(u32, 8192); pub const SQLITE_OPEN_SUPER_JOURNAL = @as(u32, 16384); pub const SQLITE_OPEN_NOMUTEX = @as(u32, 32768); pub const SQLITE_OPEN_FULLMUTEX = @as(u32, 65536); pub const SQLITE_OPEN_SHAREDCACHE = @as(u32, 131072); pub const SQLITE_OPEN_PRIVATECACHE = @as(u32, 262144); pub const SQLITE_OPEN_WAL = @as(u32, 524288); pub const SQLITE_OPEN_NOFOLLOW = @as(u32, 16777216); pub const SQLITE_OPEN_MASTER_JOURNAL = @as(u32, 16384); pub const SQLITE_IOCAP_ATOMIC = @as(u32, 1); pub const SQLITE_IOCAP_ATOMIC512 = @as(u32, 2); pub const SQLITE_IOCAP_ATOMIC1K = @as(u32, 4); pub const SQLITE_IOCAP_ATOMIC2K = @as(u32, 8); pub const SQLITE_IOCAP_ATOMIC4K = @as(u32, 16); pub const SQLITE_IOCAP_ATOMIC8K = @as(u32, 32); pub const SQLITE_IOCAP_ATOMIC16K = @as(u32, 64); pub const SQLITE_IOCAP_ATOMIC32K = @as(u32, 128); pub const SQLITE_IOCAP_ATOMIC64K = @as(u32, 256); pub const SQLITE_IOCAP_SAFE_APPEND = @as(u32, 512); pub const SQLITE_IOCAP_SEQUENTIAL = @as(u32, 1024); pub const SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN = @as(u32, 2048); pub const SQLITE_IOCAP_POWERSAFE_OVERWRITE = @as(u32, 4096); pub const SQLITE_IOCAP_IMMUTABLE = @as(u32, 8192); pub const SQLITE_IOCAP_BATCH_ATOMIC = @as(u32, 16384); pub const SQLITE_LOCK_NONE = @as(u32, 0); pub const SQLITE_LOCK_SHARED = @as(u32, 1); pub const SQLITE_LOCK_RESERVED = @as(u32, 2); pub const SQLITE_LOCK_PENDING = @as(u32, 3); pub const SQLITE_LOCK_EXCLUSIVE = @as(u32, 4); pub const SQLITE_SYNC_NORMAL = @as(u32, 2); pub const SQLITE_SYNC_FULL = @as(u32, 3); pub const SQLITE_SYNC_DATAONLY = @as(u32, 16); pub const SQLITE_FCNTL_LOCKSTATE = @as(u32, 1); pub const SQLITE_FCNTL_GET_LOCKPROXYFILE = @as(u32, 2); pub const SQLITE_FCNTL_SET_LOCKPROXYFILE = @as(u32, 3); pub const SQLITE_FCNTL_LAST_ERRNO = @as(u32, 4); pub const SQLITE_FCNTL_SIZE_HINT = @as(u32, 5); pub const SQLITE_FCNTL_CHUNK_SIZE = @as(u32, 6); pub const SQLITE_FCNTL_FILE_POINTER = @as(u32, 7); pub const SQLITE_FCNTL_SYNC_OMITTED = @as(u32, 8); pub const SQLITE_FCNTL_WIN32_AV_RETRY = @as(u32, 9); pub const SQLITE_FCNTL_PERSIST_WAL = @as(u32, 10); pub const SQLITE_FCNTL_OVERWRITE = @as(u32, 11); pub const SQLITE_FCNTL_VFSNAME = @as(u32, 12); pub const SQLITE_FCNTL_POWERSAFE_OVERWRITE = @as(u32, 13); pub const SQLITE_FCNTL_PRAGMA = @as(u32, 14); pub const SQLITE_FCNTL_BUSYHANDLER = @as(u32, 15); pub const SQLITE_FCNTL_TEMPFILENAME = @as(u32, 16); pub const SQLITE_FCNTL_MMAP_SIZE = @as(u32, 18); pub const SQLITE_FCNTL_TRACE = @as(u32, 19); pub const SQLITE_FCNTL_HAS_MOVED = @as(u32, 20); pub const SQLITE_FCNTL_SYNC = @as(u32, 21); pub const SQLITE_FCNTL_COMMIT_PHASETWO = @as(u32, 22); pub const SQLITE_FCNTL_WIN32_SET_HANDLE = @as(u32, 23); pub const SQLITE_FCNTL_WAL_BLOCK = @as(u32, 24); pub const SQLITE_FCNTL_ZIPVFS = @as(u32, 25); pub const SQLITE_FCNTL_RBU = @as(u32, 26); pub const SQLITE_FCNTL_VFS_POINTER = @as(u32, 27); pub const SQLITE_FCNTL_JOURNAL_POINTER = @as(u32, 28); pub const SQLITE_FCNTL_WIN32_GET_HANDLE = @as(u32, 29); pub const SQLITE_FCNTL_PDB = @as(u32, 30); pub const SQLITE_FCNTL_BEGIN_ATOMIC_WRITE = @as(u32, 31); pub const SQLITE_FCNTL_COMMIT_ATOMIC_WRITE = @as(u32, 32); pub const SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE = @as(u32, 33); pub const SQLITE_FCNTL_LOCK_TIMEOUT = @as(u32, 34); pub const SQLITE_FCNTL_DATA_VERSION = @as(u32, 35); pub const SQLITE_FCNTL_SIZE_LIMIT = @as(u32, 36); pub const SQLITE_FCNTL_CKPT_DONE = @as(u32, 37); pub const SQLITE_FCNTL_RESERVE_BYTES = @as(u32, 38); pub const SQLITE_FCNTL_CKPT_START = @as(u32, 39); pub const SQLITE_GET_LOCKPROXYFILE = @as(u32, 2); pub const SQLITE_SET_LOCKPROXYFILE = @as(u32, 3); pub const SQLITE_LAST_ERRNO = @as(u32, 4); pub const SQLITE_ACCESS_EXISTS = @as(u32, 0); pub const SQLITE_ACCESS_READWRITE = @as(u32, 1); pub const SQLITE_ACCESS_READ = @as(u32, 2); pub const SQLITE_SHM_UNLOCK = @as(u32, 1); pub const SQLITE_SHM_LOCK = @as(u32, 2); pub const SQLITE_SHM_SHARED = @as(u32, 4); pub const SQLITE_SHM_EXCLUSIVE = @as(u32, 8); pub const SQLITE_SHM_NLOCK = @as(u32, 8); pub const SQLITE_CONFIG_SINGLETHREAD = @as(u32, 1); pub const SQLITE_CONFIG_MULTITHREAD = @as(u32, 2); pub const SQLITE_CONFIG_SERIALIZED = @as(u32, 3); pub const SQLITE_CONFIG_MALLOC = @as(u32, 4); pub const SQLITE_CONFIG_GETMALLOC = @as(u32, 5); pub const SQLITE_CONFIG_SCRATCH = @as(u32, 6); pub const SQLITE_CONFIG_PAGECACHE = @as(u32, 7); pub const SQLITE_CONFIG_HEAP = @as(u32, 8); pub const SQLITE_CONFIG_MEMSTATUS = @as(u32, 9); pub const SQLITE_CONFIG_MUTEX = @as(u32, 10); pub const SQLITE_CONFIG_GETMUTEX = @as(u32, 11); pub const SQLITE_CONFIG_LOOKASIDE = @as(u32, 13); pub const SQLITE_CONFIG_PCACHE = @as(u32, 14); pub const SQLITE_CONFIG_GETPCACHE = @as(u32, 15); pub const SQLITE_CONFIG_LOG = @as(u32, 16); pub const SQLITE_CONFIG_URI = @as(u32, 17); pub const SQLITE_CONFIG_PCACHE2 = @as(u32, 18); pub const SQLITE_CONFIG_GETPCACHE2 = @as(u32, 19); pub const SQLITE_CONFIG_COVERING_INDEX_SCAN = @as(u32, 20); pub const SQLITE_CONFIG_SQLLOG = @as(u32, 21); pub const SQLITE_CONFIG_MMAP_SIZE = @as(u32, 22); pub const SQLITE_CONFIG_WIN32_HEAPSIZE = @as(u32, 23); pub const SQLITE_CONFIG_PCACHE_HDRSZ = @as(u32, 24); pub const SQLITE_CONFIG_PMASZ = @as(u32, 25); pub const SQLITE_CONFIG_STMTJRNL_SPILL = @as(u32, 26); pub const SQLITE_CONFIG_SMALL_MALLOC = @as(u32, 27); pub const SQLITE_CONFIG_SORTERREF_SIZE = @as(u32, 28); pub const SQLITE_CONFIG_MEMDB_MAXSIZE = @as(u32, 29); pub const SQLITE_DBCONFIG_MAINDBNAME = @as(u32, 1000); pub const SQLITE_DBCONFIG_LOOKASIDE = @as(u32, 1001); pub const SQLITE_DBCONFIG_ENABLE_FKEY = @as(u32, 1002); pub const SQLITE_DBCONFIG_ENABLE_TRIGGER = @as(u32, 1003); pub const SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER = @as(u32, 1004); pub const SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION = @as(u32, 1005); pub const SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE = @as(u32, 1006); pub const SQLITE_DBCONFIG_ENABLE_QPSG = @as(u32, 1007); pub const SQLITE_DBCONFIG_TRIGGER_EQP = @as(u32, 1008); pub const SQLITE_DBCONFIG_RESET_DATABASE = @as(u32, 1009); pub const SQLITE_DBCONFIG_DEFENSIVE = @as(u32, 1010); pub const SQLITE_DBCONFIG_WRITABLE_SCHEMA = @as(u32, 1011); pub const SQLITE_DBCONFIG_LEGACY_ALTER_TABLE = @as(u32, 1012); pub const SQLITE_DBCONFIG_DQS_DML = @as(u32, 1013); pub const SQLITE_DBCONFIG_DQS_DDL = @as(u32, 1014); pub const SQLITE_DBCONFIG_ENABLE_VIEW = @as(u32, 1015); pub const SQLITE_DBCONFIG_LEGACY_FILE_FORMAT = @as(u32, 1016); pub const SQLITE_DBCONFIG_TRUSTED_SCHEMA = @as(u32, 1017); pub const SQLITE_DBCONFIG_MAX = @as(u32, 1017); pub const SQLITE_DENY = @as(u32, 1); pub const SQLITE_IGNORE = @as(u32, 2); pub const SQLITE_CREATE_INDEX = @as(u32, 1); pub const SQLITE_CREATE_TABLE = @as(u32, 2); pub const SQLITE_CREATE_TEMP_INDEX = @as(u32, 3); pub const SQLITE_CREATE_TEMP_TABLE = @as(u32, 4); pub const SQLITE_CREATE_TEMP_TRIGGER = @as(u32, 5); pub const SQLITE_CREATE_TEMP_VIEW = @as(u32, 6); pub const SQLITE_CREATE_TRIGGER = @as(u32, 7); pub const SQLITE_CREATE_VIEW = @as(u32, 8); pub const SQLITE_DELETE = @as(u32, 9); pub const SQLITE_DROP_INDEX = @as(u32, 10); pub const SQLITE_DROP_TABLE = @as(u32, 11); pub const SQLITE_DROP_TEMP_INDEX = @as(u32, 12); pub const SQLITE_DROP_TEMP_TABLE = @as(u32, 13); pub const SQLITE_DROP_TEMP_TRIGGER = @as(u32, 14); pub const SQLITE_DROP_TEMP_VIEW = @as(u32, 15); pub const SQLITE_DROP_TRIGGER = @as(u32, 16); pub const SQLITE_DROP_VIEW = @as(u32, 17); pub const SQLITE_INSERT = @as(u32, 18); pub const SQLITE_PRAGMA = @as(u32, 19); pub const SQLITE_READ = @as(u32, 20); pub const SQLITE_SELECT = @as(u32, 21); pub const SQLITE_TRANSACTION = @as(u32, 22); pub const SQLITE_UPDATE = @as(u32, 23); pub const SQLITE_ATTACH = @as(u32, 24); pub const SQLITE_DETACH = @as(u32, 25); pub const SQLITE_ALTER_TABLE = @as(u32, 26); pub const SQLITE_REINDEX = @as(u32, 27); pub const SQLITE_ANALYZE = @as(u32, 28); pub const SQLITE_CREATE_VTABLE = @as(u32, 29); pub const SQLITE_DROP_VTABLE = @as(u32, 30); pub const SQLITE_FUNCTION = @as(u32, 31); pub const SQLITE_SAVEPOINT = @as(u32, 32); pub const SQLITE_COPY = @as(u32, 0); pub const SQLITE_RECURSIVE = @as(u32, 33); pub const SQLITE_TRACE_STMT = @as(u32, 1); pub const SQLITE_TRACE_PROFILE = @as(u32, 2); pub const SQLITE_TRACE_ROW = @as(u32, 4); pub const SQLITE_TRACE_CLOSE = @as(u32, 8); pub const SQLITE_LIMIT_LENGTH = @as(u32, 0); pub const SQLITE_LIMIT_SQL_LENGTH = @as(u32, 1); pub const SQLITE_LIMIT_COLUMN = @as(u32, 2); pub const SQLITE_LIMIT_EXPR_DEPTH = @as(u32, 3); pub const SQLITE_LIMIT_COMPOUND_SELECT = @as(u32, 4); pub const SQLITE_LIMIT_VDBE_OP = @as(u32, 5); pub const SQLITE_LIMIT_FUNCTION_ARG = @as(u32, 6); pub const SQLITE_LIMIT_ATTACHED = @as(u32, 7); pub const SQLITE_LIMIT_LIKE_PATTERN_LENGTH = @as(u32, 8); pub const SQLITE_LIMIT_VARIABLE_NUMBER = @as(u32, 9); pub const SQLITE_LIMIT_TRIGGER_DEPTH = @as(u32, 10); pub const SQLITE_LIMIT_WORKER_THREADS = @as(u32, 11); pub const SQLITE_PREPARE_PERSISTENT = @as(u32, 1); pub const SQLITE_PREPARE_NORMALIZE = @as(u32, 2); pub const SQLITE_PREPARE_NO_VTAB = @as(u32, 4); pub const SQLITE_INTEGER = @as(u32, 1); pub const SQLITE_FLOAT = @as(u32, 2); pub const SQLITE_BLOB = @as(u32, 4); pub const SQLITE_NULL = @as(u32, 5); pub const SQLITE3_TEXT = @as(u32, 3); pub const SQLITE_UTF8 = @as(u32, 1); pub const SQLITE_UTF16LE = @as(u32, 2); pub const SQLITE_UTF16BE = @as(u32, 3); pub const SQLITE_UTF16 = @as(u32, 4); pub const SQLITE_ANY = @as(u32, 5); pub const SQLITE_UTF16_ALIGNED = @as(u32, 8); pub const SQLITE_DETERMINISTIC = @as(u64, 2048); pub const SQLITE_DIRECTONLY = @as(u64, 524288); pub const SQLITE_SUBTYPE = @as(u64, 1048576); pub const SQLITE_INNOCUOUS = @as(u64, 2097152); pub const SQLITE_WIN32_DATA_DIRECTORY_TYPE = @as(u32, 1); pub const SQLITE_WIN32_TEMP_DIRECTORY_TYPE = @as(u32, 2); pub const SQLITE_TXN_NONE = @as(u32, 0); pub const SQLITE_TXN_READ = @as(u32, 1); pub const SQLITE_TXN_WRITE = @as(u32, 2); pub const SQLITE_INDEX_SCAN_UNIQUE = @as(u32, 1); pub const SQLITE_INDEX_CONSTRAINT_EQ = @as(u32, 2); pub const SQLITE_INDEX_CONSTRAINT_GT = @as(u32, 4); pub const SQLITE_INDEX_CONSTRAINT_LE = @as(u32, 8); pub const SQLITE_INDEX_CONSTRAINT_LT = @as(u32, 16); pub const SQLITE_INDEX_CONSTRAINT_GE = @as(u32, 32); pub const SQLITE_INDEX_CONSTRAINT_MATCH = @as(u32, 64); pub const SQLITE_INDEX_CONSTRAINT_LIKE = @as(u32, 65); pub const SQLITE_INDEX_CONSTRAINT_GLOB = @as(u32, 66); pub const SQLITE_INDEX_CONSTRAINT_REGEXP = @as(u32, 67); pub const SQLITE_INDEX_CONSTRAINT_NE = @as(u32, 68); pub const SQLITE_INDEX_CONSTRAINT_ISNOT = @as(u32, 69); pub const SQLITE_INDEX_CONSTRAINT_ISNOTNULL = @as(u32, 70); pub const SQLITE_INDEX_CONSTRAINT_ISNULL = @as(u32, 71); pub const SQLITE_INDEX_CONSTRAINT_IS = @as(u32, 72); pub const SQLITE_INDEX_CONSTRAINT_FUNCTION = @as(u32, 150); pub const SQLITE_MUTEX_FAST = @as(u32, 0); pub const SQLITE_MUTEX_RECURSIVE = @as(u32, 1); pub const SQLITE_MUTEX_STATIC_MAIN = @as(u32, 2); pub const SQLITE_MUTEX_STATIC_MEM = @as(u32, 3); pub const SQLITE_MUTEX_STATIC_MEM2 = @as(u32, 4); pub const SQLITE_MUTEX_STATIC_OPEN = @as(u32, 4); pub const SQLITE_MUTEX_STATIC_PRNG = @as(u32, 5); pub const SQLITE_MUTEX_STATIC_LRU = @as(u32, 6); pub const SQLITE_MUTEX_STATIC_LRU2 = @as(u32, 7); pub const SQLITE_MUTEX_STATIC_PMEM = @as(u32, 7); pub const SQLITE_MUTEX_STATIC_APP1 = @as(u32, 8); pub const SQLITE_MUTEX_STATIC_APP2 = @as(u32, 9); pub const SQLITE_MUTEX_STATIC_APP3 = @as(u32, 10); pub const SQLITE_MUTEX_STATIC_VFS1 = @as(u32, 11); pub const SQLITE_MUTEX_STATIC_VFS2 = @as(u32, 12); pub const SQLITE_MUTEX_STATIC_VFS3 = @as(u32, 13); pub const SQLITE_MUTEX_STATIC_MASTER = @as(u32, 2); pub const SQLITE_TESTCTRL_FIRST = @as(u32, 5); pub const SQLITE_TESTCTRL_PRNG_SAVE = @as(u32, 5); pub const SQLITE_TESTCTRL_PRNG_RESTORE = @as(u32, 6); pub const SQLITE_TESTCTRL_PRNG_RESET = @as(u32, 7); pub const SQLITE_TESTCTRL_BITVEC_TEST = @as(u32, 8); pub const SQLITE_TESTCTRL_FAULT_INSTALL = @as(u32, 9); pub const SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS = @as(u32, 10); pub const SQLITE_TESTCTRL_PENDING_BYTE = @as(u32, 11); pub const SQLITE_TESTCTRL_ASSERT = @as(u32, 12); pub const SQLITE_TESTCTRL_ALWAYS = @as(u32, 13); pub const SQLITE_TESTCTRL_RESERVE = @as(u32, 14); pub const SQLITE_TESTCTRL_OPTIMIZATIONS = @as(u32, 15); pub const SQLITE_TESTCTRL_ISKEYWORD = @as(u32, 16); pub const SQLITE_TESTCTRL_SCRATCHMALLOC = @as(u32, 17); pub const SQLITE_TESTCTRL_INTERNAL_FUNCTIONS = @as(u32, 17); pub const SQLITE_TESTCTRL_LOCALTIME_FAULT = @as(u32, 18); pub const SQLITE_TESTCTRL_EXPLAIN_STMT = @as(u32, 19); pub const SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD = @as(u32, 19); pub const SQLITE_TESTCTRL_NEVER_CORRUPT = @as(u32, 20); pub const SQLITE_TESTCTRL_VDBE_COVERAGE = @as(u32, 21); pub const SQLITE_TESTCTRL_BYTEORDER = @as(u32, 22); pub const SQLITE_TESTCTRL_ISINIT = @as(u32, 23); pub const SQLITE_TESTCTRL_SORTER_MMAP = @as(u32, 24); pub const SQLITE_TESTCTRL_IMPOSTER = @as(u32, 25); pub const SQLITE_TESTCTRL_PARSER_COVERAGE = @as(u32, 26); pub const SQLITE_TESTCTRL_RESULT_INTREAL = @as(u32, 27); pub const SQLITE_TESTCTRL_PRNG_SEED = @as(u32, 28); pub const SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS = @as(u32, 29); pub const SQLITE_TESTCTRL_SEEK_COUNT = @as(u32, 30); pub const SQLITE_TESTCTRL_LAST = @as(u32, 30); pub const SQLITE_STATUS_MEMORY_USED = @as(u32, 0); pub const SQLITE_STATUS_PAGECACHE_USED = @as(u32, 1); pub const SQLITE_STATUS_PAGECACHE_OVERFLOW = @as(u32, 2); pub const SQLITE_STATUS_SCRATCH_USED = @as(u32, 3); pub const SQLITE_STATUS_SCRATCH_OVERFLOW = @as(u32, 4); pub const SQLITE_STATUS_MALLOC_SIZE = @as(u32, 5); pub const SQLITE_STATUS_PARSER_STACK = @as(u32, 6); pub const SQLITE_STATUS_PAGECACHE_SIZE = @as(u32, 7); pub const SQLITE_STATUS_SCRATCH_SIZE = @as(u32, 8); pub const SQLITE_STATUS_MALLOC_COUNT = @as(u32, 9); pub const SQLITE_DBSTATUS_LOOKASIDE_USED = @as(u32, 0); pub const SQLITE_DBSTATUS_CACHE_USED = @as(u32, 1); pub const SQLITE_DBSTATUS_SCHEMA_USED = @as(u32, 2); pub const SQLITE_DBSTATUS_STMT_USED = @as(u32, 3); pub const SQLITE_DBSTATUS_LOOKASIDE_HIT = @as(u32, 4); pub const SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE = @as(u32, 5); pub const SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL = @as(u32, 6); pub const SQLITE_DBSTATUS_CACHE_HIT = @as(u32, 7); pub const SQLITE_DBSTATUS_CACHE_MISS = @as(u32, 8); pub const SQLITE_DBSTATUS_CACHE_WRITE = @as(u32, 9); pub const SQLITE_DBSTATUS_DEFERRED_FKS = @as(u32, 10); pub const SQLITE_DBSTATUS_CACHE_USED_SHARED = @as(u32, 11); pub const SQLITE_DBSTATUS_CACHE_SPILL = @as(u32, 12); pub const SQLITE_DBSTATUS_MAX = @as(u32, 12); pub const SQLITE_STMTSTATUS_FULLSCAN_STEP = @as(u32, 1); pub const SQLITE_STMTSTATUS_SORT = @as(u32, 2); pub const SQLITE_STMTSTATUS_AUTOINDEX = @as(u32, 3); pub const SQLITE_STMTSTATUS_VM_STEP = @as(u32, 4); pub const SQLITE_STMTSTATUS_REPREPARE = @as(u32, 5); pub const SQLITE_STMTSTATUS_RUN = @as(u32, 6); pub const SQLITE_STMTSTATUS_MEMUSED = @as(u32, 99); pub const SQLITE_CHECKPOINT_PASSIVE = @as(u32, 0); pub const SQLITE_CHECKPOINT_FULL = @as(u32, 1); pub const SQLITE_CHECKPOINT_RESTART = @as(u32, 2); pub const SQLITE_CHECKPOINT_TRUNCATE = @as(u32, 3); pub const SQLITE_VTAB_CONSTRAINT_SUPPORT = @as(u32, 1); pub const SQLITE_VTAB_INNOCUOUS = @as(u32, 2); pub const SQLITE_VTAB_DIRECTONLY = @as(u32, 3); pub const SQLITE_ROLLBACK = @as(u32, 1); pub const SQLITE_FAIL = @as(u32, 3); pub const SQLITE_REPLACE = @as(u32, 5); pub const SQLITE_SCANSTAT_NLOOP = @as(u32, 0); pub const SQLITE_SCANSTAT_NVISIT = @as(u32, 1); pub const SQLITE_SCANSTAT_EST = @as(u32, 2); pub const SQLITE_SCANSTAT_NAME = @as(u32, 3); pub const SQLITE_SCANSTAT_EXPLAIN = @as(u32, 4); pub const SQLITE_SCANSTAT_SELECTID = @as(u32, 5); pub const SQLITE_SERIALIZE_NOCOPY = @as(u32, 1); pub const SQLITE_DESERIALIZE_FREEONCLOSE = @as(u32, 1); pub const SQLITE_DESERIALIZE_RESIZEABLE = @as(u32, 2); pub const SQLITE_DESERIALIZE_READONLY = @as(u32, 4); pub const NOT_WITHIN = @as(u32, 0); pub const PARTLY_WITHIN = @as(u32, 1); pub const FULLY_WITHIN = @as(u32, 2); pub const __SQLITESESSION_H_ = @as(u32, 1); pub const SQLITE_CHANGESETSTART_INVERT = @as(u32, 2); pub const SQLITE_CHANGESETAPPLY_NOSAVEPOINT = @as(u32, 1); pub const SQLITE_CHANGESETAPPLY_INVERT = @as(u32, 2); pub const SQLITE_CHANGESET_DATA = @as(u32, 1); pub const SQLITE_CHANGESET_NOTFOUND = @as(u32, 2); pub const SQLITE_CHANGESET_CONFLICT = @as(u32, 3); pub const SQLITE_CHANGESET_CONSTRAINT = @as(u32, 4); pub const SQLITE_CHANGESET_FOREIGN_KEY = @as(u32, 5); pub const SQLITE_CHANGESET_OMIT = @as(u32, 0); pub const SQLITE_CHANGESET_REPLACE = @as(u32, 1); pub const SQLITE_CHANGESET_ABORT = @as(u32, 2); pub const SQLITE_SESSION_CONFIG_STRMSIZE = @as(u32, 1); pub const FTS5_TOKENIZE_QUERY = @as(u32, 1); pub const FTS5_TOKENIZE_PREFIX = @as(u32, 2); pub const FTS5_TOKENIZE_DOCUMENT = @as(u32, 4); pub const FTS5_TOKENIZE_AUX = @as(u32, 8); pub const FTS5_TOKEN_COLOCATED = @as(u32, 1); //-------------------------------------------------------------------------------- // Section: Types (37) //-------------------------------------------------------------------------------- pub const sqlite3 = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const sqlite3_mutex = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const sqlite3_stmt = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const sqlite3_value = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const sqlite3_context = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const sqlite3_blob = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const sqlite3_str = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const sqlite3_pcache = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const sqlite3_backup = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const Fts5Context = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const Fts5Tokenizer = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const sqlite3_callback = fn( param0: ?*anyopaque, param1: i32, param2: ?*?*i8, param3: ?*?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub const sqlite3_file = extern struct { pMethods: ?*const sqlite3_io_methods, }; pub const sqlite3_io_methods = extern struct { iVersion: i32, xClose: isize, xRead: isize, xWrite: isize, xTruncate: isize, xSync: isize, xFileSize: isize, xLock: isize, xUnlock: isize, xCheckReservedLock: isize, xFileControl: isize, xSectorSize: isize, xDeviceCharacteristics: isize, xShmMap: isize, xShmLock: isize, xShmBarrier: isize, xShmUnmap: isize, xFetch: isize, xUnfetch: isize, }; pub const sqlite3_syscall_ptr = fn( ) callconv(@import("std").os.windows.WINAPI) void; pub const sqlite3_vfs = extern struct { iVersion: i32, szOsFile: i32, mxPathname: i32, pNext: ?*sqlite3_vfs, zName: ?[*:0]const u8, pAppData: ?*anyopaque, xOpen: isize, xDelete: isize, xAccess: isize, xFullPathname: isize, xDlOpen: isize, xDlError: isize, xDlSym: isize, xDlClose: isize, xRandomness: isize, xSleep: isize, xCurrentTime: isize, xGetLastError: isize, xCurrentTimeInt64: isize, xSetSystemCall: isize, xGetSystemCall: isize, xNextSystemCall: isize, }; pub const sqlite3_mem_methods = extern struct { xMalloc: isize, xFree: isize, xRealloc: isize, xSize: isize, xRoundup: isize, xInit: isize, xShutdown: isize, pAppData: ?*anyopaque, }; pub const sqlite3_destructor_type = fn( param0: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const sqlite3_module = extern struct { iVersion: i32, xCreate: isize, xConnect: isize, xBestIndex: isize, xDisconnect: isize, xDestroy: isize, xOpen: isize, xClose: isize, xFilter: isize, xNext: isize, xEof: isize, xColumn: isize, xRowid: isize, xUpdate: isize, xBegin: isize, xSync: isize, xCommit: isize, xRollback: isize, xFindFunction: isize, xRename: isize, xSavepoint: isize, xRelease: isize, xRollbackTo: isize, xShadowName: isize, }; pub const sqlite3_index_info = extern struct { pub const sqlite3_index_orderby = extern struct { iColumn: i32, desc: u8, }; pub const sqlite3_index_constraint_usage = extern struct { argvIndex: i32, omit: u8, }; pub const sqlite3_index_constraint = extern struct { iColumn: i32, op: u8, usable: u8, iTermOffset: i32, }; nConstraint: i32, aConstraint: ?*sqlite3_index_constraint, nOrderBy: i32, aOrderBy: ?*sqlite3_index_orderby, aConstraintUsage: ?*sqlite3_index_constraint_usage, idxNum: i32, idxStr: ?PSTR, needToFreeIdxStr: i32, orderByConsumed: i32, estimatedCost: f64, estimatedRows: i64, idxFlags: i32, colUsed: u64, }; pub const sqlite3_vtab = extern struct { pModule: ?*const sqlite3_module, nRef: i32, zErrMsg: ?PSTR, }; pub const sqlite3_vtab_cursor = extern struct { pVtab: ?*sqlite3_vtab, }; pub const sqlite3_mutex_methods = extern struct { xMutexInit: isize, xMutexEnd: isize, xMutexAlloc: ?*?*?*?*?*?*?*?*?*sqlite3_mutex, xMutexFree: isize, xMutexEnter: isize, xMutexTry: isize, xMutexLeave: isize, xMutexHeld: isize, xMutexNotheld: isize, }; pub const sqlite3_pcache_page = extern struct { pBuf: ?*anyopaque, pExtra: ?*anyopaque, }; pub const sqlite3_pcache_methods2 = extern struct { iVersion: i32, pArg: ?*anyopaque, xInit: isize, xShutdown: isize, xCreate: ?*?*?*?*?*?*?*?*?*sqlite3_pcache, xCachesize: isize, xPagecount: isize, xFetch: ?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*sqlite3_pcache_page, xUnpin: isize, xRekey: isize, xTruncate: isize, xDestroy: isize, xShrink: isize, }; pub const sqlite3_pcache_methods = extern struct { pArg: ?*anyopaque, xInit: isize, xShutdown: isize, xCreate: ?*?*?*?*?*?*?*?*?*sqlite3_pcache, xCachesize: isize, xPagecount: isize, xFetch: isize, xUnpin: isize, xRekey: isize, xTruncate: isize, xDestroy: isize, }; pub const sqlite3_snapshot = extern struct { hidden: [48]u8, }; pub const sqlite3_rtree_geometry = extern struct { pContext: ?*anyopaque, nParam: i32, aParam: ?*f64, pUser: ?*anyopaque, xDelUser: isize, }; pub const sqlite3_rtree_query_info = extern struct { pContext: ?*anyopaque, nParam: i32, aParam: ?*f64, pUser: ?*anyopaque, xDelUser: isize, aCoord: ?*f64, anQueue: ?*u32, nCoord: i32, iLevel: i32, mxLevel: i32, iRowid: i64, rParentScore: f64, eParentWithin: i32, eWithin: i32, rScore: f64, apSqlParam: ?*?*sqlite3_value, }; pub const fts5_extension_function = fn( pApi: ?*const Fts5ExtensionApi, pFts: ?*Fts5Context, pCtx: ?*sqlite3_context, nVal: i32, apVal: ?*?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) void; pub const Fts5PhraseIter = extern struct { a: ?*const u8, b: ?*const u8, }; pub const Fts5ExtensionApi = extern struct { iVersion: i32, xUserData: isize, xColumnCount: isize, xRowCount: isize, xColumnTotalSize: isize, xTokenize: isize, xPhraseCount: isize, xPhraseSize: isize, xInstCount: isize, xInst: isize, xRowid: isize, xColumnText: isize, xColumnSize: isize, xQueryPhrase: isize, xSetAuxdata: isize, xGetAuxdata: isize, xPhraseFirst: isize, xPhraseNext: isize, xPhraseFirstColumn: isize, xPhraseNextColumn: isize, }; pub const fts5_tokenizer = extern struct { xCreate: isize, xDelete: isize, xTokenize: isize, }; pub const fts5_api = extern struct { iVersion: i32, xCreateTokenizer: isize, xFindTokenizer: isize, xCreateFunction: isize, }; pub const sqlite3_loadext_entry = fn( db: ?*sqlite3, pzErrMsg: ?*?*i8, pThunk: ?*const sqlite3_api_routines, ) callconv(@import("std").os.windows.WINAPI) i32; pub const sqlite3_api_routines = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { aggregate_context: isize, aggregate_count: isize, bind_blob: isize, bind_double: isize, bind_int: isize, bind_int64: isize, bind_null: isize, bind_parameter_count: isize, bind_parameter_index: isize, bind_parameter_name: isize, bind_text: isize, bind_text16: isize, bind_value: isize, busy_handler: isize, busy_timeout: isize, changes: isize, close: isize, collation_needed: isize, collation_needed16: isize, column_blob: isize, column_bytes: isize, column_bytes16: isize, column_count: isize, column_database_name: isize, column_database_name16: isize, column_decltype: isize, column_decltype16: isize, column_double: isize, column_int: isize, column_int64: isize, column_name: isize, column_name16: isize, column_origin_name: isize, column_origin_name16: isize, column_table_name: isize, column_table_name16: isize, column_text: isize, column_text16: isize, column_type: isize, column_value: ?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*sqlite3_value, commit_hook: isize, complete: isize, complete16: isize, create_collation: isize, create_collation16: isize, create_function: isize, create_function16: isize, create_module: isize, data_count: isize, db_handle: ?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*sqlite3, declare_vtab: isize, enable_shared_cache: isize, errcode: isize, errmsg: isize, errmsg16: isize, exec: isize, expired: isize, finalize: isize, free: isize, free_table: isize, get_autocommit: isize, get_auxdata: isize, get_table: isize, global_recover: isize, interruptx: isize, last_insert_rowid: isize, libversion: isize, libversion_number: isize, malloc: isize, mprintf: isize, open: isize, open16: isize, prepare: isize, prepare16: isize, profile: isize, progress_handler: isize, realloc: isize, reset: isize, result_blob: isize, result_double: isize, result_error: isize, result_error16: isize, result_int: isize, result_int64: isize, result_null: isize, result_text: isize, result_text16: isize, result_text16be: isize, result_text16le: isize, result_value: isize, rollback_hook: isize, set_authorizer: isize, set_auxdata: isize, xsnprintf: isize, step: isize, table_column_metadata: isize, thread_cleanup: isize, total_changes: isize, trace: isize, transfer_bindings: isize, update_hook: isize, user_data: isize, value_blob: isize, value_bytes: isize, value_bytes16: isize, value_double: isize, value_int: isize, value_int64: isize, value_numeric_type: isize, value_text: isize, value_text16: isize, value_text16be: isize, value_text16le: isize, value_type: isize, vmprintf: isize, overload_function: isize, prepare_v2: isize, prepare16_v2: isize, clear_bindings: isize, create_module_v2: isize, bind_zeroblob: isize, blob_bytes: isize, blob_close: isize, blob_open: isize, blob_read: isize, blob_write: isize, create_collation_v2: isize, file_control: isize, memory_highwater: isize, memory_used: isize, mutex_alloc: ?*?*?*?*?*?*?*?*?*sqlite3_mutex, mutex_enter: isize, mutex_free: isize, mutex_leave: isize, mutex_try: isize, open_v2: isize, release_memory: isize, result_error_nomem: isize, result_error_toobig: isize, sleep: isize, soft_heap_limit: isize, vfs_find: ?*?*?*?*?*?*?*?*?*?*sqlite3_vfs, vfs_register: isize, vfs_unregister: isize, xthreadsafe: isize, result_zeroblob: isize, result_error_code: isize, test_control: isize, randomness: isize, context_db_handle: ?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*sqlite3, extended_result_codes: isize, limit: isize, next_stmt: ?*?*?*?*?*?*?*?*?*?*?*?*sqlite3_stmt, sql: isize, status: isize, backup_finish: isize, backup_init: ?*?*?*?*?*?*?*?*?*?*?*?*sqlite3_backup, backup_pagecount: isize, backup_remaining: isize, backup_step: isize, compileoption_get: isize, compileoption_used: isize, create_function_v2: isize, db_config: isize, db_mutex: ?*?*?*?*?*?*?*?*?*?*?*?*sqlite3_mutex, db_status: isize, extended_errcode: isize, log: isize, soft_heap_limit64: isize, sourceid: isize, stmt_status: isize, strnicmp: isize, unlock_notify: isize, wal_autocheckpoint: isize, wal_checkpoint: isize, wal_hook: isize, blob_reopen: isize, vtab_config: isize, vtab_on_conflict: isize, close_v2: isize, db_filename: isize, db_readonly: isize, db_release_memory: isize, errstr: isize, stmt_busy: isize, stmt_readonly: isize, stricmp: isize, uri_boolean: isize, uri_int64: isize, uri_parameter: isize, xvsnprintf: isize, wal_checkpoint_v2: isize, auto_extension: isize, bind_blob64: isize, bind_text64: isize, cancel_auto_extension: isize, load_extension: isize, malloc64: isize, msize: isize, realloc64: isize, reset_auto_extension: isize, result_blob64: isize, result_text64: isize, strglob: isize, value_dup: ?*?*?*?*?*?*?*?*?*?*sqlite3_value, value_free: isize, result_zeroblob64: isize, bind_zeroblob64: isize, value_subtype: isize, result_subtype: isize, status64: isize, strlike: isize, db_cacheflush: isize, system_errno: isize, trace_v2: isize, expanded_sql: isize, set_last_insert_rowid: isize, prepare_v3: isize, prepare16_v3: isize, bind_pointer: isize, result_pointer: isize, value_pointer: isize, vtab_nochange: isize, value_nochange: isize, vtab_collation: isize, keyword_count: isize, keyword_name: isize, keyword_check: isize, str_new: ?*?*?*?*?*?*?*?*?*?*?*?*sqlite3_str, str_finish: isize, str_appendf: isize, str_vappendf: isize, str_append: isize, str_appendall: isize, str_appendchar: isize, str_reset: isize, str_errcode: isize, str_length: isize, str_value: isize, create_window_function: isize, normalized_sql: isize, stmt_isexplain: isize, value_frombind: isize, drop_modules: isize, hard_heap_limit64: isize, uri_key: isize, filename_database: isize, filename_journal: isize, filename_wal: isize, create_filename: isize, free_filename: isize, database_file_object: ?*?*?*?*?*?*?*?*?*?*sqlite3_file, txn_state: isize, }, .X86 => extern struct { aggregate_context: isize, aggregate_count: isize, bind_blob: isize, bind_double: isize, bind_int: isize, bind_int64: isize, bind_null: isize, bind_parameter_count: isize, bind_parameter_index: isize, bind_parameter_name: isize, bind_text: isize, bind_text16: isize, bind_value: isize, busy_handler: isize, busy_timeout: isize, changes: isize, close: isize, collation_needed: isize, collation_needed16: isize, column_blob: isize, column_bytes: isize, column_bytes16: isize, column_count: isize, column_database_name: isize, column_database_name16: isize, column_decltype: isize, column_decltype16: isize, column_double: isize, column_int: isize, column_int64: isize, column_name: isize, column_name16: isize, column_origin_name: isize, column_origin_name16: isize, column_table_name: isize, column_table_name16: isize, column_text: isize, column_text16: isize, column_type: isize, column_value: ?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*sqlite3_value, commit_hook: isize, complete: isize, complete16: isize, create_collation: isize, create_collation16: isize, create_function: isize, create_function16: isize, create_module: isize, data_count: isize, db_handle: ?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*sqlite3, declare_vtab: isize, enable_shared_cache: isize, errcode: isize, errmsg: isize, errmsg16: isize, exec: isize, expired: isize, finalize: isize, free: isize, free_table: isize, get_autocommit: isize, get_auxdata: isize, get_table: isize, global_recover: isize, interruptx: isize, last_insert_rowid: isize, libversion: isize, libversion_number: isize, malloc: isize, mprintf: isize, open: isize, open16: isize, prepare: isize, prepare16: isize, profile: isize, progress_handler: isize, realloc: isize, reset: isize, result_blob: isize, result_double: isize, result_error: isize, result_error16: isize, result_int: isize, result_int64: isize, result_null: isize, result_text: isize, result_text16: isize, result_text16be: isize, result_text16le: isize, result_value: isize, rollback_hook: isize, set_authorizer: isize, set_auxdata: isize, xsnprintf: isize, step: isize, table_column_metadata: isize, thread_cleanup: isize, total_changes: isize, trace: isize, transfer_bindings: isize, update_hook: isize, user_data: isize, value_blob: isize, value_bytes: isize, value_bytes16: isize, value_double: isize, value_int: isize, value_int64: isize, value_numeric_type: isize, value_text: isize, value_text16: isize, value_text16be: isize, value_text16le: isize, value_type: isize, vmprintf: isize, overload_function: isize, prepare_v2: isize, prepare16_v2: isize, clear_bindings: isize, create_module_v2: isize, bind_zeroblob: isize, blob_bytes: isize, blob_close: isize, blob_open: isize, blob_read: isize, blob_write: isize, create_collation_v2: isize, file_control: isize, memory_highwater: isize, memory_used: isize, mutex_alloc: ?*?*?*?*?*?*?*?*?*sqlite3_mutex, mutex_enter: isize, mutex_free: isize, mutex_leave: isize, mutex_try: isize, open_v2: isize, release_memory: isize, result_error_nomem: isize, result_error_toobig: isize, sleep: isize, soft_heap_limit: isize, vfs_find: ?*?*?*?*?*?*?*?*?*?*sqlite3_vfs, vfs_register: isize, vfs_unregister: isize, xthreadsafe: isize, result_zeroblob: isize, result_error_code: isize, test_control: isize, randomness: isize, context_db_handle: ?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*sqlite3, extended_result_codes: isize, limit: isize, next_stmt: ?*?*?*?*?*?*?*?*?*?*?*?*sqlite3_stmt, sql: isize, status: isize, backup_finish: isize, backup_init: ?*?*?*?*?*?*?*?*?*?*?*?*sqlite3_backup, backup_pagecount: isize, backup_remaining: isize, backup_step: isize, compileoption_get: isize, compileoption_used: isize, create_function_v2: isize, db_config: isize, db_mutex: ?*?*?*?*?*?*?*?*?*?*?*?*sqlite3_mutex, db_status: isize, extended_errcode: isize, log: isize, soft_heap_limit64: isize, sourceid: isize, stmt_status: isize, strnicmp: isize, unlock_notify: isize, wal_autocheckpoint: isize, wal_checkpoint: isize, wal_hook: isize, blob_reopen: isize, vtab_config: isize, vtab_on_conflict: isize, close_v2: isize, db_filename: isize, db_readonly: isize, db_release_memory: isize, errstr: isize, stmt_busy: isize, stmt_readonly: isize, stricmp: isize, uri_boolean: isize, uri_int64: isize, uri_parameter: isize, xvsnprintf: isize, wal_checkpoint_v2: isize, auto_extension: isize, bind_blob64: isize, bind_text64: isize, cancel_auto_extension: isize, load_extension: isize, malloc64: isize, msize: isize, realloc64: isize, reset_auto_extension: isize, result_blob64: isize, result_text64: isize, strglob: isize, value_dup: ?*?*?*?*?*?*?*?*?*?*sqlite3_value, value_free: isize, result_zeroblob64: isize, bind_zeroblob64: isize, value_subtype: isize, result_subtype: isize, status64: isize, strlike: isize, db_cacheflush: isize, system_errno: isize, trace_v2: isize, expanded_sql: isize, set_last_insert_rowid: isize, prepare_v3: isize, prepare16_v3: isize, bind_pointer: isize, result_pointer: isize, value_pointer: isize, vtab_nochange: isize, value_nochange: isize, vtab_collation: isize, keyword_count: isize, keyword_name: isize, keyword_check: isize, str_new: ?*?*?*?*?*?*?*?*?*?*?*?*sqlite3_str, str_finish: isize, str_appendf: isize, str_vappendf: isize, str_append: isize, str_appendall: isize, str_appendchar: isize, str_reset: isize, str_errcode: isize, str_length: isize, str_value: isize, create_window_function: isize, normalized_sql: isize, stmt_isexplain: isize, value_frombind: isize, drop_modules: isize, hard_heap_limit64: isize, uri_key: isize, filename_database: isize, filename_journal: isize, filename_wal: isize, create_filename: isize, free_filename: isize, database_file_object: ?*?*?*?*?*?*?*?*?*?*sqlite3_file, txn_state: isize, }, }; //-------------------------------------------------------------------------------- // Section: Functions (265) //-------------------------------------------------------------------------------- pub extern "winsqlite3" fn sqlite3_libversion( ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_sourceid( ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_libversion_number( ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_compileoption_used( zOptName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_compileoption_get( N: i32, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_threadsafe( ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_close( param0: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_close_v2( param0: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_exec( param0: ?*sqlite3, sql: ?[*:0]const u8, callback: isize, param3: ?*anyopaque, errmsg: ?*?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_initialize( ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_shutdown( ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_os_init( ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_os_end( ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_config( param0: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_db_config( param0: ?*sqlite3, op: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_extended_result_codes( param0: ?*sqlite3, onoff: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_last_insert_rowid( param0: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) i64; pub extern "winsqlite3" fn sqlite3_set_last_insert_rowid( param0: ?*sqlite3, param1: i64, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_changes( param0: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_total_changes( param0: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_interrupt( param0: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_complete( sql: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_complete16( sql: ?*const anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_busy_handler( param0: ?*sqlite3, param1: isize, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_busy_timeout( param0: ?*sqlite3, ms: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_get_table( db: ?*sqlite3, zSql: ?[*:0]const u8, pazResult: ?*?*?*i8, pnRow: ?*i32, pnColumn: ?*i32, pzErrmsg: ?*?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_free_table( result: ?*?*i8, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_mprintf( param0: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_vmprintf( param0: ?[*:0]const u8, param1: ?*i8, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_snprintf( param0: i32, param1: ?PSTR, param2: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_vsnprintf( param0: i32, param1: ?PSTR, param2: ?[*:0]const u8, param3: ?*i8, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_malloc( param0: i32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_malloc64( param0: u64, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_realloc( param0: ?*anyopaque, param1: i32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_realloc64( param0: ?*anyopaque, param1: u64, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_free( param0: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_msize( param0: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u64; pub extern "winsqlite3" fn sqlite3_memory_used( ) callconv(@import("std").os.windows.WINAPI) i64; pub extern "winsqlite3" fn sqlite3_memory_highwater( resetFlag: i32, ) callconv(@import("std").os.windows.WINAPI) i64; pub extern "winsqlite3" fn sqlite3_randomness( N: i32, P: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_set_authorizer( param0: ?*sqlite3, xAuth: isize, pUserData: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_trace( param0: ?*sqlite3, xTrace: isize, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_profile( param0: ?*sqlite3, xProfile: isize, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_trace_v2( param0: ?*sqlite3, uMask: u32, xCallback: isize, pCtx: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_progress_handler( param0: ?*sqlite3, param1: i32, param2: isize, param3: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_open( filename: ?[*:0]const u8, ppDb: ?*?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_open16( filename: ?*const anyopaque, ppDb: ?*?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_open_v2( filename: ?[*:0]const u8, ppDb: ?*?*sqlite3, flags: i32, zVfs: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_uri_parameter( zFilename: ?[*:0]const u8, zParam: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_uri_boolean( zFile: ?[*:0]const u8, zParam: ?[*:0]const u8, bDefault: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_uri_int64( param0: ?[*:0]const u8, param1: ?[*:0]const u8, param2: i64, ) callconv(@import("std").os.windows.WINAPI) i64; pub extern "winsqlite3" fn sqlite3_uri_key( zFilename: ?[*:0]const u8, N: i32, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_filename_database( param0: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_filename_journal( param0: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_filename_wal( param0: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_database_file_object( param0: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) ?*sqlite3_file; pub extern "winsqlite3" fn sqlite3_create_filename( zDatabase: ?[*:0]const u8, zJournal: ?[*:0]const u8, zWal: ?[*:0]const u8, nParam: i32, azParam: ?*const ?*i8, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_free_filename( param0: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_errcode( db: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_extended_errcode( db: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_errmsg( param0: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_errmsg16( param0: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_errstr( param0: i32, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_limit( param0: ?*sqlite3, id: i32, newVal: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_prepare( db: ?*sqlite3, zSql: ?[*:0]const u8, nByte: i32, ppStmt: ?*?*sqlite3_stmt, pzTail: ?*const ?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_prepare_v2( db: ?*sqlite3, zSql: ?[*:0]const u8, nByte: i32, ppStmt: ?*?*sqlite3_stmt, pzTail: ?*const ?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_prepare_v3( db: ?*sqlite3, zSql: ?[*:0]const u8, nByte: i32, prepFlags: u32, ppStmt: ?*?*sqlite3_stmt, pzTail: ?*const ?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_prepare16( db: ?*sqlite3, zSql: ?*const anyopaque, nByte: i32, ppStmt: ?*?*sqlite3_stmt, pzTail: ?*const ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_prepare16_v2( db: ?*sqlite3, zSql: ?*const anyopaque, nByte: i32, ppStmt: ?*?*sqlite3_stmt, pzTail: ?*const ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_prepare16_v3( db: ?*sqlite3, zSql: ?*const anyopaque, nByte: i32, prepFlags: u32, ppStmt: ?*?*sqlite3_stmt, pzTail: ?*const ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_sql( pStmt: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_expanded_sql( pStmt: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_stmt_readonly( pStmt: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_stmt_isexplain( pStmt: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_stmt_busy( param0: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_bind_blob( param0: ?*sqlite3_stmt, param1: i32, param2: ?*const anyopaque, n: i32, param4: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_bind_blob64( param0: ?*sqlite3_stmt, param1: i32, param2: ?*const anyopaque, param3: u64, param4: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_bind_double( param0: ?*sqlite3_stmt, param1: i32, param2: f64, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_bind_int( param0: ?*sqlite3_stmt, param1: i32, param2: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_bind_int64( param0: ?*sqlite3_stmt, param1: i32, param2: i64, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_bind_null( param0: ?*sqlite3_stmt, param1: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_bind_text( param0: ?*sqlite3_stmt, param1: i32, param2: ?[*:0]const u8, param3: i32, param4: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_bind_text16( param0: ?*sqlite3_stmt, param1: i32, param2: ?*const anyopaque, param3: i32, param4: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_bind_text64( param0: ?*sqlite3_stmt, param1: i32, param2: ?[*:0]const u8, param3: u64, param4: isize, encoding: u8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_bind_value( param0: ?*sqlite3_stmt, param1: i32, param2: ?*const sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_bind_pointer( param0: ?*sqlite3_stmt, param1: i32, param2: ?*anyopaque, param3: ?[*:0]const u8, param4: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_bind_zeroblob( param0: ?*sqlite3_stmt, param1: i32, n: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_bind_zeroblob64( param0: ?*sqlite3_stmt, param1: i32, param2: u64, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_bind_parameter_count( param0: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_bind_parameter_name( param0: ?*sqlite3_stmt, param1: i32, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_bind_parameter_index( param0: ?*sqlite3_stmt, zName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_clear_bindings( param0: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_column_count( pStmt: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_column_name( param0: ?*sqlite3_stmt, N: i32, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_column_name16( param0: ?*sqlite3_stmt, N: i32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_column_database_name( param0: ?*sqlite3_stmt, param1: i32, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_column_database_name16( param0: ?*sqlite3_stmt, param1: i32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_column_table_name( param0: ?*sqlite3_stmt, param1: i32, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_column_table_name16( param0: ?*sqlite3_stmt, param1: i32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_column_origin_name( param0: ?*sqlite3_stmt, param1: i32, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_column_origin_name16( param0: ?*sqlite3_stmt, param1: i32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_column_decltype( param0: ?*sqlite3_stmt, param1: i32, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_column_decltype16( param0: ?*sqlite3_stmt, param1: i32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_step( param0: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_data_count( pStmt: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_column_blob( param0: ?*sqlite3_stmt, iCol: i32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_column_double( param0: ?*sqlite3_stmt, iCol: i32, ) callconv(@import("std").os.windows.WINAPI) f64; pub extern "winsqlite3" fn sqlite3_column_int( param0: ?*sqlite3_stmt, iCol: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_column_int64( param0: ?*sqlite3_stmt, iCol: i32, ) callconv(@import("std").os.windows.WINAPI) i64; pub extern "winsqlite3" fn sqlite3_column_text( param0: ?*sqlite3_stmt, iCol: i32, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "winsqlite3" fn sqlite3_column_text16( param0: ?*sqlite3_stmt, iCol: i32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_column_value( param0: ?*sqlite3_stmt, iCol: i32, ) callconv(@import("std").os.windows.WINAPI) ?*sqlite3_value; pub extern "winsqlite3" fn sqlite3_column_bytes( param0: ?*sqlite3_stmt, iCol: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_column_bytes16( param0: ?*sqlite3_stmt, iCol: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_column_type( param0: ?*sqlite3_stmt, iCol: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_finalize( pStmt: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_reset( pStmt: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_create_function( db: ?*sqlite3, zFunctionName: ?[*:0]const u8, nArg: i32, eTextRep: i32, pApp: ?*anyopaque, xFunc: isize, xStep: isize, xFinal: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_create_function16( db: ?*sqlite3, zFunctionName: ?*const anyopaque, nArg: i32, eTextRep: i32, pApp: ?*anyopaque, xFunc: isize, xStep: isize, xFinal: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_create_function_v2( db: ?*sqlite3, zFunctionName: ?[*:0]const u8, nArg: i32, eTextRep: i32, pApp: ?*anyopaque, xFunc: isize, xStep: isize, xFinal: isize, xDestroy: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_create_window_function( db: ?*sqlite3, zFunctionName: ?[*:0]const u8, nArg: i32, eTextRep: i32, pApp: ?*anyopaque, xStep: isize, xFinal: isize, xValue: isize, xInverse: isize, xDestroy: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_aggregate_count( param0: ?*sqlite3_context, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_expired( param0: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_transfer_bindings( param0: ?*sqlite3_stmt, param1: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_global_recover( ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_thread_cleanup( ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_memory_alarm( param0: isize, param1: ?*anyopaque, param2: i64, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_value_blob( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_value_double( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) f64; pub extern "winsqlite3" fn sqlite3_value_int( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_value_int64( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) i64; pub extern "winsqlite3" fn sqlite3_value_pointer( param0: ?*sqlite3_value, param1: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_value_text( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "winsqlite3" fn sqlite3_value_text16( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_value_text16le( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_value_text16be( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_value_bytes( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_value_bytes16( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_value_type( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_value_numeric_type( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_value_nochange( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_value_frombind( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_value_subtype( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "winsqlite3" fn sqlite3_value_dup( param0: ?*const sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) ?*sqlite3_value; pub extern "winsqlite3" fn sqlite3_value_free( param0: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_aggregate_context( param0: ?*sqlite3_context, nBytes: i32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_user_data( param0: ?*sqlite3_context, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_context_db_handle( param0: ?*sqlite3_context, ) callconv(@import("std").os.windows.WINAPI) ?*sqlite3; pub extern "winsqlite3" fn sqlite3_get_auxdata( param0: ?*sqlite3_context, N: i32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_set_auxdata( param0: ?*sqlite3_context, N: i32, param2: ?*anyopaque, param3: isize, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_blob( param0: ?*sqlite3_context, param1: ?*const anyopaque, param2: i32, param3: isize, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_blob64( param0: ?*sqlite3_context, param1: ?*const anyopaque, param2: u64, param3: isize, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_double( param0: ?*sqlite3_context, param1: f64, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_error( param0: ?*sqlite3_context, param1: ?[*:0]const u8, param2: i32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_error16( param0: ?*sqlite3_context, param1: ?*const anyopaque, param2: i32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_error_toobig( param0: ?*sqlite3_context, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_error_nomem( param0: ?*sqlite3_context, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_error_code( param0: ?*sqlite3_context, param1: i32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_int( param0: ?*sqlite3_context, param1: i32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_int64( param0: ?*sqlite3_context, param1: i64, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_null( param0: ?*sqlite3_context, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_text( param0: ?*sqlite3_context, param1: ?[*:0]const u8, param2: i32, param3: isize, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_text64( param0: ?*sqlite3_context, param1: ?[*:0]const u8, param2: u64, param3: isize, encoding: u8, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_text16( param0: ?*sqlite3_context, param1: ?*const anyopaque, param2: i32, param3: isize, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_text16le( param0: ?*sqlite3_context, param1: ?*const anyopaque, param2: i32, param3: isize, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_text16be( param0: ?*sqlite3_context, param1: ?*const anyopaque, param2: i32, param3: isize, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_value( param0: ?*sqlite3_context, param1: ?*sqlite3_value, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_pointer( param0: ?*sqlite3_context, param1: ?*anyopaque, param2: ?[*:0]const u8, param3: isize, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_zeroblob( param0: ?*sqlite3_context, n: i32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_result_zeroblob64( param0: ?*sqlite3_context, n: u64, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_result_subtype( param0: ?*sqlite3_context, param1: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_create_collation( param0: ?*sqlite3, zName: ?[*:0]const u8, eTextRep: i32, pArg: ?*anyopaque, xCompare: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_create_collation_v2( param0: ?*sqlite3, zName: ?[*:0]const u8, eTextRep: i32, pArg: ?*anyopaque, xCompare: isize, xDestroy: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_create_collation16( param0: ?*sqlite3, zName: ?*const anyopaque, eTextRep: i32, pArg: ?*anyopaque, xCompare: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_collation_needed( param0: ?*sqlite3, param1: ?*anyopaque, param2: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_collation_needed16( param0: ?*sqlite3, param1: ?*anyopaque, param2: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_sleep( param0: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_win32_set_directory( type: u32, zValue: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_win32_set_directory8( type: u32, zValue: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_win32_set_directory16( type: u32, zValue: ?*const anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_get_autocommit( param0: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_db_handle( param0: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) ?*sqlite3; pub extern "winsqlite3" fn sqlite3_db_filename( db: ?*sqlite3, zDbName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_db_readonly( db: ?*sqlite3, zDbName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_txn_state( param0: ?*sqlite3, zSchema: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_next_stmt( pDb: ?*sqlite3, pStmt: ?*sqlite3_stmt, ) callconv(@import("std").os.windows.WINAPI) ?*sqlite3_stmt; pub extern "winsqlite3" fn sqlite3_commit_hook( param0: ?*sqlite3, param1: isize, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_rollback_hook( param0: ?*sqlite3, param1: isize, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_update_hook( param0: ?*sqlite3, param1: isize, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_enable_shared_cache( param0: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_release_memory( param0: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_db_release_memory( param0: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_soft_heap_limit64( N: i64, ) callconv(@import("std").os.windows.WINAPI) i64; pub extern "winsqlite3" fn sqlite3_hard_heap_limit64( N: i64, ) callconv(@import("std").os.windows.WINAPI) i64; pub extern "winsqlite3" fn sqlite3_soft_heap_limit( N: i32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_table_column_metadata( db: ?*sqlite3, zDbName: ?[*:0]const u8, zTableName: ?[*:0]const u8, zColumnName: ?[*:0]const u8, pzDataType: ?*const ?*i8, pzCollSeq: ?*const ?*i8, pNotNull: ?*i32, pPrimaryKey: ?*i32, pAutoinc: ?*i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_load_extension( db: ?*sqlite3, zFile: ?[*:0]const u8, zProc: ?[*:0]const u8, pzErrMsg: ?*?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_enable_load_extension( db: ?*sqlite3, onoff: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_auto_extension( xEntryPoint: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_cancel_auto_extension( xEntryPoint: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_reset_auto_extension( ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_create_module( db: ?*sqlite3, zName: ?[*:0]const u8, p: ?*const sqlite3_module, pClientData: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_create_module_v2( db: ?*sqlite3, zName: ?[*:0]const u8, p: ?*const sqlite3_module, pClientData: ?*anyopaque, xDestroy: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_drop_modules( db: ?*sqlite3, azKeep: ?*const ?*i8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_declare_vtab( param0: ?*sqlite3, zSQL: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_overload_function( param0: ?*sqlite3, zFuncName: ?[*:0]const u8, nArg: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_blob_open( param0: ?*sqlite3, zDb: ?[*:0]const u8, zTable: ?[*:0]const u8, zColumn: ?[*:0]const u8, iRow: i64, flags: i32, ppBlob: ?*?*sqlite3_blob, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_blob_reopen( param0: ?*sqlite3_blob, param1: i64, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_blob_close( param0: ?*sqlite3_blob, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_blob_bytes( param0: ?*sqlite3_blob, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_blob_read( param0: ?*sqlite3_blob, Z: ?*anyopaque, N: i32, iOffset: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_blob_write( param0: ?*sqlite3_blob, z: ?*const anyopaque, n: i32, iOffset: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_vfs_find( zVfsName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) ?*sqlite3_vfs; pub extern "winsqlite3" fn sqlite3_vfs_register( param0: ?*sqlite3_vfs, makeDflt: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_vfs_unregister( param0: ?*sqlite3_vfs, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_mutex_alloc( param0: i32, ) callconv(@import("std").os.windows.WINAPI) ?*sqlite3_mutex; pub extern "winsqlite3" fn sqlite3_mutex_free( param0: ?*sqlite3_mutex, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_mutex_enter( param0: ?*sqlite3_mutex, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_mutex_try( param0: ?*sqlite3_mutex, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_mutex_leave( param0: ?*sqlite3_mutex, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_db_mutex( param0: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) ?*sqlite3_mutex; pub extern "winsqlite3" fn sqlite3_file_control( param0: ?*sqlite3, zDbName: ?[*:0]const u8, op: i32, param3: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_test_control( op: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_keyword_count( ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_keyword_name( param0: i32, param1: ?*const ?*i8, param2: ?*i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_keyword_check( param0: ?[*:0]const u8, param1: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_str_new( param0: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) ?*sqlite3_str; pub extern "winsqlite3" fn sqlite3_str_finish( param0: ?*sqlite3_str, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_str_appendf( param0: ?*sqlite3_str, zFormat: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_str_vappendf( param0: ?*sqlite3_str, zFormat: ?[*:0]const u8, param2: ?*i8, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_str_append( param0: ?*sqlite3_str, zIn: ?[*:0]const u8, N: i32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_str_appendall( param0: ?*sqlite3_str, zIn: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_str_appendchar( param0: ?*sqlite3_str, N: i32, C: CHAR, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_str_reset( param0: ?*sqlite3_str, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_str_errcode( param0: ?*sqlite3_str, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_str_length( param0: ?*sqlite3_str, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_str_value( param0: ?*sqlite3_str, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_status( op: i32, pCurrent: ?*i32, pHighwater: ?*i32, resetFlag: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_status64( op: i32, pCurrent: ?*i64, pHighwater: ?*i64, resetFlag: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_db_status( param0: ?*sqlite3, op: i32, pCur: ?*i32, pHiwtr: ?*i32, resetFlg: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_stmt_status( param0: ?*sqlite3_stmt, op: i32, resetFlg: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_backup_init( pDest: ?*sqlite3, zDestName: ?[*:0]const u8, pSource: ?*sqlite3, zSourceName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) ?*sqlite3_backup; pub extern "winsqlite3" fn sqlite3_backup_step( p: ?*sqlite3_backup, nPage: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_backup_finish( p: ?*sqlite3_backup, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_backup_remaining( p: ?*sqlite3_backup, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_backup_pagecount( p: ?*sqlite3_backup, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_stricmp( param0: ?[*:0]const u8, param1: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_strnicmp( param0: ?[*:0]const u8, param1: ?[*:0]const u8, param2: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_strglob( zGlob: ?[*:0]const u8, zStr: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_strlike( zGlob: ?[*:0]const u8, zStr: ?[*:0]const u8, cEsc: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_log( iErrCode: i32, zFormat: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "winsqlite3" fn sqlite3_wal_hook( param0: ?*sqlite3, param1: isize, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "winsqlite3" fn sqlite3_wal_autocheckpoint( db: ?*sqlite3, N: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_wal_checkpoint( db: ?*sqlite3, zDb: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_wal_checkpoint_v2( db: ?*sqlite3, zDb: ?[*:0]const u8, eMode: i32, pnLog: ?*i32, pnCkpt: ?*i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_vtab_config( param0: ?*sqlite3, op: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_vtab_on_conflict( param0: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_vtab_nochange( param0: ?*sqlite3_context, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_vtab_collation( param0: ?*sqlite3_index_info, param1: i32, ) callconv(@import("std").os.windows.WINAPI) ?PSTR; pub extern "winsqlite3" fn sqlite3_db_cacheflush( param0: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_system_errno( param0: ?*sqlite3, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_serialize( db: ?*sqlite3, zSchema: ?[*:0]const u8, piSize: ?*i64, mFlags: u32, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "winsqlite3" fn sqlite3_deserialize( db: ?*sqlite3, zSchema: ?[*:0]const u8, pData: ?*u8, szDb: i64, szBuf: i64, mFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_rtree_geometry_callback( db: ?*sqlite3, zGeom: ?[*:0]const u8, xGeom: isize, pContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "winsqlite3" fn sqlite3_rtree_query_callback( db: ?*sqlite3, zQueryFunc: ?[*:0]const u8, xQueryFunc: isize, pContext: ?*anyopaque, xDestructor: isize, ) callconv(@import("std").os.windows.WINAPI) i32; //-------------------------------------------------------------------------------- // 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 (2) //-------------------------------------------------------------------------------- const CHAR = @import("../foundation.zig").CHAR; const PSTR = @import("../foundation.zig").PSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "sqlite3_callback")) { _ = sqlite3_callback; } if (@hasDecl(@This(), "sqlite3_syscall_ptr")) { _ = sqlite3_syscall_ptr; } if (@hasDecl(@This(), "sqlite3_destructor_type")) { _ = sqlite3_destructor_type; } if (@hasDecl(@This(), "fts5_extension_function")) { _ = fts5_extension_function; } if (@hasDecl(@This(), "sqlite3_loadext_entry")) { _ = sqlite3_loadext_entry; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/system/sql_lite.zig
//-------------------------------------------------------------------------------- // Section: Types (2) //-------------------------------------------------------------------------------- const IID_IThumbnailExtractor_Value = Guid.initString("969dc708-5c76-11d1-8d86-0000f804b057"); pub const IID_IThumbnailExtractor = &IID_IThumbnailExtractor_Value; pub const IThumbnailExtractor = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ExtractThumbnail: fn( self: *const IThumbnailExtractor, pStg: ?*IStorage, ulLength: u32, ulHeight: u32, pulOutputLength: ?*u32, pulOutputHeight: ?*u32, phOutputBitmap: ?*?HBITMAP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnFileUpdated: fn( self: *const IThumbnailExtractor, pStg: ?*IStorage, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IThumbnailExtractor_ExtractThumbnail(self: *const T, pStg: ?*IStorage, ulLength: u32, ulHeight: u32, pulOutputLength: ?*u32, pulOutputHeight: ?*u32, phOutputBitmap: ?*?HBITMAP) callconv(.Inline) HRESULT { return @ptrCast(*const IThumbnailExtractor.VTable, self.vtable).ExtractThumbnail(@ptrCast(*const IThumbnailExtractor, self), pStg, ulLength, ulHeight, pulOutputLength, pulOutputHeight, phOutputBitmap); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IThumbnailExtractor_OnFileUpdated(self: *const T, pStg: ?*IStorage) callconv(.Inline) HRESULT { return @ptrCast(*const IThumbnailExtractor.VTable, self.vtable).OnFileUpdated(@ptrCast(*const IThumbnailExtractor, self), pStg); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDummyHICONIncluder_Value = Guid.initString("947990de-cc28-11d2-a0f7-00805f858fb1"); pub const IID_IDummyHICONIncluder = &IID_IDummyHICONIncluder_Value; pub const IDummyHICONIncluder = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Dummy: fn( self: *const IDummyHICONIncluder, h1: ?HICON, h2: ?HDC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDummyHICONIncluder_Dummy(self: *const T, h1: ?HICON, h2: ?HDC) callconv(.Inline) HRESULT { return @ptrCast(*const IDummyHICONIncluder.VTable, self.vtable).Dummy(@ptrCast(*const IDummyHICONIncluder, self), h1, h2); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (0) //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (7) //-------------------------------------------------------------------------------- const Guid = @import("../../zig.zig").Guid; const HBITMAP = @import("../../graphics/gdi.zig").HBITMAP; const HDC = @import("../../graphics/gdi.zig").HDC; const HICON = @import("../../ui/windows_and_messaging.zig").HICON; const HRESULT = @import("../../foundation.zig").HRESULT; const IStorage = @import("../../system/com/structured_storage.zig").IStorage; const IUnknown = @import("../../system/com.zig").IUnknown; test { @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/system/com/ui.zig
const ImageReader = zigimg.ImageReader; const ImageSeekStream = zigimg.ImageSeekStream; const PixelFormat = zigimg.PixelFormat; const assert = std.debug.assert; const bmp = zigimg.bmp; const color = zigimg.color; const errors = zigimg.errors; const std = @import("std"); const testing = std.testing; const zigimg = @import("zigimg"); const helpers = @import("../helpers.zig"); const MemoryRGBABitmap = @embedFile("../fixtures/bmp/windows_rgba_v5.bmp"); fn verifyBitmapRGBAV5(the_bitmap: bmp.Bitmap, pixels_opt: ?color.ColorStorage) !void { try helpers.expectEq(the_bitmap.file_header.size, 153738); try helpers.expectEq(the_bitmap.file_header.reserved, 0); try helpers.expectEq(the_bitmap.file_header.pixel_offset, 138); try helpers.expectEq(the_bitmap.width(), 240); try helpers.expectEq(the_bitmap.height(), 160); try helpers.expectEqSlice(u8, @tagName(the_bitmap.info_header), "V5"); _ = switch (the_bitmap.info_header) { .V5 => |v5Header| { try helpers.expectEq(v5Header.header_size, bmp.BitmapInfoHeaderV5.HeaderSize); try helpers.expectEq(v5Header.width, 240); try helpers.expectEq(v5Header.height, 160); try helpers.expectEq(v5Header.color_plane, 1); try helpers.expectEq(v5Header.bit_count, 32); try helpers.expectEq(v5Header.compression_method, bmp.CompressionMethod.Bitfields); try helpers.expectEq(v5Header.image_raw_size, 240 * 160 * 4); try helpers.expectEq(v5Header.horizontal_resolution, 2835); try helpers.expectEq(v5Header.vertical_resolution, 2835); try helpers.expectEq(v5Header.palette_size, 0); try helpers.expectEq(v5Header.important_colors, 0); try helpers.expectEq(v5Header.red_mask, 0x00ff0000); try helpers.expectEq(v5Header.green_mask, 0x0000ff00); try helpers.expectEq(v5Header.blue_mask, 0x000000ff); try helpers.expectEq(v5Header.alpha_mask, 0xff000000); try helpers.expectEq(v5Header.color_space, bmp.BitmapColorSpace.sRgb); try helpers.expectEq(v5Header.cie_end_points.red.x, 0); try helpers.expectEq(v5Header.cie_end_points.red.y, 0); try helpers.expectEq(v5Header.cie_end_points.red.z, 0); try helpers.expectEq(v5Header.cie_end_points.green.x, 0); try helpers.expectEq(v5Header.cie_end_points.green.y, 0); try helpers.expectEq(v5Header.cie_end_points.green.z, 0); try helpers.expectEq(v5Header.cie_end_points.blue.x, 0); try helpers.expectEq(v5Header.cie_end_points.blue.y, 0); try helpers.expectEq(v5Header.cie_end_points.blue.z, 0); try helpers.expectEq(v5Header.gamma_red, 0); try helpers.expectEq(v5Header.gamma_green, 0); try helpers.expectEq(v5Header.gamma_blue, 0); try helpers.expectEq(v5Header.intent, bmp.BitmapIntent.Graphics); try helpers.expectEq(v5Header.profile_data, 0); try helpers.expectEq(v5Header.profile_size, 0); try helpers.expectEq(v5Header.reserved, 0); }, else => unreachable, }; try testing.expect(pixels_opt != null); if (pixels_opt) |pixels| { try testing.expect(pixels == .Bgra32); try helpers.expectEq(pixels.len(), 240 * 160); const first_pixel = pixels.Bgra32[0]; try helpers.expectEq(first_pixel.R, 0xFF); try helpers.expectEq(first_pixel.G, 0xFF); try helpers.expectEq(first_pixel.B, 0xFF); try helpers.expectEq(first_pixel.A, 0xFF); const second_pixel = pixels.Bgra32[1]; try helpers.expectEq(second_pixel.R, 0xFF); try helpers.expectEq(second_pixel.G, 0x00); try helpers.expectEq(second_pixel.B, 0x00); try helpers.expectEq(second_pixel.A, 0xFF); const third_pixel = pixels.Bgra32[2]; try helpers.expectEq(third_pixel.R, 0x00); try helpers.expectEq(third_pixel.G, 0xFF); try helpers.expectEq(third_pixel.B, 0x00); try helpers.expectEq(third_pixel.A, 0xFF); const fourth_pixel = pixels.Bgra32[3]; try helpers.expectEq(fourth_pixel.R, 0x00); try helpers.expectEq(fourth_pixel.G, 0x00); try helpers.expectEq(fourth_pixel.B, 0xFF); try helpers.expectEq(fourth_pixel.A, 0xFF); const colored_pixel = pixels.Bgra32[(22 * 240) + 16]; try helpers.expectEq(colored_pixel.R, 195); try helpers.expectEq(colored_pixel.G, 195); try helpers.expectEq(colored_pixel.B, 255); try helpers.expectEq(colored_pixel.A, 255); } } test "Read simple version 4 24-bit RGB bitmap" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/bmp/simple_v4.bmp"); defer file.close(); var the_bitmap = bmp.Bitmap{}; var stream_source = std.io.StreamSource{ .file = file }; var pixels_opt: ?color.ColorStorage = null; try the_bitmap.read(helpers.zigimg_test_allocator, stream_source.reader(), stream_source.seekableStream(), &pixels_opt); defer { if (pixels_opt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try helpers.expectEq(the_bitmap.width(), 8); try helpers.expectEq(the_bitmap.height(), 1); try testing.expect(pixels_opt != null); if (pixels_opt) |pixels| { try testing.expect(pixels == .Bgr24); const red = pixels.Bgr24[0]; try helpers.expectEq(red.R, 0xFF); try helpers.expectEq(red.G, 0x00); try helpers.expectEq(red.B, 0x00); const green = pixels.Bgr24[1]; try helpers.expectEq(green.R, 0x00); try helpers.expectEq(green.G, 0xFF); try helpers.expectEq(green.B, 0x00); const blue = pixels.Bgr24[2]; try helpers.expectEq(blue.R, 0x00); try helpers.expectEq(blue.G, 0x00); try helpers.expectEq(blue.B, 0xFF); const cyan = pixels.Bgr24[3]; try helpers.expectEq(cyan.R, 0x00); try helpers.expectEq(cyan.G, 0xFF); try helpers.expectEq(cyan.B, 0xFF); const magenta = pixels.Bgr24[4]; try helpers.expectEq(magenta.R, 0xFF); try helpers.expectEq(magenta.G, 0x00); try helpers.expectEq(magenta.B, 0xFF); const yellow = pixels.Bgr24[5]; try helpers.expectEq(yellow.R, 0xFF); try helpers.expectEq(yellow.G, 0xFF); try helpers.expectEq(yellow.B, 0x00); const black = pixels.Bgr24[6]; try helpers.expectEq(black.R, 0x00); try helpers.expectEq(black.G, 0x00); try helpers.expectEq(black.B, 0x00); const white = pixels.Bgr24[7]; try helpers.expectEq(white.R, 0xFF); try helpers.expectEq(white.G, 0xFF); try helpers.expectEq(white.B, 0xFF); } } test "Read a valid version 5 RGBA bitmap from file" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/bmp/windows_rgba_v5.bmp"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var the_bitmap = bmp.Bitmap{}; var pixels_opt: ?color.ColorStorage = null; try the_bitmap.read(helpers.zigimg_test_allocator, stream_source.reader(), stream_source.seekableStream(), &pixels_opt); defer { if (pixels_opt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try verifyBitmapRGBAV5(the_bitmap, pixels_opt); } test "Read a valid version 5 RGBA bitmap from memory" { var stream_source = std.io.StreamSource{ .const_buffer = std.io.fixedBufferStream(MemoryRGBABitmap) }; var the_bitmap = bmp.Bitmap{}; var pixels_opt: ?color.ColorStorage = null; try the_bitmap.read(helpers.zigimg_test_allocator, stream_source.reader(), stream_source.seekableStream(), &pixels_opt); defer { if (pixels_opt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try verifyBitmapRGBAV5(the_bitmap, pixels_opt); } test "Should error when reading an invalid file" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/bmp/notbmp.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var the_bitmap = bmp.Bitmap{}; var pixels: ?color.ColorStorage = null; const invalidFile = the_bitmap.read(helpers.zigimg_test_allocator, stream_source.reader(), stream_source.seekableStream(), &pixels); try helpers.expectError(invalidFile, errors.ImageError.InvalidMagicHeader); }
tests/formats/bmp_test.zig
const std = @import("std"); const assert = std.debug.assert; pub const Image = struct { const Color = enum(u8) { Black = 0, White = 1, Transparent = 2, LAST = 3, OTHER = 99, }; allocator: *std.mem.Allocator, w: usize, h: usize, l: usize, data: [128 * 25 * 6]Color, // the intention was to dynamically allocate data, but I got a compiler error: // // broken LLVM module found: Call parameter type does not match function signature! // %31 = getelementptr inbounds %Image, %Image* %30, i32 0, i32 4, !dbg !1078 // { %"[]u8", i16 }* call fastcc void @std.mem.Allocator.alloc(%"[]u8"* sret %31, %std.builtin.StackTrace* %error_return_trace, %std.mem.Allocator* %34, i64 %38), !dbg !1121 // // Unable to dump stack trace: debug info stripped // make: *** [img.zig_test] Abort trap: 6 pub fn init(allocator: *std.mem.Allocator, w: usize, h: usize) Image { var self = Image{ .allocator = allocator, .w = w, .h = h, .l = 0, .data = undefined, }; return self; } pub fn deinit(self: Image) void { _ = self; } fn pos(self: Image, l: usize, c: usize, r: usize) usize { return (l * self.h + r) * self.w + c; } pub fn parse(self: *Image, data: []const u8) void { var j: usize = 0; var l: usize = 0; var r: usize = 0; var c: usize = 0; const layer_size = self.w * self.h; const num_layers = (data.len + layer_size - 1) / layer_size; if (self.l < num_layers) { if (self.l > 0) { // std.debug.warn("FREE {} layers\n", self.l); // self.allocator.free(self.data); self.l = 0; } // self.data = self.allocator.alloc(u8, layer_size * num_layers); self.l = num_layers; // std.debug.warn("ALLOC {} layers\n", self.l); } while (j < data.len) : (j += 1) { var num = data[j] - '0'; if (num >= @enumToInt(Color.LAST)) num = @enumToInt(Color.OTHER); const color = @intToEnum(Color, num); self.data[self.pos(l, c, r)] = color; // std.debug.warn("DATA {} {} {} = {}\n", l, r, c, color); c += 1; if (c >= self.w) { c = 0; r += 1; } if (r >= self.h) { c = 0; r = 0; l += 1; } } self.l = l; } pub fn find_layer_with_fewest_blacks(self: *Image) usize { var min_black: usize = std.math.maxInt(u32); var min_product: usize = 0; var l: usize = 0; while (l < self.l) : (l += 1) { var count_black: usize = 0; var count_white: usize = 0; var count_trans: usize = 0; var r: usize = 0; while (r < self.h) : (r += 1) { var c: usize = 0; while (c < self.w) : (c += 1) { switch (self.data[self.pos(l, c, r)]) { Color.Black => count_black += 1, Color.White => count_white += 1, Color.Transparent => count_trans += 1, else => break, } } } // std.debug.warn("LAYER {} has {} blacks\n", l, count_black); if (min_black > count_black) { min_black = count_black; min_product = count_white * count_trans; } } // std.debug.warn("LAYER MIN has {} blacks, product is {}\n", min_black, min_product); return min_product; } pub fn render(self: *Image) !void { const out = std.io.getStdOut().writer(); // std.debug.warn("TYPE [{}]\n", @typeName(@typeOf(out))); var r: usize = 0; while (r < self.h) : (r += 1) { var c: usize = 0; while (c < self.w) : (c += 1) { var l: usize = 0; while (l < self.l) : (l += 1) { const color = self.data[self.pos(l, c, r)]; switch (color) { Color.Transparent => continue, Color.Black => { try out.print("{s}", .{" "}); break; }, Color.White => { try out.print("{s}", .{"\u{2588}"}); break; }, else => break, } } } try out.print("{s}", .{"\n"}); } } }; test "total orbit count" { const data: []const u8 = "123456789012"; var image = Image.init(std.testing.allocator, 3, 2); defer image.deinit(); image.parse(data); assert(image.l == 2); _ = image.find_layer_with_fewest_blacks(); }
2019/p08/img.zig
const std = @import("std"); const sg = @import("sokol").gfx; const sapp = @import("sokol").app; const sgapp = @import("sokol").app_gfx_glue; const vec2 = @import("shaders/sokol_math.zig").Vec2; const vec3 = @import("shaders/sokol_math.zig").Vec3; const mat4 = @import("shaders/sokol_math.zig").Mat4; const shd = @import("shaders/heightmap.glsl.zig"); const zigimg = @import("zigimg"); const nooice = @import("nooice"); const terrain_generation = @import("src/terrain_generation.zig"); const c = @cImport({ @cInclude("DDSLoader/src/dds.h"); }); const state = struct { var rx: f32 = 0.0; var ry: f32 = 0.0; var pass_action: sg.PassAction = .{}; var pip: sg.Pipeline = .{}; var bind: sg.Bindings = .{}; // const view: mat4 = mat4.lookat(.{ .x = 0, .y = 5.0, .z = 0 }, vec3.zero(), vec3.up()); const view: mat4 = mat4.lookat(.{ .x = 1, .y = 1, .z = 2 }, .{ .x = 0, .y = 0, .z = 0 }, vec3.up().mul(1)); }; // a vertex struct with position, color and uv-coords const VertexHeightmap = packed struct { height: f32, u: i16, v: i16 }; const Vertex = packed struct { x: f32, y: f32, z: f32, u: i16, v: i16 }; export fn init() void { sg.setup(.{ .context = sgapp.context() }); var allocator = std.heap.GeneralPurposeAllocator(.{}){}; // Cube vertex buffer with packed vertex formats for color and texture coords. // Note that a vertex format which must be portable across all // backends must only use the normalized integer formats // (BYTE4N, UBYTE4N, SHORT2N, SHORT4N), which can be converted // to floating point formats in the vertex shader inputs. // The reason is that D3D11 cannot convert from non-normalized // formats to floating point inputs (only to integer inputs), // and WebGL2 / GLES2 don't support integer vertex shader inputs. // const heightmap = zigimg.image.Image.fromFilePath(&allocator.allocator, "data/heightmap.png") catch unreachable; terrain_generation.make_heightmap(&allocator.allocator, 512, 512) catch unreachable; // const heightmap_info: zigimg.image.ImageInfo = .{ // .width = 1024, // .height = 1024, // .pixel_format = .Grayscale16, // }; // const heightmap = zigimg.image.Image.fromFilePathAsHeaderless(&allocator.allocator, "data/heightmap.raw", heightmap_info) catch unreachable; const heightmap = zigimg.image.Image.fromFilePath(&allocator.allocator, "data/gen/heightmap.pgm") catch unreachable; // const vertices = [_]Vertex{ // // pos color texcoords // .{ .x = -1.0, .y = 0, .z = -1.0, .u = 0, .v = 0 }, // .{ .x = -1.0, .y = 0, .z = 1.0, .u = 32767, .v = 0 }, // .{ .x = 1.0, .y = 0, .z = 1.0, .u = 32767, .v = 32767 }, // .{ .x = 1.0, .y = 0, .z = -1.0, .u = 0, .v = 32767 }, // }; // state.bind.vertex_buffers[0] = sg.makeBuffer(.{ .data = sg.asRange(vertices) }); // const indices = [_]u16{ 0, 1, 2, 0, 2, 3 }; // state.bind.index_buffer = sg.makeBuffer(.{ .type = .INDEXBUFFER, .data = sg.asRange(indices) }); // const vertices_hm = [_]VertexHeightmap{ // .{ .height = 0, .u = 0, .v = 0 }, // .{ .height = 0, .u = 0, .v = 32767 }, // .{ .height = 0, .u = 32767, .v = 32767 }, // .{ .height = 0.5, .u = 32767, .v = 0 }, // }; // const indices_hm = [_]u32{ 0, 1, 2, 0, 2, 3 }; var vertices_hm = allocator.allocator.alloc(VertexHeightmap, heightmap.height * heightmap.width) catch unreachable; defer allocator.allocator.free(vertices_hm); { const seed = 0; var y: usize = 0; while (y < heightmap.height) : (y += 1) { var x: usize = 0; while (x < heightmap.width) : (x += 1) { var xf = @intToFloat(f32, x); var yf = @intToFloat(f32, y); var i = x + y * heightmap.width; var v = &vertices_hm[i]; var gs = heightmap.pixels.?.Grayscale16[i].value; var height_f64 = @intToFloat(f64, gs); // var height_f64 = (std.math.sin(xf * 0.01) + std.math.cos(yf * 0.02)) * 0.1; // v.*.height = (nooice.fbm.noise_fbm_2d(xf, yf, seed, 5, 0.5, 300) * 1 + 0.5) * 0.2; // v.*.height = (nooice.fbm.noise_fbm_2d(xf, yf, seed, 1, 0.5, 100) * 0.2) + 0.5; // v.*.height = nooice.noise.noise_normalized(nooice.fbm.noise_2d(@intCast(u32, x), @intCast(u32, y), seed), f32) * 0.1; // v.*.height = nooice.coherent.noise_coherent_2d(xf * 0.01, yf * 0.01, seed) * 0.2; v.*.height = @floatCast(f32, height_f64 / @as(f32, std.math.maxInt(u16))) * 0.3 - 0.15; // v.*.height = -@floatCast(f32, height_f64); v.*.u = @floatToInt(i16, @as(f32, 32767.0) * xf / @intToFloat(f32, heightmap.width)); v.*.v = @floatToInt(i16, @as(f32, 32767.0) * yf / @intToFloat(f32, heightmap.height)); // std.debug.print("i: {any}, v: {any}\n", .{ i, v.* }); } } } var indices_hm = allocator.allocator.alloc(u32, (heightmap.height - 1) * (heightmap.width - 1) * 6) catch unreachable; defer allocator.allocator.free(indices_hm); { var i: u32 = 0; var y: u32 = 0; const width = @intCast(u32, heightmap.width); const height = @intCast(u32, heightmap.height); while (y < height - 1) : (y += 1) { var x: u32 = 0; while (x < width - 1) : (x += 1) { const indices_quad = [_]u32{ x + y * width, x + (y + 1) * width, x + 1 + y * width, x + 1 + (y + 1) * width, }; indices_hm[i + 0] = indices_quad[0]; indices_hm[i + 1] = indices_quad[1]; indices_hm[i + 2] = indices_quad[2]; indices_hm[i + 3] = indices_quad[2]; indices_hm[i + 4] = indices_quad[1]; indices_hm[i + 5] = indices_quad[3]; // std.debug.print("quad: {any}\n", .{indices_quad}); // std.debug.print("indices: {any}\n", .{indices_hm[i .. i + 6]}); // std.debug.print("tri: {any} {any} {any}\n", .{ // vertices_hm[indices_hm[i + 0]], // vertices_hm[indices_hm[i + 1]], // vertices_hm[indices_hm[i + 2]], // }); // std.debug.print("tri: {any} {any} {any}\n", .{ // vertices_hm[indices_hm[i + 3]], // vertices_hm[indices_hm[i + 4]], // vertices_hm[indices_hm[i + 5]], // }); i += 6; } } } state.bind.vertex_buffers[0] = sg.makeBuffer(.{ .data = sg.asRange(vertices_hm) }); state.bind.index_buffer = sg.makeBuffer(.{ .type = .INDEXBUFFER, .data = sg.asRange(indices_hm) }); // Splatmat Texture const splatmap = zigimg.image.Image.fromFilePath(&allocator.allocator, "data/gen/splatmap.pgm") catch unreachable; defer splatmap.deinit(); std.debug.print("pixel format: {s}\n", .{splatmap.pixel_format}); // std.debug.assert(splatmap.pixel_format == zigimg.PixelFormat.Rgba32); const pixels_splatmap = splatmap.pixels.?.Grayscale8; var img_desc_splatmap: sg.ImageDesc = .{ .width = @intCast(i32, splatmap.width), .height = @intCast(i32, splatmap.height), .pixel_format = .R8, }; img_desc_splatmap.data.subimage[0][0] = sg.asRange(pixels_splatmap); state.bind.fs_images[shd.SLOT_splatmapTex] = sg.makeImage(img_desc_splatmap); // Grass Texture // const grassdds = c.dds_load("data/terrain/Rock007_1K_Color_bc7.dds"); // defer c.dds_free(grassdds); // std.debug.print("dds: {any}\n", .{grassdds.*}); const grass = zigimg.image.Image.fromFilePath(&allocator.allocator, "data/terrain/Grass004_1K_Color_8.png") catch unreachable; defer grass.deinit(); std.debug.print("pixel format: {s}\n", .{grass.pixel_format}); // const grassdata = grassdds.*.blBuffer[0 .. grassdds.*.dwWidth * grassdds.*.dwHeight * 4]; // const grassdata = grassdds.*.blBuffer[0..grassdds.*.dwBufferSize]; std.debug.assert(grass.pixel_format == zigimg.PixelFormat.Rgba32); const pixels_grass = grass.pixels.?.Rgba32; var img_desc_grass: sg.ImageDesc = .{ .width = @intCast(i32, grass.width), .height = @intCast(i32, grass.height), .pixel_format = .RGBA8, // .pixel_format = .R8, }; img_desc_grass.data.subimage[0][0] = sg.asRange(pixels_grass); state.bind.fs_images[shd.SLOT_grassTex] = sg.makeImageWithMipmaps(img_desc_grass); // Rock Texture // var rockdds = c.dds_load("data/terrain/Rock007_1K_Color_bc7.dds").*; // defer c.dds_free(&rockdds); // std.debug.print("dds: {any}\n", .{rockdds}); // const grassdata = grassdds.*.blBuffer[0 .. grassdds.*.dwWidth * grassdds.*.dwHeight * 4]; // const rockdata = rockdds.blBuffer[0..rockdds.dwBufferSize]; const rock = zigimg.image.Image.fromFilePath(&allocator.allocator, "data/terrain/Rock007_1K_Color_8.png") catch unreachable; defer rock.deinit(); std.debug.print("pixel format: {s}\n", .{rock.pixel_format}); std.debug.assert(rock.pixel_format == zigimg.PixelFormat.Rgba32); const pixels_rock = rock.pixels.?.Rgba32; var img_desc_rock: sg.ImageDesc = .{ .width = @intCast(i32, rock.width), .height = @intCast(i32, rock.height), .pixel_format = .RGBA8, // .pixel_format = .BC7_RGBA, // .num_mipmaps = 11, }; img_desc_rock.data.subimage[0][0] = sg.asRange(pixels_rock); state.bind.fs_images[shd.SLOT_rockTex] = sg.makeImageWithMipmaps(img_desc_rock); // shader and pipeline object var pip_desc_hm: sg.PipelineDesc = .{ .shader = sg.makeShader(shd.heightmapShaderDesc(sg.queryBackend())), .index_type = .UINT32, .depth = .{ .compare = .LESS_EQUAL, .write_enabled = true, }, .cull_mode = .BACK, // .cull_mode = .NONE, .face_winding = .CCW, }; pip_desc_hm.layout.attrs[shd.ATTR_vs_height].format = .FLOAT; pip_desc_hm.layout.attrs[shd.ATTR_vs_texcoord0].format = .SHORT2N; state.pip = sg.makePipeline(pip_desc_hm); // pass action for clearing the frame buffer state.pass_action.colors[0] = .{ .action = .CLEAR, .value = .{ .r = 0.25, .g = 0.5, .b = 0.75, .a = 1 } }; } export fn frame() void { // state.rx += 1.0; state.ry += 0.25; const vs_params = computeVsParams(state.rx, state.ry); sg.beginDefaultPass(state.pass_action, sapp.width(), sapp.height()); sg.applyPipeline(state.pip); sg.applyBindings(state.bind); sg.applyUniforms(.VS, shd.SLOT_vs_params, sg.asRange(vs_params)); sg.draw(0, 6 * 1023 * 1023, 1); sg.endPass(); sg.commit(); } export fn cleanup() void { sg.shutdown(); } pub fn main() void { sapp.run( .{ .init_cb = init, .frame_cb = frame, .cleanup_cb = cleanup, .width = 800, .height = 600, .sample_count = 4, .window_title = "Misty Fantasy", }, ); } var time: f32 = 0; fn computeVsParams(rx: f32, ry: f32) shd.VsParams { time += 0.01; const rxm = mat4.rotate(rx, .{ .x = 1.0, .y = 0.0, .z = 0.0 }); const rym = mat4.rotate(ry, .{ .x = 0.0, .y = 1.0, .z = 0.0 }); const model = mat4.mul(rxm, rym); // const model = mat4.identity(); const aspect = sapp.widthf() / sapp.heightf(); const proj = mat4.persp(60.0, aspect, 0.01, 10.0); return shd.VsParams{ // .vp = mat4.mul(proj, state.view), .vp = proj, .mvp = mat4.mul(mat4.mul(proj, state.view), model), .time = time, .screen_size = [2]f32{ sapp.widthf(), sapp.heightf() }, // .screen_size = vec2.new(sapp.widthf(), sapp.heightf()), }; }
main.zig
const std = @import("std"); const warn = std.debug.warn; const BlockTree = @import("./block_tree.zig").BlockTree; const DeflateSlidingWindow = @import("./raw_deflate_reader.zig").DeflateSlidingWindow; pub fn RawBlock(comptime InputBitStream: type) type { return struct { const Self = @This(); const ThisBlock = Block(InputBitStream); bytes_left: u16, pub fn fromBitStream(stream: *InputBitStream) !ThisBlock { stream.alignToByte(); const len: u16 = try stream.readBitsNoEof(u16, 16); const nlen: u16 = try stream.readBitsNoEof(u16, 16); // Integrity check if (len != (nlen ^ 0xFFFF)) { return error.Failed; } return ThisBlock{ .Raw = Self{ .bytes_left = len, }, }; } pub fn readElementFrom(self: *Self, stream: *InputBitStream) !u9 { if (self.bytes_left >= 1) { const v: u9 = try stream.readBitsNoEof(u9, 8); self.bytes_left -= 1; return v; } else { return error.EndOfBlock; } } }; } pub fn HuffmanBlock(comptime InputBitStream: type) type { return struct { const Self = @This(); const ThisBlock = Block(InputBitStream); tree: BlockTree(InputBitStream), pub fn readElementFrom(self: *Self, stream: *InputBitStream) !u9 { const v: u9 = try self.tree.readLitFrom(stream); if (v == 256) { return error.EndOfBlock; } else { return v; } } pub fn readDistFrom(self: *Self, stream: *InputBitStream) !u9 { return try self.tree.readDistFrom(stream); } }; } pub fn Block(comptime InputBitStream: type) type { return union(enum) { Empty: void, Raw: RawBlock(InputBitStream), Huffman: HuffmanBlock(InputBitStream), }; }
src/block.zig
const std = @import("std"); const Type = @import("../../type.zig").Type; const Target = std.Target; /// Defines how to pass a type as part of a function signature, /// both for parameters as well as return values. pub const Class = enum { direct, indirect, none }; const none: [2]Class = .{ .none, .none }; const memory: [2]Class = .{ .indirect, .none }; const direct: [2]Class = .{ .direct, .none }; /// Classifies a given Zig type to determine how they must be passed /// or returned as value within a wasm function. /// When all elements result in `.none`, no value must be passed in or returned. pub fn classifyType(ty: Type, target: Target) [2]Class { if (!ty.hasRuntimeBitsIgnoreComptime()) return none; switch (ty.zigTypeTag()) { .Struct => { // When the (maybe) scalar type exceeds max 'direct' integer size if (ty.abiSize(target) > 8) return memory; // When the struct type is non-scalar if (ty.structFieldCount() > 1) return memory; // When the struct's alignment is non-natural const field = ty.structFields().values()[0]; if (field.abi_align != 0) { if (field.abi_align > field.ty.abiAlignment(target)) { return memory; } } if (field.ty.isInt() or field.ty.isAnyFloat()) { return direct; } return classifyType(field.ty, target); }, .Int, .Enum, .ErrorSet, .Vector => { const int_bits = ty.intInfo(target).bits; if (int_bits <= 64) return direct; if (int_bits > 64 and int_bits <= 128) return .{ .direct, .direct }; return memory; }, .Float => { const float_bits = ty.floatBits(target); if (float_bits <= 64) return direct; if (float_bits > 64 and float_bits <= 128) return .{ .direct, .direct }; return memory; }, .Bool => return direct, .Array => return memory, .ErrorUnion => { const has_tag = ty.errorUnionSet().hasRuntimeBitsIgnoreComptime(); const has_pl = ty.errorUnionPayload().hasRuntimeBitsIgnoreComptime(); if (!has_pl) return direct; if (!has_tag) { return classifyType(ty.errorUnionPayload(), target); } return memory; }, .Optional => { if (ty.isPtrLikeOptional()) return direct; var buf: Type.Payload.ElemType = undefined; const pl_has_bits = ty.optionalChild(&buf).hasRuntimeBitsIgnoreComptime(); if (!pl_has_bits) return direct; return memory; }, .Pointer => { // Slices act like struct and will be passed by reference if (ty.isSlice()) return memory; return direct; }, .Union => { const layout = ty.unionGetLayout(target); if (layout.payload_size == 0 and layout.tag_size != 0) { return classifyType(ty.unionTagType().?, target); } if (ty.unionFields().count() > 1) return memory; return classifyType(ty.unionFields().values()[0].ty, target); }, .AnyFrame, .Frame => return direct, .NoReturn, .Void, .Type, .ComptimeFloat, .ComptimeInt, .Undefined, .Null, .BoundFn, .Fn, .Opaque, .EnumLiteral, => unreachable, } } /// Returns the scalar type a given type can represent. /// Asserts given type can be represented as scalar, such as /// a struct with a single scalar field. pub fn scalarType(ty: Type, target: std.Target) Type { switch (ty.zigTypeTag()) { .Struct => { std.debug.assert(ty.structFieldCount() == 1); return scalarType(ty.structFieldType(0), target); }, .Union => { const layout = ty.unionGetLayout(target); if (layout.payload_size == 0 and layout.tag_size != 0) { return scalarType(ty.unionTagType().?, target); } std.debug.assert(ty.unionFields().count() == 1); return scalarType(ty.unionFields().values()[0].ty, target); }, else => return ty, } }
src/arch/wasm/abi.zig
const std = @import("std"); const mem = std.mem; const Allocator = mem.Allocator; const ArrayList = std.ArrayList; const HashMap = std.HashMap; fn trimStart(slice: []const u8, ch: u8) []const u8 { var i: usize = 0; for (slice) |b| { if (b != '-') break; i += 1; } return slice[i..]; } fn argInAllowedSet(maybe_set: ?[]const []const u8, arg: []const u8) bool { if (maybe_set) |set| { for (set) |possible| { if (mem.eql(u8, arg, possible)) { return true; } } return false; } else { return true; } } // modifies the current argument index during iteration fn readFlagArguments(allocator: &Allocator, args: []const []const u8, maybe_required: ?usize, allowed_set: ?[]const []const u8, index: &usize) !FlagArg { if (maybe_required) |required| switch (required) { 0 => return FlagArg { .None = undefined }, // TODO: Required to force non-tag but value? 1 => { if (*index + 1 >= args.len) { return error.MissingFlagArguments; } *index += 1; const arg = args[*index]; if (!argInAllowedSet(allowed_set, arg)) { return error.ArgumentNotInAllowedSet; } return FlagArg { .Single = arg }; }, else => |needed| { var extra = ArrayList([]const u8).init(allocator); errdefer extra.deinit(); var j: usize = 0; while (j < needed) : (j += 1) { if (*index + 1 >= args.len) { return error.MissingFlagArguments; } *index += 1; const arg = args[*index]; if (!argInAllowedSet(allowed_set, arg)) { return error.ArgumentNotInAllowedSet; } try extra.append(arg); } return FlagArg { .Many = extra }; }, } else { // collect all remaining arguments var extra = ArrayList([]const u8).init(allocator); errdefer extra.deinit(); while (*index < args.len) : (*index += 1) { const arg = args[*index]; if (!argInAllowedSet(allowed_set, arg)) { return error.ArgumentNotInAllowedSet; } try extra.append(arg); } return FlagArg { .Many = extra }; } } // 32-bit FNV-1a fn hash_str(str: []const u8) u32 { var hash: u32 = 2166136261; for (str) |b| { hash = hash ^ b; hash = hash *% 16777619; } return hash; } fn eql_str(a: []const u8, b: []const u8) bool { return mem.eql(u8, a, b); } const HashMapFlags = HashMap([]const u8, FlagArg, hash_str, eql_str); // A store for querying found flags and positional arguments. pub const Args = struct { flags: HashMapFlags, positionals: ArrayList([]const u8), pub fn parse(allocator: &Allocator, comptime spec: []const Flag, args: []const []const u8) !Args { var parsed = Args { .flags = HashMapFlags.init(allocator), .positionals = ArrayList([]const u8).init(allocator), }; var i: usize = 0; next: while (i < args.len) : (i += 1) { const arg = args[i]; if (arg.len != 0 and arg[0] == '-') { // TODO: struct/hashmap lookup would be nice here. for (spec) |flag| { if (mem.eql(u8, arg, flag.name)) { const flag_name_trimmed = trimStart(flag.name, '-'); const flag_args = readFlagArguments(allocator, args, flag.required, flag.allowed_set, &i) catch |err| { switch (err) { error.ArgumentNotInAllowedSet => { std.debug.warn("argument is invalid for flag: {}\n", arg); std.debug.warn("allowed options are "); for (??flag.allowed_set) |possible| { std.debug.warn("'{}' ", possible); } std.debug.warn("\n"); }, error.MissingFlagArguments => { std.debug.warn("missing argument for flag: {}\n", arg); }, else => {}, } return err; }; _ = try parsed.flags.put(flag_name_trimmed, flag_args); continue :next; } } // TODO: Better errors with context, just store a string with the error. std.debug.warn("could not match flag: {}\n", arg); return error.UnknownFlag; } else { try parsed.positionals.append(arg); } } return parsed; } pub fn deinit(self: &Args) void { self.flags.deinit(); self.positionals.deinit(); } // e.g. --help pub fn present(self: &Args, name: []const u8) bool { return self.flags.contains(name); } // e.g. --name value pub fn single(self: &Args, name: []const u8) ?[]const u8 { // TODO: Can we enforce these accesses at compile-time, need to move to a struct instead // of a hash-map in that case. Assume the user has handled the required options according // to the given spec. if (self.flags.get(name)) |entry| { switch (entry.value) { FlagArg.Single => |inner| { return inner; }, else => @panic("attempted to retrieve flag with wrong type"), } } else { return null; } } // e.g. --names value1 value2 value3 pub fn many(self: &Args, name: []const u8) ?[]const []const u8 { if (self.flags.get(name)) |entry| { switch (entry.value) { FlagArg.Many => |inner| { return inner.toSliceConst(); }, else => @panic("attempted to retrieve flag with wrong type"), } } else { return null; } } }; // Arguments for a flag. e.g. --command arg1 arg2. const FlagArg = union(enum) { None, Single: []const u8, Many: ArrayList([]const u8), }; // Specification for how a flag should be parsed. pub const Flag = struct { name: []const u8, required: ?usize, allowed_set: ?[]const []const u8, pub fn Bool(comptime name: []const u8) Flag { return ArgN(name, 0); } pub fn Arg1(comptime name: []const u8) Flag { return ArgN(name, 1); } pub fn ArgN(comptime name: []const u8, comptime n: ?usize) Flag { return Flag { .name = name, .required = n, .allowed_set = null, }; } pub fn Option(comptime name: []const u8, comptime set: []const []const u8) Flag { return Flag { .name = name, .required = 1, .allowed_set = set, }; } }; test "example" { const spec1 = comptime []const Flag { Flag.Bool("--help"), Flag.Bool("--init"), Flag.Arg1("--build-file"), Flag.Arg1("--cache-dir"), Flag.Bool("--verbose"), Flag.Arg1("--prefix"), Flag.Arg1("--build-file"), Flag.Arg1("--cache-dir"), Flag.Arg1("--object"), Flag.Option("--color", []const []const u8 { "on", "off", "auto" }), Flag.Bool("--verbose-tokenize"), Flag.Bool("--verbose-ast"), Flag.Bool("--verbose-link"), Flag.Bool("--verbose-ir"), Flag.Bool("--verbose-llvm-ir"), Flag.Bool("--verbose-cimport"), }; const cliargs = []const []const u8 { "zig", "build", "--help", "value", "--init", "--object", "obj1", "--object", "obj2", "pos1", "pos2", "pos3", "pos4", "--object", "obj3", "obj4", }; var args = try Args.parse(std.debug.global_allocator, spec1, cliargs); std.debug.warn("help: {}\n", args.present("help")); std.debug.warn("init: {}\n", args.present("init")); std.debug.warn("init2: {}\n", args.present("init2")); // Need ability to specify merging flags into a list or keeping single for 1+ arguments. We // currently overwrite and take the last. std.debug.warn("object: {}\n", args.single("object")); }
src/arg.zig
const builtin = @import("builtin"); const std = @import("std"); const dwarf = std.dwarf; const platform = @import("../platform.zig"); const out = platform.out; const in = platform.in; pub const SERIAL_COM1: u16 = 0x3F8; var port: u16 = undefined; fn configureBaudRate(com: u16, divisor: u16) void { // Enable DLAB // Expect the highest 8 bits on the data port // then the lowest 8 bits will follow. out(com + 3, @as(u8, 0x80)); out(com, (divisor >> 8)); out(com, divisor); } fn configureLine(com: u16) void { out(com + 3, @as(u8, 0x03)); } fn configureBuffers(com: u16) void { out(com + 2, @as(u8, 0xC7)); } fn selfTest(com: u16) void { out(com + 4, @as(u8, 0x1E)); // Loopback out(com, @as(u8, 0xAE)); if (in(u8, com) != 0xAE) { platform.hang(); // Nothing to do here. } out(com + 4, @as(u8, 0x0F)); // Normal operation mode. } pub fn initialize(com: u16, divisor: u16) void { // No interrupts out(com + 1, @as(u8, 0x00)); configureBaudRate(com, divisor); configureLine(com); configureBuffers(com); out(com + 3, @as(u8, 0x03)); port = com; } fn is_transmit_empty() bool { return (in(u8, port + 5) & 0x20) != 0; } pub fn write(c: u8) void { while (!is_transmit_empty()) {} out(port, c); } pub fn writeText(s: []const u8) void { for (s) |c| { write(c); } } pub fn printf(comptime format: []const u8, args: anytype) void { var buf: [4096]u8 = undefined; writeText(std.fmt.bufPrint(buf[0..], format, args) catch unreachable); } fn has_received() bool { return (in(u8, port + 5) & 1) != 0; } pub fn read() u8 { while (!has_received()) {} return in(u8, port); } fn hang() noreturn { while (true) {} } var kernel_panic_allocator_bytes: [100 * 1024]u8 = undefined; var kernel_panic_allocator_state = std.heap.FixedBufferAllocator.init(kernel_panic_allocator_bytes[0..]); const kernel_panic_allocator = &kernel_panic_allocator_state.allocator; extern var __debug_info_start: u8; extern var __debug_info_end: u8; extern var __debug_abbrev_start: u8; extern var __debug_abbrev_end: u8; extern var __debug_str_start: u8; extern var __debug_str_end: u8; extern var __debug_line_start: u8; extern var __debug_line_end: u8; extern var __debug_ranges_start: u8; extern var __debug_ranges_end: u8; fn dwarfSectionFromSymbolAbs(start: *u8, end: *u8) dwarf.DwarfInfo.Section { return dwarf.DwarfInfo.Section{ .offset = 0, .size = @ptrToInt(end) - @ptrToInt(start), }; } fn dwarfSectionFromSymbol(start: *u8, end: *u8) []const u8 { return @ptrCast([*]u8, start)[0 .. (@ptrToInt(end) - @ptrToInt(start)) / @sizeOf(u8)]; } fn getSelfDebugInfo() !*dwarf.DwarfInfo { const S = struct { var have_self_debug_info = false; var self_debug_info: dwarf.DwarfInfo = undefined; }; if (S.have_self_debug_info) return &S.self_debug_info; S.self_debug_info = dwarf.DwarfInfo{ .endian = builtin.Endian.Little, .debug_info = dwarfSectionFromSymbol(&__debug_info_start, &__debug_info_end), .debug_abbrev = dwarfSectionFromSymbol(&__debug_abbrev_start, &__debug_abbrev_end), .debug_str = dwarfSectionFromSymbol(&__debug_str_start, &__debug_str_end), .debug_line = dwarfSectionFromSymbol(&__debug_line_start, &__debug_line_end), .debug_ranges = dwarfSectionFromSymbol(&__debug_ranges_start, &__debug_ranges_end), }; try dwarf.openDwarfDebugInfo(&S.self_debug_info, kernel_panic_allocator); return &S.self_debug_info; } pub fn ppanic(comptime format: []const u8, args: anytype) noreturn { var buf: [4096]u8 = undefined; panic(std.fmt.bufPrint(buf[0..], format, args) catch unreachable, null); } pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn { writeText("\n!!!!!!!!!!!!! KERNEL PANIC !!!!!!!!!!!!!!!\n"); writeText(msg); writeText("\n"); hang(); } fn printLineFromFile(_: anytype, line_info: dwarf.LineInfo) anyerror!void { writeText("TODO: print line from file\n"); }
src/kernel/debug/serial.zig
const std = @import("std"); const DiscordLogger = @import("./discord_logger/discord_logger.zig").DiscordLogger; const TwitchLogger = @import("./twitch_logger/twitch_logger.zig").TwitchLogger; // Set the log level to warning pub const log_level: std.log.Level = .warn; pub var discord: ?DiscordLogger = null; const discord_channel_id = "757722210742829059"; pub var twitch: ?TwitchLogger = null; const twitch_channel = "kristoff_it"; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); // Discord { const auth = std.os.getenv("DISCORD_TOKEN") orelse @panic("missing discord auth"); discord = DiscordLogger.init(auth, &gpa.allocator); } // Twitch { const auth = std.os.getenv("TWITCH_OAUTH") orelse @panic("missing twitch auth"); const nick = "kristoff_it"; twitch = TwitchLogger.init(auth, nick, &gpa.allocator); } std.log.warn("Shields at 80% captain!", .{}); } // Define root.log to override the std implementation pub fn log( comptime level: std.log.Level, comptime scope: @TypeOf(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { // Ignore all non-critical logging from sources other than // .my_project, .nice_library and .default const scope_prefix = "(" ++ switch (scope) { .my_project, .nice_library, .default => @tagName(scope), else => if (@enumToInt(level) <= @enumToInt(std.log.Level.crit)) @tagName(scope) else return, } ++ "): "; const prefix = "[" ++ @tagName(level) ++ "] " ++ scope_prefix; // Print the message to stderr, silently ignoring any errors const held = std.debug.getStderrMutex().acquire(); defer held.release(); const stderr = std.io.getStdErr().writer(); nosuspend stderr.print(prefix ++ format ++ "\n", args) catch return; (discord orelse return).sendMessage(discord_channel_id, prefix ++ format, args) catch return; (twitch orelse return).sendMessage(twitch_channel, prefix ++ format, args) catch return; } // pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace) noreturn { // std.debug.print("{}\n", .{msg}); // twitch.?.sendSimpleMessage(twitch_channel, msg) catch unreachable; // discord.?.sendSimpleMessage(discord_channel_id, msg) catch unreachable; // @breakpoint(); // unreachable; // }
src/main.zig
const std = @import("std"); const pkmn = @import("pkmn"); const Timer = std.time.Timer; pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); var fuzz = false; const args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); if (args.len < 3 or args.len > 5) usageAndExit(args[0], fuzz); const gen = std.fmt.parseUnsigned(u8, args[1], 10) catch errorAndExit("gen", args[1], args[0], fuzz); if (gen < 1 or gen > 8) errorAndExit("gen", args[1], args[0], fuzz); var battles: ?usize = null; var duration: ?usize = null; if (args[2].len > 1 and std.ascii.isAlpha(args[2][args[2].len - 1])) { fuzz = true; const last = args[2].len - 1; const mod: usize = switch (args[2][last]) { 's' => 1, 'm' => std.time.s_per_min, 'h' => std.time.s_per_hour, 'd' => std.time.s_per_day, else => errorAndExit("duration", args[2], args[0], fuzz), }; duration = mod * (std.fmt.parseUnsigned(usize, args[2][0..last], 10) catch errorAndExit("duration", args[2], args[0], fuzz)) * std.time.ns_per_s; } else { battles = std.fmt.parseUnsigned(usize, args[2], 10) catch errorAndExit("battles", args[2], args[0], fuzz); if (battles.? == 0) errorAndExit("battles", args[2], args[0], fuzz); } const seed = if (args.len > 3) std.fmt.parseUnsigned(u64, args[3], 10) catch errorAndExit("seed", args[3], args[0], fuzz) else seed: { var secret: [std.rand.DefaultCsprng.secret_seed_length]u8 = undefined; std.crypto.random.bytes(&secret); var csprng = std.rand.DefaultCsprng.init(secret); const random = csprng.random(); break :seed random.int(usize); }; const playouts = if (args.len == 5) std.fmt.parseUnsigned(usize, args[4], 10) catch errorAndExit("playouts", args[4], args[0], fuzz) else null; try benchmark(gen, seed, battles, playouts, duration); } pub fn benchmark(gen: u8, seed: u64, battles: ?usize, playouts: ?usize, duration: ?usize) !void { std.debug.assert(gen >= 1 and gen <= 8); var random = pkmn.PSRNG.init(seed); var options: [pkmn.OPTIONS_SIZE]pkmn.Choice = undefined; var time: u64 = 0; var turns: usize = 0; var elapsed = try Timer.start(); var out = std.io.getStdOut().writer(); var i: usize = 0; var n = battles orelse std.math.maxInt(usize); while (i < n and (if (duration) |d| elapsed.read() < d else true)) : (i += 1) { if (duration != null) try out.print("{d}: {d}\n", .{ i, random.src.seed }); var original = switch (gen) { 1 => pkmn.gen1.helpers.Battle.random(&random, duration == null), else => unreachable, }; var j: usize = 0; var m = playouts orelse 1; while (j < m and (if (duration) |d| elapsed.read() < d else true)) : (j += 1) { var battle = original; var c1 = pkmn.Choice{}; var c2 = pkmn.Choice{}; var p1 = pkmn.PSRNG.init(random.newSeed()); var p2 = pkmn.PSRNG.init(random.newSeed()); var timer = try Timer.start(); var result = try battle.update(c1, c2, null); while (result.type == .None) : (result = try battle.update(c1, c2, null)) { c1 = options[p1.range(u8, 0, battle.choices(.P1, result.p1, &options))]; c2 = options[p2.range(u8, 0, battle.choices(.P2, result.p2, &options))]; } time += timer.read(); turns += battle.turn; } } if (battles != null) try out.print("{d},{d},{d}\n", .{ time, turns, random.src.seed }); } fn errorAndExit(msg: []const u8, arg: []const u8, cmd: []const u8, fuzz: bool) noreturn { const err = std.io.getStdErr().writer(); err.print("Invalid {s}: {s}\n", .{ msg, arg }) catch {}; usageAndExit(cmd, fuzz); } fn usageAndExit(cmd: []const u8, fuzz: bool) noreturn { const err = std.io.getStdErr().writer(); if (fuzz) { err.print("Usage: {s} <GEN> <DURATION> <SEED?>\n", .{cmd}) catch {}; } else { err.print("Usage: {s} <GEN> <BATTLES> <SEED?> <PLAYOUTS?>\n", .{cmd}) catch {}; } std.process.exit(1); }
src/test/benchmark.zig
const std = @import("std"); const fs = std.fs; const testing = std.testing; /// Reads contents from path, relative to cwd, and store in target_buf pub fn readFileRaw(path: []const u8, target_buf: []u8) !usize { return try readFileRawRel(fs.cwd(), path, target_buf); } /// Reads contents from path, relative to dir, and store in target_buf pub fn readFileRawRel(dir: std.fs.Dir, path: []const u8, target_buf: []u8) !usize { var file = try dir.openFile(path, .{ .read = true }); defer file.close(); return try file.readAll(target_buf[0..]); } test "readFileRaw" { var buf = try std.BoundedArray(u8, 1024 * 1024).init(0); try testing.expect(buf.slice().len == 0); try buf.resize(try readFileRaw("testdata/01-warnme/01-warnme-status-ok.pi", buf.buffer[0..])); try testing.expect(buf.slice().len > 0); } /// Reads contents from path, relative to cwd, and store in target_buf pub fn readFile(comptime S: usize, path: []const u8, target_buf: *std.BoundedArray(u8, S)) !void { return try readFileRel(S, fs.cwd(), path, target_buf); } /// Reads contents from path, relative to dir, and store in target_buf pub fn readFileRel(comptime S: usize, dir: std.fs.Dir, path: []const u8, target_buf: *std.BoundedArray(u8, S)) !void { var file = try dir.openFile(path, .{ .read = true }); defer file.close(); const size = try file.getEndPos(); try target_buf.resize(std.math.min(size, target_buf.capacity())); _ = try file.readAll(target_buf.slice()[0..]); } // test "readfile rel" { // std.debug.print("\nwoop\n", .{}); // var buf = utils.initBoundedArray(u8, 1024 * 1024); // var dir = try std.fs.cwd().openDir("src", .{}); // std.debug.print("dir: {s}\n", .{dir}); // try readFileRel(buf.buffer.len, dir, "../VERSION", &buf); // std.debug.print("Contents: {s}\n", .{buf.slice()}); // } test "realpath - got issues" { var scrap: [2048]u8 = undefined; // std.fs.realpath // These two examples provides the same result... (ZIGBUG?) { var dir = try std.fs.cwd().openDir("src", .{}); var realpath = try dir.realpath("..", scrap[0..]); std.debug.print("realpath: {s}\n", .{realpath}); } { var dir = std.fs.cwd(); var realpath = try dir.realpath("..", scrap[0..]); std.debug.print("realpath: {s}\n", .{realpath}); } } /// Needed as there are some quirks with folder-resolution, at least for Windows. /// TODO: investigate and file bug/PR pub fn getRealPath(base: []const u8, sub: []const u8, scrap: []u8) ![]u8 { // Blank base == cwd var tmp_result = if (base.len > 0) try std.fmt.bufPrint(scrap[0..], "{s}/{s}", .{ base, sub }) else try std.fmt.bufPrint(scrap[0..], "./{s}", .{sub}); var result = try std.fs.cwd().realpath(tmp_result, scrap[0..]); return result; } // test "getRealPath" { // var base_path = "src"; // var sub_path = "../VERSION"; // var scrap: [2048]u8 = undefined; // var result = try getRealPath(base_path, sub_path, scrap[0..]); // std.debug.print("result: {s}\n", .{result}); // } test "readFile" { var buf = try std.BoundedArray(u8, 1024 * 1024).init(0); try testing.expect(buf.slice().len == 0); try readFile(buf.buffer.len, "testdata/01-warnme/01-warnme-status-ok.pi", &buf); try testing.expect(buf.slice().len > 0); } /// Autosense buffer for type of line ending: Check buf for \r\n, and if found: return \r\n, otherwise \n pub fn getLineEnding(buf: []const u8) []const u8 { if (std.mem.indexOf(u8, buf, "\r\n") != null) return "\r\n"; return "\n"; } /// Returns the slice which is without the last path-segment pub fn getParent(fileOrDir: []const u8) []const u8 { std.debug.assert(fileOrDir.len > 0); var i: usize = fileOrDir.len - 2; while (i > 0) : (i -= 1) { if (fileOrDir[i] == '/' or fileOrDir[i] == '\\') { break; } } return fileOrDir[0..i]; } test "getParent" { try testing.expectEqualStrings("", getParent("myfile")); try testing.expectEqualStrings("folder", getParent("folder/file")); }
src/io.zig
const std = @import("std"); const stdx = @import("../stdx.zig"); const t = stdx.testing; const vec2 = Vec2.init; pub const geom = @import("geom.zig"); usingnamespace @import("matrix.zig"); pub fn Point2(comptime T: type) type { return struct { x: T, y: T, pub fn init(x: T, y: T) @This() { return .{ .x = x, .y = y, }; } }; } pub const Vec3 = struct { x: f32, y: f32, z: f32, pub fn init(x: f32, y: f32, z: f32) Vec3 { return .{ .x = x, .y = y, .z = z, }; } /// Uses rotors to rotate the 3d vector around the y axis. pub fn rotateY(self: Vec3, rad: f32) Vec3 { const half_rad = rad * 0.5; const a = Vec3.init(1, 0, 0); const b = Vec3.init(std.math.cos(half_rad), 0, std.math.sin(half_rad)); const ra_dot = a.mul(self.dot(a) * -2); const ra = self.add(ra_dot); const rb_dot = b.mul(ra.dot(b) * -2); const rba = ra.add(rb_dot); return rba; } /// Rotates the vector along an arbitrary axis. Assumes axis vector is normalized. pub fn rotateAxis(self: Vec3, axis: Vec3, rad: f32) Vec3 { const v_para = axis.mul(self.dot(axis)); const v_perp = self.add(v_para.mul(-1)); const v_perp_term = v_perp.mul(std.math.cos(rad)); const axv_term = axis.cross(self).mul(std.math.sin(rad)); return Vec3.init( v_para.x + v_perp_term.x + axv_term.x, v_para.y + v_perp_term.y + axv_term.y, v_para.z + v_perp_term.z + axv_term.z, ); } pub fn dot(self: Vec3, v: Vec3) f32 { return self.x * v.x + self.y * v.y + self.z * v.z; } pub fn cross(self: Vec3, v: Vec3) Vec3 { const x = self.y * v.z - self.z * v.y; const y = self.z * v.x - self.x * v.z; const z = self.x * v.y - self.y * v.x; return Vec3.init(x, y, z); } pub fn normalize(self: Vec3) Vec3 { const len = self.length(); return Vec3.init(self.x / len, self.y / len, self.z / len); } /// Component multiplication. pub fn mul(self: Vec3, s: f32) Vec3 { return Vec3.init(self.x * s, self.y * s, self.z * s); } /// Component addition. pub fn add(self: Vec3, v: Vec3) Vec3 { return Vec3.init(self.x + v.x, self.y + v.y, self.z + v.z); } pub fn length(self: Vec3) f32 { return std.math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z); } }; test "Vec3.rotateY" { const pif = @as(f32, pi); // On xz plane. var v = Vec3.init(1, 0, 0); try eqApproxVec3(v.rotateY(0), Vec3.init(1, 0, 0)); try eqApproxVec3(v.rotateY(pif*0.5), Vec3.init(0, 0, 1)); try eqApproxVec3(v.rotateY(pif), Vec3.init(-1, 0, 0)); try eqApproxVec3(v.rotateY(pif*1.5), Vec3.init(0, 0, -1)); // Tilted into y. v = Vec3.init(1, 1, 0); try eqApproxVec3(v.rotateY(0), Vec3.init(1, 1, 0)); try eqApproxVec3(v.rotateY(pif*0.5), Vec3.init(0, 1, 1)); try eqApproxVec3(v.rotateY(pif), Vec3.init(-1, 1, 0)); try eqApproxVec3(v.rotateY(pif*1.5), Vec3.init(0, 1, -1)); } test "Vec3.rotateAxis" { const pif = @as(f32, pi); // Rotate from +y toward +z var v = Vec3.init(0, 1, 0); try eqApproxVec3(v.rotateAxis(Vec3.init(1, 0, 0), 0), Vec3.init(0, 1, 0)); try eqApproxVec3(v.rotateAxis(Vec3.init(1, 0, 0), pif*0.5), Vec3.init(0, 0, 1)); try eqApproxVec3(v.rotateAxis(Vec3.init(1, 0, 0), pif), Vec3.init(0, -1, 0)); try eqApproxVec3(v.rotateAxis(Vec3.init(1, 0, 0), pif*1.5), Vec3.init(0, 0, -1)); } pub fn eqApproxVec2(act: Vec2, exp: Vec2) !void { try t.eqApproxEps(act.x, exp.x); try t.eqApproxEps(act.y, exp.y); } pub fn eqApproxVec3(act: Vec3, exp: Vec3) !void { try t.eqApprox(act.x, exp.x, 1e-4); try t.eqApprox(act.y, exp.y, 1e-4); try t.eqApprox(act.z, exp.z, 1e-4); } pub fn eqApproxVec4(act: Vec4, exp: Vec4) !void { try t.eqApprox(act.x, exp.x, 1e-4); try t.eqApprox(act.y, exp.y, 1e-4); try t.eqApprox(act.z, exp.z, 1e-4); try t.eqApprox(act.w, exp.w, 1e-4); } pub const Vec4 = struct { x: f32, y: f32, z: f32, w: f32, pub fn init(x: f32, y: f32, z: f32, w: f32) Vec4 { return .{ .x = x, .y = y, .z = z, .w = w }; } /// Component division. pub fn div(self: Vec4, s: f32) Vec4 { return Vec4.init(self.x / s, self.y / s, self.z / s, self.w / s); } }; pub const Vec2 = struct { const Self = @This(); x: f32, y: f32, pub fn init(x: f32, y: f32) Self { return .{ .x = x, .y = y }; } pub fn initTo(from: Vec2, to: Vec2) Self { return .{ .x = to.x - from.x, .y = to.y - from.y }; } pub fn squareLength(self: Self) f32 { return self.x * self.x + self.y * self.y; } pub fn length(self: Self) f32 { return std.math.sqrt(self.x * self.x + self.y * self.y); } pub fn normalize(self: Self) Vec2 { const len = self.length(); return Self.init(self.x / len, self.y / len); } pub fn toLength(self: Self, len: f32) Vec2 { const factor = len / self.length(); return Self.init(self.x * factor, self.y * factor); } pub fn normalizeWith(self: Self, factor: f32) Vec2 { return Self.init(self.x / factor, self.y / factor); } pub fn neg(self: Self) Vec2 { return Self.init(-self.x, -self.y); } /// Cross product. /// Useful for determining the z direction. pub fn cross(self: Self, v: Vec2) f32 { return self.x * v.y - self.y * v.x; } /// Component addition. pub fn add(self: Self, v: Vec2) Vec2 { return vec2(self.x + v.x, self.y + v.y); } /// Dot product. pub fn dot(self: Self, v: Vec2) f32 { return self.x * v.x + self.y * v.y; } /// Component multiplication. pub fn mul(self: Self, s: f32) Vec2 { return Self.init(self.x * s, self.y * s); } /// Component division. pub fn div(self: Self, s: f32) Vec2 { return Self.init(self.x / s, self.y / s); } }; pub const Counter = struct { c: usize, pub fn init(start_count: usize) Counter { return .{ .c = start_count, }; } pub fn inc(self: *@This()) usize { self.c += 1; return self.c; } pub fn get(self: *const @This()) usize { return self.c; } }; pub const pi = std.math.pi; pub const pi_2 = std.math.pi * 2.0; pub const pi_half = std.math.pi * 0.5; pub fn degToRad(deg: f32) f32 { return deg * pi_2 / 360; }
stdx/math/math.zig
const MachO = @This(); const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const fs = std.fs; const log = std.log.scoped(.link); const macho = std.macho; const math = std.math; const mem = std.mem; const Module = @import("../Module.zig"); const link = @import("../link.zig"); const File = link.File; pub const base_tag: File.Tag = File.Tag.macho; base: File, /// Stored in native-endian format, depending on target endianness needs to be bswapped on read/write. /// Same order as in the file. segment_cmds: std.ArrayListUnmanaged(macho.segment_command_64) = std.ArrayListUnmanaged(macho.segment_command_64){}, /// Stored in native-endian format, depending on target endianness needs to be bswapped on read/write. /// Same order as in the file. sections: std.ArrayListUnmanaged(macho.section_64) = std.ArrayListUnmanaged(macho.section_64){}, entry_addr: ?u64 = null, error_flags: File.ErrorFlags = File.ErrorFlags{}, pub const TextBlock = struct { pub const empty = TextBlock{}; }; pub const SrcFn = struct { pub const empty = SrcFn{}; }; pub fn openPath(allocator: *Allocator, dir: fs.Dir, sub_path: []const u8, options: link.Options) !*File { assert(options.object_format == .macho); const file = try dir.createFile(sub_path, .{ .truncate = false, .read = true, .mode = link.determineMode(options) }); errdefer file.close(); var macho_file = try allocator.create(MachO); errdefer allocator.destroy(macho_file); macho_file.* = openFile(allocator, file, options) catch |err| switch (err) { error.IncrFailed => try createFile(allocator, file, options), else => |e| return e, }; return &macho_file.base; } /// Returns error.IncrFailed if incremental update could not be performed. fn openFile(allocator: *Allocator, file: fs.File, options: link.Options) !MachO { switch (options.output_mode) { .Exe => {}, .Obj => {}, .Lib => return error.IncrFailed, } var self: MachO = .{ .base = .{ .file = file, .tag = .macho, .options = options, .allocator = allocator, }, }; errdefer self.deinit(); // TODO implement reading the macho file return error.IncrFailed; //try self.populateMissingMetadata(); //return self; } /// Truncates the existing file contents and overwrites the contents. /// Returns an error if `file` is not already open with +read +write +seek abilities. fn createFile(allocator: *Allocator, file: fs.File, options: link.Options) !MachO { switch (options.output_mode) { .Exe => {}, .Obj => {}, .Lib => return error.TODOImplementWritingLibFiles, } var self: MachO = .{ .base = .{ .file = file, .tag = .macho, .options = options, .allocator = allocator, }, }; errdefer self.deinit(); if (options.output_mode == .Exe) { // The first segment command for executables is always a __PAGEZERO segment. try self.segment_cmds.append(allocator, .{ .cmd = macho.LC_SEGMENT_64, .cmdsize = @sizeOf(macho.segment_command_64), .segname = self.makeString("__PAGEZERO"), .vmaddr = 0, .vmsize = 0, .fileoff = 0, .filesize = 0, .maxprot = 0, .initprot = 0, .nsects = 0, .flags = 0, }); } return self; } fn makeString(self: *MachO, comptime bytes: []const u8) [16]u8 { var buf: [16]u8 = undefined; if (bytes.len > buf.len) @compileError("MachO segment/section name too long"); mem.copy(u8, buf[0..], bytes); return buf; } fn writeMachOHeader(self: *MachO) !void { var hdr: macho.mach_header_64 = undefined; hdr.magic = macho.MH_MAGIC_64; const CpuInfo = struct { cpu_type: macho.cpu_type_t, cpu_subtype: macho.cpu_subtype_t, }; const cpu_info: CpuInfo = switch (self.base.options.target.cpu.arch) { .aarch64 => .{ .cpu_type = macho.CPU_TYPE_ARM64, .cpu_subtype = macho.CPU_SUBTYPE_ARM_ALL, }, .x86_64 => .{ .cpu_type = macho.CPU_TYPE_X86_64, .cpu_subtype = macho.CPU_SUBTYPE_X86_64_ALL, }, else => return error.UnsupportedMachOArchitecture, }; hdr.cputype = cpu_info.cpu_type; hdr.cpusubtype = cpu_info.cpu_subtype; const filetype: u32 = switch (self.base.options.output_mode) { .Exe => macho.MH_EXECUTE, .Obj => macho.MH_OBJECT, .Lib => switch (self.base.options.link_mode) { .Static => return error.TODOStaticLibMachOType, .Dynamic => macho.MH_DYLIB, }, }; hdr.filetype = filetype; // TODO consider other commands const ncmds = try math.cast(u32, self.segment_cmds.items.len); hdr.ncmds = ncmds; hdr.sizeofcmds = ncmds * @sizeOf(macho.segment_command_64); // TODO should these be set to something else? hdr.flags = 0; hdr.reserved = 0; try self.base.file.?.pwriteAll(@ptrCast([*]const u8, &hdr)[0..@sizeOf(macho.mach_header_64)], 0); } pub fn flush(self: *MachO, module: *Module) !void { // TODO implement flush { const buf = try self.base.allocator.alloc(macho.segment_command_64, self.segment_cmds.items.len); defer self.base.allocator.free(buf); for (buf) |*seg, i| { seg.* = self.segment_cmds.items[i]; } try self.base.file.?.pwriteAll(mem.sliceAsBytes(buf), @sizeOf(macho.mach_header_64)); } if (self.entry_addr == null and self.base.options.output_mode == .Exe) { log.debug("flushing. no_entry_point_found = true\n", .{}); self.error_flags.no_entry_point_found = true; } else { log.debug("flushing. no_entry_point_found = false\n", .{}); self.error_flags.no_entry_point_found = false; try self.writeMachOHeader(); } } pub fn deinit(self: *MachO) void { self.segment_cmds.deinit(self.base.allocator); self.sections.deinit(self.base.allocator); } pub fn allocateDeclIndexes(self: *MachO, decl: *Module.Decl) !void {} pub fn updateDecl(self: *MachO, module: *Module, decl: *Module.Decl) !void {} pub fn updateDeclLineNumber(self: *MachO, module: *Module, decl: *const Module.Decl) !void {} pub fn updateDeclExports( self: *MachO, module: *Module, decl: *const Module.Decl, exports: []const *Module.Export, ) !void {} pub fn freeDecl(self: *MachO, decl: *Module.Decl) void {} pub fn getDeclVAddr(self: *MachO, decl: *const Module.Decl) u64 { @panic("TODO implement getDeclVAddr for MachO"); }
src-self-hosted/link/MachO.zig
const std = @import("std"); const Args = std.process.args; // mem pub const halloc = std.heap.page_allocator; pub const talloc = std.testing.allocator; // sort pub const sort = std.sort; pub fn i64LessThan(_: void, a: i64, b: i64) bool { return a < b; } pub fn i64GreaterThan(_: void, a: i64, b: i64) bool { return a > b; } pub fn usizeLessThan(_: void, a: usize, b: usize) bool { return a < b; } pub fn usizeGreaterThan(_: void, a: usize, b: usize) bool { return a > b; } // io pub const out = &std.io.getStdOut().writer(); pub const print = out.print; pub const inputfile = @embedFile("input.txt"); pub const test0file = @embedFile("test0.txt"); pub const test1file = @embedFile("test1.txt"); pub const test2file = @embedFile("test2.txt"); pub const test3file = @embedFile("test3.txt"); pub const test4file = @embedFile("test4.txt"); pub const test5file = @embedFile("test5.txt"); pub const test6file = @embedFile("test6.txt"); pub const test7file = @embedFile("test7.txt"); pub const test8file = @embedFile("test8.txt"); pub const test9file = @embedFile("test9.txt"); pub fn input() []const u8 { var args = Args(); _ = args.skip(); var res: []const u8 = inputfile; if (args.next(halloc)) |arg1| { halloc.free(arg1 catch unreachable); res = test1file; } return res; } // parsing pub const split = std.mem.split; pub const tokenize = std.mem.tokenize; pub const parseInt = std.fmt.parseInt; pub const parseUnsigned = std.fmt.parseUnsigned; // math pub const absCast = math.absCast; pub const math = std.math; pub const minInt = math.minInt; pub const maxInt = math.maxInt; // test pub const assert = std.testing.expect; pub const assertEq = std.testing.expectEqual; pub fn assertStrEq(exp: []const u8, act: []const u8) anyerror!void { if (!std.mem.eql(u8, exp, act)) { std.debug.print("expected, '{s}' but was '{s}'\n", .{ exp, act }); } try assert(std.mem.eql(u8, exp, act)); } pub fn DEBUG() i32 { const debuglevel = @import("std").process.getEnvVarOwned(halloc, "AoC_DEBUG") catch return 0; const i = parseInt(i32, debuglevel, 10) catch return 0; halloc.free(debuglevel); return i; } pub fn Ints(alloc: std.mem.Allocator, comptime T: type, inp: anytype) anyerror![]T { var ints = std.ArrayList(T).init(alloc); var it = std.mem.tokenize(u8, inp, ":, \n"); while (it.next()) |is| { if (is.len == 0) { break; } const i = std.fmt.parseInt(T, is, 10) catch { continue; }; try ints.append(i); } return ints.toOwnedSlice(); } pub fn BoundedInts(comptime T: type, b: anytype, inp: anytype) anyerror![]T { var n: T = 0; var num = false; for (inp) |ch| { if ('0' <= ch and ch <= '9') { num = true; n = n * 10 + @as(T, ch - '0'); } else if (num) { try b.append(n); n = 0; num = false; } } if (num) { try b.append(n); } return b.slice(); } pub fn BoundedSignedInts(comptime T: type, b: anytype, inp: anytype) anyerror![]T { var n: T = 0; var m: T = 1; var num = false; for (inp) |ch| { if (ch == '-') { m = -1; num = true; } else if ('0' <= ch and ch <= '9') { num = true; n = n * 10 + @as(T, ch - '0'); } else if (num) { try b.append(n * m); n = 0; m = 1; num = false; } else { m = 1; } } if (num) { try b.append(n * m); } return b.slice(); } pub fn splitToOwnedSlice(alloc: std.mem.Allocator, inp: []const u8, sep: []const u8) ![][]const u8 { var bits = std.ArrayList([]const u8).init(alloc); var it = std.mem.split(u8, inp, sep); while (it.next()) |bit| { if (bit.len == 0) { break; } try bits.append(bit); } return bits.toOwnedSlice(); } pub fn readLines(alloc: std.mem.Allocator, inp: anytype) [][]const u8 { var lines = std.ArrayList([]const u8).init(alloc); var lit = std.mem.split(u8, inp, "\n"); while (lit.next()) |line| { if (line.len == 0) { break; } lines.append(line) catch unreachable; } return lines.toOwnedSlice(); } pub fn readChunks(alloc: std.mem.Allocator, inp: anytype) [][]const u8 { var chunks = std.ArrayList([]const u8).init(alloc); var cit = std.mem.split(u8, inp, "\n\n"); while (cit.next()) |chunk| { if (chunk.len == 0) { break; } if (chunk[chunk.len - 1] == '\n') { chunks.append(chunk[0 .. chunk.len - 1]) catch unreachable; } else { chunks.append(chunk) catch unreachable; } } return chunks.toOwnedSlice(); } pub fn readChunkyObjects(alloc: std.mem.Allocator, inp: anytype, chunkSep: []const u8, recordSep: []const u8, fieldSep: []const u8) [](std.StringHashMap([]const u8)) { var report = std.ArrayList(std.StringHashMap([]const u8)).init(alloc); var cit = split(u8, inp, chunkSep); while (cit.next()) |chunk| { if (chunk.len == 0) { break; } var map = std.StringHashMap([]const u8).init(alloc); var fit = tokenize(u8, chunk, recordSep); while (fit.next()) |field| { if (field.len == 0) { break; } var kvit = split(u8, field, fieldSep); const k = kvit.next().?; const v = kvit.next().?; map.put(k, v) catch unreachable; } report.append(map) catch unreachable; } return report.toOwnedSlice(); } pub fn minc(m: anytype, k: anytype) void { if (m.*.get(k)) |v| { m.*.put(k, v + 1) catch {}; } else { m.*.put(k, 1) catch {}; } } pub fn stringLessThan(_: void, a: []const u8, b: []const u8) bool { var i: usize = 0; while (i < a.len and i < b.len and a[i] == b[i]) { i += 1; } if (a[i] == b[i]) { return a.len < b.len; } return a[i] < b[i]; } pub fn rotateLinesNonSymmetric(alloc: std.mem.Allocator, lines: [][]const u8) [][]u8 { const end = lines.len - 1; var tmp = alloc.alloc([]u8, lines[0].len) catch unreachable; var i: usize = 0; while (i < lines[0].len) { tmp[i] = alloc.alloc(u8, lines.len) catch unreachable; i += 1; } i = 0; while (i < lines[0].len) { var j: usize = 0; while (j < lines.len) { tmp[i][j] = lines[end - j][i]; j += 1; } i += 1; } return tmp; } pub fn rotateLines(lines: [][]u8) void { const l = lines.len; assertEq(l, lines[0].len) catch unreachable; var i: usize = 0; while (i < l) : (i += 1) { var j = i; while (j < l - i - 1) : (j += 1) { var tmp = lines[i][j]; lines[i][j] = lines[l - j - 1][i]; lines[l - j - 1][i] = lines[l - i - 1][l - j - 1]; lines[l - i - 1][l - j - 1] = lines[j][l - i - 1]; lines[j][l - i - 1] = tmp; } } } pub fn reverseLines(lines: [][]const u8) void { const end = lines.len - 1; var j: usize = 0; while (j < lines.len / 2) { var tmp = lines[j]; lines[j] = lines[end - j]; lines[end - j] = tmp; j += 1; } } pub fn countCharsInLines(lines: [][]const u8, findCh: u8) usize { var c: usize = 0; for (lines) |line| { for (line) |ch| { if (ch == findCh) { c += 1; } } } return c; } pub fn prettyLines(lines: [][]const u8) void { for (lines) |line| { std.debug.print("{}\n", .{line}); } } pub fn BENCH() bool { const is_bench = @import("std").process.getEnvVarOwned(halloc, "AoC_BENCH") catch return false; halloc.free(is_bench); return true; } pub fn benchme(inp: []const u8, call: fn (in: []const u8, bench: bool) anyerror!void) anyerror!void { var it: i128 = 0; const is_bench = BENCH(); var start = @import("std").time.nanoTimestamp(); var elapsed: i128 = 0; while (true) { try call(inp, is_bench); it += 1; elapsed = @import("std").time.nanoTimestamp() - start; if (!is_bench or elapsed > 1000000000) { break; } } if (is_bench) { try print("bench {} iterations in {}ns: {}ns\n", .{ it, elapsed, @divTrunc(elapsed, it) }); } } pub const ByteMap = struct { m: []const u8, w: usize, h: usize, alloc: std.mem.Allocator, pub fn init(alloc: std.mem.Allocator, inp: []const u8) !*ByteMap { var bm = try alloc.create(ByteMap); bm.m = inp; bm.alloc = alloc; var w: usize = 0; while (w < inp.len and inp[w] != '\n') : (w += 1) {} bm.w = w + 1; bm.h = inp.len / bm.w; // try print("{} x {} = {}\n", .{ bm.w, bm.h, inp.len }); return bm; } pub fn deinit(self: *ByteMap) void { self.alloc.destroy(self); } pub fn width(self: *ByteMap) usize { return self.w - 1; } pub fn height(self: *ByteMap) usize { return self.h; } pub fn size(self: *ByteMap) usize { return (self.w - 1) * self.h; } pub fn indexToXY(self: *ByteMap, i: usize) [2]usize { return [2]usize{ i % self.w, i / self.w }; } pub fn xyToIndex(self: *ByteMap, x: usize, y: usize) usize { return x + y * self.w; } pub fn contains(self: *ByteMap, i: usize) bool { return i >= 0 and (i % self.w) < (self.w - 1) and i < self.w * self.h; } pub fn containsXY(self: *ByteMap, x: usize, y: usize) bool { return x < self.w - 1 and y < self.h; } pub fn get(self: *ByteMap, i: usize) u8 { return self.m[i]; } pub fn getXY(self: *ByteMap, x: usize, y: usize) u8 { return self.m[x + y * self.w]; } pub fn set(self: *ByteMap, i: usize, v: u8) void { self.m[i] = v; } pub fn setXY(self: *ByteMap, x: usize, y: usize, v: u8) void { self.m[x + y * self.w] = v; } pub fn add(self: *ByteMap, i: usize, v: u8) void { self.m[i] += v; } pub fn addXY(self: *ByteMap, x: usize, y: usize, v: u8) void { self.m[x + y * self.w] += v; } pub fn visit(self: *ByteMap, call: fn (i: usize, v: u8) [2]u8) usize { var changes: usize = 0; var y: usize = 0; while (y < self.h) : (y += 1) { var x: usize = 0; while (x < self.h - 1) : (x += 1) { var i = x + y * self.w; var res = call(i, self.m[i]); if (res[1] != 0) { self.m[i] = res[0]; } } } return changes; } }; test "bytemap" { var bm = try ByteMap.init(talloc, "2199943210\n3987894921\n9856789892\n8767896789\n9899965678\n"); defer bm.deinit(); try assertEq(@as(usize, 10), bm.width()); try assertEq(@as(usize, 5), bm.height()); try assertEq(true, bm.containsXY(0, 0)); try assertEq(true, bm.contains(bm.xyToIndex(0, 0))); try assertEq(true, bm.containsXY(9, 0)); try assertEq(true, bm.contains(bm.xyToIndex(9, 0))); try assertEq(false, bm.containsXY(10, 0)); try assertEq(false, bm.contains(bm.xyToIndex(10, 0))); try assertEq(true, bm.containsXY(0, 4)); try assertEq(true, bm.contains(bm.xyToIndex(0, 4))); try assertEq(false, bm.containsXY(0, 5)); try assertEq(false, bm.contains(bm.xyToIndex(0, 5))); }
2021/05/aoc-lib.zig
const std = @import("std"); const readIntLittle = std.mem.readIntLittle; const writeIntLittle = std.mem.writeIntLittle; pub const Fe = struct { limbs: [5]u64, const MASK51: u64 = 0x7ffffffffffff; pub const zero = Fe{ .limbs = .{ 0, 0, 0, 0, 0 } }; pub const one = Fe{ .limbs = .{ 1, 0, 0, 0, 0 } }; pub const sqrtm1 = Fe{ .limbs = .{ 1718705420411056, 234908883556509, 2233514472574048, 2117202627021982, 765476049583133 } }; // sqrt(-1) pub const curve25519BasePoint = Fe{ .limbs = .{ 9, 0, 0, 0, 0 } }; pub const edwards25519d = Fe{ .limbs = .{ 929955233495203, 466365720129213, 1662059464998953, 2033849074728123, 1442794654840575 } }; // 37095705934669439343138083508754565189542113879843219016388785533085940283555 pub const edwards25519d2 = Fe{ .limbs = .{ 1859910466990425, 932731440258426, 1072319116312658, 1815898335770999, 633789495995903 } }; // 2d pub const edwards25519sqrtamd = Fe{ .limbs = .{ 278908739862762, 821645201101625, 8113234426968, 1777959178193151, 2118520810568447 } }; // 1/sqrt(a-d) pub const edwards25519eonemsqd = Fe{ .limbs = .{ 1136626929484150, 1998550399581263, 496427632559748, 118527312129759, 45110755273534 } }; // 1-d^2 pub const edwards25519sqdmone = Fe{ .limbs = .{ 1507062230895904, 1572317787530805, 683053064812840, 317374165784489, 1572899562415810 } }; // (d-1)^2 pub const edwards25519sqrtadm1 = Fe{ .limbs = .{ 2241493124984347, 425987919032274, 2207028919301688, 1220490630685848, 974799131293748 } }; pub inline fn isZero(fe: Fe) bool { var reduced = fe; reduced.reduce(); const limbs = reduced.limbs; return (limbs[0] | limbs[1] | limbs[2] | limbs[3] | limbs[4]) == 0; } pub inline fn equivalent(a: Fe, b: Fe) bool { return a.sub(b).isZero(); } pub fn fromBytes(s: [32]u8) Fe { var fe: Fe = undefined; fe.limbs[0] = readIntLittle(u64, s[0..8]) & MASK51; fe.limbs[1] = (readIntLittle(u64, s[6..14]) >> 3) & MASK51; fe.limbs[2] = (readIntLittle(u64, s[12..20]) >> 6) & MASK51; fe.limbs[3] = (readIntLittle(u64, s[19..27]) >> 1) & MASK51; fe.limbs[4] = (readIntLittle(u64, s[24..32]) >> 12) & MASK51; return fe; } pub fn toBytes(fe: Fe) [32]u8 { var reduced = fe; reduced.reduce(); var s: [32]u8 = undefined; writeIntLittle(u64, s[0..8], reduced.limbs[0] | (reduced.limbs[1] << 51)); writeIntLittle(u64, s[8..16], (reduced.limbs[1] >> 13) | (reduced.limbs[2] << 38)); writeIntLittle(u64, s[16..24], (reduced.limbs[2] >> 26) | (reduced.limbs[3] << 25)); writeIntLittle(u64, s[24..32], (reduced.limbs[3] >> 39) | (reduced.limbs[4] << 12)); return s; } pub fn rejectNonCanonical(s: [32]u8, comptime ignore_extra_bit: bool) !void { var c: u16 = (s[31] & 0x7f) ^ 0x7f; comptime var i = 30; inline while (i > 0) : (i -= 1) { c |= s[i] ^ 0xff; } c = (c -% 1) >> 8; const d = (@as(u16, 0xed - 1) -% @as(u16, s[0])) >> 8; const x = if (ignore_extra_bit) 0 else s[31] >> 7; if ((((c & d) | x) & 1) != 0) { return error.NonCanonical; } } fn reduce(fe: *Fe) void { comptime var i = 0; comptime var j = 0; const limbs = &fe.limbs; inline while (j < 2) : (j += 1) { i = 0; inline while (i < 4) : (i += 1) { limbs[i + 1] += limbs[i] >> 51; limbs[i] &= MASK51; } limbs[0] += 19 * (limbs[4] >> 51); limbs[4] &= MASK51; } limbs[0] += 19; i = 0; inline while (i < 4) : (i += 1) { limbs[i + 1] += limbs[i] >> 51; limbs[i] &= MASK51; } limbs[0] += 19 * (limbs[4] >> 51); limbs[4] &= MASK51; limbs[0] += 0x8000000000000 - 19; limbs[1] += 0x8000000000000 - 1; limbs[2] += 0x8000000000000 - 1; limbs[3] += 0x8000000000000 - 1; limbs[4] += 0x8000000000000 - 1; i = 0; inline while (i < 4) : (i += 1) { limbs[i + 1] += limbs[i] >> 51; limbs[i] &= MASK51; } limbs[4] &= MASK51; } pub inline fn add(a: Fe, b: Fe) Fe { var fe: Fe = undefined; comptime var i = 0; inline while (i < 5) : (i += 1) { fe.limbs[i] = a.limbs[i] + b.limbs[i]; } return fe; } pub inline fn sub(a: Fe, b: Fe) Fe { var fe = b; comptime var i = 0; inline while (i < 4) : (i += 1) { fe.limbs[i + 1] += fe.limbs[i] >> 51; fe.limbs[i] &= MASK51; } fe.limbs[0] += 19 * (fe.limbs[4] >> 51); fe.limbs[4] &= MASK51; fe.limbs[0] = (a.limbs[0] + 0xfffffffffffda) - fe.limbs[0]; fe.limbs[1] = (a.limbs[1] + 0xffffffffffffe) - fe.limbs[1]; fe.limbs[2] = (a.limbs[2] + 0xffffffffffffe) - fe.limbs[2]; fe.limbs[3] = (a.limbs[3] + 0xffffffffffffe) - fe.limbs[3]; fe.limbs[4] = (a.limbs[4] + 0xffffffffffffe) - fe.limbs[4]; return fe; } pub inline fn neg(a: Fe) Fe { return zero.sub(a); } pub inline fn isNegative(a: Fe) bool { return (a.toBytes()[0] & 1) != 0; } pub inline fn cMov(fe: *Fe, a: Fe, c: u64) void { const mask: u64 = 0 -% c; var x = fe.*; comptime var i = 0; inline while (i < 5) : (i += 1) { x.limbs[i] ^= a.limbs[i]; } i = 0; inline while (i < 5) : (i += 1) { x.limbs[i] &= mask; } i = 0; inline while (i < 5) : (i += 1) { fe.limbs[i] ^= x.limbs[i]; } } pub fn cSwap2(a0: *Fe, b0: *Fe, a1: *Fe, b1: *Fe, c: u64) void { const mask: u64 = 0 -% c; var x0 = a0.*; var x1 = a1.*; comptime var i = 0; inline while (i < 5) : (i += 1) { x0.limbs[i] ^= b0.limbs[i]; x1.limbs[i] ^= b1.limbs[i]; } i = 0; inline while (i < 5) : (i += 1) { x0.limbs[i] &= mask; x1.limbs[i] &= mask; } i = 0; inline while (i < 5) : (i += 1) { a0.limbs[i] ^= x0.limbs[i]; b0.limbs[i] ^= x0.limbs[i]; a1.limbs[i] ^= x1.limbs[i]; b1.limbs[i] ^= x1.limbs[i]; } } inline fn _carry128(r: *[5]u128) Fe { var rs: [5]u64 = undefined; comptime var i = 0; inline while (i < 4) : (i += 1) { rs[i] = @truncate(u64, r[i]) & MASK51; r[i + 1] += @intCast(u64, r[i] >> 51); } rs[4] = @truncate(u64, r[4]) & MASK51; var carry = @intCast(u64, r[4] >> 51); rs[0] += 19 * carry; carry = rs[0] >> 51; rs[0] &= MASK51; rs[1] += carry; carry = rs[1] >> 51; rs[1] &= MASK51; rs[2] += carry; return .{ .limbs = rs }; } pub inline fn mul(a: Fe, b: Fe) Fe { var ax: [5]u128 = undefined; var bx: [5]u128 = undefined; var a19: [5]u128 = undefined; var r: [5]u128 = undefined; comptime var i = 0; inline while (i < 5) : (i += 1) { ax[i] = @intCast(u128, a.limbs[i]); bx[i] = @intCast(u128, b.limbs[i]); } i = 1; inline while (i < 5) : (i += 1) { a19[i] = 19 * ax[i]; } r[0] = ax[0] * bx[0] + a19[1] * bx[4] + a19[2] * bx[3] + a19[3] * bx[2] + a19[4] * bx[1]; r[1] = ax[0] * bx[1] + ax[1] * bx[0] + a19[2] * bx[4] + a19[3] * bx[3] + a19[4] * bx[2]; r[2] = ax[0] * bx[2] + ax[1] * bx[1] + ax[2] * bx[0] + a19[3] * bx[4] + a19[4] * bx[3]; r[3] = ax[0] * bx[3] + ax[1] * bx[2] + ax[2] * bx[1] + ax[3] * bx[0] + a19[4] * bx[4]; r[4] = ax[0] * bx[4] + ax[1] * bx[3] + ax[2] * bx[2] + ax[3] * bx[1] + ax[4] * bx[0]; return _carry128(&r); } inline fn _sq(a: Fe, double: comptime bool) Fe { var ax: [5]u128 = undefined; var r: [5]u128 = undefined; comptime var i = 0; inline while (i < 5) : (i += 1) { ax[i] = @intCast(u128, a.limbs[i]); } const a0_2 = 2 * ax[0]; const a1_2 = 2 * ax[1]; const a1_38 = 38 * ax[1]; const a2_38 = 38 * ax[2]; const a3_38 = 38 * ax[3]; const a3_19 = 19 * ax[3]; const a4_19 = 19 * ax[4]; r[0] = ax[0] * ax[0] + a1_38 * ax[4] + a2_38 * ax[3]; r[1] = a0_2 * ax[1] + a2_38 * ax[4] + a3_19 * ax[3]; r[2] = a0_2 * ax[2] + ax[1] * ax[1] + a3_38 * ax[4]; r[3] = a0_2 * ax[3] + a1_2 * ax[2] + a4_19 * ax[4]; r[4] = a0_2 * ax[4] + a1_2 * ax[3] + ax[2] * ax[2]; if (double) { i = 0; inline while (i < 5) : (i += 1) { r[i] *= 2; } } return _carry128(&r); } pub inline fn sq(a: Fe) Fe { return _sq(a, false); } pub inline fn sq2(a: Fe) Fe { return _sq(a, true); } pub inline fn mul32(a: Fe, comptime n: u32) Fe { const sn = @intCast(u128, n); var fe: Fe = undefined; var x: u128 = 0; comptime var i = 0; inline while (i < 5) : (i += 1) { x = a.limbs[i] * sn + (x >> 51); fe.limbs[i] = @truncate(u64, x) & MASK51; } fe.limbs[0] += @intCast(u64, x >> 51) * 19; return fe; } inline fn sqn(a: Fe, comptime n: comptime_int) Fe { var i: usize = 0; var fe = a; while (i < n) : (i += 1) { fe = fe.sq(); } return fe; } pub fn invert(a: Fe) Fe { var t0 = a.sq(); var t1 = t0.sqn(2).mul(a); t0 = t0.mul(t1); t1 = t1.mul(t0.sq()); t1 = t1.mul(t1.sqn(5)); var t2 = t1.sqn(10).mul(t1); t2 = t2.mul(t2.sqn(20)).sqn(10); t1 = t1.mul(t2); t2 = t1.sqn(50).mul(t1); return t1.mul(t2.mul(t2.sqn(100)).sqn(50)).sqn(5).mul(t0); } pub fn pow2523(a: Fe) Fe { var c = a; var i: usize = 0; while (i < 249) : (i += 1) { c = c.sq().mul(a); } return c.sq().sq().mul(a); } pub fn abs(a: Fe) Fe { var r = a; r.cMov(a.neg(), @boolToInt(a.isNegative())); return r; } };
lib/std/crypto/25519/field.zig
const aoc = @import("../aoc.zig"); const std = @import("std"); const BagsHeld = struct { name: []const u8, qty: u8 }; pub fn run(problem: *aoc.Problem) !aoc.Solution { var contains_in = aoc.StringMultimap([]const u8).init(problem.allocator); defer contains_in.deinit(); var containing = aoc.StringMultimap(BagsHeld).init(problem.allocator); defer containing.deinit(); while (problem.line()) |line| { var statements = std.mem.split(u8, line, " bag"); const contains = statements.next().?; while (statements.next()) |statement| { if (extractBag(statement)) |bag| { try contains_in.put(bag.name, contains); try containing.put(contains, bag); } } } const contains_shiny_gold = blk: { var to_process = std.ArrayList([]const u8).init(problem.allocator); defer to_process.deinit(); var already_processed = std.StringHashMap(void).init(problem.allocator); defer already_processed.deinit(); try to_process.append("shiny gold"); while (to_process.popOrNull()) |p| { if (!already_processed.contains(p)) { try already_processed.putNoClobber(p, {}); try to_process.appendSlice(contains_in.get(p) orelse continue); } } break :blk already_processed.count() - 1; }; const shiny_gold_contents = countBags(containing, "shiny gold"); return problem.solution(contains_shiny_gold, shiny_gold_contents); } fn extractBag(statement: []const u8) ?BagsHeld { if (statement[statement.len - 1] == '.' or std.mem.eql(u8, statement, "s contain no other")) { return null; } var idx = statement.len - 1; var saw_space = false; while (true) : (idx -= 1) { if (statement[idx] == ' ') { if (saw_space) { return BagsHeld { .name = statement[idx+1..], .qty = statement[idx-1] - '0' }; } saw_space = true; } } unreachable; } fn countBags(containing: aoc.StringMultimap(BagsHeld), name: []const u8) usize { if (containing.get(name)) |bags| { var sum: usize = 0; for (bags) |bag| { sum += bag.qty + bag.qty * countBags(containing, bag.name); } return sum; } else { return 0; } }
src/main/zig/2020/day07.zig
const kernel = @import("kernel.zig"); const log = kernel.log.scoped(.CoreHeap); const TODO = kernel.TODO; const Physical = kernel.Physical; const Virtual = kernel.Virtual; const Heap = @This(); pub const AllocationResult = struct { physical: u64, virtual: u64, asked_size: u64, given_size: u64, }; const Region = struct { virtual: Virtual.Address, size: u64, allocated: u64, }; regions: [region_count]Region, // TODO: use another synchronization primitive lock: kernel.Spinlock, const region_size = 2 * kernel.mb; const region_count = kernel.core_memory_region.size / region_size; pub inline fn allocate(heap: *Heap, comptime T: type) ?*T { return @intToPtr(*T, (heap.allocate_extended(@sizeOf(T), @alignOf(T)) orelse return null).value); } pub inline fn allocate_many(heap: *Heap, comptime T: type, count: u64) ?[]T { return @intToPtr([*]T, (heap.allocate_extended(@sizeOf(T) * count, @alignOf(T)) orelse return null).value)[0..count]; } pub fn allocate_extended(heap: *Heap, size: u64, alignment: u64) ?Virtual.Address { log.debug("Heap: 0x{x}", .{@ptrToInt(heap)}); kernel.assert(@src(), size < region_size); heap.lock.acquire(); defer heap.lock.release(); const region = blk: { for (heap.regions) |*region| { if (region.size > 0) { region.allocated = kernel.align_forward(region.allocated, alignment); kernel.assert(@src(), (region.size - region.allocated) >= size); break :blk region; } else { log.debug("have to allocate region", .{}); const virtual_address = kernel.address_space.allocate(region_size) orelse return null; region.* = Region{ .virtual = virtual_address, .size = region_size, .allocated = 0, }; break :blk region; } } @panic("unreachableeee"); }; const result_address = region.virtual.value + region.allocated; region.allocated += size; return Virtual.Address.new(result_address); }
src/kernel/core_heap.zig
const SDL = @import("sdl2"); const std = @import("std"); const zigimg = @import("zigimg"); const Allocator = std.mem.Allocator; /// Convert a zigimg.Image into an SDL Texture /// # Arguments /// * `renderer`: the renderer onto which to generate the texture. /// Use the same renderer to display that texture. /// * `image`: the image. This must have either 24 bit RGB color storage or 32bit ARGB /// # Returns /// An SDL Texture. The texture must be destroyed by the caller to free its memory. pub fn sdlTextureFromImage(renderer: SDL.Renderer, image: zigimg.image.Image) !SDL.Texture { const pixel_info = try PixelInfo.from(image); const data: *c_void = blk: { if (image.pixels) |storage| { switch (storage) { .Bgr24 => |bgr24| break :blk @ptrCast(*c_void, bgr24.ptr), .Bgra32 => |bgra32| break :blk @ptrCast(*c_void, bgra32.ptr), .Rgba32 => |rgba32| break :blk @ptrCast(*c_void, rgba32.ptr), .Rgb24 => |rgb24| break :blk @ptrCast(*c_void, rgb24.ptr), else => return error.InvalidColorStorage, } } else { return error.EmptyColorStorage; } }; const surface_ptr = SDL.c.SDL_CreateRGBSurfaceFrom(data, @intCast(c_int, image.width), @intCast(c_int, image.height), pixel_info.bits, pixel_info.pitch, pixel_info.pixelmask.red, pixel_info.pixelmask.green, pixel_info.pixelmask.blue, pixel_info.pixelmask.alpha); if (surface_ptr == null) { return error.CreateRgbSurface; } const surface = SDL.Surface{ .ptr = surface_ptr }; defer surface.destroy(); return try SDL.createTextureFromSurface(renderer, surface); } /// Convert a zigimg.Image into an SDL Texture /// This image achieves the same effect as sdlTextureFromImage, but it uses the color /// iterator provided by the image. /// # Arguments /// * `renderer`: the renderer onto which to generate the texture. /// Use the same renderer to display that texture. /// * `image`: the image. This must have either 24 bit RGB color storage or 32bit ARGB /// # Returns /// An SDL Texture. The texture must be destroyed by the caller to free its memory. pub fn sdlTextureFromImageUsingColorIterator(renderer: SDL.Renderer, image: zigimg.image.Image) !SDL.Texture { const surface_ptr = SDL.c.SDL_CreateRGBSurfaceWithFormat(0, @intCast(c_int, image.width), @intCast(c_int, image.height), 32, SDL.c.SDL_PIXELFORMAT_RGBA8888); if (surface_ptr == null) { return error.CreateRgbSurface; } const surface = SDL.Surface{ .ptr = surface_ptr }; defer surface.destroy(); var color_iter = image.iterator(); if (surface.ptr.pixels == null) { return error.NullPixelSurface; } var pixels = @ptrCast([*]u8, surface.ptr.pixels); var offset: usize = 0; while (color_iter.next()) |fcol| { pixels[offset] = @floatToInt(u8, @round(fcol.A * 255)); pixels[offset + 1] = @floatToInt(u8, @round(fcol.B * 255)); pixels[offset + 2] = @floatToInt(u8, @round(fcol.G * 255)); pixels[offset + 3] = @floatToInt(u8, @round(fcol.R * 255)); offset += 4; } return try SDL.createTextureFromSurface(renderer, surface); } /// a helper structure that contains some info about the pixel layout const PixelInfo = struct { /// bits per pixel bits: c_int, /// the pitch (see SDL docs, this is the width of the image times the size per pixel in byte) pitch: c_int, /// the pixelmask for the (A)RGB storage pixelmask: PixelMask, const Self = @This(); pub fn from(image: zigimg.image.Image) !Self { const Sizes = struct { bits: c_int, pitch: c_int }; const sizes: Sizes = switch (image.pixels orelse return error.EmptyColorStorage) { .Bgra32 => Sizes{ .bits = 32, .pitch = 4 * @intCast(c_int, image.width) }, .Rgba32 => Sizes{ .bits = 32, .pitch = 4 * @intCast(c_int, image.width) }, .Rgb24 => Sizes{ .bits = 24, .pitch = 3 * @intCast(c_int, image.width) }, .Bgr24 => Sizes{ .bits = 24, .pitch = 3 * @intCast(c_int, image.width) }, else => return error.InvalidColorStorage, }; return Self{ .bits = @intCast(c_int, sizes.bits), .pitch = @intCast(c_int, sizes.pitch), .pixelmask = try PixelMask.fromColorStorage(image.pixels orelse return error.EmptyColorStorage) }; } }; /// helper structure for getting the pixelmasks out of an image const PixelMask = struct { red: u32, green: u32, blue: u32, alpha: u32, const Self = @This(); /// construct a pixelmask given the colorstorage. /// *Attention*: right now only works for 24-bit RGB, BGR and 32-bit RGBA,BGRA pub fn fromColorStorage(storage: zigimg.color.ColorStorage) !Self { switch (storage) { .Bgra32 => return Self{ .red = 0x00ff0000, .green = 0x0000ff00, .blue = 0x000000ff, .alpha = 0xff000000, }, .Rgba32 => return Self{ .red = 0x000000ff, .green = 0x0000ff00, .blue = 0x00ff0000, .alpha = 0xff000000, }, .Bgr24 => return Self{ .red = 0xff0000, .green = 0x00ff00, .blue = 0x0000ff, .alpha = 0, }, .Rgb24 => return Self{ .red = 0x0000ff, .green = 0x00ff00, .blue = 0xff0000, .alpha = 0, }, else => return error.InvalidColorStorage, } } }; /// the program configuration pub const ProgramConfig = struct { /// the image file we want to display with sdl image_file: std.fs.File, /// the conversion strategy we want to apply to get from image data to a texture image_conversion: Image2TexConversion, }; /// the conversion algorithm pub const Image2TexConversion = enum { /// use the color storage of the image directly buffer, /// use the color iterator color_iterator, }; /// a quick&dirty command line parser pub fn parseProcessArgs(allocator: *std.mem.Allocator) !ProgramConfig { var iter = std.process.args(); const first = iter.next(allocator); //first argument is the name of the executable. Throw that away. if (first) |exe_name_or_error| { allocator.free(try exe_name_or_error); } var first_argument: [:0]u8 = undefined; if (iter.next(allocator)) |arg_or_error| { first_argument = try arg_or_error; } else { std.log.err("Unknown or too few command line arguments!", .{}); printUsage(); return error.UnknownCommandLine; } defer allocator.free(first_argument); var file: std.fs.File = undefined; var conversion: Image2TexConversion = Image2TexConversion.buffer; if (std.ascii.eqlIgnoreCase(first_argument, "--color-iter")) { var second_argument: [:0]u8 = undefined; if (iter.next(allocator)) |arg_or_error| { second_argument = try arg_or_error; } else { std.log.err("Expected image file name!", .{}); printUsage(); return error.NoImageSpecified; } defer allocator.free(second_argument); file = try std.fs.cwd().openFile(second_argument, .{}); conversion = Image2TexConversion.color_iterator; std.log.info("Using color iterator for conversion", .{}); } else { file = try std.fs.cwd().openFile(first_argument, .{}); } return ProgramConfig{ .image_file = file, .image_conversion = conversion, }; } pub fn printUsage() void { std.log.info("Usage: sdl-example [--color-iter] image\n\timage\t\trelative path to an image file which will be displayed\n\t--color-iter\tspecify that the color iterator should be used to convert the image to a texture.", .{}); }
src/utils.zig
const std = @import("std"); const states = @import("state.zig"); const State = states.State; const style = @embedFile("style.css"); fn printToc(state: *State, stream: var) !void { var it = state.map.iterator(); try stream.print("<ul>", .{}); var buf = try state.allocator.alloc(u8, 1024); defer state.allocator.free(buf); // TODO have State have a tree-like structure instead of just a // table of <std.*> to docstring. while (it.next()) |kv| { const atag = try std.fmt.bufPrint(buf, "\t<a id=\"toc-{}\" href=\"#{}\">{}</a>", .{ kv.key, kv.key, kv.key, }); try stream.print("\t<li>{}</li>", .{atag}); } try stream.print("</ul>", .{}); } fn printContents(state: *State, stream: var) !void { var it = state.map.iterator(); try stream.print("<ul>", .{}); var buf = try state.allocator.alloc(u8, 1024); defer state.allocator.free(buf); while (it.next()) |kv| { const h1tag = try std.fmt.bufPrint(buf, "\t<h1 id=\"{}\"><a href=\"#toc-{}\">{}</a> <a class=\"hdr\" href=\"#{}\">[link]</a></h1>", .{ kv.key, kv.key, kv.key, kv.key, }); try stream.print("\t{}<p>{}</p>", .{ h1tag, kv.value }); } try stream.print("</ul>", .{}); } pub fn genHtml(state: *State, out_path: []const u8) !void { var file = try std.fs.cwd().createFile(out_path, .{ .read = false, .truncate = true }); defer file.close(); var stream = file.outStream(); try stream.print("<!doctype html>\n<html>\n", .{}); try stream.print("<head>\n<meta chatset=\"utf-8\">\n<title>zig docs</title>\n", .{}); try stream.print("<style type=\"text/css\">\n", .{}); try stream.print("{}\n", .{style}); try stream.print("</style>\n", .{}); try stream.print("</head>\n", .{}); try stream.print("<body>\n", .{}); try stream.print("<div id=\"contents\">\n", .{}); try printToc(state, stream); try stream.print("</div>\n", .{}); try printContents(state, stream); try stream.print("</body>\n", .{}); try stream.print("</html>\n", .{}); std.debug.warn("OK\n", .{}); }
src/htmlgen.zig
const std = @import("std"); const mem = std.mem; const State = @import("ast.zig").State; const Parser = @import("parse.zig").Parser; const Node = @import("parse.zig").Node; const Lexer = @import("lexer.zig").Lexer; const TokenId = @import("token.zig").TokenId; const log = @import("log.zig"); pub fn stateAtxHeader(p: *Parser) !void { p.state = Parser.State.AtxHeader; if (try p.lex.peekNext()) |tok| { if (tok.ID == TokenId.Whitespace and mem.eql(u8, tok.string, " ")) { var openTok = p.lex.lastToken(); var i: u32 = 0; var level: u32 = 0; while (i < openTok.string.len) : ({ level += 1; i += 1; }) {} var newChild = Node{ .ID = Node.ID.AtxHeading, .Value = null, .PositionStart = Node.Position{ .Line = openTok.lineNumber, .Column = openTok.column, .Offset = openTok.startOffset, }, .PositionEnd = Node.Position{ .Line = openTok.lineNumber, .Column = openTok.column, .Offset = openTok.endOffset, }, .Children = std.ArrayList(Node).init(p.allocator), .Level = level, }; // skip the whitespace after the header opening try p.lex.skipNext(); while (try p.lex.next()) |ntok| { if (ntok.ID == TokenId.Whitespace and mem.eql(u8, ntok.string, "\n")) { log.Debug("Found a newline, exiting state"); break; } var subChild = Node{ .ID = Node.ID.Text, .Value = ntok.string, .PositionStart = Node.Position{ .Line = ntok.lineNumber, .Column = ntok.column, .Offset = ntok.startOffset, }, .PositionEnd = Node.Position{ .Line = ntok.lineNumber, .Column = ntok.column, .Offset = ntok.endOffset, }, .Children = std.ArrayList(Node).init(p.allocator), .Level = level, }; try newChild.Children.append(subChild); } newChild.PositionEnd = newChild.Children.items[newChild.Children.items.len - 1].PositionEnd; try p.root.append(newChild); p.state = Parser.State.Start; } } }
src/md/parse_atx_heading.zig
const std = @import("std"); const essence = @import("essence"); const sga = essence.sga; fn decompress(allocator: std.mem.Allocator, args: [][:0]const u8) !void { if (args.len != 2) return error.InvalidArgs; var archive_path = args[0]; var out_dir_path = args[1]; var archive_file = try std.fs.cwd().openFile(archive_path, .{}); defer archive_file.close(); std.fs.cwd().makeDir(out_dir_path) catch |err| switch (err) { error.PathAlreadyExists => {}, else => @panic("Could not create output directory!"), }; var out_dir = try std.fs.cwd().openDir(out_dir_path, .{ .access_sub_paths = true }); defer out_dir.close(); var data_buf = std.ArrayList(u8).init(allocator); defer data_buf.deinit(); var archive = try sga.Archive.fromFile(allocator, archive_file); defer archive.deinit(); for (archive.root_nodes.items) |node| try writeTreeToFileSystem(allocator, archive_file.reader(), &data_buf, node, out_dir); } // TODO: Modularize code fn tree(allocator: std.mem.Allocator, args: [][:0]const u8) !void { if (args.len != 1) return error.InvalidArgs; var archive_path = args[0]; var archive_file = try std.fs.cwd().openFile(archive_path, .{}); defer archive_file.close(); var archive = try sga.Archive.fromFile(allocator, archive_file); defer archive.deinit(); for (archive.root_nodes.items) |node| try node.printTree(0); } // TODO: Move some of this functionality to a decompress in `sga.zig` fn writeTreeToFileSystem(allocator: std.mem.Allocator, reader: anytype, data_buf: *std.ArrayList(u8), node: sga.Node, dir: std.fs.Dir) anyerror!void { var name = switch (node) { .toc => |f| f.name, .folder => |f| f.name, .file => |f| f.name, }; if (node.getChildren()) |children| { dir.makeDir(name) catch |err| switch (err) { error.PathAlreadyExists => {}, else => @panic("oof"), }; var sub_dir = try dir.openDir(name, .{ .access_sub_paths = true }); defer sub_dir.close(); for (children.items) |child| try writeTreeToFileSystem(allocator, reader, data_buf, child, sub_dir); } else { var file = try dir.createFile(name, .{}); defer file.close(); var writer = file.writer(); switch (node.file.entry.storage_type) { .stream_compress, .buffer_compress => { try reader.context.seekTo(node.file.header.data_offset + node.file.entry.data_offset + 2); var stream = try std.compress.deflate.decompressor(allocator, reader, null); defer stream.deinit(); try data_buf.ensureTotalCapacity(node.file.entry.compressed_length); data_buf.items.len = node.file.entry.compressed_length; _ = try stream.reader().readAll(data_buf.items); switch (node.file.entry.verification_type) { .none => {}, else => {}, // TODO: Implement // else => std.log.info("File {s}'s integrity not verified: {s} not implemented", .{ node.file.name, node.file.entry.verification_type }), } try writer.writeAll(data_buf.items); }, .store => { try data_buf.ensureTotalCapacity(node.file.entry.uncompressed_length); try reader.context.seekTo(node.file.header.data_offset + node.file.entry.data_offset); data_buf.items.len = node.file.entry.uncompressed_length; _ = try reader.readAll(data_buf.items); std.debug.assert(std.hash.Crc32.hash(data_buf.items) == node.file.entry.crc); try writer.writeAll(data_buf.items); }, } } } fn compress(allocator: std.mem.Allocator, args: [][:0]const u8) !void { if (args.len != 2) return error.InvalidArgs; var header: sga.SGAHeader = undefined; header.version = 10; header.product = .essence; header.offset = header.calcOffset(); _ = allocator; var dir = try std.fs.cwd().openDir(args[0], .{ .access_sub_paths = true, .iterate = true }); defer dir.close(); var out_file = try std.fs.cwd().createFile(args[1], .{}); defer out_file.close(); // std.log.info("{d}", .{header.calcOffset()}); // const writer = out_file.writer(); // try header.encode(writer); // _ = allocator; // var header: sga.SGAHeader = undefined; } fn xor(allocator: std.mem.Allocator, args: [][:0]const u8) !void { _ = allocator; if (args.len != 1) return error.InvalidArgs; var file = try std.fs.cwd().openFile(args[0], .{ .mode = .write_only }); defer file.close(); var header = try sga.SGAHeader.decode(file.reader()); header.signature = [_]u8{ 00, 00, 00, 00, 00, 00, 00, 00 } ** 32; try header.encode(file.writer()); } fn printHelp() void { std.debug.print( \\ \\sgatool [decompress|compress|tree] ... \\ decompress <archive_path> <out_dir_path> \\ compress <dir_path> <out_archive_path> \\ tree <archive_path> \\ \\ xor <archive_path> \\ \\NOTE: compress and decompress use the first directory layer as the TOC entries \\NOTE 2: at the moment, compress does not support *actual* file compression or md5/sha hashing, it'll just \\lump your files into the SGA unhashed and uncompressed :P \\ , .{}); } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); if (args.len < 3) { printHelp(); return; } if (std.mem.eql(u8, args[1], "decompress")) { decompress(allocator, args[2..]) catch |err| switch (err) { error.InvalidArgs => printHelp(), else => std.log.err("{s}", .{err}), }; } else if (std.mem.eql(u8, args[1], "compress")) { compress(allocator, args[2..]) catch |err| switch (err) { error.InvalidArgs => printHelp(), else => std.log.err("{s}", .{err}), }; } else if (std.mem.eql(u8, args[1], "tree")) { tree(allocator, args[2..]) catch |err| switch (err) { error.InvalidArgs => printHelp(), else => std.log.err("{s}", .{err}), }; } else if (std.mem.eql(u8, args[1], "xor")) { xor(allocator, args[2..]) catch |err| switch (err) { error.InvalidArgs => printHelp(), else => std.log.err("{s}", .{err}), }; } else { printHelp(); } }
tools/sgatool.zig
const sf = struct { pub usingnamespace @import("../sfml.zig"); pub usingnamespace sf.system; pub usingnamespace sf.graphics; }; const CircleShape = @This(); // Constructor/destructor /// Inits a circle shape with a radius. The circle will be white and have 30 points pub fn create(radius: f32) !CircleShape { var circle = sf.c.sfCircleShape_create(); if (circle == null) return sf.Error.nullptrUnknownReason; sf.c.sfCircleShape_setFillColor(circle, sf.c.sfWhite); sf.c.sfCircleShape_setRadius(circle, radius); return CircleShape{ ._ptr = circle.? }; } /// Destroys a circle shape pub fn destroy(self: *CircleShape) void { sf.c.sfCircleShape_destroy(self._ptr); self._ptr = undefined; } // Draw function /// The draw function of this shape /// Meant to be called by your_target.draw(your_shape, .{}); pub fn sfDraw(self: CircleShape, target: anytype, states: ?*sf.c.sfRenderStates) void { switch (@TypeOf(target)) { sf.RenderWindow => sf.c.sfRenderWindow_drawCircleShape(target._ptr, self._ptr, states), sf.RenderTexture => sf.c.sfRenderTexture_drawCircleShape(target._ptr, self._ptr, states), else => @compileError("target must be a render target"), } } // Getters/setters /// Gets the fill color of this circle shape pub fn getFillColor(self: CircleShape) sf.Color { return sf.Color._fromCSFML(sf.c.sfCircleShape_getFillColor(self._ptr)); } /// Sets the fill color of this circle shape pub fn setFillColor(self: *CircleShape, color: sf.Color) void { sf.c.sfCircleShape_setFillColor(self._ptr, color._toCSFML()); } /// Gets the outline color of this circle shape pub fn getOutlineColor(self: CircleShape) sf.Color { return sf.Color._fromCSFML(sf.c.sfCircleShape_getOutlineColor(self._ptr)); } /// Sets the outline color of this circle shape pub fn setOutlineColor(self: *CircleShape, color: sf.Color) void { sf.c.sfCircleShape_setOutlineColor(self._ptr, color._toCSFML()); } /// Gets the outline thickness of this circle shape pub fn getOutlineThickness(self: CircleShape) f32 { return sf.c.sfCircleShape_getOutlineThickness(self._ptr); } /// Sets the outline thickness of this circle shape pub fn setOutlineThickness(self: *CircleShape, thickness: f32) void { sf.c.sfCircleShape_setOutlineThickness(self._ptr, thickness); } /// Gets the radius of this circle shape pub fn getRadius(self: CircleShape) f32 { return sf.c.sfCircleShape_getRadius(self._ptr); } /// Sets the radius of this circle shape pub fn setRadius(self: *CircleShape, radius: f32) void { sf.c.sfCircleShape_setRadius(self._ptr, radius); } /// Gets the position of this circle shape pub fn getPosition(self: CircleShape) sf.Vector2f { return sf.Vector2f._fromCSFML(sf.c.sfCircleShape_getPosition(self._ptr)); } /// Sets the position of this circle shape pub fn setPosition(self: *CircleShape, pos: sf.Vector2f) void { sf.c.sfCircleShape_setPosition(self._ptr, pos._toCSFML()); } /// Adds the offset to this shape's position pub fn move(self: *CircleShape, offset: sf.Vector2f) void { sf.c.sfCircleShape_move(self._ptr, offset._toCSFML()); } /// Gets the origin of this circle shape pub fn getOrigin(self: CircleShape) sf.Vector2f { return sf.Vector2f._fromCSFML(sf.c.sfCircleShape_getOrigin(self._ptr)); } /// Sets the origin of this circle shape pub fn setOrigin(self: *CircleShape, origin: sf.Vector2f) void { sf.c.sfCircleShape_setOrigin(self._ptr, origin._toCSFML()); } /// Gets the rotation of this circle shape pub fn getRotation(self: CircleShape) f32 { return sf.c.sfCircleShape_getRotation(self._ptr); } /// Sets the rotation of this circle shape pub fn setRotation(self: *CircleShape, angle: f32) void { sf.c.sfCircleShape_setRotation(self._ptr, angle); } /// Rotates this shape by a given amount pub fn rotate(self: *CircleShape, angle: f32) void { sf.c.sfCircleShape_rotate(self._ptr, angle); } /// Gets the texture of this shape pub fn getTexture(self: CircleShape) ?sf.Texture { const t = sf.c.sfCircleShape_getTexture(self._ptr); if (t) |tex| { return sf.Texture{ ._const_ptr = tex }; } else return null; } /// Sets the texture of this shape pub fn setTexture(self: *CircleShape, texture: ?sf.Texture) void { var tex = if (texture) |t| t._get() else null; sf.c.sfCircleShape_setTexture(self._ptr, tex, 0); } /// Gets the sub-rectangle of the texture that the shape will display pub fn getTextureRect(self: CircleShape) sf.IntRect { return sf.IntRect._fromCSFML(sf.c.sfCircleShape_getTextureRect(self._ptr)); } /// Sets the sub-rectangle of the texture that the shape will display pub fn setTextureRect(self: *CircleShape, rect: sf.IntRect) void { sf.c.sfCircleShape_getCircleRect(self._ptr, rect._toCSFML()); } /// Gets the bounds in the local coordinates system pub fn getLocalBounds(self: CircleShape) sf.FloatRect { return sf.FloatRect._fromCSFML(sf.c.sfCircleShape_getLocalBounds(self._ptr)); } /// Gets the bounds in the global coordinates pub fn getGlobalBounds(self: CircleShape) sf.FloatRect { return sf.FloatRect._fromCSFML(sf.c.sfCircleShape_getGlobalBounds(self._ptr)); } /// Pointer to the csfml structure _ptr: *sf.c.sfCircleShape, test "circle shape: sane getters and setters" { const tst = @import("std").testing; var circle = try CircleShape.create(30); defer circle.destroy(); circle.setFillColor(sf.Color.Yellow); circle.setOutlineColor(sf.Color.Red); circle.setOutlineThickness(3); circle.setRadius(50); circle.setRotation(15); circle.setPosition(.{ .x = 1, .y = 2 }); circle.setOrigin(.{ .x = 20, .y = 25 }); circle.setTexture(null); try tst.expectEqual(sf.Color.Yellow, circle.getFillColor()); try tst.expectEqual(sf.Color.Red, circle.getOutlineColor()); try tst.expectEqual(@as(f32, 3), circle.getOutlineThickness()); try tst.expectEqual(@as(f32, 50), circle.getRadius()); try tst.expectEqual(@as(f32, 15), circle.getRotation()); try tst.expectEqual(sf.Vector2f{ .x = 1, .y = 2 }, circle.getPosition()); try tst.expectEqual(sf.Vector2f{ .x = 20, .y = 25 }, circle.getOrigin()); try tst.expectEqual(@as(?sf.Texture, null), circle.getTexture()); circle.rotate(5); circle.move(.{ .x = -5, .y = 5 }); try tst.expectEqual(@as(f32, 20), circle.getRotation()); try tst.expectEqual(sf.Vector2f{ .x = -4, .y = 7 }, circle.getPosition()); _ = circle.getGlobalBounds(); _ = circle.getLocalBounds(); _ = circle.getTextureRect(); }
src/sfml/graphics/CircleShape.zig
usingnamespace @import("./DOtherSideTypes.zig"); pub extern fn dos_qcoreapplication_application_dir_path() [*c]u8; pub extern fn dos_qcoreapplication_process_events(flags: enum_DosQEventLoopProcessEventFlag) void; pub extern fn dos_qcoreapplication_process_events_timed(flags: enum_DosQEventLoopProcessEventFlag, ms: c_int) void; pub extern fn dos_qguiapplication_create() void; pub extern fn dos_qguiapplication_exec() void; pub extern fn dos_qguiapplication_quit() void; pub extern fn dos_qguiapplication_delete() void; pub extern fn dos_qapplication_create() void; pub extern fn dos_qapplication_exec() void; pub extern fn dos_qapplication_quit() void; pub extern fn dos_qapplication_delete() void; pub extern fn dos_qqmlapplicationengine_create() ?*DosQQmlApplicationEngine; pub extern fn dos_qqmlapplicationengine_load(vptr: ?*DosQQmlApplicationEngine, filename: [*c]const u8) void; pub extern fn dos_qqmlapplicationengine_load_url(vptr: ?*DosQQmlApplicationEngine, url: ?*DosQUrl) void; pub extern fn dos_qqmlapplicationengine_load_data(vptr: ?*DosQQmlApplicationEngine, data: [*c]const u8) void; pub extern fn dos_qqmlapplicationengine_add_import_path(vptr: ?*DosQQmlApplicationEngine, path: [*c]const u8) void; pub extern fn dos_qqmlapplicationengine_context(vptr: ?*DosQQmlApplicationEngine) ?*DosQQmlContext; pub extern fn dos_qqmlapplicationengine_addImageProvider(vptr: ?*DosQQmlApplicationEngine, name: [*c]const u8, vptr_i: ?*DosQQuickImageProvider) void; pub extern fn dos_qqmlapplicationengine_delete(vptr: ?*DosQQmlApplicationEngine) void; pub extern fn dos_qquickimageprovider_create(callback: RequestPixmapCallback) ?*DosQQuickImageProvider; pub extern fn dos_qquickimageprovider_delete(vptr: ?*DosQQuickImageProvider) void; pub extern fn dos_qpixmap_create(...) ?*DosPixmap; pub extern fn dos_qpixmap_create_qpixmap(other: ?*const DosPixmap) ?*DosPixmap; pub extern fn dos_qpixmap_create_width_and_height(width: c_int, height: c_int) ?*DosPixmap; pub extern fn dos_qpixmap_delete(vptr: ?*DosPixmap) void; pub extern fn dos_qpixmap_load(vptr: ?*DosPixmap, filepath: [*c]const u8, format: [*c]const u8) void; pub extern fn dos_qpixmap_loadFromData(vptr: ?*DosPixmap, data: [*c]const u8, len: c_uint) void; pub extern fn dos_qpixmap_fill(vptr: ?*DosPixmap, r: u8, g: u8, b: u8, a: u8) void; pub extern fn dos_qpixmap_assign(vptr: ?*DosPixmap, other: ?*const DosPixmap) void; pub extern fn dos_qpixmap_isNull(vptr: ?*DosPixmap) bool; pub extern fn dos_qquickstyle_set_style(style: [*c]const u8) void; pub extern fn dos_qquickstyle_set_fallback_style(style: [*c]const u8) void; pub extern fn dos_qquickview_create() ?*DosQQuickView; pub extern fn dos_qquickview_show(vptr: ?*DosQQuickView) void; pub extern fn dos_qquickview_source(vptr: ?*const DosQQuickView) [*c]u8; pub extern fn dos_qquickview_set_source_url(vptr: ?*DosQQuickView, url: ?*DosQUrl) void; pub extern fn dos_qquickview_set_source(vptr: ?*DosQQuickView, filename: [*c]const u8) void; pub extern fn dos_qquickview_set_resize_mode(vptr: ?*DosQQuickView, resizeMode: c_int) void; pub extern fn dos_qquickview_delete(vptr: ?*DosQQuickView) void; pub extern fn dos_qquickview_rootContext(vptr: ?*DosQQuickView) ?*DosQQmlContext; pub extern fn dos_qqmlcontext_baseUrl(vptr: ?*const DosQQmlContext) [*c]u8; pub extern fn dos_qqmlcontext_setcontextproperty(vptr: ?*DosQQmlContext, name: [*c]const u8, value: ?*DosQVariant) void; pub extern fn dos_chararray_delete(ptr: [*c]u8) void; pub extern fn dos_qvariantarray_delete(ptr: [*c]DosQVariantArray) void; pub extern fn dos_qvariant_create() ?*DosQVariant; pub extern fn dos_qvariant_create_int(value: c_int) ?*DosQVariant; pub extern fn dos_qvariant_create_bool(value: bool) ?*DosQVariant; pub extern fn dos_qvariant_create_string(value: [*c]const u8) ?*DosQVariant; pub extern fn dos_qvariant_create_qobject(value: ?*DosQObject) ?*DosQVariant; pub extern fn dos_qvariant_create_qvariant(value: ?*const DosQVariant) ?*DosQVariant; pub extern fn dos_qvariant_create_float(value: f32) ?*DosQVariant; pub extern fn dos_qvariant_create_double(value: f64) ?*DosQVariant; pub extern fn dos_qvariant_create_array(size: c_int, array: [*c]?*DosQVariant) ?*DosQVariant; pub extern fn dos_qvariant_setInt(vptr: ?*DosQVariant, value: c_int) void; pub extern fn dos_qvariant_setBool(vptr: ?*DosQVariant, value: bool) void; pub extern fn dos_qvariant_setFloat(vptr: ?*DosQVariant, value: f32) void; pub extern fn dos_qvariant_setDouble(vptr: ?*DosQVariant, value: f64) void; pub extern fn dos_qvariant_setString(vptr: ?*DosQVariant, value: [*c]const u8) void; pub extern fn dos_qvariant_setQObject(vptr: ?*DosQVariant, value: ?*DosQObject) void; pub extern fn dos_qvariant_setArray(vptr: ?*DosQVariant, size: c_int, array: [*c]?*DosQVariant) void; pub extern fn dos_qvariant_isnull(vptr: ?*const DosQVariant) bool; pub extern fn dos_qvariant_delete(vptr: ?*DosQVariant) void; pub extern fn dos_qvariant_assign(vptr: ?*DosQVariant, other: ?*const DosQVariant) void; pub extern fn dos_qvariant_toInt(vptr: ?*const DosQVariant) c_int; pub extern fn dos_qvariant_toBool(vptr: ?*const DosQVariant) bool; pub extern fn dos_qvariant_toString(vptr: ?*const DosQVariant) [*c]u8; pub extern fn dos_qvariant_toFloat(vptr: ?*const DosQVariant) f32; pub extern fn dos_qvariant_toDouble(vptr: ?*const DosQVariant) f64; pub extern fn dos_qvariant_toArray(vptr: ?*const DosQVariant) [*c]DosQVariantArray; pub extern fn dos_qvariant_toQObject(vptr: ?*const DosQVariant) ?*DosQObject; pub extern fn dos_qmetaobject_create(superClassMetaObject: ?*DosQMetaObject, className: [*c]const u8, signalDefinitions: [*c]const SignalDefinitions, slotDefinitions: [*c]const SlotDefinitions, propertyDefinitions: [*c]const PropertyDefinitions) ?*DosQMetaObject; pub extern fn dos_qmetaobject_delete(vptr: ?*DosQMetaObject) void; pub extern fn dos_qmetaobject_invoke_method(context: ?*DosQObject, callback: ?fn (?*DosQObject, ?*c_void) callconv(.C) void, data: ?*c_void, connection_type: enum_DosQtConnectionType) bool; pub extern fn dos_qabstractlistmodel_qmetaobject() ?*DosQMetaObject; pub extern fn dos_qabstractlistmodel_create(callbackObject: ?*c_void, metaObject: ?*DosQMetaObject, dObjectCallback: DObjectCallback, callbacks: [*c]DosQAbstractItemModelCallbacks) ?*DosQAbstractListModel; pub extern fn dos_qabstractlistmodel_index(vptr: ?*DosQAbstractListModel, row: c_int, column: c_int, parent: ?*DosQModelIndex) ?*DosQModelIndex; pub extern fn dos_qabstractlistmodel_parent(vptr: ?*DosQAbstractListModel, child: ?*DosQModelIndex) ?*DosQModelIndex; pub extern fn dos_qabstractlistmodel_columnCount(vptr: ?*DosQAbstractListModel, parent: ?*DosQModelIndex) c_int; pub extern fn dos_qabstracttablemodel_qmetaobject() ?*DosQMetaObject; pub extern fn dos_qabstracttablemodel_create(callbackObject: ?*c_void, metaObject: ?*DosQMetaObject, dObjectCallback: DObjectCallback, callbacks: [*c]DosQAbstractItemModelCallbacks) ?*DosQAbstractTableModel; pub extern fn dos_qabstracttablemodel_index(vptr: ?*DosQAbstractTableModel, row: c_int, column: c_int, parent: ?*DosQModelIndex) ?*DosQModelIndex; pub extern fn dos_qabstracttablemodel_parent(vptr: ?*DosQAbstractTableModel, child: ?*DosQModelIndex) ?*DosQModelIndex; pub extern fn dos_qabstractitemmodel_qmetaobject() ?*DosQMetaObject; pub extern fn dos_qabstractitemmodel_create(callbackObject: ?*c_void, metaObject: ?*DosQMetaObject, dObjectCallback: DObjectCallback, callbacks: [*c]DosQAbstractItemModelCallbacks) ?*DosQAbstractItemModel; pub extern fn dos_qabstractitemmodel_setData(vptr: ?*DosQAbstractItemModel, index: ?*DosQModelIndex, data: ?*DosQVariant, role: c_int) bool; pub extern fn dos_qabstractitemmodel_roleNames(vptr: ?*DosQAbstractItemModel) ?*DosQHashIntQByteArray; pub extern fn dos_qabstractitemmodel_flags(vptr: ?*DosQAbstractItemModel, index: ?*DosQModelIndex) c_int; pub extern fn dos_qabstractitemmodel_headerData(vptr: ?*DosQAbstractItemModel, section: c_int, orientation: c_int, role: c_int) ?*DosQVariant; pub extern fn dos_qabstractitemmodel_hasChildren(vptr: ?*DosQAbstractItemModel, parentIndex: ?*DosQModelIndex) bool; pub extern fn dos_qabstractitemmodel_hasIndex(vptr: ?*DosQAbstractItemModel, row: c_int, column: c_int, dosParentIndex: ?*DosQModelIndex) bool; pub extern fn dos_qabstractitemmodel_canFetchMore(vptr: ?*DosQAbstractItemModel, parentIndex: ?*DosQModelIndex) bool; pub extern fn dos_qabstractitemmodel_fetchMore(vptr: ?*DosQAbstractItemModel, parentIndex: ?*DosQModelIndex) void; pub extern fn dos_qabstractitemmodel_beginInsertRows(vptr: ?*DosQAbstractItemModel, parent: ?*DosQModelIndex, first: c_int, last: c_int) void; pub extern fn dos_qabstractitemmodel_endInsertRows(vptr: ?*DosQAbstractItemModel) void; pub extern fn dos_qabstractitemmodel_beginRemoveRows(vptr: ?*DosQAbstractItemModel, parent: ?*DosQModelIndex, first: c_int, last: c_int) void; pub extern fn dos_qabstractitemmodel_endRemoveRows(vptr: ?*DosQAbstractItemModel) void; pub extern fn dos_qabstractitemmodel_beginInsertColumns(vptr: ?*DosQAbstractItemModel, parent: ?*DosQModelIndex, first: c_int, last: c_int) void; pub extern fn dos_qabstractitemmodel_endInsertColumns(vptr: ?*DosQAbstractItemModel) void; pub extern fn dos_qabstractitemmodel_beginRemoveColumns(vptr: ?*DosQAbstractItemModel, parent: ?*DosQModelIndex, first: c_int, last: c_int) void; pub extern fn dos_qabstractitemmodel_endRemoveColumns(vptr: ?*DosQAbstractItemModel) void; pub extern fn dos_qabstractitemmodel_beginResetModel(vptr: ?*DosQAbstractItemModel) void; pub extern fn dos_qabstractitemmodel_endResetModel(vptr: ?*DosQAbstractItemModel) void; pub extern fn dos_qabstractitemmodel_dataChanged(vptr: ?*DosQAbstractItemModel, topLeft: ?*const DosQModelIndex, bottomRight: ?*const DosQModelIndex, rolesPtr: [*c]c_int, rolesLength: c_int) void; pub extern fn dos_qabstractitemmodel_createIndex(vptr: ?*DosQAbstractItemModel, row: c_int, column: c_int, data: ?*c_void) ?*DosQModelIndex; pub extern fn dos_qobject_qmetaobject() ?*DosQMetaObject; pub extern fn dos_qobject_create(dObjectPointer: ?*c_void, metaObject: ?*DosQMetaObject, dObjectCallback: DObjectCallback) ?*DosQObject; pub extern fn dos_qobject_signal_emit(vptr: ?*DosQObject, name: [*c]const u8, parametersCount: c_int, parameters: [*c]?*c_void) void; pub extern fn dos_qobject_signal_connect(senderVPtr: ?*DosQObject, signal: [*c]const u8, receiverVPtr: ?*DosQObject, method: [*c]const u8, type: c_int) bool; pub extern fn dos_qobject_signal_disconnect(senderVPtr: ?*DosQObject, signal: [*c]const u8, receiverVPtr: ?*DosQObject, method: [*c]const u8) bool; pub extern fn dos_qobject_objectName(vptr: ?*const DosQObject) [*c]u8; pub extern fn dos_qobject_setObjectName(vptr: ?*DosQObject, name: [*c]const u8) void; pub extern fn dos_qobject_delete(vptr: ?*DosQObject) void; pub extern fn dos_qobject_deleteLater(vptr: ?*DosQObject) void; pub extern fn dos_qobject_property(vptr: ?*DosQObject, propertyName: [*c]const u8) ?*DosQVariant; pub extern fn dos_qobject_setProperty(vptr: ?*DosQObject, propertyName: [*c]const u8, value: ?*DosQVariant) bool; pub extern fn dos_slot_macro(str: [*c]const u8) [*c]u8; pub extern fn dos_signal_macro(str: [*c]const u8) [*c]u8; pub extern fn dos_qobject_connect_static(sender: ?*DosQObject, signal: [*c]const u8, receiver: ?*DosQObject, slot: [*c]const u8, connection_type: enum_DosQtConnectionType) void; pub extern fn dos_qobject_disconnect_static(sender: ?*DosQObject, signal: [*c]const u8, receiver: ?*DosQObject, slot: [*c]const u8) void; pub extern fn dos_qmodelindex_create() ?*DosQModelIndex; pub extern fn dos_qmodelindex_create_qmodelindex(index: ?*DosQModelIndex) ?*DosQModelIndex; pub extern fn dos_qmodelindex_delete(vptr: ?*DosQModelIndex) void; pub extern fn dos_qmodelindex_row(vptr: ?*const DosQModelIndex) c_int; pub extern fn dos_qmodelindex_column(vptr: ?*const DosQModelIndex) c_int; pub extern fn dos_qmodelindex_isValid(vptr: ?*const DosQModelIndex) bool; pub extern fn dos_qmodelindex_data(vptr: ?*const DosQModelIndex, role: c_int) ?*DosQVariant; pub extern fn dos_qmodelindex_parent(vptr: ?*const DosQModelIndex) ?*DosQModelIndex; pub extern fn dos_qmodelindex_child(vptr: ?*const DosQModelIndex, row: c_int, column: c_int) ?*DosQModelIndex; pub extern fn dos_qmodelindex_sibling(vptr: ?*const DosQModelIndex, row: c_int, column: c_int) ?*DosQModelIndex; pub extern fn dos_qmodelindex_assign(l: ?*DosQModelIndex, r: ?*const DosQModelIndex) void; pub extern fn dos_qmodelindex_internalPointer(vptr: ?*DosQModelIndex) ?*c_void; pub extern fn dos_qhash_int_qbytearray_create() ?*DosQHashIntQByteArray; pub extern fn dos_qhash_int_qbytearray_delete(vptr: ?*DosQHashIntQByteArray) void; pub extern fn dos_qhash_int_qbytearray_insert(vptr: ?*DosQHashIntQByteArray, key: c_int, value: [*c]const u8) void; pub extern fn dos_qhash_int_qbytearray_value(vptr: ?*const DosQHashIntQByteArray, key: c_int) [*c]u8; pub extern fn dos_qresource_register(filename: [*c]const u8) void; pub extern fn dos_qurl_create(url: [*c]const u8, parsingMode: c_int) ?*DosQUrl; pub extern fn dos_qurl_delete(vptr: ?*DosQUrl) void; pub extern fn dos_qurl_to_string(vptr: ?*const DosQUrl) [*c]u8; pub extern fn dos_qurl_isValid(vptr: ?*const DosQUrl) bool; pub extern fn dos_qdeclarative_qmlregistertype(qmlRegisterType: [*c]const QmlRegisterType) c_int; pub extern fn dos_qdeclarative_qmlregistersingletontype(qmlRegisterType: [*c]const QmlRegisterType) c_int; pub extern fn dos_qpointer_create(object: ?*DosQObject) ?*DosQPointer; pub extern fn dos_qpointer_delete(self: ?*DosQPointer) void; pub extern fn dos_qpointer_is_null(self: ?*DosQPointer) bool; pub extern fn dos_qpointer_clear(self: ?*DosQPointer) void; pub extern fn dos_qpointer_data(self: ?*DosQPointer) ?*DosQObject; pub const DosQEventLoopProcessEventFlag = enum_DosQEventLoopProcessEventFlag; pub const DosQtConnectionType = enum_DosQtConnectionType;
src/DOtherSide.zig
const std = @import("std"); const info = std.log.info; const warn = std.log.warn; const n64 = @import("n64.zig"); const Controller = n64.Controller; const PIFCommand = enum(u8) { GetStatus = 0x00, GetButtons = 0x01, WriteMemcard = 0x03, Reset = 0xFF, }; // PIF constants pub const pifRAMBase = 0x1FC0_07C0; const pifStatus = 0x3F; pub var pifRAM: [0x40]u8 = undefined; pub fn checkStatus() void { if ((pifRAM[pifStatus] & 1) != 0) { info("[PIF] Scanning PIF RAM...", .{}); const hexB: []const u8 = &pifRAM; info("[PIF] Before: {}h", .{std.fmt.fmtSliceHexUpper(hexB)}); var channel: i32 = 0; var idx: usize = 0; pifLoop: while (idx <= pifStatus) { const t = pifRAM[idx]; info("[PIF] t: {X}h", .{t}); if (t == 0) { channel += 1; idx += 1; } else if (t < 0x80) { const r = pifRAM[idx + 1] & 0x3F; const cmd = pifRAM[idx + 2]; switch (cmd) { @enumToInt(PIFCommand.GetStatus), @enumToInt(PIFCommand.Reset) => { info("[PIF] Get Controller Status.", .{}); if (channel == 0) { pifRAM[idx + 3 + 0] = 0x05; pifRAM[idx + 3 + 1] = 0x00; pifRAM[idx + 3 + 2] = 0x00; } else { // Write Device Not present byte pifRAM[idx + 1] |= 0x80; } }, @enumToInt(PIFCommand.GetButtons) => { info("[PIF] Get Buttons.", .{}); if (channel == 0) { pifRAM[idx + 3 + 0] = @truncate(u8, @bitCast(u32, n64.controller)); pifRAM[idx + 3 + 1] = @truncate(u8, @bitCast(u32, n64.controller) >> 8); pifRAM[idx + 3 + 2] = n64.controller.x; pifRAM[idx + 3 + 3] = n64.controller.y; } else { // Write Device Not present byte pifRAM[idx + 1] |= 0x80; } }, @enumToInt(PIFCommand.WriteMemcard) => { warn("[PIF] Unhandled command Write To Memcard.", .{}); }, else => { warn("[PIF] Unhandled command {X}h.", .{cmd}); @panic("unhandled PIF command"); } } channel += 1; idx += 2 + t + r; } else if (t == 0xFE) { break :pifLoop; } else { idx += 1; } } // pifRAM[pifStatus] = 0; const hexA: []const u8 = &pifRAM; info("[PIF] After: {}h", .{std.fmt.fmtSliceHexUpper(hexB)}); } }
src/core/pif.zig
const std = @import("std"); const utils = @import("utils.zig"); const Registry = @import("registry.zig").Registry; const Storage = @import("registry.zig").Storage; const Entity = @import("registry.zig").Entity; /// single item view. Iterating raw() directly is the fastest way to get at the data. An iterator is also available to iterate /// either the Entities or the Components. If T is sorted note that raw() will be in the reverse order so it should be looped /// backwards. The iterators will return data in the sorted order though. pub fn BasicView(comptime T: type) type { return struct { const Self = @This(); storage: *Storage(T), pub fn init(storage: *Storage(T)) Self { return Self{ .storage = storage, }; } pub fn len(self: Self) usize { return self.storage.len(); } /// Direct access to the array of components pub fn raw(self: Self) []T { return self.storage.raw(); } /// Direct access to the array of entities pub fn data(self: Self) []const Entity { return self.storage.data(); } /// Returns the object associated with an entity pub fn get(self: Self, entity: Entity) *T { return self.storage.get(entity); } pub fn getConst(self: *Self, entity: Entity) T { return self.storage.getConst(entity); } pub fn iterator(self: Self) utils.ReverseSliceIterator(T) { return utils.ReverseSliceIterator(T).init(self.storage.instances.items); } pub fn entityIterator(self: Self) utils.ReverseSliceIterator(Entity) { return self.storage.set.reverseIterator(); } }; } pub fn MultiView(comptime n_includes: usize, comptime n_excludes: usize) type { return struct { const Self = @This(); registry: *Registry, type_ids: [n_includes]u32, exclude_type_ids: [n_excludes]u32, pub const Iterator = struct { view: *Self, index: usize, entities: *const []Entity, pub fn init(view: *Self) Iterator { const ptr = view.registry.components.get(view.type_ids[0]).?; const entities = @intToPtr(*Storage(u8), ptr).dataPtr(); return .{ .view = view, .index = entities.len, .entities = entities, }; } pub fn next(it: *Iterator) ?Entity { while (true) blk: { if (it.index == 0) return null; it.index -= 1; const entity = it.entities.*[it.index]; // entity must be in all other Storages for (it.view.type_ids) |tid| { const ptr = it.view.registry.components.get(tid).?; if (!@intToPtr(*Storage(u1), ptr).contains(entity)) { break :blk; } } // entity must not be in all other excluded Storages for (it.view.exclude_type_ids) |tid| { const ptr = it.view.registry.components.get(tid).?; if (@intToPtr(*Storage(u1), ptr).contains(entity)) { break :blk; } } return entity; } } // Reset the iterator to the initial index pub fn reset(it: *Iterator) void { it.index = it.entities.len; } }; pub fn init(registry: *Registry, type_ids: [n_includes]u32, exclude_type_ids: [n_excludes]u32) Self { return Self{ .registry = registry, .type_ids = type_ids, .exclude_type_ids = exclude_type_ids, }; } pub fn get(self: *Self, comptime T: type, entity: Entity) *T { return self.registry.assure(T).get(entity); } pub fn getConst(self: *Self, comptime T: type, entity: Entity) T { return self.registry.assure(T).getConst(entity); } fn sort(self: *Self) void { // get our component counts in an array so we can sort the type_ids based on how many entities are in each var sub_items: [n_includes]usize = undefined; for (self.type_ids) |tid, i| { const ptr = self.registry.components.get(tid).?; const store = @intToPtr(*Storage(u8), ptr); sub_items[i] = store.len(); } const asc_usize = struct { fn sort(_: void, a: usize, b: usize) bool { return a < b; } }; utils.sortSub(usize, u32, sub_items[0..], self.type_ids[0..], asc_usize.sort); } pub fn iterator(self: *Self) Iterator { self.sort(); return Iterator.init(self); } }; } test "single basic view" { var store = Storage(f32).init(std.testing.allocator); defer store.deinit(); store.add(3, 30); store.add(5, 50); store.add(7, 70); var view = BasicView(f32).init(&store); try std.testing.expectEqual(view.len(), 3); store.remove(7); try std.testing.expectEqual(view.len(), 2); var i: usize = 0; var iter = view.iterator(); while (iter.next()) |comp| { if (i == 0) try std.testing.expectEqual(comp, 50); if (i == 1) try std.testing.expectEqual(comp, 30); i += 1; } i = 0; var entIter = view.entityIterator(); while (entIter.next()) |ent| { if (i == 0) { try std.testing.expectEqual(ent, 5); try std.testing.expectEqual(view.getConst(ent), 50); } if (i == 1) { try std.testing.expectEqual(ent, 3); try std.testing.expectEqual(view.getConst(ent), 30); } i += 1; } } test "single basic view data" { var store = Storage(f32).init(std.testing.allocator); defer store.deinit(); store.add(3, 30); store.add(5, 50); store.add(7, 70); var view = BasicView(f32).init(&store); try std.testing.expectEqual(view.get(3).*, 30); for (view.data()) |entity, i| { if (i == 0) try std.testing.expectEqual(entity, 3); if (i == 1) try std.testing.expectEqual(entity, 5); if (i == 2) try std.testing.expectEqual(entity, 7); } for (view.raw()) |data, i| { if (i == 0) try std.testing.expectEqual(data, 30); if (i == 1) try std.testing.expectEqual(data, 50); if (i == 2) try std.testing.expectEqual(data, 70); } try std.testing.expectEqual(view.len(), 3); } test "basic multi view" { var reg = Registry.init(std.testing.allocator); defer reg.deinit(); var e0 = reg.create(); var e1 = reg.create(); var e2 = reg.create(); reg.add(e0, @as(i32, -0)); reg.add(e1, @as(i32, -1)); reg.add(e2, @as(i32, -2)); reg.add(e0, @as(u32, 0)); reg.add(e2, @as(u32, 2)); _ = reg.view(.{u32}, .{}); var view = reg.view(.{ i32, u32 }, .{}); var iterated_entities: usize = 0; var iter = view.iterator(); while (iter.next()) |_| { iterated_entities += 1; } try std.testing.expectEqual(iterated_entities, 2); iterated_entities = 0; reg.remove(u32, e0); iter.reset(); while (iter.next()) |_| { iterated_entities += 1; } try std.testing.expectEqual(iterated_entities, 1); } test "basic multi view with excludes" { var reg = Registry.init(std.testing.allocator); defer reg.deinit(); var e0 = reg.create(); var e1 = reg.create(); var e2 = reg.create(); reg.add(e0, @as(i32, -0)); reg.add(e1, @as(i32, -1)); reg.add(e2, @as(i32, -2)); reg.add(e0, @as(u32, 0)); reg.add(e2, @as(u32, 2)); reg.add(e2, @as(u8, 255)); var view = reg.view(.{ i32, u32 }, .{u8}); var iterated_entities: usize = 0; var iter = view.iterator(); while (iter.next()) |_| { iterated_entities += 1; } try std.testing.expectEqual(iterated_entities, 1); iterated_entities = 0; reg.remove(u8, e2); iter.reset(); while (iter.next()) |_| { iterated_entities += 1; } try std.testing.expectEqual(iterated_entities, 2); }
src/ecs/views.zig
const std = @import("std"); const mem = std.mem; const assert = std.debug.assert; const ir = @import("ir.zig"); const Type = @import("type.zig").Type; const Value = @import("value.zig").Value; const Target = std.Target; pub const ErrorMsg = struct { byte_offset: usize, msg: []const u8, }; pub const Symbol = struct { errors: []ErrorMsg, pub fn deinit(self: *Symbol, allocator: *mem.Allocator) void { for (self.errors) |err| { allocator.free(err.msg); } allocator.free(self.errors); self.* = undefined; } }; pub fn generateSymbol(typed_value: ir.TypedValue, module: ir.Module, code: *std.ArrayList(u8)) !Symbol { switch (typed_value.ty.zigTypeTag()) { .Fn => { const index = typed_value.val.cast(Value.Payload.Function).?.index; const module_fn = module.fns[index]; var function = Function{ .module = &module, .mod_fn = &module_fn, .code = code, .inst_table = std.AutoHashMap(*ir.Inst, Function.MCValue).init(code.allocator), .errors = std.ArrayList(ErrorMsg).init(code.allocator), }; defer function.inst_table.deinit(); defer function.errors.deinit(); for (module_fn.body) |inst| { const new_inst = function.genFuncInst(inst) catch |err| switch (err) { error.CodegenFail => { assert(function.errors.items.len != 0); break; }, else => |e| return e, }; try function.inst_table.putNoClobber(inst, new_inst); } return Symbol{ .errors = function.errors.toOwnedSlice() }; }, else => @panic("TODO implement generateSymbol for non-function types"), } } const Function = struct { module: *const ir.Module, mod_fn: *const ir.Module.Fn, code: *std.ArrayList(u8), inst_table: std.AutoHashMap(*ir.Inst, MCValue), errors: std.ArrayList(ErrorMsg), const MCValue = union(enum) { none, unreach, /// A pointer-sized integer that fits in a register. immediate: u64, /// The constant was emitted into the code, at this offset. embedded_in_code: usize, /// The value is in a target-specific register. The value can /// be @intToEnum casted to the respective Reg enum. register: usize, }; fn genFuncInst(self: *Function, inst: *ir.Inst) !MCValue { switch (inst.tag) { .unreach => return self.genPanic(inst.src), .constant => unreachable, // excluded from function bodies .assembly => return self.genAsm(inst.cast(ir.Inst.Assembly).?), .ptrtoint => return self.genPtrToInt(inst.cast(ir.Inst.PtrToInt).?), .bitcast => return self.genBitCast(inst.cast(ir.Inst.BitCast).?), } } fn genPanic(self: *Function, src: usize) !MCValue { // TODO change this to call the panic function switch (self.module.target.cpu.arch) { .i386, .x86_64 => { try self.code.append(0xcc); // int3 }, else => return self.fail(src, "TODO implement panic for {}", .{self.module.target.cpu.arch}), } return .unreach; } fn genRet(self: *Function, src: usize) !void { // TODO change this to call the panic function switch (self.module.target.cpu.arch) { .i386, .x86_64 => { try self.code.append(0xc3); // ret }, else => return self.fail(src, "TODO implement ret for {}", .{self.module.target.cpu.arch}), } } fn genRelativeFwdJump(self: *Function, src: usize, amount: u32) !void { switch (self.module.target.cpu.arch) { .i386, .x86_64 => { if (amount <= std.math.maxInt(u8)) { try self.code.resize(self.code.items.len + 2); self.code.items[self.code.items.len - 2] = 0xeb; self.code.items[self.code.items.len - 1] = @intCast(u8, amount); } else { try self.code.resize(self.code.items.len + 5); self.code.items[self.code.items.len - 5] = 0xe9; // jmp rel32 const imm_ptr = self.code.items[self.code.items.len - 4 ..][0..4]; mem.writeIntLittle(u32, imm_ptr, amount); } }, else => return self.fail(src, "TODO implement relative forward jump for {}", .{self.module.target.cpu.arch}), } } fn genAsm(self: *Function, inst: *ir.Inst.Assembly) !MCValue { // TODO convert to inline function switch (self.module.target.cpu.arch) { .arm => return self.genAsmArch(.arm, inst), .armeb => return self.genAsmArch(.armeb, inst), .aarch64 => return self.genAsmArch(.aarch64, inst), .aarch64_be => return self.genAsmArch(.aarch64_be, inst), .aarch64_32 => return self.genAsmArch(.aarch64_32, inst), .arc => return self.genAsmArch(.arc, inst), .avr => return self.genAsmArch(.avr, inst), .bpfel => return self.genAsmArch(.bpfel, inst), .bpfeb => return self.genAsmArch(.bpfeb, inst), .hexagon => return self.genAsmArch(.hexagon, inst), .mips => return self.genAsmArch(.mips, inst), .mipsel => return self.genAsmArch(.mipsel, inst), .mips64 => return self.genAsmArch(.mips64, inst), .mips64el => return self.genAsmArch(.mips64el, inst), .msp430 => return self.genAsmArch(.msp430, inst), .powerpc => return self.genAsmArch(.powerpc, inst), .powerpc64 => return self.genAsmArch(.powerpc64, inst), .powerpc64le => return self.genAsmArch(.powerpc64le, inst), .r600 => return self.genAsmArch(.r600, inst), .amdgcn => return self.genAsmArch(.amdgcn, inst), .riscv32 => return self.genAsmArch(.riscv32, inst), .riscv64 => return self.genAsmArch(.riscv64, inst), .sparc => return self.genAsmArch(.sparc, inst), .sparcv9 => return self.genAsmArch(.sparcv9, inst), .sparcel => return self.genAsmArch(.sparcel, inst), .s390x => return self.genAsmArch(.s390x, inst), .tce => return self.genAsmArch(.tce, inst), .tcele => return self.genAsmArch(.tcele, inst), .thumb => return self.genAsmArch(.thumb, inst), .thumbeb => return self.genAsmArch(.thumbeb, inst), .i386 => return self.genAsmArch(.i386, inst), .x86_64 => return self.genAsmArch(.x86_64, inst), .xcore => return self.genAsmArch(.xcore, inst), .nvptx => return self.genAsmArch(.nvptx, inst), .nvptx64 => return self.genAsmArch(.nvptx64, inst), .le32 => return self.genAsmArch(.le32, inst), .le64 => return self.genAsmArch(.le64, inst), .amdil => return self.genAsmArch(.amdil, inst), .amdil64 => return self.genAsmArch(.amdil64, inst), .hsail => return self.genAsmArch(.hsail, inst), .hsail64 => return self.genAsmArch(.hsail64, inst), .spir => return self.genAsmArch(.spir, inst), .spir64 => return self.genAsmArch(.spir64, inst), .kalimba => return self.genAsmArch(.kalimba, inst), .shave => return self.genAsmArch(.shave, inst), .lanai => return self.genAsmArch(.lanai, inst), .wasm32 => return self.genAsmArch(.wasm32, inst), .wasm64 => return self.genAsmArch(.wasm64, inst), .renderscript32 => return self.genAsmArch(.renderscript32, inst), .renderscript64 => return self.genAsmArch(.renderscript64, inst), .ve => return self.genAsmArch(.ve, inst), } } fn genAsmArch(self: *Function, comptime arch: Target.Cpu.Arch, inst: *ir.Inst.Assembly) !MCValue { if (arch != .x86_64 and arch != .i386) { return self.fail(inst.base.src, "TODO implement inline asm support for more architectures", .{}); } for (inst.args.inputs) |input, i| { if (input.len < 3 or input[0] != '{' or input[input.len - 1] != '}') { return self.fail(inst.base.src, "unrecognized asm input constraint: '{}'", .{input}); } const reg_name = input[1 .. input.len - 1]; const reg = parseRegName(arch, reg_name) orelse return self.fail(inst.base.src, "unrecognized register: '{}'", .{reg_name}); const arg = try self.resolveInst(inst.args.args[i]); try self.genSetReg(inst.base.src, arch, reg, arg); } if (mem.eql(u8, inst.args.asm_source, "syscall")) { try self.code.appendSlice(&[_]u8{ 0x0f, 0x05 }); } else { return self.fail(inst.base.src, "TODO implement support for more x86 assembly instructions", .{}); } if (inst.args.output) |output| { if (output.len < 4 or output[0] != '=' or output[1] != '{' or output[output.len - 1] != '}') { return self.fail(inst.base.src, "unrecognized asm output constraint: '{}'", .{output}); } const reg_name = output[2 .. output.len - 1]; const reg = parseRegName(arch, reg_name) orelse return self.fail(inst.base.src, "unrecognized register: '{}'", .{reg_name}); return MCValue{ .register = @enumToInt(reg) }; } else { return MCValue.none; } } fn genSetReg(self: *Function, src: usize, comptime arch: Target.Cpu.Arch, reg: Reg(arch), mcv: MCValue) !void { switch (arch) { .x86_64 => switch (reg) { .rax => switch (mcv) { .none, .unreach => unreachable, .immediate => |x| { // Setting the eax register zeroes the upper part of rax, so if the number is small // enough, that is preferable. // Best case: zero // 31 c0 xor eax,eax if (x == 0) { return self.code.appendSlice(&[_]u8{ 0x31, 0xc0 }); } // Next best case: set eax with 4 bytes // b8 04 03 02 01 mov eax,0x01020304 if (x <= std.math.maxInt(u32)) { try self.code.resize(self.code.items.len + 5); self.code.items[self.code.items.len - 5] = 0xb8; const imm_ptr = self.code.items[self.code.items.len - 4 ..][0..4]; mem.writeIntLittle(u32, imm_ptr, @intCast(u32, x)); return; } // Worst case: set rax with 8 bytes // 48 b8 08 07 06 05 04 03 02 01 movabs rax,0x0102030405060708 try self.code.resize(self.code.items.len + 10); self.code.items[self.code.items.len - 10] = 0x48; self.code.items[self.code.items.len - 9] = 0xb8; const imm_ptr = self.code.items[self.code.items.len - 8 ..][0..8]; mem.writeIntLittle(u64, imm_ptr, x); return; }, .embedded_in_code => return self.fail(src, "TODO implement x86_64 genSetReg %rax = embedded_in_code", .{}), .register => return self.fail(src, "TODO implement x86_64 genSetReg %rax = register", .{}), }, .rdx => switch (mcv) { .none, .unreach => unreachable, .immediate => |x| { // Setting the edx register zeroes the upper part of rdx, so if the number is small // enough, that is preferable. // Best case: zero // 31 d2 xor edx,edx if (x == 0) { return self.code.appendSlice(&[_]u8{ 0x31, 0xd2 }); } // Next best case: set edx with 4 bytes // ba 04 03 02 01 mov edx,0x1020304 if (x <= std.math.maxInt(u32)) { try self.code.resize(self.code.items.len + 5); self.code.items[self.code.items.len - 5] = 0xba; const imm_ptr = self.code.items[self.code.items.len - 4 ..][0..4]; mem.writeIntLittle(u32, imm_ptr, @intCast(u32, x)); return; } // Worst case: set rdx with 8 bytes // 48 ba 08 07 06 05 04 03 02 01 movabs rdx,0x0102030405060708 try self.code.resize(self.code.items.len + 10); self.code.items[self.code.items.len - 10] = 0x48; self.code.items[self.code.items.len - 9] = 0xba; const imm_ptr = self.code.items[self.code.items.len - 8 ..][0..8]; mem.writeIntLittle(u64, imm_ptr, x); return; }, .embedded_in_code => return self.fail(src, "TODO implement x86_64 genSetReg %rdx = embedded_in_code", .{}), .register => return self.fail(src, "TODO implement x86_64 genSetReg %rdx = register", .{}), }, .rdi => switch (mcv) { .none, .unreach => unreachable, .immediate => |x| { // Setting the edi register zeroes the upper part of rdi, so if the number is small // enough, that is preferable. // Best case: zero // 31 ff xor edi,edi if (x == 0) { return self.code.appendSlice(&[_]u8{ 0x31, 0xff }); } // Next best case: set edi with 4 bytes // bf 04 03 02 01 mov edi,0x1020304 if (x <= std.math.maxInt(u32)) { try self.code.resize(self.code.items.len + 5); self.code.items[self.code.items.len - 5] = 0xbf; const imm_ptr = self.code.items[self.code.items.len - 4 ..][0..4]; mem.writeIntLittle(u32, imm_ptr, @intCast(u32, x)); return; } // Worst case: set rdi with 8 bytes // 48 bf 08 07 06 05 04 03 02 01 movabs rax,0x0102030405060708 try self.code.resize(self.code.items.len + 10); self.code.items[self.code.items.len - 10] = 0x48; self.code.items[self.code.items.len - 9] = 0xbf; const imm_ptr = self.code.items[self.code.items.len - 8 ..][0..8]; mem.writeIntLittle(u64, imm_ptr, x); return; }, .embedded_in_code => return self.fail(src, "TODO implement x86_64 genSetReg %rdi = embedded_in_code", .{}), .register => return self.fail(src, "TODO implement x86_64 genSetReg %rdi = register", .{}), }, .rsi => switch (mcv) { .none, .unreach => unreachable, .immediate => return self.fail(src, "TODO implement x86_64 genSetReg %rsi = immediate", .{}), .embedded_in_code => |code_offset| { // Examples: // lea rsi, [rip + 0x01020304] // lea rsi, [rip - 7] // f: 48 8d 35 04 03 02 01 lea rsi,[rip+0x1020304] # 102031a <_start+0x102031a> // 16: 48 8d 35 f9 ff ff ff lea rsi,[rip+0xfffffffffffffff9] # 16 <_start+0x16> // // We need the offset from RIP in a signed i32 twos complement. // The instruction is 7 bytes long and RIP points to the next instruction. try self.code.resize(self.code.items.len + 7); const rip = self.code.items.len; const big_offset = @intCast(i64, code_offset) - @intCast(i64, rip); const offset = @intCast(i32, big_offset); self.code.items[self.code.items.len - 7] = 0x48; self.code.items[self.code.items.len - 6] = 0x8d; self.code.items[self.code.items.len - 5] = 0x35; const imm_ptr = self.code.items[self.code.items.len - 4 ..][0..4]; mem.writeIntLittle(i32, imm_ptr, offset); return; }, .register => return self.fail(src, "TODO implement x86_64 genSetReg %rsi = register", .{}), }, else => return self.fail(src, "TODO implement genSetReg for x86_64 '{}'", .{@tagName(reg)}), }, else => return self.fail(src, "TODO implement genSetReg for more architectures", .{}), } } fn genPtrToInt(self: *Function, inst: *ir.Inst.PtrToInt) !MCValue { // no-op return self.resolveInst(inst.args.ptr); } fn genBitCast(self: *Function, inst: *ir.Inst.BitCast) !MCValue { const operand = try self.resolveInst(inst.args.operand); return operand; } fn resolveInst(self: *Function, inst: *ir.Inst) !MCValue { if (self.inst_table.getValue(inst)) |mcv| { return mcv; } if (inst.cast(ir.Inst.Constant)) |const_inst| { const mcvalue = try self.genTypedValue(inst.src, .{ .ty = inst.ty, .val = const_inst.val }); try self.inst_table.putNoClobber(inst, mcvalue); return mcvalue; } else { return self.inst_table.getValue(inst).?; } } fn genTypedValue(self: *Function, src: usize, typed_value: ir.TypedValue) !MCValue { switch (typed_value.ty.zigTypeTag()) { .Pointer => { const ptr_elem_type = typed_value.ty.elemType(); switch (ptr_elem_type.zigTypeTag()) { .Array => { // TODO more checks to make sure this can be emitted as a string literal const bytes = try typed_value.val.toAllocatedBytes(self.code.allocator); defer self.code.allocator.free(bytes); const smaller_len = std.math.cast(u32, bytes.len) catch return self.fail(src, "TODO handle a larger string constant", .{}); // Emit the string literal directly into the code; jump over it. try self.genRelativeFwdJump(src, smaller_len); const offset = self.code.items.len; try self.code.appendSlice(bytes); return MCValue{ .embedded_in_code = offset }; }, else => |t| return self.fail(src, "TODO implement emitTypedValue for pointer to '{}'", .{@tagName(t)}), } }, .Int => { const info = typed_value.ty.intInfo(self.module.target); const ptr_bits = self.module.target.cpu.arch.ptrBitWidth(); if (info.bits > ptr_bits or info.signed) { return self.fail(src, "TODO const int bigger than ptr and signed int", .{}); } return MCValue{ .immediate = typed_value.val.toUnsignedInt() }; }, .ComptimeInt => unreachable, // semantic analysis prevents this .ComptimeFloat => unreachable, // semantic analysis prevents this else => return self.fail(src, "TODO implement const of type '{}'", .{typed_value.ty}), } } fn fail(self: *Function, src: usize, comptime format: []const u8, args: var) error{ CodegenFail, OutOfMemory } { @setCold(true); const msg = try std.fmt.allocPrint(self.errors.allocator, format, args); { errdefer self.errors.allocator.free(msg); (try self.errors.addOne()).* = .{ .byte_offset = src, .msg = msg, }; } return error.CodegenFail; } }; fn Reg(comptime arch: Target.Cpu.Arch) type { return switch (arch) { .i386 => enum { eax, ebx, ecx, edx, ebp, esp, esi, edi, ax, bx, cx, dx, bp, sp, si, di, ah, bh, ch, dh, al, bl, cl, dl, }, .x86_64 => enum { rax, rbx, rcx, rdx, rbp, rsp, rsi, rdi, r8, r9, r10, r11, r12, r13, r14, r15, eax, ebx, ecx, edx, ebp, esp, esi, edi, r8d, r9d, r10d, r11d, r12d, r13d, r14d, r15d, ax, bx, cx, dx, bp, sp, si, di, r8w, r9w, r10w, r11w, r12w, r13w, r14w, r15w, ah, bh, ch, dh, al, bl, cl, dl, r8b, r9b, r10b, r11b, r12b, r13b, r14b, r15b, }, else => @compileError("TODO add more register enums"), }; } fn parseRegName(comptime arch: Target.Cpu.Arch, name: []const u8) ?Reg(arch) { return std.meta.stringToEnum(Reg(arch), name); }
src-self-hosted/codegen.zig
const std = @import("std"); const testing = std.testing; const triangle = @import("triangle.zig"); test "equilateral all sides are equal" { const actual = comptime try triangle.Triangle.init(2, 2, 2); comptime testing.expect(actual.isEquilateral()); } test "equilateral any side is unequal" { const actual = comptime try triangle.Triangle.init(2, 3, 2); comptime testing.expect(!actual.isEquilateral()); } test "equilateral no sides are equal" { const actual = comptime try triangle.Triangle.init(5, 4, 6); comptime testing.expect(!actual.isEquilateral()); } test "equilateral all zero sies is not a triangle" { const actual = triangle.Triangle.init(0, 0, 0); testing.expectError(triangle.TriangleError.Degenerate, actual); } test "equilateral sides may be floats" { const actual = comptime try triangle.Triangle.init(0.5, 0.5, 0.5); comptime testing.expect(actual.isEquilateral()); } test "isosceles last two sides are equal" { const actual = comptime try triangle.Triangle.init(3, 4, 4); comptime testing.expect(actual.isIsosceles()); } test "isosceles first two sides are equal" { const actual = comptime try triangle.Triangle.init(4, 4, 3); comptime testing.expect(actual.isIsosceles()); } test "isosceles first and last sides are equal" { const actual = comptime try triangle.Triangle.init(4, 3, 4); comptime testing.expect(actual.isIsosceles()); } test "equilateral triangles are also isosceles" { const actual = comptime try triangle.Triangle.init(4, 3, 4); comptime testing.expect(actual.isIsosceles()); } test "isosceles no sides are equal" { const actual = comptime try triangle.Triangle.init(2, 3, 4); comptime testing.expect(!actual.isIsosceles()); } test "isosceles first triangle inequality violation" { const actual = triangle.Triangle.init(1, 1, 3); testing.expectError(triangle.TriangleError.InvalidInequality, actual); } test "isosceles second triangle inequality violation" { const actual = triangle.Triangle.init(1, 3, 1); testing.expectError(triangle.TriangleError.InvalidInequality, actual); } test "isosceles third triangle inequality violation" { const actual = triangle.Triangle.init(3, 1, 1); testing.expectError(triangle.TriangleError.InvalidInequality, actual); } test "isosceles sides may be floats" { const actual = comptime try triangle.Triangle.init(0.5, 0.4, 0.5); comptime testing.expect(actual.isIsosceles()); } test "scalene no sides are equal" { const actual = comptime try triangle.Triangle.init(5, 4, 6); comptime testing.expect(actual.isScalene()); } test "scalene all sides are equal" { const actual = comptime try triangle.Triangle.init(4, 4, 4); comptime testing.expect(!actual.isScalene()); } test "scalene two sides are equal" { const actual = comptime try triangle.Triangle.init(4, 4, 3); comptime testing.expect(!actual.isScalene()); } test "scalene two sides are equal" { const actual = comptime try triangle.Triangle.init(4, 4, 3); comptime testing.expect(!actual.isScalene()); } test "scalene may not violate triangle inequality" { const actual = triangle.Triangle.init(7, 3, 2); testing.expectError(triangle.TriangleError.InvalidInequality, actual); } test "scalene sides may be floats" { const actual = comptime try triangle.Triangle.init(0.5, 0.4, 0.6); comptime testing.expect(actual.isScalene()); }
exercises/practice/triangle/test_triangle.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/day04.txt"); // const data = @embedFile("../data/day04-tst.txt"); pub fn main() !void { var it = split(u8, data, "\n"); var passports = List(std.BufMap).init(gpa); var current_passport = std.BufMap.init(gpa); // Make this false for part1 result const part2 = true; while (true) { var line = it.next(); if (line == null or line.?.len == 0) { try passports.append(current_passport); current_passport = std.BufMap.init(gpa); if (line == null) { break; } continue; } var entries = tokenize(u8, line.?, "\n\r "); while (entries.next()) |entry| { var split_entry = tokenize(u8, entry, ":"); var key = split_entry.next().?; var value = split_entry.next().?; // cid is optional. Just ignore it if (!std.mem.eql(u8, key, "cid")) { try current_passport.put(key, value); } } } const eye_colors = blk: { var tmp = std.BufSet.init(gpa); try tmp.insert("amb"); try tmp.insert("blu"); try tmp.insert("brn"); try tmp.insert("gry"); try tmp.insert("grn"); try tmp.insert("hzl"); try tmp.insert("oth"); break :blk tmp; }; var valid_passports: usize = 0; for (passports.items) |passport| { if (passport.count() == 7) { if (part2) { var byr = parseInt(u32, passport.get("byr").?, 10) catch 0; if (byr < 1920 or byr > 2002) continue; var iyr = parseInt(u32, passport.get("iyr").?, 10) catch 0; if (iyr < 2010 or iyr > 2020) continue; var eyr = parseInt(u32, passport.get("eyr").?, 10) catch 0; if (eyr < 2020 or eyr > 2030) continue; var hgt_str = passport.get("hgt").?; if (std.mem.count(u8, hgt_str, "in") > 0) { var hgt = parseInt(u16, hgt_str[0 .. hgt_str.len - 2], 10) catch 0; if (hgt < 59 or hgt > 76) continue; } else if (std.mem.count(u8, hgt_str, "cm") > 0) { var hgt = parseInt(u16, hgt_str[0 .. hgt_str.len - 2], 10) catch 0; if (hgt < 150 or hgt > 193) continue; } else { continue; } var hcl = passport.get("hcl").?; if (hcl.len != 7) continue; if (hcl[0] != '#') continue; var valid_hcl = true; for (hcl[1..]) |c| { if ((c < '0' or c > '9') and (c < 'a' or c > 'f')) { valid_hcl = false; break; } } if (!valid_hcl) continue; var ecl = passport.get("ecl").?; if (!eye_colors.contains(ecl)) continue; var pid = passport.get("pid").?; if (pid.len != 9) continue; var valid_pid = true; for (pid) |c| { if (c < '0' or c > '9') { valid_pid = false; break; } } if (!valid_pid) continue; } valid_passports += 1; } } print("{}\n", .{valid_passports}); } // 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/day04.zig
pub const STBI_default = @enumToInt(enum_unnamed_1.STBI_default); pub const STBI_grey = @enumToInt(enum_unnamed_1.STBI_grey); pub const STBI_grey_alpha = @enumToInt(enum_unnamed_1.STBI_grey_alpha); pub const STBI_rgb = @enumToInt(enum_unnamed_1.STBI_rgb); pub const STBI_rgb_alpha = @enumToInt(enum_unnamed_1.STBI_rgb_alpha); const enum_unnamed_1 = extern enum(c_int) { STBI_default = 0, STBI_grey = 1, STBI_grey_alpha = 2, STBI_rgb = 3, STBI_rgb_alpha = 4, _, }; pub const stbi_uc = u8; pub const stbi_us = c_ushort; const struct_unnamed_9 = extern struct { read: ?fn (?*c_void, [*c]u8, c_int) callconv(.C) c_int, skip: ?fn (?*c_void, c_int) callconv(.C) void, eof: ?fn (?*c_void) callconv(.C) c_int, }; pub const stbi_io_callbacks = struct_unnamed_9; pub extern fn stbi_load_from_memory(buffer: [*c]const stbi_uc, len: c_int, x: [*c]c_int, y: [*c]c_int, channels_in_file: [*c]c_int, desired_channels: c_int) [*c]stbi_uc; pub extern fn stbi_load_from_callbacks(clbk: [*c]const stbi_io_callbacks, user: ?*c_void, x: [*c]c_int, y: [*c]c_int, channels_in_file: [*c]c_int, desired_channels: c_int) [*c]stbi_uc; pub extern fn stbi_load_gif_from_memory(buffer: [*c]const stbi_uc, len: c_int, delays: [*c][*c]c_int, x: [*c]c_int, y: [*c]c_int, z: [*c]c_int, comp: [*c]c_int, req_comp: c_int) [*c]stbi_uc; pub extern fn stbi_load_16_from_memory(buffer: [*c]const stbi_uc, len: c_int, x: [*c]c_int, y: [*c]c_int, channels_in_file: [*c]c_int, desired_channels: c_int) [*c]stbi_us; pub extern fn stbi_load_16_from_callbacks(clbk: [*c]const stbi_io_callbacks, user: ?*c_void, x: [*c]c_int, y: [*c]c_int, channels_in_file: [*c]c_int, desired_channels: c_int) [*c]stbi_us; pub extern fn stbi_loadf_from_memory(buffer: [*c]const stbi_uc, len: c_int, x: [*c]c_int, y: [*c]c_int, channels_in_file: [*c]c_int, desired_channels: c_int) [*c]f32; pub extern fn stbi_loadf_from_callbacks(clbk: [*c]const stbi_io_callbacks, user: ?*c_void, x: [*c]c_int, y: [*c]c_int, channels_in_file: [*c]c_int, desired_channels: c_int) [*c]f32; pub extern fn stbi_hdr_to_ldr_gamma(gamma: f32) void; pub extern fn stbi_hdr_to_ldr_scale(scale: f32) void; pub extern fn stbi_ldr_to_hdr_gamma(gamma: f32) void; pub extern fn stbi_ldr_to_hdr_scale(scale: f32) void; pub extern fn stbi_is_hdr_from_callbacks(clbk: [*c]const stbi_io_callbacks, user: ?*c_void) c_int; pub extern fn stbi_is_hdr_from_memory(buffer: [*c]const stbi_uc, len: c_int) c_int; pub extern fn stbi_failure_reason() [*c]const u8; pub extern fn stbi_image_free(retval_from_stbi_load: ?*c_void) void; pub extern fn stbi_info_from_memory(buffer: [*c]const stbi_uc, len: c_int, x: [*c]c_int, y: [*c]c_int, comp: [*c]c_int) c_int; pub extern fn stbi_info_from_callbacks(clbk: [*c]const stbi_io_callbacks, user: ?*c_void, x: [*c]c_int, y: [*c]c_int, comp: [*c]c_int) c_int; pub extern fn stbi_is_16_bit_from_memory(buffer: [*c]const stbi_uc, len: c_int) c_int; pub extern fn stbi_is_16_bit_from_callbacks(clbk: [*c]const stbi_io_callbacks, user: ?*c_void) c_int; pub extern fn stbi_set_unpremultiply_on_load(flag_true_if_should_unpremultiply: c_int) void; pub extern fn stbi_convert_iphone_png_to_rgb(flag_true_if_should_convert: c_int) void; pub extern fn stbi_set_flip_vertically_on_load(flag_true_if_should_flip: c_int) void; pub extern fn stbi_set_flip_vertically_on_load_thread(flag_true_if_should_flip: c_int) void; pub extern fn stbi_zlib_decode_malloc_guesssize(buffer: [*c]const u8, len: c_int, initial_size: c_int, outlen: [*c]c_int) [*c]u8; pub extern fn stbi_zlib_decode_malloc_guesssize_headerflag(buffer: [*c]const u8, len: c_int, initial_size: c_int, outlen: [*c]c_int, parse_header: c_int) [*c]u8; pub extern fn stbi_zlib_decode_malloc(buffer: [*c]const u8, len: c_int, outlen: [*c]c_int) [*c]u8; pub extern fn stbi_zlib_decode_buffer(obuffer: [*c]u8, olen: c_int, ibuffer: [*c]const u8, ilen: c_int) c_int; pub extern fn stbi_zlib_decode_noheader_malloc(buffer: [*c]const u8, len: c_int, outlen: [*c]c_int) [*c]u8; pub extern fn stbi_zlib_decode_noheader_buffer(obuffer: [*c]u8, olen: c_int, ibuffer: [*c]const u8, ilen: c_int) c_int;
src/deps/stb/stb_image.zig
const std = @import("std"); const Currency = @import("Currency.zig"); const armors = @import("armors.zig"); const Armor = armors.Armor; const Shield = armors.Shield; const weapons = @import("weapons.zig"); const Weapon = weapons.Weapon; const tools = @import("tools.zig"); const Tool = tools.Tool; const tt = @import("root"); const Element = tt.web.html.Element; pub const CharacterLevel = struct { str: u32 = 0, dex: u32 = 0, con: u32 = 0, int: u32 = 0, wis: u32 = 0, cha: u32 = 0, }; fn modify(value: u32, mod: i32) u32 { const result = @intCast(u32, @intCast(i32, value) + mod); if (result < 0) return 0; return result; } fn abilityModifier(score: u32) i32 { return @divFloor(@intCast(i32, score) - 10, 2); } test "abilityModifier" { try std.testing.expectEqual(abilityModifier(1), -5); try std.testing.expectEqual(abilityModifier(2), -4); try std.testing.expectEqual(abilityModifier(3), -4); try std.testing.expectEqual(abilityModifier(4), -3); try std.testing.expectEqual(abilityModifier(5), -3); try std.testing.expectEqual(abilityModifier(6), -2); try std.testing.expectEqual(abilityModifier(7), -2); try std.testing.expectEqual(abilityModifier(8), -1); try std.testing.expectEqual(abilityModifier(9), -1); try std.testing.expectEqual(abilityModifier(10), 0); try std.testing.expectEqual(abilityModifier(11), 0); try std.testing.expectEqual(abilityModifier(12), 1); try std.testing.expectEqual(abilityModifier(13), 1); try std.testing.expectEqual(abilityModifier(14), 2); try std.testing.expectEqual(abilityModifier(15), 2); try std.testing.expectEqual(abilityModifier(16), 3); try std.testing.expectEqual(abilityModifier(17), 3); try std.testing.expectEqual(abilityModifier(18), 4); try std.testing.expectEqual(abilityModifier(19), 4); try std.testing.expectEqual(abilityModifier(20), 5); } pub const Character = struct { name: []const u8, str: u32, dex: u32, con: u32, int: u32, wis: u32, cha: u32, levels: []const CharacterLevel = &[_]CharacterLevel{}, armor: ?Armor = null, shield: ?Shield = null, // weapons: []const Weapon = &[_]Weapon{}, pub fn dexScore(self: Character) u32 { var score: u32 = self.dex; for (self.levels) |level| { score = std.math.min(20, score + level.dex); } return score; } pub fn ac(self: Character) u32 { var value: u32 = undefined; if (self.armor) |armor| { if (armor.ac.max_dex) |max_dex| { value = modify(armor.ac.base, std.math.min(abilityModifier(self.dexScore()), max_dex)); } else { value = armor.ac.base; } } else { value = modify(10, abilityModifier(self.dexScore())); } if (self.shield) |s| { value += s.ac; } return value; } }; test "Character.ac" { const char = Character{ .name = "foo", .str = 10, .dex = 20, .con = 10, .int = 16, .wis = 12, .cha = 10, .armor = armors.studded_leather, .shield = armors.shield, }; try std.testing.expectEqual(char.ac(), 19); } pub fn charToHtml(char: *const Character, allocator: std.mem.Allocator) !Element { var root = Element.init(null, .div, allocator); _ = try (try root.addElement(.h1)).addText(char.name); var ability_table = try root.addElement(.table); var thead = try ability_table.addElement(.thead); _ = try (try thead.addElement(.td)).addText("Str"); _ = try (try thead.addElement(.td)).addText("Dex"); _ = try (try thead.addElement(.td)).addText("Con"); _ = try (try thead.addElement(.td)).addText("Int"); _ = try (try thead.addElement(.td)).addText("Wis"); _ = try (try thead.addElement(.td)).addText("Cha"); var tr = try ability_table.addElement(.tr); _ = try (try tr.addElement(.td)).addText(try std.fmt.allocPrintZ(allocator, "{}", .{char.str})); _ = try (try tr.addElement(.td)).addText(try std.fmt.allocPrintZ(allocator, "{}", .{char.dex})); _ = try (try tr.addElement(.td)).addText(try std.fmt.allocPrintZ(allocator, "{}", .{char.con})); _ = try (try tr.addElement(.td)).addText(try std.fmt.allocPrintZ(allocator, "{}", .{char.int})); _ = try (try tr.addElement(.td)).addText(try std.fmt.allocPrintZ(allocator, "{}", .{char.wis})); _ = try (try tr.addElement(.td)).addText(try std.fmt.allocPrintZ(allocator, "{}", .{char.cha})); return root; } test "charToHtml" { const char = Character{ .name = "foo", .str = 10, .dex = 20, .con = 10, .int = 16, .wis = 12, .cha = 10, .armor = armors.studded_leather, .shield = armors.shield, }; _ = charToHtml(char, std.testing.allocator); }
src/dnd/char.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; //-------------------------------------------------------------------------------------------------- pub fn print(grid: [10][10]u8) void { for (grid) |row| { std.log.info("{d}", .{row}); } std.log.info("--------------------------------", .{}); } //-------------------------------------------------------------------------------------------------- pub fn increment(grid: *[10][10]u8) void { for (grid) |*row| { for (row.*) |*item| { item.* += 1; } } } //-------------------------------------------------------------------------------------------------- pub fn increment_adjacent(grid: *[10][10]u8, x: usize, y: usize) bool { const start_x = if (x > 0) x - 1 else x; const start_y = if (y > 0) y - 1 else y; const end_x = if (x < 9) x + 1 else x; const end_y = if (y < 9) y + 1 else y; var new_flashes = false; var j: usize = start_y; while (j <= end_y) : (j += 1) { var i: usize = start_x; while (i <= end_x) : (i += 1) { if (grid[j][i] != 0) { grid[j][i] += 1; if (grid[j][i] > 9) { new_flashes = true; } } } } return new_flashes; } //-------------------------------------------------------------------------------------------------- pub fn perform_flashes(grid: *[10][10]u8) void { var new_flashes = true; while (new_flashes) { new_flashes = false; for (grid) |*row, y| { for (row.*) |*item, x| { if (item.* > 9) { item.* = 0; if (increment_adjacent(grid, x, y)) { new_flashes = true; } } } // x } // y } // while (new_flashes) } //-------------------------------------------------------------------------------------------------- pub fn count_flashed(grid: [10][10]u8) u32 { var sum: u32 = 0; for (grid) |row| { for (row) |item| { if (item == 0) { sum += 1; } } } return sum; } //-------------------------------------------------------------------------------------------------- pub fn part1() anyerror!void { const file = std.fs.cwd().openFile("data/day11_input.txt", .{}) catch |err| label: { std.debug.print("unable to open file: {e}\n", .{err}); const stderr = std.io.getStdErr(); break :label stderr; }; defer file.close(); var octopuses = [_][10]u8{.{0} ** 10} ** 10; { var reader = std.io.bufferedReader(file.reader()); var istream = reader.reader(); var buf: [10]u8 = undefined; var row: usize = 0; while (try istream.readUntilDelimiterOrEof(&buf, '\n')) |line| : (row += 1) { for (line) |char, col| { _ = char; octopuses[row][col] = std.fmt.parseInt(u8, buf[col .. col + 1], 10) catch 9; } } } var flashes: u32 = 0; var step: u32 = 0; while (step < 100) : (step += 1) { increment(&octopuses); perform_flashes(&octopuses); flashes += count_flashed(octopuses); } std.log.info("steps: {d}", .{step}); std.log.info("Part 1 flashes: {d}", .{flashes}); } //-------------------------------------------------------------------------------------------------- pub fn part2() anyerror!void { const file = std.fs.cwd().openFile("data/day11_input.txt", .{}) catch |err| label: { std.debug.print("unable to open file: {e}\n", .{err}); const stderr = std.io.getStdErr(); break :label stderr; }; defer file.close(); var octopuses = [_][10]u8{.{0} ** 10} ** 10; { var reader = std.io.bufferedReader(file.reader()); var istream = reader.reader(); var buf: [10]u8 = undefined; var row: usize = 0; while (try istream.readUntilDelimiterOrEof(&buf, '\n')) |line| : (row += 1) { for (line) |char, col| { _ = char; octopuses[row][col] = std.fmt.parseInt(u8, buf[col .. col + 1], 10) catch 9; } } } var step: u32 = 0; while (true) : (step += 1) { increment(&octopuses); perform_flashes(&octopuses); const flashes: u32 = count_flashed(octopuses); if (flashes == (10 * 10)) { step += 1; // Continuation won't happen if we break break; } } print(octopuses); std.log.info("Part 2 steps: {d}", .{step}); } //-------------------------------------------------------------------------------------------------- pub fn main() anyerror!void { try part1(); try part2(); } //--------------------------------------------------------------------------------------------------
src/day11.zig
const std = @import("std"); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const alloc = &gpa.allocator; const PassportCheck = struct { byr: bool = false, iyr: bool = false, eyr: bool = false, hgt: bool = false, hcl: bool = false, ecl: bool = false, pid: bool = false, //cid: bool = false, optional pub fn valid(p: *PassportCheck) bool { return p.byr and p.iyr and p.eyr and p.hgt and p.hcl and p.ecl and p.pid; } }; pub fn main() !void { defer _ = gpa.deinit(); const inputData = try std.fs.cwd().readFileAlloc(alloc, "input", std.math.maxInt(u64)); defer alloc.free(inputData); const valid_p1 = part1(inputData); const valid_p2 = part2(inputData); std.debug.print("p1 {}\n", .{valid_p1}); std.debug.print("p2 {}\n", .{valid_p2}); } fn part1(inputData: []const u8) usize { var it = std.mem.split(inputData, "\n"); var cur_passport = PassportCheck{}; var count: usize = 0; while (it.next()) |line| { if (line.len == 0) { if (cur_passport.valid()) { count += 1; } cur_passport = PassportCheck{}; } var field_it = std.mem.tokenize(line, " "); while (field_it.next()) |field| { var kv_it = std.mem.split(field, ":"); const key = kv_it.next().?; if (std.mem.eql(u8, key, "byr")) { cur_passport.byr = true; } else if (std.mem.eql(u8, key, "iyr")) { cur_passport.iyr = true; } else if (std.mem.eql(u8, key, "eyr")) { cur_passport.eyr = true; } else if (std.mem.eql(u8, key, "hgt")) { cur_passport.hgt = true; } else if (std.mem.eql(u8, key, "hcl")) { cur_passport.hcl = true; } else if (std.mem.eql(u8, key, "ecl")) { cur_passport.ecl = true; } else if (std.mem.eql(u8, key, "pid")) { cur_passport.pid = true; } else if (std.mem.eql(u8, key, "cid")) {} else { @panic("Unknown field"); } } } return count; } fn part2(inputData: []const u8) !usize { var it = std.mem.split(inputData, "\n"); var cur_passport = PassportCheck{}; var count: usize = 0; while (it.next()) |line| { if (line.len == 0) { if (cur_passport.valid()) { count += 1; } cur_passport = PassportCheck{}; } var field_it = std.mem.tokenize(line, " "); while (field_it.next()) |field| { var kv_it = std.mem.split(field, ":"); const key = kv_it.next().?; const value = kv_it.next().?; if (std.mem.eql(u8, key, "byr")) { if (value.len != 4) { continue; } const year = try std.fmt.parseInt(usize, value, 10); cur_passport.byr = year >= 1920 and year <= 2002; } else if (std.mem.eql(u8, key, "iyr")) { if (value.len != 4) { continue; } const year = try std.fmt.parseInt(usize, value, 10); cur_passport.iyr = year >= 2010 and year <= 2020; } else if (std.mem.eql(u8, key, "eyr")) { if (value.len != 4) { continue; } const year = try std.fmt.parseInt(usize, value, 10); cur_passport.eyr = year >= 2020 and year <= 2030; } else if (std.mem.eql(u8, key, "hgt")) { if (value.len == 0) { continue; } var p: usize = 0; while (p < value.len and value[p] >= '0' and value[p] <= '9') { p += 1; } const height = try std.fmt.parseInt(usize, value[0..p], 10); if (std.mem.eql(u8, value[p..], "cm")) { cur_passport.hgt = height >= 150 and height <= 193; } else if (std.mem.eql(u8, value[p..], "in")) { cur_passport.hgt = height >= 59 and height <= 76; } else { continue; } } else if (std.mem.eql(u8, key, "hcl")) { if (value.len == 0) { continue; } const starts_with_hash = value[0] == '#'; if (value[1..].len != 6) { continue; } var valid: bool = true; for (value[1..]) |c| { valid = valid and (c >= 'a' and c <= 'f') or (c >= '0' and c <= '9'); } cur_passport.hcl = starts_with_hash and valid; } else if (std.mem.eql(u8, key, "ecl")) { const valid_colors = [_][]const u8{ "amb", "blu", "brn", "gry", "grn", "hzl", "oth" }; var valid: bool = false; for (valid_colors) |color| { valid = valid or std.mem.eql(u8, value, color); } cur_passport.ecl = valid; } else if (std.mem.eql(u8, key, "pid")) { if (value.len != 9) { continue; } var valid: bool = true; for (value) |d| { valid = valid and (d >= '0' and d <= '9'); } cur_passport.pid = valid; } else if (std.mem.eql(u8, key, "cid")) {} else { @panic("Unknown field"); } } } return count; }
Day4/day4.zig
const std = @import("std"); const c = @import("../../c_global.zig").c_imp; // dross-zig const Vector2 = @import("../../core/vector2.zig").Vector2; const tx = @import("../texture.zig"); const Texture = tx.Texture; // ----------------------------------------------------------------------------- // ----------------------------------------- // - FrameStatistics - // ----------------------------------------- var stats: ?*FrameStatistics = undefined; pub const FrameStatistics = struct { /// The total time taken to process a frame (in ms) frame_time: f64 = -1.0, /// The total time taken to draw (in ms) draw_time: f64 = -1.0, /// The total time the user-defined update function takes (in ms) update_time: f64 = -1.0, /// The number of quads being renderered quad_count: i64 = -1.0, /// The number of draw calls per frame draw_calls: i64 = -1.0, const Self = @This(); /// Creates a new instance of FrameStatistics. /// Comments: The memory allocated will be engine-owned. pub fn new(allocator: *std.mem.Allocator) !void { stats = try allocator.create(FrameStatistics); stats.?.frame_time = -1.0; stats.?.draw_time = -1.0; stats.?.update_time = -1.0; } /// Cleans up and de-allocates if a FrameStatistics instance exists. pub fn free(allocator: *std.mem.Allocator) void { allocator.destroy(stats.?); } /// Sets the frame time pub fn setFrameTime(new_time: f64) void { stats.?.frame_time = new_time; } /// Returns the currently stored frame time pub fn frameTime() f64 { return stats.?.frame_time; } /// Sets the draw time pub fn setDrawTime(new_time: f64) void { stats.?.draw_time = new_time; } /// Returns the currently stored draw time pub fn drawTime() f64 { return stats.?.draw_time; } /// Sets the update time pub fn setUpdateTime(new_time: f64) void { stats.?.update_time = new_time; } /// Returns the currently stored update time pub fn updateTime() f64 { return stats.?.update_time; } /// Returns the total numbert of draw calls recorded for the frame pub fn drawCalls() i64 { return stats.?.draw_calls; } /// Returns the total of quads being renderered pub fn quadCount() i64 { return stats.?.quad_count; } /// Returns the total vertex count being drawn pub fn vertexCount() i64 { return stats.?.quad_count * 4; } /// Returns the total index count being drawn pub fn indexCount() i64 { return stats.?.quad_count * 6; } /// Resets the frame statistics: /// `quad_count` /// `draw_calls` pub fn reset() void { stats.?.quad_count = 0; stats.?.draw_calls = 0; } /// Increments the quad count. pub fn incrementQuadCount() void { stats.?.quad_count += 1; } /// Increments the draw call count. pub fn incrementDrawCall() void { stats.?.draw_calls += 1; } /// Debug prints all of the stats pub fn display() void { std.debug.print("[Timer]Frame: {d:5} ms\n", .{stats.?.frame_time}); //std.debug.print("[Timer]User Update: {d:5} ms\n", .{stats.?.update_time}); //std.debug.print("[Timer]Draw: {d:5} ms\n", .{stats.?.draw_time}); //std.debug.print("[Timer]Draw Calls: {}\n", .{stats.?.draw_calls}); //std.debug.print("[Timer]Quad Count: {}\n", .{stats.?.quad_count}); } };
src/utils/profiling/frame_statistics.zig
const DEBUGMODE = @import("builtin").mode == @import("builtin").Mode.Debug; const std = @import("std"); const sg = @import("sokol").gfx; const sapp = @import("sokol").app; const stime = @import("sokol").time; const sgapp = @import("sokol").app_gfx_glue; const sdtx = @import("sokol").debugtext; const sa = @import("sokol").audio; const formats = @import("fileformats"); const PNG = formats.Png; const map = @import("level.zig"); const fs = @import("fs"); const math = @import("math.zig"); const shd = @import("shaders/main.zig"); const errhandler = @import("errorhandler.zig"); const TILE_WIDTH = 8; const TILE_HEIGHT = 8; const ACTOR_WIDTH = 16; const ACTOR_HEIGHT = 16; var camera: map.Vec3 = .{ .z = 3 }; pub fn getCamera() *map.Vec3 { return &camera; } //////////////////////////////////////////////////////////////////////////////////////////////// pub fn times(n: isize) callconv(.Inline) []const void { // Thanks shake return @as([*]void, undefined)[0..@intCast(usize, n)]; } pub const Texture = struct { sktexture: sg.Image, width: u32, height: u32, pub fn fromRaw(data: anytype, width: u32, height: u32) Texture { var img_desc: sg.ImageDesc = .{ .width = @intCast(i32, width), .height = @intCast(i32, height) }; img_desc.data.subimage[0][0] = sg.asRange(data); return Texture{ .sktexture = sg.makeImage(img_desc), .width = width, .height = height, }; } pub fn fromPNGPath(filename: [:0]const u8) !Texture { var pngdata = try PNG.fromFile(filename); var img_desc: sg.ImageDesc = .{ .width = @intCast(i32, pngdata.width), .height = @intCast(i32, pngdata.height), }; img_desc.data.subimage[0][0] = sg.asRange(pngdata.raw); return Texture{ .sktexture = sg.makeImage(img_desc), .width = pngdata.width, .height = pngdata.height, }; } }; //////////////////////////////////////////////////////////////////////////////////////////////// const Vertex = packed struct { x: f32 = 0, y: f32 = 0, z: f32 = 0, color: u32 = 0xFFFFFFFF, u: i16, v: i16 }; var pass_action: sg.PassAction = .{}; var tile_pip: sg.Pipeline = .{}; var actor_pip: sg.Pipeline = .{}; var bind: sg.Bindings = .{}; var GPA = std.heap.GeneralPurposeAllocator(.{}){}; var tilelist = std.ArrayList(Tile).init(&GPA.allocator); var WorldStream: std.json.TokenStream = undefined; var cworld: map.World = undefined; var clevel: map.Level = undefined; var tileset: Texture = undefined; var actorset: Texture = undefined; const mapdata = @embedFile("../maps/test.mh.map"); export fn audio(a: [*c]f32, b: i32, c: i32) void {} export fn init() void { sa.setup(.{ .stream_cb = audio, .num_channels = 2 }); fs.init(); sg.setup(.{ .context = sgapp.context() }); pass_action.colors[0] = .{ .action = .CLEAR, .value = .{ .r = 0.08, .g = 0.08, .b = 0.11, .a = 1.0 }, // HELLO EIGENGRAU! }; tileset = Texture.fromPNGPath("sprites/test.png") catch { @panic("Unable to load Tileset."); }; actorset = Texture.fromPNGPath("sprites/actor.png") catch { @panic("Unable to load actor Tileset."); }; const QuadVertices = [4]Vertex{ .{ .x = 2, .y = 0, .u = 6553, .v = 6553 }, .{ .x = 2, .y = 2, .u = 6553, .v = 0 }, .{ .x = 0, .y = 2, .u = 0, .v = 0 }, .{ .x = 0, .y = 0, .u = 0, .v = 6553 }, }; const QuadIndices = [6]u16{ 0, 1, 3, 1, 2, 3 }; bind.vertex_buffers[0] = sg.makeBuffer(.{ .data = sg.asRange(QuadVertices) }); bind.index_buffer = sg.makeBuffer(.{ .type = .INDEXBUFFER, .data = sg.asRange(QuadIndices), }); ///////////////////////////////////////////////////////////////////////// var tile_pip_desc: sg.PipelineDesc = .{ .shader = sg.makeShader(shd.mainShaderDesc(sg.queryBackend())), .index_type = .UINT16, .cull_mode = .FRONT, .depth = .{ .compare = .LESS_EQUAL, .write_enabled = true, }, }; tile_pip_desc.colors[0].blend = .{ .enabled = true, .src_factor_rgb = .SRC_ALPHA, .dst_factor_rgb = .ONE_MINUS_SRC_ALPHA, .src_factor_alpha = .SRC_ALPHA, .dst_factor_alpha = .ONE_MINUS_SRC_ALPHA, }; tile_pip_desc.layout.attrs[shd.ATTR_vs_pos].format = .FLOAT3; tile_pip_desc.layout.attrs[shd.ATTR_vs_color0].format = .UBYTE4N; tile_pip_desc.layout.attrs[shd.ATTR_vs_texcoord0].format = .SHORT2N; tile_pip = sg.makePipeline(tile_pip_desc); /////////////////////////////////////////////////////////////////////////// var actor_pip_desc: sg.PipelineDesc = .{ .shader = sg.makeShader(shd.mainShaderDesc(sg.queryBackend())), .index_type = .UINT16, .cull_mode = .NONE, .depth = .{ .compare = .LESS_EQUAL, .write_enabled = true, }, }; actor_pip_desc.colors[0].blend = .{ .enabled = true, .src_factor_rgb = .SRC_ALPHA, .dst_factor_rgb = .ONE_MINUS_SRC_ALPHA, .src_factor_alpha = .SRC_ALPHA, .dst_factor_alpha = .ONE_MINUS_SRC_ALPHA, }; actor_pip_desc.layout.attrs[shd.ATTR_vs_pos].format = .FLOAT3; actor_pip_desc.layout.attrs[shd.ATTR_vs_color0].format = .UBYTE4N; actor_pip_desc.layout.attrs[shd.ATTR_vs_texcoord0].format = .SHORT2N; actor_pip = sg.makePipeline(actor_pip_desc); /////////////////////////////////////////////////////////////////////////// stime.setup(); cworld = map.loadMap(mapdata) catch @panic("Error loading world :("); clevel = cworld.levels[0]; if (comptime DEBUGMODE) { var sdtx_desc: sdtx.Desc = .{}; sdtx_desc.fonts[0] = @import("fontdata.zig").fontdesc; sdtx.setup(sdtx_desc); sdtx.font(0); } } //////////////////////////////////////////////////////////////////////////////////////////////// var screenWidth: f32 = 0; var screenHeight: f32 = 0; var delta: f32 = 0; var last_time: u64 = 0; pub fn i2f(int: anytype) callconv(.Inline) f32 { // I added this function for pure convenience return @intToFloat(f32, int); // It shouldnt affect runtime performance } export fn frame() void { screenWidth = sapp.widthf(); screenHeight = sapp.heightf(); if (comptime DEBUGMODE) { sdtx.canvas(screenWidth * 0.5, screenHeight * 0.5); sdtx.origin(1, 1); sdtx.color1i(0xFFAA67C7); sdtx.print("m e t a h o m e : ---------------------------------\n\n", .{}); sdtx.color1i(0xFFFFAE00); sdtx.print("hello again! =)\nwelcome to my little side-project!\n\n", .{}); sdtx.print("use the ARROW KEYS to move spriteboy\n", .{}); sdtx.print("use Z to display collision boxes\n", .{}); } sg.beginDefaultPass(pass_action, sapp.width(), sapp.height()); // RENDER TILES //////////////////////////////////////////////////////////////////////////// bind.fs_images[shd.SLOT_tex] = tileset.sktexture; sg.applyPipeline(tile_pip); sg.applyBindings(bind); var TILE_ROWS = i2f(tileset.width) / TILE_WIDTH; var TILE_COLUMNS = i2f(tileset.height) / TILE_HEIGHT; for (clevel.tiles) |tile| { const scale = math.Mat4.scale((TILE_WIDTH * camera.z) / screenWidth, (TILE_HEIGHT * camera.z) / screenHeight, 1); const trans = math.Mat4.translate(.{ .x = ((i2f(tile.x) * 2 * camera.z) - (camera.x * 2 * camera.z)) / screenWidth, .y = ((i2f(tile.y) * 2 * camera.z) - (camera.y * 2 * camera.z)) / -screenHeight, .z = 0, }); sg.applyUniforms(.FS, shd.SLOT_fs_params, sg.asRange(shd.FsParams{ .globalcolor = .{ 0.4, 0.5, 0.6, 1 }, .cropping = .{ TILE_WIDTH / i2f(tileset.width), TILE_HEIGHT / i2f(tileset.height), i2f(tile.spr.x) / i2f(tileset.width), i2f(tile.spr.y) / i2f(tileset.height), }, })); if (keys.attack and tile.collide) { sg.applyUniforms(.FS, shd.SLOT_fs_params, sg.asRange(shd.FsParams{ .globalcolor = .{ 0.6, 0.5, 0.8, 1 }, .cropping = .{ TILE_WIDTH / i2f(tileset.width), TILE_HEIGHT / i2f(tileset.height), 0.0, 0.0, }, })); } sg.applyUniforms(.VS, shd.SLOT_vs_params, sg.asRange(shd.VsParams{ .mvp = math.Mat4.mul(trans, scale) })); sg.draw(0, 6, 1); } bind.fs_images[shd.SLOT_tex] = actorset.sktexture; sg.applyPipeline(actor_pip); sg.applyBindings(bind); for (clevel.actors) |*actor| { if (actor.process) { switch (actor.kind) { .Player => actor.processPlayer(delta), else => {}, } actor.pos.x += actor.vel.x * delta; actor.pos.y += actor.vel.y * delta; } if (actor.visible) { var flip_x: f32 = if (actor.flip_x) -1 else 1; var flip_y: f32 = if (actor.flip_y) -1 else 1; var offs_x: f32 = if (actor.flip_x) i2f(ACTOR_WIDTH) else 0; var offs_y: f32 = if (actor.flip_y) i2f(ACTOR_HEIGHT) else 0; const scale = math.Mat4.scale((ACTOR_WIDTH * camera.z * flip_x) / screenWidth, (ACTOR_HEIGHT * camera.z * flip_y) / screenHeight, 5); const trans = math.Mat4.translate(.{ .x = (((actor.pos.x + offs_x) * 2 * camera.z) - (camera.x * 2 * camera.z)) / screenWidth, .y = (((actor.pos.y + offs_y) * 2 * camera.z) - (camera.y * 2 * camera.z)) / -screenHeight, .z = 0, }); sg.applyUniforms(.FS, shd.SLOT_fs_params, sg.asRange(shd.FsParams{ .globalcolor = .{ 1, 1, 1, 1 }, .cropping = .{ i2f(ACTOR_WIDTH) / i2f(actorset.width), i2f(ACTOR_HEIGHT) / i2f(actorset.height), (i2f(actor.spr.x) * i2f(ACTOR_WIDTH)) / i2f(actorset.width), (i2f(actor.spr.y) * i2f(ACTOR_HEIGHT)) / i2f(actorset.height), }, })); sg.applyUniforms(.VS, shd.SLOT_vs_params, sg.asRange(shd.VsParams{ .mvp = math.Mat4.mul(trans, scale) })); sg.draw(0, 6, 1); } } if (comptime DEBUGMODE) { sdtx.draw(); } sg.endPass(); sg.commit(); delta = @floatCast(f32, stime.sec(stime.laptime(&last_time))); } //////////////////////////////////////////////////////////////////////////////////////////////// const _keystruct = struct { up: bool = false, down: bool = false, left: bool = false, right: bool = false, attack: bool = false, any: bool = false, home: bool = false, }; var keys = _keystruct{}; const _mousestruct = struct { x: f32 = 0, y: f32 = 0, dx: f32 = 0, dy: f32 = 0, left: bool = false, middle: bool = false, right: bool = false, any: bool = false, }; var mouse = _mousestruct{}; export fn input(ev: ?*const sapp.Event) void { const event = ev.?; if ((event.type == .KEY_DOWN) or (event.type == .KEY_UP)) { const key_pressed = event.type == .KEY_DOWN; keys.any = key_pressed; switch (event.key_code) { .UP => keys.up = key_pressed, .DOWN => keys.down = key_pressed, .LEFT => keys.left = key_pressed, .RIGHT => keys.right = key_pressed, .Z => keys.attack = key_pressed, .BACKSPACE => keys.home = key_pressed, else => {}, } } else if ((event.type == .MOUSE_DOWN) or (event.type == .MOUSE_UP)) { const mouse_pressed = event.type == .MOUSE_DOWN; mouse.any = mouse_pressed; switch (event.mouse_button) { .LEFT => mouse.left = mouse_pressed, .MIDDLE => mouse.middle = mouse_pressed, .RIGHT => mouse.right = mouse_pressed, else => {}, } } else if (event.type == .MOUSE_MOVE) { mouse.x = event.mouse_x; mouse.y = event.mouse_y; mouse.dx = event.mouse_dx; mouse.dy = event.mouse_dy; } } pub fn getKeys() *_keystruct { return &keys; } //////////////////////////////////////////////////////////////////////////////////////////////// pub fn main() void { sapp.run(.{ .init_cb = init, .frame_cb = frame, .cleanup_cb = cleanup, .event_cb = input, .fail_cb = fail, .width = 1024, .height = 600, .window_title = "m e t a h o m e", }); } //////////////////////////////////////////////////////////////////////////////////////////////// export fn cleanup() void { sg.shutdown(); sa.shutdown(); _ = fs.deinit(); var leaked = GPA.deinit(); } export fn fail(err: [*c]const u8) callconv(.C) void { errhandler.handle(err); }
src/main.zig
const c = @import("c.zig"); const utils = @import("utils.zig"); const std = @import("std"); usingnamespace @import("log.zig"); // zig fmt: off pub const Load = struct { pub const default = 0x0; pub const no_scale = 1 << 0; pub const no_hinting = 1 << 1; pub const render = 1 << 2; pub const no_bitmap = 1 << 3; // .. https://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#ft_load_xxx }; // zig fmt: on pub const Library = struct { base: c.FT_Library = undefined, pub fn init(ft: *Library) utils.Error!void { try utils.check(c.FT_Init_FreeType(@ptrCast(?*c.FT_Library, &ft.base)) != 0, "kira/ft2 -> could not initialize freetype2!", .{}); } pub fn deinit(ft: Library) utils.Error!void { try utils.check(c.FT_Done_FreeType(ft.base) != 0, "kira/ft2 -> failed to deinitialize freetype2!", .{}); } }; pub const Face = struct { base: c.FT_Face = undefined, pub fn new(lib: Library, path: []const u8, face_index: i32) utils.Error!Face { var result = Face{}; try utils.check(c.FT_New_Face(lib.base, @ptrCast([*c]const u8, path), face_index, @ptrCast(?*c.FT_Face, &result.base)) != 0, "kira/ft2 -> failed to load ft2 face from path!", .{}); return result; } pub fn newMemory(lib: Library, mem: []const u8, face_index: i32) utils.Error!Face { var result = Face{}; try utils.check(c.FT_New_Memory_Face(lib.base, @ptrCast([*c]const u8, mem), mem.len, face_index, @ptrCast(?*c.FT_Face, &result.base)) != 0, "kira/ft2 -> failed to load ft2 face from memory!", .{}); return result; } pub fn destroy(self: Face) utils.Error!void { try utils.check(c.FT_Done_Face(self.base) != 0, "kira/ft2 -> failed to destroy face!", .{}); } pub fn setPixelSizes(self: Face, width: u32, height: u32) utils.Error!void { try utils.check(c.FT_Set_Pixel_Sizes(self.base, width, height) != 0, "kira/ft -> failed to set pixel sizes!", .{}); } pub fn loadChar(self: Face, char_code: u64, load_flags: i32) utils.Error!void { try utils.check(c.FT_Load_Char(self.base, char_code, load_flags) == 1, "kira/ft -> failed to load char information from face!", .{}); } };
src/kiragine/kira/freetype2.zig
const std = @import("std"); const sfml = @import("sfml.zig"); const system = @import("system.zig"); pub const c = @cImport({ @cInclude("SFML/Window.h"); }); fn cStringLength(buffer: anytype) usize { var len: usize = 0; while (buffer[len] != 0) : (len += 1) {} return len; } pub const clipboard = struct { pub fn getString() []const u8 { const string = c.sfClipboard_getString(); return string[0..cStringLength(string)]; } pub fn getUnicodeString() []const u32 { const string = @ptrCast([*]const u32, c.sfClipboard_getUnicodeString()); return string[0..cStringLength(string)]; } pub fn setString(s: [:0]const u8) void { c.sfClipboard_setString(s.ptr); } pub fn setStringAlloc(s: []const u8) !void { const str = try sfml.allocator.dupeZ(u8, s); defer sfml.allocator.free(str); setString(str); } pub fn setUnicodeString(s: [:0]const u32) void { c.sfClipboard_setUnicodeString(s.ptr); } pub fn setUnicodeStringAlloc(s: []const u32) !void { const str = try sfml.allocator.dupeZ(u32, s); defer sfml.allocator.free(str); setUnicodeString(str); } }; pub const keyboard = struct { pub const Key = extern enum(c_int) { unknown = c.sfKeyUnknown, a = c.sfKeyA, b = c.sfKeyB, c = c.sfKeyC, d = c.sfKeyD, e = c.sfKeyE, f = c.sfKeyF, g = c.sfKeyG, h = c.sfKeyH, i = c.sfKeyI, j = c.sfKeyJ, k = c.sfKeyK, l = c.sfKeyL, m = c.sfKeyM, n = c.sfKeyN, o = c.sfKeyO, p = c.sfKeyP, q = c.sfKeyQ, r = c.sfKeyR, s = c.sfKeyS, t = c.sfKeyT, u = c.sfKeyU, v = c.sfKeyV, w = c.sfKeyW, x = c.sfKeyX, y = c.sfKeyY, z = c.sfKeyZ, num0 = c.sfKeyNum0, num1 = c.sfKeyNum1, num2 = c.sfKeyNum2, num3 = c.sfKeyNum3, num4 = c.sfKeyNum4, num5 = c.sfKeyNum5, num6 = c.sfKeyNum6, num7 = c.sfKeyNum7, num8 = c.sfKeyNum8, num9 = c.sfKeyNum9, escape = c.sfKeyEscape, left_control = c.sfKeyLControl, left_shift = c.sfKeyLShift, left_alt = c.sfKeyLAlt, left_system = c.sfKeyLSystem, right_control = c.sfKeyRControl, right_shift = c.sfKeyRShift, right_alt = c.sfKeyRAlt, right_system = c.sfKeyRSystem, menu = c.sfKeyMenu, left_bracket = c.sfKeyLBracket, right_bracket = c.sfKeyRBracket, semicolon = c.sfKeySemicolon, comma = c.sfKeyComma, period = c.sfKeyPeriod, quote = c.sfKeyQuote, slash = c.sfKeySlash, backslash = c.sfKeyBackslash, tilde = c.sfKeyTilde, equal = c.sfKeyEqual, hyphen = c.sfKeyHyphen, space = c.sfKeySpace, enter = c.sfKeyEnter, backspace = c.sfKeyBackspace, tab = c.sfKeyTab, page_up = c.sfKeyPageUp, page_down = c.sfKeyPageDown, end = c.sfKeyEnd, home = c.sfKeyHome, insert = c.sfKeyInsert, delete = c.sfKeyDelete, add = c.sfKeyAdd, subtract = c.sfKeySubtract, multiply = c.sfKeyMultiply, divide = c.sfKeyDivide, left = c.sfKeyLeft, right = c.sfKeyRight, up = c.sfKeyUp, down = c.sfKeyDown, numpad0 = c.sfKeyNumpad0, numpad1 = c.sfKeyNumpad1, numpad2 = c.sfKeyNumpad2, numpad3 = c.sfKeyNumpad3, numpad4 = c.sfKeyNumpad4, numpad5 = c.sfKeyNumpad5, numpad6 = c.sfKeyNumpad6, numpad7 = c.sfKeyNumpad7, numpad8 = c.sfKeyNumpad8, numpad9 = c.sfKeyNumpad9, f1 = c.sfKeyF1, f2 = c.sfKeyF2, f3 = c.sfKeyF3, f4 = c.sfKeyF4, f5 = c.sfKeyF5, f6 = c.sfKeyF6, f7 = c.sfKeyF7, f8 = c.sfKeyF8, f9 = c.sfKeyF9, f10 = c.sfKeyF10, f11 = c.sfKeyF11, f12 = c.sfKeyF12, f13 = c.sfKeyF13, f14 = c.sfKeyF14, f15 = c.sfKeyF15, pause = c.sfKeyPause, count = c.sfKeyCount, pub fn toCSFML(self: Key) c.sfKeyCode { return @intToEnum(c.sfKeyCode, @enumToInt(self)); } pub fn fromCSFML(other: c.sfKeyCode) Key { return @intToEnum(Key, @enumToInt(other)); } }; pub fn isKeyPressed(key: Key) bool { return c.sfKeyboard_isKeyPressed(key.toCSFML()) == c.sfTrue; } pub fn setVirtualKeyboardVisible(visible: bool) void { c.sfKeyboard_setVirtualKeyboardVisible(@boolToInt(visible)); } }; pub const mouse = struct { pub const Button = extern enum(c_int) { left = c.sfMouseLeft, right = c.sfMouseRight, middle = c.sfMouseMiddle, x_button1 = c.sfMouseXButton1, x_button2 = c.sfMouseXButton2, pub fn toCSFML(self: Button) c.sfMouseButton { return @intToEnum(c.sfMouseButton, @enumToInt(self)); } pub fn fromCSFML(other: c.sfMouseButton) Button { return @intToEnum(Button, @enumToInt(other)); } }; pub const Wheel = extern enum(c_int) { vertical_wheel = c.sfMouseVerticalWheel, horizontal_wheel = c.sfMouseHorizontalWheel, pub fn toCSFML(self: Wheel) c.sfMouseWheel { return @intToEnum(c.sfMouseWheel, @enumToInt(self)); } pub fn fromCSFML(other: c.sfMouseWheel) Wheel { return @intToEnum(Wheel, @enumToInt(other)); } }; pub fn isButtonPressed(button: Button) bool { return c.sfMouse_isButtonPressed(button.toCSFML()) == c.sfTrue; } pub fn getPosition(relative_to: ?*const Window) system.Vector2i { return c.sfMouse_getPosition(relative_to.internal); } pub fn setPosition(position: system.Vector2i, relative_to: ?*const Window) void { c.sfMouse_setPosition(position, relative_to.internal); } }; pub const joystick = struct { pub const count = c.sfJoystickCount; pub const button_count = c.sfJoystickButtonCount; pub const axis_count = c.sfJoystickAxisCount; pub const Axis = extern enum(c_int) { x = c.sfJoystickX, y = c.sfJoystickY, z = c.sfJoystickZ, r = c.sfJoystickR, u = c.sfJoystickU, v = c.sfJoystickV, pov_x = c.sfJoystickPovX, pov_y = c.sfJoystickPovY, pub fn toCSFML(self: Axis) c.sfJoystickAxis { return @intToEnum(c.sfJoystickAxis, @enumToInt(self)); } pub fn fromCSFML(other: c.sfJoystickAxis) Axis { return @intToEnum(Axis, @enumToInt(other)); } }; pub const Identification = struct { name: []const u8, vendor_id: u32, product_id: u32, pub fn fromCSFML(csfml: c.sfJoystickIdentification) JoystickIdentification { return .{ .name = csfml.name[0..cStringLength(csfml.name)], .vendor_id = @intCast(u32, csfml.vendorId), .product_id = @intCast(u32, csfml.productId), }; } }; pub fn isConnected(id: u32) bool { return c.sfJoystick_isConnected(@intCast(c_uint, id)) == c.sfTrue; } pub fn getButtonCount(id: u32) u32 { return @intCast(u32, c.sfJoystick_getButtonCount(@intCast(c_uint, id))); } pub fn hasAxis(id: u32, axis: Axis) bool { return c.sfJoystick_hasAxis(@intCast(c_uint, id), axis.toCSFML()) == c.sfTrue; } pub fn isButtonPressed(id: u32, button: u32) bool { return c.sfJoystick_isButtonPressed(@intCast(c_uint, id)) == c.sfTrue; } pub fn getAxisPosition(id: u32, axis: Axis) f32 { return c.sfJoystick_getAxisPosition(@intCast(c_uint, id), axis.toCSFML()); } pub fn getIdentification(id: u32) Identification { return Identification.fromCSFML(c.sfJoystick_getIdentification(@intCast(c_uint, id))); } pub fn update() void { c.sfJoystick_update(); } }; pub const sensor = struct { pub const SensorType = extern enum(c_int) { accelerometer = c.sfSensorAccelerometer, gyroscope = c.sfSensorGyroscope, magnetometer = c.sfSensorMagnetometer, gravity = c.sfSensorGravity, user_acceleration = c.sfSensorUserAcceleration, sensor_orientation = c.sfSensorOrientation, pub fn toCSFML(self: SensorType) c.sfSensorType { return @intToEnum(c.sfSensorType, @enumToInt(self)); } pub fn fromCSFML(other: c.sfSensorType) SensorType { return @intToEnum(SensorType, @enumToInt(other)); } }; pub const count = std.meta.fields(SensorType).len; pub fn isAvailable(sens: SensorType) bool { return c.sfSensor_isAvailable(sens.toCSFML()); } pub fn setEnabled(sens: SensorType, enabled: bool) void { c.sfSensor_setEnabled(sens.toCSFML(), @boolToInt(enabled)); } pub fn getValue(sens: SensorType) system.sfVector3f { return c.sfSensor_getValue(sens.toCSFML()); } }; pub const touch = struct { pub fn isDown(finger: u32) bool { return c.sfTouch_isDown(@intCast(c_uint, finger)) == c.sfTrue; } pub fn getPosition(finger: u32, relative_to: *const Window) system.Vector2i { return c.sfTouch_getPosition(@intCast(c_uint, finger), relative_to.internal); } }; pub const event = struct { pub const EventType = extern enum(c_int) { closed = c.sfEvtClosed, resized = c.sfEvtResized, lost_focus = c.sfEvtLostFocus, gained_focus = c.sfEvtGainedFocus, text_entered = c.sfEvtTextEntered, key_pressed = c.sfEvtKeyPressed, key_released = c.sfEvtKeyReleased, mouse_wheel_scrolled = c.sfEvtMouseWheelScrolled, mouse_button_pressed = c.sfEvtMouseButtonPressed, mouse_button_released = c.sfEvtMouseButtonReleased, mouse_moved = c.sfEvtMouseMoved, mouse_entered = c.sfEvtMouseEntered, mouse_left = c.sfEvtMouseLeft, joystick_button_pressed = c.sfEvtJoystickButtonPressed, joystick_button_released = c.sfEvtJoystickButtonReleased, joystick_moved = c.sfEvtJoystickMoved, joystick_connected = c.sfEvtJoystickConnected, joystick_disconnected = c.sfEvtJoystickDisconnected, touch_began = c.sfEvtTouchBegan, touch_moved = c.sfEvtTouchMoved, touch_ended = c.sfEvtTouchEnded, sensor_changed = c.sfEvtSensorChanged, pub fn toCSFML(self: EventType) c.sfEventType { return @intToEnum(c.sfEventType, @enumToInt(self)); } pub fn fromCSFML(evt: c.sfEventType) EventType { if (evt == @intToEnum(c.sfEventType, c.sfEvtMouseWheelMoved)) { @panic("sf::Event::MouseWheelEvent (sfMouseWheelEvent) unsupported"); } return @intToEnum(EventType, @enumToInt(evt)); } }; pub const KeyEvent = struct { code: keyboard.Key, alt: bool, control: bool, shift: bool, system: bool, pub fn fromCSFML(csfml: c.sfKeyEvent) KeyEvent { return .{ .code = keyboard.Key.fromCSFML(csfml.code), .alt = csfml.alt == c.sfTrue, .control = csfml.control == c.sfTrue, .shift = csfml.shift == c.sfTrue, .system = csfml.system == c.sfTrue, }; } pub fn toCSFML(self: KeyEvent, evt_type: c.sfEventType) c.sfKeyEvent { return .{ .@"type" = evt_type, .code = self.code.toCSFML(), .alt = if (self.alt) c.sfTrue else c.sfFalse, .control = if (self.control) c.sfTrue else c.sfFalse, .shift = if (self.shift) c.sfTrue else c.sfFalse, .system = if (self.system) c.sfTrue else c.sfFalse, }; } }; pub const TextEvent = struct { unicode: u32, pub fn fromCSFML(csfml: c.sfTextEvent) TextEvent { return .{ .unicode = @intCast(u32, csfml.unicode), }; } pub fn toCSFML(self: TextEvent, evt_type: c.sfEventType) c.sfTextEvent { return .{ .@"type" = evt_type, .unicode = self.unicode, }; } }; pub const MouseMoveEvent = struct { x: i32, y: i32, pub fn fromCSFML(csfml: c.sfMouseMoveEvent) MouseMoveEvent { return .{ .x = @intCast(i32, csfml.x), .y = @intCast(i32, csfml.y), }; } pub fn toCSFML(self: MouseMoveEvent, evt_type: c.sfEventType) c.sfMouseMoveEvent { return .{ .@"type" = evt_type, .x = @intCast(c_int, self.x), .y = @intCast(c_int, self.y), }; } }; pub const MouseButtonEvent = struct { button: mouse.Button, x: i32, y: i32, pub fn fromCSFML(csfml: c.sfMouseButtonEvent) MouseButtonEvent { return .{ .button = mouse.Button.fromCSFML(csfml.button), .x = @intCast(i32, csfml.x), .y = @intCast(i32, csfml.y), }; } pub fn toCSFML(self: MouseButtonEvent, evt_type: c.sfEventType) c.sfMouseButtonEvent { return .{ .@"type" = evt_type, .button = self.button.toCSFML(), .x = @intCast(c_int, self.x), .y = @intCast(c_int, self.y), }; } }; pub const MouseWheelScrollEvent = struct { wheel: mouse.Wheel, delta: f32, x: i32, y: i32, pub fn fromCSFML(csfml: c.sfMouseWheelScrollEvent) MouseWheelScrollEvent { return .{ .wheel = mouse.Wheel.fromCSFML(csfml.wheel), .delta = csfml.delta, .x = @intCast(i32, csfml.x), .y = @intCast(i32, csfml.y), }; } pub fn toCSFML(self: MouseWheelScrollEvent, evt_type: c.sfEventType) c.sfMouseWheelScrollEvent { return .{ .@"type" = evt_type, .wheel = self.wheel.toCSFML(), .delta = self.delta, .x = @intCast(c_int, self.x), .y = @intCast(c_int, self.y), }; } }; pub const JoystickMoveEvent = struct { joystick_id: u32, axis: joystick.Axis, position: f32, pub fn fromCSFML(csfml: c.sfJoystickMoveEvent) JoystickMoveEvent { return .{ .joystick_id = @intCast(u32, csfml.joystickId), .axis = joystick.Axis.fromCSFML(csfml.axis), .position = csfml.position, }; } pub fn toCSFML(self: JoystickMoveEvent, evt_type: c.sfEventType) c.sfJoystickMoveEvent { return .{ .@"type" = evt_type, .joystickId = @intCast(c_uint, self.joystick_id), .axis = self.axis.toCSFML(), .position = self.position, }; } }; pub const JoystickButtonEvent = struct { joystick_id: u32, button: u32, pub fn fromCSFML(csfml: c.sfJoystickButtonEvent) JoystickButtonEvent { return .{ .joystick_id = @intCast(u32, csfml.joystickId), .button = @intCast(u32, csfml.button), }; } pub fn toCSFML(self: JoystickButtonEvent, evt_type: c.sfEventType) c.sfJoystickButtonEvent { return .{ .@"type" = evt_type, .joystickId = @intCast(c_uint, self.joystick_id), .button = @intCast(c_uint, self.button), }; } }; pub const JoystickConnectEvent = struct { joystick_id: u32, pub fn fromCSFML(csfml: c.sfJoystickConnectEvent) JoystickConnectEvent { return .{ .joystick_id = @intCast(u32, csfml.joystickId), }; } pub fn toCSFML(self: JoystickConnectEvent, evt_type: c.sfEventType) c.sfJoystickConnectEvent { return .{ .@"type" = evt_type, .joystickId = @intCast(c_uint, self.joystick_id), }; } }; pub const SizeEvent = struct { width: u32, height: u32, pub fn fromCSFML(csfml: c.sfSizeEvent) SizeEvent { return .{ .width = @intCast(u32, csfml.width), .height = @intCast(u32, csfml.height), }; } pub fn toCSFML(self: SizeEvent, evt_type: c.sfEventType) c.sfSizeEvent { return .{ .@"type" = evt_type, .width = @intCast(c_uint, self.width), .height = @intCast(c_uint, self.height), }; } }; pub const TouchEvent = struct { finger: u32, x: i32, y: i32, pub fn fromCSFML(csfml: c.sfTouchEvent) TouchEvent { return .{ .finger = @intCast(u32, csfml.finger), .x = @intCast(i32, csfml.x), .y = @intCast(i32, csfml.y), }; } pub fn toCSFML(self: TouchEvent, evt_type: c.sfEventType) c.sfTouchEvent { return .{ .@"type" = evt_type, .finger = @intCast(c_uint, self.finger), .x = @intCast(c_int, self.x), .y = @intCast(c_int, self.y), }; } }; pub const SensorEvent = struct { sensor_type: sensor.SensorType, x: f32, y: f32, z: f32, pub fn fromCSFML(csfml: c.sfSensorEvent) SensorEvent { return .{ .sensor_type = sensor.SensorType.fromCSFML(csfml.sensorType), .x = csfml.x, .y = csfml.y, .z = csfml.z, }; } pub fn toCSFML(self: SensorEvent, evt_type: c.sfEventType) c.sfSensorEvent { return .{ .@"type" = evt_type, .sensorType = self.sensor_type.toCSFML(), .x = self.x, .y = self.y, .z = self.z, }; } }; pub const Event = union(EventType) { closed: void, resized: SizeEvent, lost_focus: void, gained_focus: void, text_entered: TextEvent, key_pressed: KeyEvent, key_released: KeyEvent, mouse_wheel_scrolled: MouseWheelScrollEvent, mouse_button_pressed: MouseButtonEvent, mouse_button_released: MouseButtonEvent, mouse_moved: MouseMoveEvent, mouse_entered: void, mouse_left: void, joystick_button_pressed: JoystickButtonEvent, joystick_button_released: JoystickButtonEvent, joystick_moved: JoystickMoveEvent, joystick_connected: JoystickConnectEvent, joystick_disconnected: JoystickConnectEvent, touch_began: TouchEvent, touch_moved: TouchEvent, touch_ended: TouchEvent, sensor_changed: SensorEvent, pub fn fromCSFML(evt: c.sfEvent) Event { return switch (EventType.fromCSFML(evt.@"type")) { .closed => .{ .closed = {} }, .resized => .{ .resized = SizeEvent.fromCSFML(evt.size) }, .lost_focus => .{ .lost_focus = {} }, .gained_focus => .{ .gained_focus = {} }, .text_entered => .{ .text_entered = TextEvent.fromCSFML(evt.text) }, .key_pressed => .{ .key_pressed = KeyEvent.fromCSFML(evt.key) }, .key_released => .{ .key_released = KeyEvent.fromCSFML(evt.key) }, .mouse_wheel_scrolled => .{ .mouse_wheel_scrolled = MouseWheelScrollEvent.fromCSFML(evt.mouseWheelScroll) }, .mouse_button_pressed => .{ .mouse_button_pressed = MouseButtonEvent.fromCSFML(evt.mouseButton) }, .mouse_button_released => .{ .mouse_button_released = MouseButtonEvent.fromCSFML(evt.mouseButton) }, .mouse_moved => .{ .mouse_moved = MouseMoveEvent.fromCSFML(evt.mouseMove) }, .mouse_entered => .{ .mouse_entered = {} }, .mouse_left => .{ .mouse_left = {} }, .joystick_button_pressed => .{ .joystick_button_pressed = JoystickButtonEvent.fromCSFML(evt.joystickButton) }, .joystick_button_released => .{ .joystick_button_released = JoystickButtonEvent.fromCSFML(evt.joystickButton) }, .joystick_moved => .{ .joystick_moved = JoystickMoveEvent.fromCSFML(evt.joystickMove) }, .joystick_connected => .{ .joystick_connected = JoystickConnectEvent.fromCSFML(evt.joystickConnect) }, .joystick_disconnected => .{ .joystick_disconnected = JoystickConnectEvent.fromCSFML(evt.joystickConnect) }, .touch_began => .{ .touch_began = TouchEvent.fromCSFML(evt.touch) }, .touch_moved => .{ .touch_moved = TouchEvent.fromCSFML(evt.touch) }, .touch_ended => .{ .touch_ended = TouchEvent.fromCSFML(evt.touch) }, .sensor_changed => .{ .sensor_changed = SensorEvent.fromCSFML(evt.sensor) }, }; } pub fn toCSFML(self: Event) c.sfEvent { const evt_type = @as(EventType, self).toCSFML(); return switch (self) { .closed => .{ .@"type" = evt_type }, .lost_focus => .{ .@"type" = evt_type }, .gained_focus => .{ .@"type" = evt_type }, .mouse_entered => .{ .@"type" = evt_type }, .mouse_left => .{ .@"type" = evt_type }, .resized => |e| .{ .size = e.toCSFML(evt_type) }, .text_entered => |e| .{ .text = e.toCSFML(evt_type) }, .key_pressed => |e| .{ .key = e.toCSFML(evt_type) }, .key_released => |e| .{ .key = e.toCSFML(evt_type) }, .mouse_wheel_scrolled => |e| .{ .mouseWheelScroll = e.toCSFML(evt_type) }, .mouse_button_pressed => |e| .{ .mouseButton = e.toCSFML(evt_type) }, .mouse_button_released => |e| .{ .mouseButton = e.toCSFML(evt_type) }, .mouse_moved => |e| .{ .mouseMove = e.toCSFML(evt_type) }, .joystick_button_pressed => |e| .{ .joystickButton = e.toCSFML(evt_type) }, .joystick_button_released => |e| .{ .joystickButton = e.toCSFML(evt_type) }, .joystick_moved => |e| .{ .joystickMove = e.toCSFML(evt_type) }, .joystick_connected => |e| .{ .joystickConnect = e.toCSFML(evt_type) }, .joystick_disconnected => |e| .{ .joystickConnect = e.toCSFML(evt_type) }, .touch_began => |e| .{ .touch = e.toCSFML(evt_type) }, .touch_moved => |e| .{ .touch = e.toCSFML(evt_type) }, .touch_ended => |e| .{ .touch = e.toCSFML(evt_type) }, .sensor_changed => |e| .{ .sensor = e.toCSFML(evt_type) }, }; } }; }; pub const Context = struct { internal: *c.sfContext, pub fn create() !Context { return Context{ .internal = c.sfContext_create() orelse return error.SfmlError }; } pub fn destroy(self: *Context) void { c.sfContext_destro(self.internal); } pub fn setActive(self: *Context, active: bool) bool { return c.sfContext_setActive(self.internal, @intCast(c.sfBool, @boolToInt(active))) == c.sfTrue; } pub fn getSettings(self: *const Context) ContextSettings { return ContextSettings.fromCSFML(c.sfContext_getSettings(self.internal)); } pub fn getActiveContextId() u64 { return @intCast(u64, c.sfContext_getActiveContextId()); } }; pub const ContextSettings = struct { depth_bits: u32 = 0, stencil_bits: u32 = 0, antialiasing_level: u32 = 0, major_version: u32 = 1, minor_version: u32 = 1, attribute_flags: u32 = Window.context_attribute.default, srgb_capable: bool = false, pub fn fromCSFML(cs: c.sfContextSettings) ContextSettings { return .{ .depth_bits = @intCast(u32, cs.depthBits), .stencil_bits = @intCast(u32, cs.stencilBits), .antialiasing_level = @intCast(u32, cs.antialiasingLevel), .major_version = @intCast(u32, cs.majorVersion), .minor_version = @intCast(u32, cs.minorVersion), .attribute_flags = cs.attributeFlags, .srgb_capable = cs.sRgbCapable == c.sfTrue, }; } pub fn toCSFML(self: *const ContextSettings) c.sfContextSettings { return .{ .depthBits = @intCast(c_uint, self.depth_bits), .stencilBits = @intCast(c_uint, self.stencil_bits), .antialiasingLevel = @intCast(c_uint, self.antialiasing_level), .majorVersion = @intCast(c_uint, self.major_version), .minorVersion = @intCast(c_uint, self.minor_version), .attributeFlags = self.attribute_flags, .sRgbCapable = @boolToInt(self.srgb_capable), }; } }; pub const Cursor = struct { pub const CursorType = extern enum(c_int) { cursor_arrow = c.sfCursorType.sfCursorArrow, cursor_arrow_wait = c.sfCursorType.sfCursorArrowWait, cursor_wait = c.sfCursorType.sfCursorWait, cursor_text = c.sfCursorType.sfCursorText, cursor_hand = c.sfCursorType.sfCursorHand, cursor_size_horizontal = c.sfCursorType.sfCursorSizeHorizontal, cursor_size_vertical = c.sfCursorType.sfCursorSizeVertical, cursor_size_top_left_bottom_right = c.sfCursorType.sfCursorSizeTopLeftBottomRight, cursor_size_bottom_left_top_right = c.sfCursorType.sfCursorSizeBottomLeftTopRight, cursor_size_all = c.sfCursorType.sfCursorSizeAll, cursor_cross = c.sfCursorType.sfCursorCross, cursor_help = c.sfCursorType.sfCursorHelp, cursor_not_allowed = c.sfCursorType.sfCursorNotAllowed, pub fn toCSFML(self: CursorType) c.sfCursorType { return @intToEnum(c.sfCursorType, @enumToInt(self)); } pub fn fromCSFML(evt: c.sfCursorType) CursorType { return @intToEnum(CursorType, @enumToInt(evt)); } }; internal: *c.sfCursor, pub fn createFromPixels(pixels: []const u8, size: system.Vector2u, hotspot: system.Vector2u) !Cursor { std.debug.assert(pixels.len == size.x * size.y); return Cursor{ .internal = c.sfCursor_createFromPixels(pixels.ptr, size, hotspot) orelse return error.SfmlError, }; } pub fn createFromSystem(t: CursorType) !Cursor { return Cursor{ .internal = c.sfCursor_createFromSystem(t.toCSFML()) orelse return error.SfmlError, }; } pub fn destroy(self: *Cursor) void { c.sfCursor_destroy(self.internal); } }; pub const VideoMode = struct { width: u32, height: u32, bits_per_pixel: u32, pub fn init(w: u32, h: u32, bpp: u32) VideoMode { return .{ .width = w, .height = h, .bits_per_pixel = bpp }; } pub fn fromCSFML(csfml: c.sfVideoMode) VideoMode { return .{ .width = @intCast(u32, csfml.width), .height = @intCast(u32, csfml.height), .bits_per_pixel = @intCast(u32, csfml.bitsPerPixel), }; } pub fn toCSFML(self: VideoMode) c.sfVideoMode { return .{ .width = @intCast(c_uint, self.width), .height = @intCast(c_uint, self.height), .bitsPerPixel = @intCast(c_uint, self.bits_per_pixel), }; } pub fn getDesktopMode() VideoMode { return fromCSFML(c.sfVideoMode_getDesktopMode()); } pub fn getFullscreenModes(allocator: *std.mem.Allocator) ![]VideoMode { var mode_count: usize = undefined; var modes = c.sfVideoMode_getFullscreenModes(&mode_count); var result = try allocator.alloc(VideoMode, mode_count); var i: usize = 0; while (i < mode_count) : (i += 1) { result[i] = fromCSFML(modes[i]); } return result; } pub fn isValid(mode: VideoMode) bool { return c.sfVideoMode_isValid(mode.toCSFML()) == c.sfTrue; } }; pub const WindowHandle = c.sfWindowHandle; pub const Window = struct { pub const style = struct { pub const none = @intCast(u32, c.sfNone); pub const titlebar = @intCast(u32, c.sfTitlebar); pub const resize = @intCast(u32, c.sfResize); pub const close = @intCast(u32, c.sfClose); pub const fullscreen = @intCast(u32, c.sfFullscreen); pub const default = @intCast(u32, c.sfDefaultStyle); }; pub const context_attribute = struct { pub const default = @intCast(u32, c.sfContextDefault); pub const core = @intCast(u32, c.sfContextCore); pub const debug = @intCast(u32, c.sfContextDebug); }; internal: *c.sfWindow, pub fn create( mode: VideoMode, title: []const u8, style_flags: u32, settings: *const ContextSettings ) !Window { const string = try sfml.allocator.dupeZ(u8, title); defer sfml.allocator.free(string); const internal = c.sfWindow_create( mode.toCSFML(), string, style_flags, &settings.toCSFML(), ) orelse return error.SfmlError; return Window{ .internal = internal }; } // TODO: write implementations for functions below pub fn createUnicode( mode: VideoMode, title: []const u32, style_flags: u32, settings: *const ContextSettings ) !Window { const string = try sfml.allocator.dupeZ(u32, title); defer sfml.allocator.free(string); const internal = c.sfWindow_createUnicode( mode.toCSFML(), string, style_flags, settings.toCSFML(), ) orelse return error.SfmlError; return Window{ .internal = internal }; } pub fn createFromHandle(handle: WindowHandle, settings: *const ContextSettings) !Window { return Window{ .internal = c.sfWindow_createFromHandle(handle, settings.toCSFML()) orelse return error.SfmlError, }; } pub fn destroy(self: *Window) void { c.sfWindow_destroy(self.internal); } pub fn close(self: *Window) void { c.sfWindow_close(self.internal); } pub fn isOpen(self: *Window) bool { return c.sfWindow_isOpen(self.internal) == c.sfTrue; } pub fn getSettings(self: *const Window) ContextSettings { return ContextSettings.fromCSFML(c.sfWindow_getSettings(self.internal)); } pub fn pollEvent(self: *Window, evt: *event.Event) bool { var cevt: c.sfEvent = undefined; var result: bool = false; while (self.isOpen()) { result = c.sfWindow_pollEvent(self.internal, &cevt) == c.sfTrue; // This invalid event can sometimes be sent through the event queue // It's not a valid event therefore it causes a crash. // Ignoring it *seems* to make it work. if (@enumToInt(cevt.@"type") == -1431655766) continue; evt.* = event.Event.fromCSFML(cevt); break; } return result; } pub fn waitEvent(self: *Window, evt: *event.Event) bool { var cevt: c.sfEvent = undefined; var result: bool = false; while (self.isOpen()) { result = c.sfWindow_waitEvent(self.internal, &cevt) == c.sfTrue; // This invalid event can sometimes be sent through the event queue // It's not a valid event therefore it causes a crash. // Ignoring it *seems* to make it work. if (@enumToInt(cevt.@"type") == -1431655766) continue; evt.* = event.Event.fromCSFML(cevt); break; } return result; } pub fn getPosition(self: *const Window) system.Vector2i { return c.sfWindow_getPosition(self.internal); } pub fn setPosition(self: *Window, position: system.Vector2i) void { c.sfWindow_setPosition(self.internal, position); } pub fn getSize(self: *const Window) system.Vector2u { return c.sfWindow_getSize(self.internal); } pub fn setSize(self: *Window, size: system.Vector2u) void { c.sfWindow_setSize(self.internal, size); } pub fn setTitle(self: *Window, title: []const u8) void { const string = try sfml.allocator.dupeZ(u8, title); defer sfml.allocator.free(string); c.sfWindow_setTitle(self.internal, string); } pub fn setUnicodeTitle(self: *Window, title: []const u32) void { const string = try sfml.allocator.dupeZ(u32, title); defer sfml.allocator.free(string); c.sfWindow_setTitle(self.internal, string); } pub fn setIcon(self: *Window, w: u32, h: u32, pixels: []const u8) void { std.debug.assert(pixels.len == w * h * 4); c.sfWindow_setIcon( self.internal, @intCast(c_uint, w), @intCast(c_uint, h), @ptrCast([*c]c.sfUint8, pixels.ptr), ); } pub fn setVisible(self: *Window, visible: bool) void { c.sfWindow_setVisible(self.internal, @boolToInt(visible)); } pub fn setVerticalSyncEnabled(self: *Window, enabled: bool) void { c.sfWindow_setVerticalSyncEnabled(self.internal, @boolToInt(enabled)); } pub fn setMouseCursorVisible(self: *Window, visible: bool) void { c.sfWindow_setMouseCursorVisible(self.internal, @boolToInt(enabled)); } pub fn setMouseCursorGrabbed(self: *Window, grabbed: bool) void { c.sfWindow_setMouseCursorGrabbed(self.internal, @boolToInt(enabled)); } pub fn setMouseCursor(self: *Window, cursor: *const Cursor) void { c.sfWindow_setMouseCursor(self.internal, cursor.internal); } pub fn setKeyRepeatEnabled(self: *Window, enabled: bool) void { c.sfWindow_setKeyRepeatEnabled(self.internal, @boolToInt(enabled)); } pub fn setFramerateLimit(self: *Window, limit: u32) void { c.sfWindow_setFramerateLimit(self.internal, @intCast(c_uint, limit)); } pub fn setJoystickThreshold(self: *Window, threshold: f32) void { c.sfWindow_setJoystickThreshold(self.internal, threshold); } pub fn setActive(self: *Window, active: bool) bool { return c.sfWindow_setActive(self.internal, @boolToInt(enabled)) == c.sfTrue; } pub fn requestFocus(self: *Window) void { c.sfWindow_requestFocus(self.internal); } pub fn hasFocus(self: *const Window) bool { return c.sfWindow_hasFocus(self.internal) == c.sfTrue; } pub fn display(self: *Window) void { c.sfWindow_display(self.internal); } pub fn getSystemHandle(self: *const Window) WindowHandle { return c.sfWindow_getSystemHandle(self.internal); } };
src/window.zig
const std = @import("std"); const assert = std.debug.assert; const zig = std.zig; pub fn build(b: *std.build.Builder) !void { try generateEntities(); const mode = b.standardReleaseOptions(); const lib = b.addStaticLibrary("htmlentities.zig", "src/main.zig"); lib.setBuildMode(mode); lib.install(); var main_tests = b.addTest("src/main.zig"); main_tests.setBuildMode(mode); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&main_tests.step); } const embedded_json = @embedFile("entities.json"); fn strLessThan(_: void, lhs: []const u8, rhs: []const u8) bool { return std.mem.lessThan(u8, lhs, rhs); } fn generateEntities() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var allocator = arena.allocator(); var json_parser = std.json.Parser.init(allocator, false); var tree = try json_parser.parse(embedded_json); var buffer = std.ArrayList(u8).init(allocator); var writer = buffer.writer(); try writer.writeAll("pub const ENTITIES = [_]@import(\"main.zig\").Entity{\n"); var keys = try std.ArrayList([]const u8).initCapacity(allocator, tree.root.Object.count()); var entries_it = tree.root.Object.iterator(); while (entries_it.next()) |entry| { keys.appendAssumeCapacity(entry.key_ptr.*); } std.sort.insertionSort([]const u8, keys.items, {}, strLessThan); for (keys.items) |key| { var value = tree.root.Object.get(key).?.Object; try std.fmt.format(writer, ".{{ .entity = \"{}\", .codepoints = ", .{zig.fmtEscapes(key)}); var codepoints_array = value.get("codepoints").?.Array; if (codepoints_array.items.len == 1) { try std.fmt.format(writer, ".{{ .Single = {} }}, ", .{codepoints_array.items[0].Integer}); } else { try std.fmt.format(writer, ".{{ .Double = [2]u32{{ {}, {} }} }}, ", .{ codepoints_array.items[0].Integer, codepoints_array.items[1].Integer }); } try std.fmt.format(writer, ".characters = \"{}\" }},\n", .{zig.fmtEscapes(value.get("characters").?.String)}); } try writer.writeAll("};\n"); try buffer.append(0); var zig_tree = try zig.parse(allocator, buffer.items[0 .. buffer.items.len - 1 :0]); var out_file = try std.fs.cwd().createFile("src/entities.zig", .{}); const formatted = try zig_tree.render(allocator); try out_file.writer().writeAll(formatted); out_file.close(); }
build.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const meta = std.meta; const mcp = @import("mcproto.zig"); const serde = @import("serde.zig"); const VarNum = @import("varnum.zig").VarNum; const VarInt = VarNum(i32); const VarLong = VarNum(i64); const nbt = @import("nbt.zig"); pub const blockgen = @import("gen/blocks.zig"); pub const GlobalPaletteMaxId = blockgen.GlobalPaletteMaxId; pub const GlobalPaletteInt = blockgen.GlobalPaletteInt; pub const Ds = serde.DefaultSpec; // yeah its hard coded pub const MAX_HEIGHT = 256; pub const MIN_Y = 0; pub fn isAir(val: GlobalPaletteInt) bool { const result = blockgen.BlockMaterial.fromGlobalPaletteId(val) catch return false; return switch (result) { .air, .cave_air, .void_air => true, else => false, }; } pub const DEFAULT_FLAT_SECTIONS = [_]ChunkSection.UserType{ .{ .block_count = 4096, .block_states = .{ .bits_per_entry = 0, .palette = .{ .single = 6 }, // andesite .data_array = &[_]GlobalPaletteInt{}, }, .biomes = .{ .bits_per_entry = 0, .palette = .{ .single = 1 }, // plains? .data_array = &[_]GlobalPaletteInt{}, }, }, } ++ [_]ChunkSection.UserType{ .{ .block_count = 0, .block_states = .{ .bits_per_entry = 0, .palette = .{ .single = 0 }, .data_array = &[_]GlobalPaletteInt{}, }, .biomes = .{ .bits_per_entry = 0, .palette = .{ .single = 1 }, .data_array = &[_]GlobalPaletteInt{}, }, }, } ** (section_count - 1); // copied from stdlib const MaskInt = std.DynamicBitSetUnmanaged.MaskInt; fn numMasks(bit_length: usize) usize { return (bit_length + (@bitSizeOf(MaskInt) - 1)) / @bitSizeOf(MaskInt); } const section_count = MAX_HEIGHT / 16; pub const Chunk = struct { chunk_x: i32, chunk_z: i32, block_entities: std.ArrayListUnmanaged(BlockEntity.UserType), // yeah, so, height is hardcoded as 0-256. we'll just use an array sections: [section_count]ChunkSection.UserType, height_map: [16][16]MbInt, const MbInt = std.math.IntFittingRange(0, MAX_HEIGHT - 1); const ratio = 64 / meta.bitCount(MbInt); const long_count = ((16 * 16) + (ratio - 1)) / ratio; const Self = @This(); pub fn generateHeightMap(sections: []const ChunkSection.UserType) [16][16]MbInt { // TODO: this is probably not compliant to what a client is actually expecting from MOTION_BLOCKING var map = [_][16]MbInt{[_]MbInt{0} ** 16} ** 16; var i: usize = sections.len; while (i > 0) { i -= 1; const section = sections[i]; if (section.block_states.palette == .single) { if (!isAir(@intCast(GlobalPaletteInt, section.block_states.palette.single))) { for (map) |*row| { for (row) |*cell| { cell.* = @intCast(MbInt, (i + 1) * 16); } } break; } } else { var z: u4 = 0; while (z < 16) : (z += 1) { var x: u4 = 0; while (x < 16) : (x += 1) { var y5: u5 = 16; while (y5 > 0) { y5 -= 1; const y = @intCast(u4, y5); if (!isAir(section.block_states.entryAt(x, y, z))) { map[z][x] = @intCast(MbInt, y + (16 * i) + 1); } } } } } } return map; } pub fn generateCompactHeightMap(height_map: [16][16]MbInt) [long_count]i64 { var longs: [long_count]i64 = undefined; //var total: usize = 0; var x: u4 = 0; var z: u4 = 0; var i: usize = 0; while (i < long_count) : (i += 1) { var current_long: i64 = 0; var j: usize = 0; while (j < ratio) : (j += 1) { const height = height_map[z][x]; current_long = (current_long << meta.bitCount(MbInt)) | height; if (x == 15) { x = 0; if (z == 15) { break; } else { z += 1; } } else { x += 1; } } const remainder = 64 % meta.bitCount(MbInt); longs[i] = current_long << remainder; } return longs; } pub fn send(self: Self, cl: anytype) !void { var longs = generateCompactHeightMap(self.height_map); const mask_count = comptime numMasks(section_count + 2); var sky_light_masks = [_]MaskInt{0} ** mask_count; var sky_light_mask = std.DynamicBitSetUnmanaged{ .masks = &sky_light_masks, .bit_length = section_count + 2 }; sky_light_mask.setValue(0, false); sky_light_mask.setValue(1, false); var empty_sky_light_masks: [mask_count]MaskInt = undefined; std.mem.copy(MaskInt, &empty_sky_light_masks, &sky_light_masks); var empty_sky_light_mask = std.DynamicBitSetUnmanaged{ .masks = &empty_sky_light_masks, .bit_length = section_count + 2 }; empty_sky_light_mask.toggleAll(); var block_light_masks = [_]MaskInt{0} ** mask_count; var block_light_mask = std.DynamicBitSetUnmanaged{ .masks = &block_light_masks, .bit_length = section_count + 2 }; var empty_block_light_masks: [mask_count]MaskInt = undefined; std.mem.copy(MaskInt, &empty_block_light_masks, &block_light_masks); var empty_block_light_mask = std.DynamicBitSetUnmanaged{ .masks = &empty_block_light_masks, .bit_length = section_count + 2 }; empty_block_light_mask.toggleAll(); const full_light = [_]u8{0xFF} ** 2048; const sky_light_arrays = [_][]const u8{&full_light} ** section_count; // section count + 2 - 2 try cl.writePacket(mcp.P.CB, mcp.P.CB.UserType{ .chunk_data_and_update_light = .{ .chunk_x = self.chunk_x, .chunk_z = self.chunk_z, .heightmaps = .{ .MOTION_BLOCKING = &longs, .WORLD_SURFACE = null, }, .data = &self.sections, .block_entities = self.block_entities.items, .trust_edges = true, .sky_light_mask = sky_light_mask, .block_light_mask = block_light_mask, .empty_sky_light_mask = empty_sky_light_mask, .empty_block_light_mask = empty_block_light_mask, .sky_light_arrays = std.mem.span(&sky_light_arrays), .block_light_arrays = &[_][]const u8{}, }, }); } // TODO: tbc here }; pub const BlockEntity = Ds.Spec(struct { xz: packed struct { z: u4, x: u4, }, z: i16, entity_type: VarInt, data: nbt.DynamicCompound, }); pub const PaletteType = enum { Block, Biome, }; pub const PalettedContainerError = error{ InvalidBitCount, }; pub fn readCompactedDataArray(comptime T: type, alloc: Allocator, reader: anytype, bit_count: usize) ![]T { const long_count = @intCast(usize, try VarInt.deserialize(alloc, reader)); const total_per_long = 64 / bit_count; var data = try std.ArrayList(T).initCapacity(alloc, long_count * total_per_long); const shift_amount = @intCast(u6, bit_count); defer data.deinit(); const mask: u64 = (1 << shift_amount) - 1; var i: usize = 0; while (i < long_count) : (i += 1) { const long = try reader.readIntBig(u64); var j: usize = 0; while (j < total_per_long) : (j += 1) { data.appendAssumeCapacity(@intCast(T, long & mask)); long = long >> shift_amount; } } try data.resize((data.items.len / 64) * 64); return data.toOwnedSlice(); } pub fn writeCompactedDataArray(comptime T: type, data: []T, writer: anytype, bit_count: usize) !void { const total_per_long = 64 / bit_count; const long_count = (data.len + (total_per_long - 1)) / total_per_long; try VarInt.write(@intCast(i32, long_count), writer); const shift_amount = @intCast(u6, bit_count); var i: usize = 0; while (i < long_count) : (i += 1) { var long: u64 = 0; var j: u6 = 0; while (j < total_per_long) : (j += 1) { const ind = i * total_per_long + j; if (ind < data.len) { long = long | (@intCast(u64, data[ind]) << (j * shift_amount)); } else { break; } } try writer.writeIntBig(u64, long); } } pub fn compactedDataArraySize(comptime T: type, data: []T, bit_count: usize) usize { if (bit_count == 0) return 1; const total_per_long = 64 / bit_count; const long_count = (data.len + (total_per_long - 1)) / total_per_long; return VarInt.size(@intCast(i32, long_count)) + @sizeOf(u64) * long_count; } pub fn PalettedContainer(comptime which_palette: PaletteType) type { return struct { bits_per_entry: u8, palette: Palette.UserType, data_array: []GlobalPaletteInt, pub const Palette = serde.Union(Ds, union(enum) { single: VarInt, indirect: serde.PrefixedArray(Ds, VarInt, VarInt), direct: void, }); const max_bits = switch (which_palette) { .Block => meta.bitCount(GlobalPaletteInt), .Biome => 6, }; // 61 total biomes i think (which means if just 4 more are added, this needs to be updated) const max_indirect_bits = switch (which_palette) { .Block => 8, .Biome => 3, }; // https://wiki.vg/Chunk_Format pub const UserType = @This(); pub fn write(self: UserType, writer: anytype) !void { try writer.writeByte(self.bits_per_entry); try Palette.write(self.palette, writer); const actual_bits = switch (self.bits_per_entry) { 0 => 0, 1...max_indirect_bits => |b| if (which_palette == .Block) (if (b < 4) 4 else b) else b, (max_indirect_bits + 1)...max_bits => max_bits, else => return error.InvalidBitCount, }; if (actual_bits == 0) { try writer.writeByte(0); } else { try writeCompactedDataArray(GlobalPaletteInt, self.data_array, writer, actual_bits); } } pub fn deserialize(alloc: Allocator, reader: anytype) !UserType { var self: UserType = undefined; self.bits_per_entry = try reader.readByte(); var actual_bits: usize = undefined; var tag: meta.Tag(Palette.UserType) = undefined; switch (self.bits_per_entry) { 0 => { actual_bits = 0; tag = .single; }, 1...max_indirect_bits => |b| { actual_bits = if (which_palette == .Block) (if (b < 4) 4 else b) else b; tag = .indirect; }, (max_indirect_bits + 1)...max_bits => { actual_bits = max_bits; tag = .direct; }, else => return error.InvalidBitCount, } self.palette = try Palette.deserialize(alloc, reader, @enumToInt(tag)); if (actual_bits == 0) { _ = try VarInt.deserialize(alloc, reader); self.data_array = &[_]u8{}; } else { self.data_array = try readCompactedDataArray(GlobalPaletteInt, alloc, reader, actual_bits); } return self; } pub fn deinit(self: UserType, alloc: Allocator) void { Palette.deinit(self.palette, alloc); alloc.free(self.data_array); } pub fn size(self: UserType) usize { const actual_bits = switch (self.bits_per_entry) { 0 => 0, 1...max_indirect_bits => |b| if (which_palette == .Block) (if (b < 4) 4 else b) else b, (max_indirect_bits + 1)...max_bits => max_bits, else => unreachable, }; return 1 + Palette.size(self.palette) + compactedDataArraySize(GlobalPaletteInt, self.data_array, actual_bits); } pub const AxisLocation = switch (which_palette) { .Block => u4, .Biome => u2, }; pub const AxisWidth = switch (which_palette) { .Block => 4, .Biome => 2, }; pub fn entryAt(self: UserType, x: AxisLocation, y: AxisLocation, z: AxisLocation) GlobalPaletteInt { const air = blockgen.BlockMaterial.toDefaultGlobalPaletteId(.air); // TODO: use cave and void air as well? const ind: usize = @intCast(usize, x) + (AxisWidth * @intCast(usize, z)) + ((AxisWidth * AxisWidth) * @intCast(usize, y)); switch (self.palette) { // TODO: it might also work to just directly access data_array instead of making sure block_count is followed .single => |id| return @intCast(GlobalPaletteInt, id), .indirect => |ids| { if (ind >= self.data_array.len) { return air; } else { return @intCast(GlobalPaletteInt, ids[@intCast(usize, self.data_array[ind])]); } }, .direct => return if (ind >= self.data_array.len) air else self.data_array[ind], } } }; } pub const ChunkSection = Ds.Spec(struct { block_count: i16, block_states: PalettedContainer(.Block), biomes: PalettedContainer(.Biome), });
src/chunk.zig
const std = @import("std"); const os = std.os; const unistd = @cImport({ @cInclude("unistd.h"); }); const signal = @cImport({ @cInclude("signal.h"); }); const stat = @cImport({ @cInclude("sys/stat.h"); }); /// Any error that might come up during process daemonization const DaemonizeError = error{FailedToSetSessionId} || os.ForkError; const SignalHandler = struct { fn ignore(sig: i32, info: *const os.siginfo_t, ctx_ptr: ?*const anyopaque) callconv(.C) void { // Ignore the signal received _ = sig; _ = ctx_ptr; _ = info; _ = ctx_ptr; } }; /// Forks the current process and makes /// the parent process quit fn fork_and_keep_child() os.ForkError!void { const is_parent_proc = (try os.fork()) != 0; // Exit off of the parent process if (is_parent_proc) { os.exit(0); } } // TODO: // * Add logging // * Chdir /// Daemonizes the calling process pub fn daemonize() DaemonizeError!void { try fork_and_keep_child(); if (unistd.setsid() < 0) { return error.FailedToSetSessionId; } // Setup signal handling var act = os.Sigaction{ .handler = .{ .sigaction = SignalHandler.ignore }, .mask = os.empty_sigset, .flags = (os.SA.SIGINFO | os.SA.RESTART | os.SA.RESETHAND), }; os.sigaction(signal.SIGCHLD, &act, null); os.sigaction(signal.SIGHUP, &act, null); // Fork yet again and keep only the child process try fork_and_keep_child(); // Set new file permissions _ = stat.umask(0); var fd: u8 = 0; // The maximum number of files a process can have open // at any time const max_files_opened = unistd.sysconf(unistd._SC_OPEN_MAX); while (fd < max_files_opened) : (fd += 1) { _ = unistd.close(fd); } } test "fork_and_keep_child works" { const getpid = os.linux.getpid; const expect = std.testing.expect; const linux = std.os.linux; const fmt = std.fmt; const first_pid = getpid(); try fork_and_keep_child(); const new_pid = getpid(); // We should now be running on a new process try expect(first_pid != new_pid); var stat_buf: linux.Stat = undefined; var buf = [_:0]u8{0} ** 128; // Current process is alive (obviously) _ = try fmt.bufPrint(&buf, "/proc/{}/stat", .{new_pid}); try expect(linux.stat(&buf, &stat_buf) == 0); // Old process should now be dead _ = try fmt.bufPrint(&buf, "/proc/{}/stat", .{first_pid}); // Give the OS some time to reap the old process std.time.sleep(250_000); try expect( // Stat should now fail linux.stat(&buf, &stat_buf) != 0); }
src/daemonize.zig