code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const Builder = std.build.Builder; const builtin = @import("builtin"); const CrossTarget = std.zig.CrossTarget; pub fn build(b: *Builder) !void { const target = CrossTarget{ .cpu_arch = .aarch64, .os_tag = .freestanding, .cpu_model = .{ .explicit = &std.Target.aarch64.cpu.cortex_a53 }, }; const kernel = b.addExecutable("kernel", "src/arm.zig"); kernel.setTarget(target); kernel.setLinkerScriptPath("linker.ld"); kernel.setOutputDir("zig-cache"); kernel.installRaw("kernel.img"); kernel.setBuildMode(builtin.Mode.ReleaseFast); // kernel.strip = true; const qemu = b.step("qemu", "Run the OS in qemu"); const upload = b.step("upload", "Upload the kernel"); const dis = b.step("dis", "Disassemble"); var qemu_args = std.ArrayList([]const u8).init(b.allocator); try qemu_args.appendSlice(&[_][]const u8{ "qemu-system-aarch64", "-kernel", kernel.getOutputPath(), "-m", "256", "-M", "raspi3", "-serial", "stdio", "-display", "none", }); const run_qemu = b.addSystemCommand(qemu_args.items); qemu.dependOn(&run_qemu.step); // const run_upload = b.addSystemCommand(upload_args.items); //const run_screen = b.addSystemCommand(screen_args.items); //run_screen.dependOn(&run_upload.step); var dis_args = std.ArrayList([]const u8).init(b.allocator); try dis_args.appendSlice(&[_][]const u8{ "llvm-objdump", "-d", kernel.getOutputPath(), }); var send_image_tool = b.addExecutable("send_image", undefined); send_image_tool.addCSourceFile("tools/uploader/raspbootcom.c", &[_][]const u8{"-std=c99"}); send_image_tool.addIncludeDir("tools/uploader/"); const run_send_image_tool = send_image_tool.run(); run_send_image_tool.addArg("/dev/tty.SLAB_USBtoUART"); run_send_image_tool.addArg("zig-cache/bin/kernel.img"); upload.dependOn(&run_send_image_tool.step); const run_dis = b.addSystemCommand(dis_args.items); dis.dependOn(&run_dis.step); run_qemu.step.dependOn(&kernel.step); run_dis.step.dependOn(&kernel.step); b.default_step.dependOn(&kernel.step); }
build.zig
const Wasm = @This(); const std = @import("std"); const mem = std.mem; const Allocator = std.mem.Allocator; const assert = std.debug.assert; const fs = std.fs; const leb = std.leb; const log = std.log.scoped(.link); const wasm = std.wasm; const Module = @import("../Module.zig"); const Compilation = @import("../Compilation.zig"); const codegen = @import("../codegen/wasm.zig"); const link = @import("../link.zig"); const trace = @import("../tracy.zig").trace; const build_options = @import("build_options"); const Cache = @import("../Cache.zig"); const TypedValue = @import("../TypedValue.zig"); pub const base_tag = link.File.Tag.wasm; base: link.File, /// List of all function Decls to be written to the output file. The index of /// each Decl in this list at the time of writing the binary is used as the /// function index. In the event where ext_funcs' size is not 0, the index of /// each function is added on top of the ext_funcs' length. /// TODO: can/should we access some data structure in Module directly? funcs: std.ArrayListUnmanaged(*Module.Decl) = .{}, /// List of all extern function Decls to be written to the `import` section of the /// wasm binary. The positin in the list defines the function index ext_funcs: std.ArrayListUnmanaged(*Module.Decl) = .{}, /// When importing objects from the host environment, a name must be supplied. /// LLVM uses "env" by default when none is given. This would be a good default for Zig /// to support existing code. /// TODO: Allow setting this through a flag? host_name: []const u8 = "env", /// The last `DeclBlock` that was initialized will be saved here. last_block: ?*DeclBlock = null, /// Table with offsets, each element represents an offset with the value being /// the offset into the 'data' section where the data lives offset_table: std.ArrayListUnmanaged(u32) = .{}, /// List of offset indexes which are free to be used for new decl's. /// Each element's value points to an index into the offset_table. offset_table_free_list: std.ArrayListUnmanaged(u32) = .{}, /// List of all `Decl` that are currently alive. /// This is ment for bookkeeping so we can safely cleanup all codegen memory /// when calling `deinit` symbols: std.ArrayListUnmanaged(*Module.Decl) = .{}, pub const FnData = struct { /// Generated code for the type of the function functype: std.ArrayListUnmanaged(u8), /// Generated code for the body of the function code: std.ArrayListUnmanaged(u8), /// Locations in the generated code where function indexes must be filled in. /// This must be kept ordered by offset. idx_refs: std.ArrayListUnmanaged(struct { offset: u32, decl: *Module.Decl }), pub const empty: FnData = .{ .functype = .{}, .code = .{}, .idx_refs = .{}, }; }; pub const DeclBlock = struct { /// Determines whether the `DeclBlock` has been initialized for codegen. init: bool, /// Index into the `symbols` list. symbol_index: u32, /// Index into the offset table offset_index: u32, /// The size of the block and how large part of the data section it occupies. /// Will be 0 when the Decl will not live inside the data section and `data` will be undefined. size: u32, /// Points to the previous and next blocks. /// Can be used to find the total size, and used to calculate the `offset` based on the previous block. prev: ?*DeclBlock, next: ?*DeclBlock, /// Pointer to data that will be written to the 'data' section. /// This data either lives in `FnData.code` or is externally managed. /// For data that does not live inside the 'data' section, this field will be undefined. (size == 0). data: [*]const u8, pub const empty: DeclBlock = .{ .init = false, .symbol_index = 0, .offset_index = 0, .size = 0, .prev = null, .next = null, .data = undefined, }; /// Unplugs the `DeclBlock` from the chain fn unplug(self: *DeclBlock) void { if (self.prev) |prev| { prev.next = self.next; } if (self.next) |next| { next.prev = self.prev; } self.next = null; self.prev = null; } }; pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Options) !*Wasm { assert(options.object_format == .wasm); if (options.use_llvm) return error.LLVM_BackendIsTODO_ForWasm; // TODO if (options.use_lld) return error.LLD_LinkingIsTODO_ForWasm; // TODO // TODO: read the file and keep valid parts instead of truncating const file = try options.emit.?.directory.handle.createFile(sub_path, .{ .truncate = true, .read = true }); errdefer file.close(); const wasm_bin = try createEmpty(allocator, options); errdefer wasm_bin.base.destroy(); wasm_bin.base.file = file; try file.writeAll(&(wasm.magic ++ wasm.version)); return wasm_bin; } pub fn createEmpty(gpa: *Allocator, options: link.Options) !*Wasm { const wasm_bin = try gpa.create(Wasm); wasm_bin.* = .{ .base = .{ .tag = .wasm, .options = options, .file = null, .allocator = gpa, }, }; return wasm_bin; } pub fn deinit(self: *Wasm) void { for (self.symbols.items) |decl| { decl.fn_link.wasm.functype.deinit(self.base.allocator); decl.fn_link.wasm.code.deinit(self.base.allocator); decl.fn_link.wasm.idx_refs.deinit(self.base.allocator); } self.funcs.deinit(self.base.allocator); self.ext_funcs.deinit(self.base.allocator); self.offset_table.deinit(self.base.allocator); self.offset_table_free_list.deinit(self.base.allocator); self.symbols.deinit(self.base.allocator); } pub fn allocateDeclIndexes(self: *Wasm, decl: *Module.Decl) !void { if (decl.link.wasm.init) return; try self.offset_table.ensureCapacity(self.base.allocator, self.offset_table.items.len + 1); try self.symbols.ensureCapacity(self.base.allocator, self.symbols.items.len + 1); const block = &decl.link.wasm; block.init = true; block.symbol_index = @intCast(u32, self.symbols.items.len); self.symbols.appendAssumeCapacity(decl); if (self.offset_table_free_list.popOrNull()) |index| { block.offset_index = index; } else { block.offset_index = @intCast(u32, self.offset_table.items.len); _ = self.offset_table.addOneAssumeCapacity(); } self.offset_table.items[block.offset_index] = 0; if (decl.ty.zigTypeTag() == .Fn) { switch (decl.val.tag()) { // dependent on function type, appends it to the correct list .function => try self.funcs.append(self.base.allocator, decl), .extern_fn => try self.ext_funcs.append(self.base.allocator, decl), else => unreachable, } } } // Generate code for the Decl, storing it in memory to be later written to // the file on flush(). pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void { std.debug.assert(decl.link.wasm.init); // Must call allocateDeclIndexes() const fn_data = &decl.fn_link.wasm; fn_data.functype.items.len = 0; fn_data.code.items.len = 0; fn_data.idx_refs.items.len = 0; var context = codegen.Context{ .gpa = self.base.allocator, .values = .{}, .code = fn_data.code.toManaged(self.base.allocator), .func_type_data = fn_data.functype.toManaged(self.base.allocator), .decl = decl, .err_msg = undefined, .locals = .{}, .target = self.base.options.target, }; defer context.deinit(); // generate the 'code' section for the function declaration const result = context.gen(.{ .ty = decl.ty, .val = decl.val }) catch |err| switch (err) { error.CodegenFail => { decl.analysis = .codegen_failure; try module.failed_decls.put(module.gpa, decl, context.err_msg); return; }, else => |e| return err, }; const code: []const u8 = switch (result) { .appended => @as([]const u8, context.code.items), .externally_managed => |payload| payload, }; fn_data.code = context.code.toUnmanaged(); fn_data.functype = context.func_type_data.toUnmanaged(); const block = &decl.link.wasm; if (decl.ty.zigTypeTag() == .Fn) { // as locals are patched afterwards, the offsets of funcidx's are off, // here we update them to correct them for (fn_data.idx_refs.items) |*func| { // For each local, add 6 bytes (count + type) func.offset += @intCast(u32, context.locals.items.len * 6); } } else { block.size = @intCast(u32, code.len); block.data = code.ptr; } // If we're updating an existing decl, unplug it first // to avoid infinite loops due to earlier links block.unplug(); if (self.last_block) |last| { if (last != block) { last.next = block; block.prev = last; } } self.last_block = block; } pub fn updateDeclExports( self: *Wasm, module: *Module, decl: *const Module.Decl, exports: []const *Module.Export, ) !void {} pub fn freeDecl(self: *Wasm, decl: *Module.Decl) void { if (self.getFuncidx(decl)) |func_idx| { switch (decl.val.tag()) { .function => _ = self.funcs.swapRemove(func_idx), .extern_fn => _ = self.ext_funcs.swapRemove(func_idx), else => unreachable, } } const block = &decl.link.wasm; if (self.last_block == block) { self.last_block = block.prev; } block.unplug(); self.offset_table_free_list.append(self.base.allocator, decl.link.wasm.offset_index) catch {}; _ = self.symbols.swapRemove(block.symbol_index); // update symbol_index as we swap removed the last symbol into the removed's position if (block.symbol_index < self.symbols.items.len) self.symbols.items[block.symbol_index].link.wasm.symbol_index = block.symbol_index; block.init = false; decl.fn_link.wasm.functype.deinit(self.base.allocator); decl.fn_link.wasm.code.deinit(self.base.allocator); decl.fn_link.wasm.idx_refs.deinit(self.base.allocator); decl.fn_link.wasm = undefined; } pub fn flush(self: *Wasm, comp: *Compilation) !void { if (build_options.have_llvm and self.base.options.use_lld) { return self.linkWithLLD(comp); } else { return self.flushModule(comp); } } pub fn flushModule(self: *Wasm, comp: *Compilation) !void { const tracy = trace(@src()); defer tracy.end(); const file = self.base.file.?; const header_size = 5 + 1; // ptr_width in bytes const ptr_width = self.base.options.target.cpu.arch.ptrBitWidth() / 8; // The size of the offset table in bytes // The table contains all decl's with its corresponding offset into // the 'data' section const offset_table_size = @intCast(u32, self.offset_table.items.len * ptr_width); // The size of the data, this together with `offset_table_size` amounts to the // total size of the 'data' section var first_decl: ?*DeclBlock = null; const data_size: u32 = if (self.last_block) |last| blk: { var size = last.size; var cur = last; while (cur.prev) |prev| : (cur = prev) { size += prev.size; } first_decl = cur; break :blk size; } else 0; // No need to rewrite the magic/version header try file.setEndPos(@sizeOf(@TypeOf(wasm.magic ++ wasm.version))); try file.seekTo(@sizeOf(@TypeOf(wasm.magic ++ wasm.version))); // Type section { const header_offset = try reserveVecSectionHeader(file); // extern functions are defined in the wasm binary first through the `import` // section, so define their func types first for (self.ext_funcs.items) |decl| try file.writeAll(decl.fn_link.wasm.functype.items); for (self.funcs.items) |decl| try file.writeAll(decl.fn_link.wasm.functype.items); try writeVecSectionHeader( file, header_offset, .type, @intCast(u32, (try file.getPos()) - header_offset - header_size), @intCast(u32, self.ext_funcs.items.len + self.funcs.items.len), ); } // Import section { // TODO: implement non-functions imports const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); for (self.ext_funcs.items) |decl, typeidx| { try leb.writeULEB128(writer, @intCast(u32, self.host_name.len)); try writer.writeAll(self.host_name); // wasm requires the length of the import name with no null-termination const decl_len = mem.len(decl.name); try leb.writeULEB128(writer, @intCast(u32, decl_len)); try writer.writeAll(decl.name[0..decl_len]); // emit kind and the function type try writer.writeByte(wasm.externalKind(.function)); try leb.writeULEB128(writer, @intCast(u32, typeidx)); } try writeVecSectionHeader( file, header_offset, .import, @intCast(u32, (try file.getPos()) - header_offset - header_size), @intCast(u32, self.ext_funcs.items.len), ); } // Function section { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); for (self.funcs.items) |_, typeidx| { const func_idx = @intCast(u32, self.getFuncIdxOffset() + typeidx); try leb.writeULEB128(writer, func_idx); } try writeVecSectionHeader( file, header_offset, .function, @intCast(u32, (try file.getPos()) - header_offset - header_size), @intCast(u32, self.funcs.items.len), ); } // Memory section if (data_size != 0) { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); try leb.writeULEB128(writer, @as(u32, 0)); // Calculate the amount of memory pages are required and write them. // Wasm uses 64kB page sizes. Round up to ensure the data segments fit into the memory try leb.writeULEB128( writer, try std.math.divCeil( u32, offset_table_size + data_size, std.wasm.page_size, ), ); try writeVecSectionHeader( file, header_offset, .memory, @intCast(u32, (try file.getPos()) - header_offset - header_size), @as(u32, 1), // wasm currently only supports 1 linear memory segment ); } // Export section if (self.base.options.module) |module| { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); var count: u32 = 0; for (module.decl_exports.entries.items) |entry| { for (entry.value) |exprt| { // Export name length + name try leb.writeULEB128(writer, @intCast(u32, exprt.options.name.len)); try writer.writeAll(exprt.options.name); switch (exprt.exported_decl.ty.zigTypeTag()) { .Fn => { // Type of the export try writer.writeByte(wasm.externalKind(.function)); // Exported function index try leb.writeULEB128(writer, self.getFuncidx(exprt.exported_decl).?); }, else => return error.TODOImplementNonFnDeclsForWasm, } count += 1; } } // export memory if size is not 0 if (data_size != 0) { try leb.writeULEB128(writer, @intCast(u32, "memory".len)); try writer.writeAll("memory"); try writer.writeByte(wasm.externalKind(.memory)); try leb.writeULEB128(writer, @as(u32, 0)); // only 1 memory 'object' can exist count += 1; } try writeVecSectionHeader( file, header_offset, .@"export", @intCast(u32, (try file.getPos()) - header_offset - header_size), count, ); } // Code section { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); for (self.funcs.items) |decl| { const fn_data = &decl.fn_link.wasm; // Write the already generated code to the file, inserting // function indexes where required. var current: u32 = 0; for (fn_data.idx_refs.items) |idx_ref| { try writer.writeAll(fn_data.code.items[current..idx_ref.offset]); current = idx_ref.offset; // Use a fixed width here to make calculating the code size // in codegen.wasm.gen() simpler. var buf: [5]u8 = undefined; leb.writeUnsignedFixed(5, &buf, self.getFuncidx(idx_ref.decl).?); try writer.writeAll(&buf); } try writer.writeAll(fn_data.code.items[current..]); } try writeVecSectionHeader( file, header_offset, .code, @intCast(u32, (try file.getPos()) - header_offset - header_size), @intCast(u32, self.funcs.items.len), ); } // Data section if (data_size != 0) { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); var len: u32 = 0; // index to memory section (currently, there can only be 1 memory section in wasm) try leb.writeULEB128(writer, @as(u32, 0)); // offset into data section try writer.writeByte(wasm.opcode(.i32_const)); try leb.writeILEB128(writer, @as(i32, 0)); try writer.writeByte(wasm.opcode(.end)); const total_size = offset_table_size + data_size; // offset table + data size try leb.writeULEB128(writer, total_size); // fill in the offset table and the data segments const file_offset = try file.getPos(); var cur = first_decl; var data_offset = offset_table_size; while (cur) |cur_block| : (cur = cur_block.next) { if (cur_block.size == 0) continue; std.debug.assert(cur_block.init); const offset = (cur_block.offset_index) * ptr_width; var buf: [4]u8 = undefined; std.mem.writeIntLittle(u32, &buf, data_offset); try file.pwriteAll(&buf, file_offset + offset); try file.pwriteAll(cur_block.data[0..cur_block.size], file_offset + data_offset); data_offset += cur_block.size; } try file.seekTo(file_offset + data_offset); try writeVecSectionHeader( file, header_offset, .data, @intCast(u32, (file_offset + data_offset) - header_offset - header_size), @intCast(u32, 1), // only 1 data section ); } } fn linkWithLLD(self: *Wasm, comp: *Compilation) !void { const tracy = trace(@src()); defer tracy.end(); var arena_allocator = std.heap.ArenaAllocator.init(self.base.allocator); defer arena_allocator.deinit(); const arena = &arena_allocator.allocator; const directory = self.base.options.emit.?.directory; // Just an alias to make it shorter to type. // If there is no Zig code to compile, then we should skip flushing the output file because it // will not be part of the linker line anyway. const module_obj_path: ?[]const u8 = if (self.base.options.module) |module| blk: { const use_stage1 = build_options.is_stage1 and self.base.options.use_llvm; if (use_stage1) { const obj_basename = try std.zig.binNameAlloc(arena, .{ .root_name = self.base.options.root_name, .target = self.base.options.target, .output_mode = .Obj, }); const o_directory = self.base.options.module.?.zig_cache_artifact_directory; const full_obj_path = try o_directory.join(arena, &[_][]const u8{obj_basename}); break :blk full_obj_path; } try self.flushModule(comp); const obj_basename = self.base.intermediary_basename.?; const full_obj_path = try directory.join(arena, &[_][]const u8{obj_basename}); break :blk full_obj_path; } else null; const compiler_rt_path: ?[]const u8 = if (self.base.options.include_compiler_rt) comp.compiler_rt_static_lib.?.full_object_path else null; const target = self.base.options.target; const link_in_crt = self.base.options.link_libc and self.base.options.output_mode == .Exe; const id_symlink_basename = "lld.id"; var man: Cache.Manifest = undefined; defer if (!self.base.options.disable_lld_caching) man.deinit(); var digest: [Cache.hex_digest_len]u8 = undefined; if (!self.base.options.disable_lld_caching) { man = comp.cache_parent.obtain(); // We are about to obtain this lock, so here we give other processes a chance first. self.base.releaseLock(); try man.addListOfFiles(self.base.options.objects); for (comp.c_object_table.items()) |entry| { _ = try man.addFile(entry.key.status.success.object_path, null); } try man.addOptionalFile(module_obj_path); try man.addOptionalFile(compiler_rt_path); man.hash.addOptional(self.base.options.stack_size_override); man.hash.addListOfBytes(self.base.options.extra_lld_args); // We don't actually care whether it's a cache hit or miss; we just need the digest and the lock. _ = try man.hit(); digest = man.final(); var prev_digest_buf: [digest.len]u8 = undefined; const prev_digest: []u8 = Cache.readSmallFile( directory.handle, id_symlink_basename, &prev_digest_buf, ) catch |err| blk: { log.debug("WASM LLD new_digest={s} error: {s}", .{ std.fmt.fmtSliceHexLower(&digest), @errorName(err) }); // Handle this as a cache miss. break :blk prev_digest_buf[0..0]; }; if (mem.eql(u8, prev_digest, &digest)) { log.debug("WASM LLD digest={s} match - skipping invocation", .{std.fmt.fmtSliceHexLower(&digest)}); // Hot diggity dog! The output binary is already there. self.base.lock = man.toOwnedLock(); return; } log.debug("WASM LLD prev_digest={s} new_digest={s}", .{ std.fmt.fmtSliceHexLower(prev_digest), std.fmt.fmtSliceHexLower(&digest) }); // We are about to change the output file to be different, so we invalidate the build hash now. directory.handle.deleteFile(id_symlink_basename) catch |err| switch (err) { error.FileNotFound => {}, else => |e| return e, }; } const full_out_path = try directory.join(arena, &[_][]const u8{self.base.options.emit.?.sub_path}); if (self.base.options.output_mode == .Obj) { // LLD's WASM driver does not support the equvialent of `-r` so we do a simple file copy // here. TODO: think carefully about how we can avoid this redundant operation when doing // build-obj. See also the corresponding TODO in linkAsArchive. const the_object_path = blk: { if (self.base.options.objects.len != 0) break :blk self.base.options.objects[0]; if (comp.c_object_table.count() != 0) break :blk comp.c_object_table.items()[0].key.status.success.object_path; if (module_obj_path) |p| break :blk p; // TODO I think this is unreachable. Audit this situation when solving the above TODO // regarding eliding redundant object -> object transformations. return error.NoObjectsToLink; }; // This can happen when using --enable-cache and using the stage1 backend. In this case // we can skip the file copy. if (!mem.eql(u8, the_object_path, full_out_path)) { try fs.cwd().copyFile(the_object_path, fs.cwd(), full_out_path, .{}); } } else { const is_obj = self.base.options.output_mode == .Obj; // Create an LLD command line and invoke it. var argv = std.ArrayList([]const u8).init(self.base.allocator); defer argv.deinit(); // We will invoke ourselves as a child process to gain access to LLD. // This is necessary because LLD does not behave properly as a library - // it calls exit() and does not reset all global data between invocations. try argv.appendSlice(&[_][]const u8{ comp.self_exe_path.?, "wasm-ld" }); if (is_obj) { try argv.append("-r"); } try argv.append("-error-limit=0"); if (self.base.options.lto) { switch (self.base.options.optimize_mode) { .Debug => {}, .ReleaseSmall => try argv.append("-O2"), .ReleaseFast, .ReleaseSafe => try argv.append("-O3"), } } if (self.base.options.output_mode == .Exe) { // Increase the default stack size to a more reasonable value of 1MB instead of // the default of 1 Wasm page being 64KB, unless overriden by the user. try argv.append("-z"); const stack_size = self.base.options.stack_size_override orelse 1048576; const arg = try std.fmt.allocPrint(arena, "stack-size={d}", .{stack_size}); try argv.append(arg); // Put stack before globals so that stack overflow results in segfault immediately // before corrupting globals. See https://github.com/ziglang/zig/issues/4496 try argv.append("--stack-first"); } else { try argv.append("--no-entry"); // So lld doesn't look for _start. try argv.append("--export-all"); } try argv.appendSlice(&[_][]const u8{ "--allow-undefined", "-o", full_out_path, }); if (link_in_crt) { // TODO work out if we want standard crt, a reactor or a command try argv.append(try comp.get_libc_crt_file(arena, "crt.o.wasm")); } if (!is_obj and self.base.options.link_libc) { try argv.append(try comp.get_libc_crt_file(arena, switch (self.base.options.link_mode) { .Static => "libc.a", .Dynamic => unreachable, })); } // Positional arguments to the linker such as object files. try argv.appendSlice(self.base.options.objects); for (comp.c_object_table.items()) |entry| { try argv.append(entry.key.status.success.object_path); } if (module_obj_path) |p| { try argv.append(p); } if (self.base.options.output_mode != .Obj and !self.base.options.skip_linker_dependencies and !self.base.options.link_libc) { try argv.append(comp.libc_static_lib.?.full_object_path); } if (compiler_rt_path) |p| { try argv.append(p); } if (self.base.options.verbose_link) { // Skip over our own name so that the LLD linker name is the first argv item. Compilation.dump_argv(argv.items[1..]); } // Sadly, we must run LLD as a child process because it does not behave // properly as a library. const child = try std.ChildProcess.init(argv.items, arena); defer child.deinit(); if (comp.clang_passthrough_mode) { child.stdin_behavior = .Inherit; child.stdout_behavior = .Inherit; child.stderr_behavior = .Inherit; const term = child.spawnAndWait() catch |err| { log.err("unable to spawn {s}: {s}", .{ argv.items[0], @errorName(err) }); return error.UnableToSpawnSelf; }; switch (term) { .Exited => |code| { if (code != 0) { // TODO https://github.com/ziglang/zig/issues/6342 std.process.exit(1); } }, else => std.process.abort(), } } else { child.stdin_behavior = .Ignore; child.stdout_behavior = .Ignore; child.stderr_behavior = .Pipe; try child.spawn(); const stderr = try child.stderr.?.reader().readAllAlloc(arena, 10 * 1024 * 1024); const term = child.wait() catch |err| { log.err("unable to spawn {s}: {s}", .{ argv.items[0], @errorName(err) }); return error.UnableToSpawnSelf; }; switch (term) { .Exited => |code| { if (code != 0) { // TODO parse this output and surface with the Compilation API rather than // directly outputting to stderr here. std.debug.print("{s}", .{stderr}); return error.LLDReportedFailure; } }, else => { log.err("{s} terminated with stderr:\n{s}", .{ argv.items[0], stderr }); return error.LLDCrashed; }, } if (stderr.len != 0) { log.warn("unexpected LLD stderr:\n{s}", .{stderr}); } } } if (!self.base.options.disable_lld_caching) { // Update the file with the digest. If it fails we can continue; it only // means that the next invocation will have an unnecessary cache miss. Cache.writeSmallFile(directory.handle, id_symlink_basename, &digest) catch |err| { log.warn("failed to save linking hash digest symlink: {s}", .{@errorName(err)}); }; // Again failure here only means an unnecessary cache miss. man.writeManifest() catch |err| { log.warn("failed to write cache manifest when linking: {s}", .{@errorName(err)}); }; // We hang on to this lock so that the output file path can be used without // other processes clobbering it. self.base.lock = man.toOwnedLock(); } } /// Get the current index of a given Decl in the function list /// This will correctly provide the index, regardless whether the function is extern or not /// TODO: we could maintain a hash map to potentially make this simpler fn getFuncidx(self: Wasm, decl: *Module.Decl) ?u32 { var offset: u32 = 0; const slice = switch (decl.val.tag()) { .function => blk: { // when the target is a regular function, we have to calculate // the offset of where the index starts offset += self.getFuncIdxOffset(); break :blk self.funcs.items; }, .extern_fn => self.ext_funcs.items, else => return null, }; return for (slice) |func, idx| { if (func == decl) break @intCast(u32, offset + idx); } else null; } /// Based on the size of `ext_funcs` returns the /// offset of the function indices fn getFuncIdxOffset(self: Wasm) u32 { return @intCast(u32, self.ext_funcs.items.len); } fn reserveVecSectionHeader(file: fs.File) !u64 { // section id + fixed leb contents size + fixed leb vector length const header_size = 1 + 5 + 5; // TODO: this should be a single lseek(2) call, but fs.File does not // currently provide a way to do this. try file.seekBy(header_size); return (try file.getPos()) - header_size; } fn writeVecSectionHeader(file: fs.File, offset: u64, section: wasm.Section, size: u32, items: u32) !void { var buf: [1 + 5 + 5]u8 = undefined; buf[0] = @enumToInt(section); leb.writeUnsignedFixed(5, buf[1..6], size); leb.writeUnsignedFixed(5, buf[6..], items); try file.pwriteAll(&buf, offset); }
src/link/Wasm.zig
const std = @import("std"); const builtin = @import("builtin"); const assert = std.debug.assert; const mem = std.mem; const meta = std.meta; /// Describes how pointer types should be hashed. pub const HashStrategy = enum { /// Do not follow pointers, only hash their value. Shallow, /// Follow pointers, hash the pointee content. /// Only dereferences one level, ie. it is changed into .Shallow when a /// pointer type is encountered. Deep, /// Follow pointers, hash the pointee content. /// Dereferences all pointers encountered. /// Assumes no cycle. DeepRecursive, }; /// Helper function to hash a pointer and mutate the strategy if needed. pub fn hashPointer(hasher: anytype, key: anytype, comptime strat: HashStrategy) void { const info = @typeInfo(@TypeOf(key)); switch (info.Pointer.size) { .One => switch (strat) { .Shallow => hash(hasher, @ptrToInt(key), .Shallow), .Deep => hash(hasher, key.*, .Shallow), .DeepRecursive => hash(hasher, key.*, .DeepRecursive), }, .Slice => switch (strat) { .Shallow => { hashPointer(hasher, key.ptr, .Shallow); hash(hasher, key.len, .Shallow); }, .Deep => hashArray(hasher, key, .Shallow), .DeepRecursive => hashArray(hasher, key, .DeepRecursive), }, .Many, .C, => switch (strat) { .Shallow => hash(hasher, @ptrToInt(key), .Shallow), else => @compileError( \\ unknown-length pointers and C pointers cannot be hashed deeply. \\ Consider providing your own hash function. ), }, } } /// Helper function to hash a set of contiguous objects, from an array or slice. pub fn hashArray(hasher: anytype, key: anytype, comptime strat: HashStrategy) void { switch (strat) { .Shallow => { for (key) |element| { hash(hasher, element, .Shallow); } }, else => { for (key) |element| { hash(hasher, element, strat); } }, } } /// Provides generic hashing for any eligible type. /// Strategy is provided to determine if pointers should be followed or not. pub fn hash(hasher: anytype, key: anytype, comptime strat: HashStrategy) void { const Key = @TypeOf(key); if (strat == .Shallow and comptime meta.trait.hasUniqueRepresentation(Key)) { @call(.{ .modifier = .always_inline }, hasher.update, .{mem.asBytes(&key)}); return; } switch (@typeInfo(Key)) { .NoReturn, .Opaque, .Undefined, .Void, .Null, .ComptimeFloat, .ComptimeInt, .Type, .EnumLiteral, .Frame, .Float, => @compileError("cannot hash this type"), // Help the optimizer see that hashing an int is easy by inlining! // TODO Check if the situation is better after #561 is resolved. .Int => @call(.{ .modifier = .always_inline }, hasher.update, .{std.mem.asBytes(&key)}), .Bool => hash(hasher, @boolToInt(key), strat), .Enum => hash(hasher, @enumToInt(key), strat), .ErrorSet => hash(hasher, @errorToInt(key), strat), .AnyFrame, .BoundFn, .Fn => hash(hasher, @ptrToInt(key), strat), .Pointer => @call(.{ .modifier = .always_inline }, hashPointer, .{ hasher, key, strat }), .Optional => if (key) |k| hash(hasher, k, strat), .Array => hashArray(hasher, key, strat), .Vector => |info| { if (info.child.bit_count % 8 == 0) { // If there's no unused bits in the child type, we can just hash // this as an array of bytes. hasher.update(mem.asBytes(&key)); } else { // Otherwise, hash every element. comptime var i = 0; inline while (i < info.len) : (i += 1) { hash(hasher, key[i], strat); } } }, .Struct => |info| { inline for (info.fields) |field| { // We reuse the hash of the previous field as the seed for the // next one so that they're dependant. hash(hasher, @field(key, field.name), strat); } }, .Union => |info| blk: { if (info.tag_type) |tag_type| { const tag = meta.activeTag(key); const s = hash(hasher, tag, strat); inline for (info.fields) |field| { const enum_field = field.enum_field.?; if (enum_field.value == @enumToInt(tag)) { hash(hasher, @field(key, enum_field.name), strat); // TODO use a labelled break when it does not crash the compiler. cf #2908 // break :blk; return; } } unreachable; } else @compileError("cannot hash untagged union type: " ++ @typeName(Key) ++ ", provide your own hash function"); }, .ErrorUnion => blk: { const payload = key catch |err| { hash(hasher, err, strat); break :blk; }; hash(hasher, payload, strat); }, } } /// Provides generic hashing for any eligible type. /// Only hashes `key` itself, pointers are not followed. /// Slices are rejected to avoid ambiguity on the user's intention. pub fn autoHash(hasher: anytype, key: anytype) void { const Key = @TypeOf(key); if (comptime meta.trait.isSlice(Key)) { comptime assert(@hasDecl(std, "StringHashMap")); // detect when the following message needs updated const extra_help = if (Key == []const u8) " Consider std.StringHashMap for hashing the contents of []const u8." else ""; @compileError("std.auto_hash.autoHash does not allow slices (here " ++ @typeName(Key) ++ ") because the intent is unclear. Consider using std.auto_hash.hash or providing your own hash function instead." ++ extra_help); } hash(hasher, key, .Shallow); } const testing = std.testing; const Wyhash = std.hash.Wyhash; fn testHash(key: anytype) u64 { // Any hash could be used here, for testing autoHash. var hasher = Wyhash.init(0); hash(&hasher, key, .Shallow); return hasher.final(); } fn testHashShallow(key: anytype) u64 { // Any hash could be used here, for testing autoHash. var hasher = Wyhash.init(0); hash(&hasher, key, .Shallow); return hasher.final(); } fn testHashDeep(key: anytype) u64 { // Any hash could be used here, for testing autoHash. var hasher = Wyhash.init(0); hash(&hasher, key, .Deep); return hasher.final(); } fn testHashDeepRecursive(key: anytype) u64 { // Any hash could be used here, for testing autoHash. var hasher = Wyhash.init(0); hash(&hasher, key, .DeepRecursive); return hasher.final(); } test "hash pointer" { const array = [_]u32{ 123, 123, 123 }; const a = &array[0]; const b = &array[1]; const c = &array[2]; const d = a; testing.expect(testHashShallow(a) == testHashShallow(d)); testing.expect(testHashShallow(a) != testHashShallow(c)); testing.expect(testHashShallow(a) != testHashShallow(b)); testing.expect(testHashDeep(a) == testHashDeep(a)); testing.expect(testHashDeep(a) == testHashDeep(c)); testing.expect(testHashDeep(a) == testHashDeep(b)); testing.expect(testHashDeepRecursive(a) == testHashDeepRecursive(a)); testing.expect(testHashDeepRecursive(a) == testHashDeepRecursive(c)); testing.expect(testHashDeepRecursive(a) == testHashDeepRecursive(b)); } test "hash slice shallow" { // Allocate one array dynamically so that we're assured it is not merged // with the other by the optimization passes. const array1 = try std.testing.allocator.create([6]u32); defer std.testing.allocator.destroy(array1); array1.* = [_]u32{ 1, 2, 3, 4, 5, 6 }; const array2 = [_]u32{ 1, 2, 3, 4, 5, 6 }; // TODO audit deep/shallow - maybe it has the wrong behavior with respect to array pointers and slices var runtime_zero: usize = 0; const a = array1[runtime_zero..]; const b = array2[runtime_zero..]; const c = array1[runtime_zero..3]; testing.expect(testHashShallow(a) == testHashShallow(a)); testing.expect(testHashShallow(a) != testHashShallow(array1)); testing.expect(testHashShallow(a) != testHashShallow(b)); testing.expect(testHashShallow(a) != testHashShallow(c)); } test "hash slice deep" { // Allocate one array dynamically so that we're assured it is not merged // with the other by the optimization passes. const array1 = try std.testing.allocator.create([6]u32); defer std.testing.allocator.destroy(array1); array1.* = [_]u32{ 1, 2, 3, 4, 5, 6 }; const array2 = [_]u32{ 1, 2, 3, 4, 5, 6 }; const a = array1[0..]; const b = array2[0..]; const c = array1[0..3]; testing.expect(testHashDeep(a) == testHashDeep(a)); testing.expect(testHashDeep(a) == testHashDeep(array1)); testing.expect(testHashDeep(a) == testHashDeep(b)); testing.expect(testHashDeep(a) != testHashDeep(c)); } test "hash struct deep" { const Foo = struct { a: u32, b: u16, c: *bool, const Self = @This(); pub fn init(allocator: *mem.Allocator, a_: u32, b_: u16, c_: bool) !Self { const ptr = try allocator.create(bool); ptr.* = c_; return Self{ .a = a_, .b = b_, .c = ptr }; } }; const allocator = std.testing.allocator; const foo = try Foo.init(allocator, 123, 10, true); const bar = try Foo.init(allocator, 123, 10, true); const baz = try Foo.init(allocator, 123, 10, false); defer allocator.destroy(foo.c); defer allocator.destroy(bar.c); defer allocator.destroy(baz.c); testing.expect(testHashDeep(foo) == testHashDeep(bar)); testing.expect(testHashDeep(foo) != testHashDeep(baz)); testing.expect(testHashDeep(bar) != testHashDeep(baz)); var hasher = Wyhash.init(0); const h = testHashDeep(foo); autoHash(&hasher, foo.a); autoHash(&hasher, foo.b); autoHash(&hasher, foo.c.*); testing.expectEqual(h, hasher.final()); const h2 = testHashDeepRecursive(&foo); testing.expect(h2 != testHashDeep(&foo)); testing.expect(h2 == testHashDeep(foo)); } test "testHash optional" { const a: ?u32 = 123; const b: ?u32 = null; testing.expectEqual(testHash(a), testHash(@as(u32, 123))); testing.expect(testHash(a) != testHash(b)); testing.expectEqual(testHash(b), 0); } test "testHash array" { const a = [_]u32{ 1, 2, 3 }; const h = testHash(a); var hasher = Wyhash.init(0); autoHash(&hasher, @as(u32, 1)); autoHash(&hasher, @as(u32, 2)); autoHash(&hasher, @as(u32, 3)); testing.expectEqual(h, hasher.final()); } test "testHash struct" { const Foo = struct { a: u32 = 1, b: u32 = 2, c: u32 = 3, }; const f = Foo{}; const h = testHash(f); var hasher = Wyhash.init(0); autoHash(&hasher, @as(u32, 1)); autoHash(&hasher, @as(u32, 2)); autoHash(&hasher, @as(u32, 3)); testing.expectEqual(h, hasher.final()); } test "testHash union" { const Foo = union(enum) { A: u32, B: bool, C: u32, }; const a = Foo{ .A = 18 }; var b = Foo{ .B = true }; const c = Foo{ .C = 18 }; testing.expect(testHash(a) == testHash(a)); testing.expect(testHash(a) != testHash(b)); testing.expect(testHash(a) != testHash(c)); b = Foo{ .A = 18 }; testing.expect(testHash(a) == testHash(b)); } test "testHash vector" { // Disabled because of #3317 if (@import("builtin").arch == .mipsel or @import("builtin").arch == .mips) return error.SkipZigTest; const a: meta.Vector(4, u32) = [_]u32{ 1, 2, 3, 4 }; const b: meta.Vector(4, u32) = [_]u32{ 1, 2, 3, 5 }; testing.expect(testHash(a) == testHash(a)); testing.expect(testHash(a) != testHash(b)); const c: meta.Vector(4, u31) = [_]u31{ 1, 2, 3, 4 }; const d: meta.Vector(4, u31) = [_]u31{ 1, 2, 3, 5 }; testing.expect(testHash(c) == testHash(c)); testing.expect(testHash(c) != testHash(d)); } test "testHash error union" { const Errors = error{Test}; const Foo = struct { a: u32 = 1, b: u32 = 2, c: u32 = 3, }; const f = Foo{}; const g: Errors!Foo = Errors.Test; testing.expect(testHash(f) != testHash(g)); testing.expect(testHash(f) == testHash(Foo{})); testing.expect(testHash(g) == testHash(Errors.Test)); }
lib/std/hash/auto_hash.zig
const std = @import("std"); const expect = std.testing.expect; const expectEqualSlices = std.testing.expectEqualSlices; const expectEqual = std.testing.expectEqual; const mem = std.mem; const x = @intToPtr([*]i32, 0x1000)[0..0x500]; const y = x[0x100..]; test "compile time slice of pointer to hard coded address" { try expectEqual(@ptrToInt(x), 0x1000); try expectEqual(x.len, 0x500); try expectEqual(@ptrToInt(y), 0x1100); try expectEqual(y.len, 0x400); } test "runtime safety lets us slice from len..len" { var an_array = [_]u8{ 1, 2, 3, }; try expect(mem.eql(u8, sliceFromLenToLen(an_array[0..], 3, 3), "")); } fn sliceFromLenToLen(a_slice: []u8, start: usize, end: usize) []u8 { return a_slice[start..end]; } test "implicitly cast array of size 0 to slice" { var msg = [_]u8{}; try assertLenIsZero(&msg); } fn assertLenIsZero(msg: []const u8) !void { try expectEqual(msg.len, 0); } test "C pointer" { var buf: [*c]const u8 = "kjdhfkjdhfdkjhfkfjhdfkjdhfkdjhfdkjhf"; var len: u32 = 10; var slice = buf[0..len]; try expectEqualSlices(u8, "kjdhfkjdhf", slice); } test "C pointer slice access" { var buf: [10]u32 = [1]u32{42} ** 10; const c_ptr = @ptrCast([*c]const u32, &buf); var runtime_zero: usize = 0; comptime try expectEqual([]const u32, @TypeOf(c_ptr[runtime_zero..1])); comptime try expectEqual(*const [1]u32, @TypeOf(c_ptr[0..1])); for (c_ptr[0..5]) |*cl| { try expectEqual(@as(u32, 42), cl.*); } } fn sliceSum(comptime q: []const u8) i32 { comptime var result = 0; inline for (q) |item| { result += item; } return result; } test "comptime slices are disambiguated" { try expectEqual(sliceSum(&[_]u8{ 1, 2 }), 3); try expectEqual(sliceSum(&[_]u8{ 3, 4 }), 7); } test "slice type with custom alignment" { const LazilyResolvedType = struct { anything: i32, }; var slice: []align(32) LazilyResolvedType = undefined; var array: [10]LazilyResolvedType align(32) = undefined; slice = &array; slice[1].anything = 42; try expectEqual(array[1].anything, 42); } test "access len index of sentinel-terminated slice" { const S = struct { fn doTheTest() !void { var slice: [:0]const u8 = "hello"; try expectEqual(slice.len, 5); try expectEqual(slice[5], 0); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "obtaining a null terminated slice" { // here we have a normal array var buf: [50]u8 = undefined; buf[0] = 'a'; buf[1] = 'b'; buf[2] = 'c'; buf[3] = 0; // now we obtain a null terminated slice: const ptr = buf[0..3 :0]; _ = ptr; var runtime_len: usize = 3; const ptr2 = buf[0..runtime_len :0]; // ptr2 is a null-terminated slice comptime try expectEqual(@TypeOf(ptr2), [:0]u8); comptime try expectEqual(@TypeOf(ptr2[0..2]), *[2]u8); var runtime_zero: usize = 0; comptime try expectEqual(@TypeOf(ptr2[runtime_zero..2]), []u8); } test "empty array to slice" { const S = struct { fn doTheTest() !void { const empty: []align(16) u8 = &[_]u8{}; const align_1: []align(1) u8 = empty; const align_4: []align(4) u8 = empty; const align_16: []align(16) u8 = empty; try expectEqual(1, @typeInfo(@TypeOf(align_1)).Pointer.alignment); try expectEqual(4, @typeInfo(@TypeOf(align_4)).Pointer.alignment); try expectEqual(16, @typeInfo(@TypeOf(align_16)).Pointer.alignment); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "@ptrCast slice to pointer" { const S = struct { fn doTheTest() !void { var array align(@alignOf(u16)) = [5]u8{ 0xff, 0xff, 0xff, 0xff, 0xff }; var slice: []u8 = &array; var ptr = @ptrCast(*u16, slice); try expectEqual(ptr.*, 65535); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "slice syntax resulting in pointer-to-array" { const S = struct { fn doTheTest() !void { try testArray(); try testArrayZ(); try testArray0(); try testArrayAlign(); try testPointer(); try testPointerZ(); try testPointer0(); try testPointerAlign(); try testSlice(); try testSliceZ(); try testSlice0(); try testSliceOpt(); try testSliceAlign(); } fn testArray() !void { var array = [5]u8{ 1, 2, 3, 4, 5 }; var slice = array[1..3]; comptime try expectEqual(@TypeOf(slice), *[2]u8); try expectEqual(slice[0], 2); try expectEqual(slice[1], 3); } fn testArrayZ() !void { var array = [5:0]u8{ 1, 2, 3, 4, 5 }; comptime try expectEqual(@TypeOf(array[1..3]), *[2]u8); comptime try expectEqual(@TypeOf(array[1..5]), *[4:0]u8); comptime try expectEqual(@TypeOf(array[1..]), *[4:0]u8); comptime try expectEqual(@TypeOf(array[1..3 :4]), *[2:4]u8); } fn testArray0() !void { { var array = [0]u8{}; var slice = array[0..0]; comptime try expectEqual(@TypeOf(slice), *[0]u8); } { var array = [0:0]u8{}; var slice = array[0..0]; comptime try expectEqual(@TypeOf(slice), *[0:0]u8); try expectEqual(slice[0], 0); } } fn testArrayAlign() !void { var array align(4) = [5]u8{ 1, 2, 3, 4, 5 }; var slice = array[4..5]; comptime try expectEqual(@TypeOf(slice), *align(4) [1]u8); try expectEqual(slice[0], 5); comptime try expectEqual(@TypeOf(array[0..2]), *align(4) [2]u8); } fn testPointer() !void { var array = [5]u8{ 1, 2, 3, 4, 5 }; var pointer: [*]u8 = &array; var slice = pointer[1..3]; comptime try expectEqual(@TypeOf(slice), *[2]u8); try expectEqual(slice[0], 2); try expectEqual(slice[1], 3); } fn testPointerZ() !void { var array = [5:0]u8{ 1, 2, 3, 4, 5 }; var pointer: [*:0]u8 = &array; comptime try expectEqual(@TypeOf(pointer[1..3]), *[2]u8); comptime try expectEqual(@TypeOf(pointer[1..3 :4]), *[2:4]u8); } fn testPointer0() !void { var pointer: [*]const u0 = &[1]u0{0}; var slice = pointer[0..1]; comptime try expectEqual(@TypeOf(slice), *const [1]u0); try expectEqual(slice[0], 0); } fn testPointerAlign() !void { var array align(4) = [5]u8{ 1, 2, 3, 4, 5 }; var pointer: [*]align(4) u8 = &array; var slice = pointer[4..5]; comptime try expectEqual(@TypeOf(slice), *align(4) [1]u8); try expectEqual(slice[0], 5); comptime try expectEqual(@TypeOf(pointer[0..2]), *align(4) [2]u8); } fn testSlice() !void { var array = [5]u8{ 1, 2, 3, 4, 5 }; var src_slice: []u8 = &array; var slice = src_slice[1..3]; comptime try expectEqual(@TypeOf(slice), *[2]u8); try expectEqual(slice[0], 2); try expectEqual(slice[1], 3); } fn testSliceZ() !void { var array = [5:0]u8{ 1, 2, 3, 4, 5 }; var slice: [:0]u8 = &array; comptime try expectEqual(@TypeOf(slice[1..3]), *[2]u8); comptime try expectEqual(@TypeOf(slice[1..]), [:0]u8); comptime try expectEqual(@TypeOf(slice[1..3 :4]), *[2:4]u8); } fn testSliceOpt() !void { var array: [2]u8 = [2]u8{ 1, 2 }; var slice: ?[]u8 = &array; comptime try expectEqual(@TypeOf(&array, slice), ?[]u8); comptime try expectEqual(@TypeOf(slice.?[0..2]), *[2]u8); } fn testSlice0() !void { { var array = [0]u8{}; var src_slice: []u8 = &array; var slice = src_slice[0..0]; comptime try expectEqual(@TypeOf(slice), *[0]u8); } { var array = [0:0]u8{}; var src_slice: [:0]u8 = &array; var slice = src_slice[0..0]; comptime try expectEqual(@TypeOf(slice), *[0]u8); } } fn testSliceAlign() !void { var array align(4) = [5]u8{ 1, 2, 3, 4, 5 }; var src_slice: []align(4) u8 = &array; var slice = src_slice[4..5]; comptime try expectEqual(@TypeOf(slice), *align(4) [1]u8); try expectEqual(slice[0], 5); comptime try expectEqual(@TypeOf(src_slice[0..2]), *align(4) [2]u8); } fn testConcatStrLiterals() !void { try expectEqualSlices("a"[0..] ++ "b"[0..], "ab"); try expectEqualSlices("a"[0.. :0] ++ "b"[0.. :0], "ab"); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "slice of hardcoded address to pointer" { const S = struct { fn doTheTest() !void { const pointer = @intToPtr([*]u8, 0x04)[0..2]; comptime try expectEqual(@TypeOf(pointer), *[2]u8); const slice: []const u8 = pointer; try expectEqual(@ptrToInt(slice.ptr), 4); try expectEqual(slice.len, 2); } }; try S.doTheTest(); } test "type coercion of pointer to anon struct literal to pointer to slice" { const S = struct { const U = union { a: u32, b: bool, c: []const u8, }; fn doTheTest() !void { var x1: u8 = 42; const t1 = &.{ x1, 56, 54 }; var slice1: []const u8 = t1; try expectEqual(slice1.len, 3); try expectEqual(slice1[0], 42); try expectEqual(slice1[1], 56); try expectEqual(slice1[2], 54); var x2: []const u8 = "hello"; const t2 = &.{ x2, ", ", "world!" }; // @compileLog(@TypeOf(t2)); var slice2: []const []const u8 = t2; try expectEqual(slice2.len, 3); try expect(mem.eql(u8, slice2[0], "hello")); try expect(mem.eql(u8, slice2[1], ", ")); try expect(mem.eql(u8, slice2[2], "world!")); } }; // try S.doTheTest(); comptime try S.doTheTest(); }
test/behavior/slice.zig
const std = @import("std"); const unicode = std.unicode; bytes: []const u8, current: ?u21, i: usize, prev: ?u21, prev_i: usize, const Self = @This(); pub fn init(str: []const u8) !Self { if (!unicode.utf8ValidateSlice(str)) { return error.InvalidUtf8; } return Self{ .bytes = str, .current = null, .i = 0, .prev = null, .prev_i = 0, }; } // nexCodePointSlice retrieves the next code point's bytes. pub fn nextCodePointSlice(self: *Self) ?[]const u8 { if (self.i >= self.bytes.len) { return null; } const cp_len = unicode.utf8ByteSequenceLength(self.bytes[self.i]) catch unreachable; self.prev_i = self.i; self.i += cp_len; return self.bytes[self.i - cp_len .. self.i]; } /// nextCodePoint retrieves the next code point as a single u21. pub fn next(self: *Self) ?u21 { const slice = self.nextCodePointSlice() orelse return null; self.prev = self.current; switch (slice.len) { 1 => self.current = @as(u21, slice[0]), 2 => self.current = unicode.utf8Decode2(slice) catch unreachable, 3 => self.current = unicode.utf8Decode3(slice) catch unreachable, 4 => self.current = unicode.utf8Decode4(slice) catch unreachable, else => unreachable, } return self.current; } /// peekN looks ahead at the next n codepoints without advancing the iterator. /// If fewer than n codepoints are available, then return the remainder of the string. pub fn peekN(self: *Self) []const u8 { const original_i = self.i; defer self.i = original_i; var end_ix = original_i; var found: usize = 0; while (found < n) : (found += 1) { const next_codepoint = self.nextCodePointSlice() orelse return self.bytes[original_i..]; end_ix += next_codepoint.len; } return self.bytes[original_i..end_ix]; } /// peek looks ahead at the next codepoint without advancing the iterator. pub fn peek(self: *Self) ?u21 { const original_i = self.i; const original_prev_i = self.prev_i; const original_prev = self.prev; defer { self.i = original_i; self.prev_i = original_prev_i; self.prev = original_prev; } return self.next(); } /// reset prepares the iterator to start over iteration. pub fn reset(self: *Self) void { self.current = null; self.i = 0; self.prev = null; self.prev_i = 0; }
src/zigstr/CodePointIterator.zig
const std = @import("std"); usingnamespace @import("imgui.zig"); pub const icons = @import("font_awesome.zig"); extern fn _ogImage(user_texture_id: ImTextureID, size: *const ImVec2, uv0: *const ImVec2, uv1: *const ImVec2) void; extern fn _ogImageButton(user_texture_id: ImTextureID, size: *const ImVec2, uv0: *const ImVec2, uv1: *const ImVec2, frame_padding: c_int) bool; extern fn _ogColoredText(r: f32, g: f32, b: f32, text: [*c]const u8) void; // arm64 cant send ImVec2s to anything... extern fn _ogButton(label: [*c]const u8, x: f32, y: f32) bool; extern fn _ogImDrawData_ScaleClipRects(self: [*c]ImDrawData, fb_scale: f32) void; extern fn _ogDockBuilderSetNodeSize(node_id: ImGuiID, size: *const ImVec2) void; extern fn _ogSetNextWindowPos(pos: *const ImVec2, cond: ImGuiCond, pivot: *const ImVec2) void; extern fn _ogSetNextWindowSize(size: *const ImVec2, cond: ImGuiCond) void; extern fn _ogPushStyleVarVec2(idx: ImGuiStyleVar, w: f32, y: f32) void; extern fn _ogInvisibleButton(str_id: [*c]const u8, w: f32, h: f32, flags: ImGuiButtonFlags) bool; extern fn _ogSelectableBool(label: [*c]const u8, selected: bool, flags: ImGuiSelectableFlags, w: f32, h: f32) bool; extern fn _ogDummy(w: f32, h: f32) void; extern fn _ogBeginChildFrame(id: ImGuiID, w: f32, h: f32, flags: ImGuiWindowFlags) bool; extern fn _ogBeginChildEx(name: [*c]const u8, id: ImGuiID, size_arg: *const ImVec2, border: bool, flags: ImGuiWindowFlags) bool; extern fn _ogDockSpace(id: ImGuiID, w: f32, h: f32, flags: ImGuiDockNodeFlags, window_class: [*c]const ImGuiWindowClass) void; extern fn _ogImDrawList_AddQuad(self: [*c]ImDrawList, p1: *const ImVec2, p2: *const ImVec2, p3: *const ImVec2, p4: *const ImVec2, col: ImU32, thickness: f32) void; extern fn _ogImDrawList_AddQuadFilled(self: [*c]ImDrawList, p1: *const ImVec2, p2: *const ImVec2, p3: *const ImVec2, p4: *const ImVec2, col: ImU32) void; extern fn _ogImDrawList_AddImage(self: [*c]ImDrawList, id: ImTextureID, p_min: *const ImVec2, p_max: *const ImVec2, uv_min: *const ImVec2, uv_max: *const ImVec2, col: ImU32) void; extern fn _ogImDrawList_AddLine(self: [*c]ImDrawList, p1: *const ImVec2, p2: *const ImVec2, col: ImU32, thickness: f32) void; extern fn _ogSetCursorScreenPos(pos: *const ImVec2) void; extern fn _ogListBoxHeaderVec2(label: [*c]const u8, size: *const ImVec2) bool; extern fn _ogColorConvertFloat4ToU32(color: *const ImVec4 ) ImU32; // implementations for ABI incompatibility bugs pub fn ogImage(texture: ImTextureID, width: i32, height: i32) void { var size = ImVec2{ .x = @intToFloat(f32, width), .y = @intToFloat(f32, height) }; _ogImage(texture, &size, &ImVec2{}, &ImVec2{ .x = 1, .y = 1 }); } pub fn ogImageButton(texture: ImTextureID, size: ImVec2, uv0: ImVec2, uv1: ImVec2, frame_padding: c_int) bool { return ogImageButtonEx(texture, size, uv0, uv1, frame_padding, .{}, .{ .x = 1, .y = 1, .z = 1, .w = 1 }); } pub fn ogImageButtonEx(texture: ImTextureID, size: ImVec2, uv0: ImVec2, uv1: ImVec2, frame_padding: c_int, bg_col: ImVec4, tint_col: ImVec4) bool { _ = tint_col; _ = bg_col; return _ogImageButton(texture, &size, &uv0, &uv1, frame_padding); } pub fn ogColoredText(r: f32, g: f32, b: f32, text: [:0]const u8) void { _ogColoredText(r, g, b, text); } pub fn ogButton(label: [*c]const u8) bool { return _ogButton(label, 0, 0); } pub fn ogButtonEx(label: [*c]const u8, size: ImVec2) bool { return _ogButton(label, size.x, size.y); } pub fn ogImDrawData_ScaleClipRects(self: [*c]ImDrawData, fb_scale: ImVec2) void { _ogImDrawData_ScaleClipRects(self, fb_scale.x); } pub fn ogDockBuilderSetNodeSize(node_id: ImGuiID, size: ImVec2) void { _ogDockBuilderSetNodeSize(node_id, &size); } pub fn ogSetNextWindowPos(pos: ImVec2, cond: ImGuiCond, pivot: ImVec2) void { _ogSetNextWindowPos(&pos, cond, &pivot); } pub fn ogSetNextWindowSize(size: ImVec2, cond: ImGuiCond) void { _ogSetNextWindowSize(&size, cond); } pub fn ogPushStyleVarVec2(idx: ImGuiStyleVar, val: ImVec2) void { _ogPushStyleVarVec2(idx, val.x, val.y); } pub fn ogInvisibleButton(str_id: [*c]const u8, size: ImVec2, flags: ImGuiButtonFlags) bool { return _ogInvisibleButton(str_id, size.x, size.y, flags); } pub fn ogSelectableBool(label: [*c]const u8, selected: bool, flags: ImGuiSelectableFlags, size: ImVec2) bool { return _ogSelectableBool(label, selected, flags, size.x, size.y); } pub fn ogDummy(size: ImVec2) void { _ogDummy(size.x, size.y); } pub fn ogSetCursorPos(cursor: ImVec2) void { igSetCursorPosX(cursor.x); igSetCursorPosY(cursor.y); } pub fn ogBeginChildFrame(id: ImGuiID, size: ImVec2, flags: ImGuiWindowFlags) bool { return _ogBeginChildFrame(id, size.x, size.y, flags); } pub fn ogBeginChildEx(name: [*c]const u8, id: ImGuiID, size_arg: ImVec2, border: bool, flags: ImGuiWindowFlags) bool { return _ogBeginChildEx(name, id, &size_arg, border, flags); } pub fn ogDockSpace(id: ImGuiID, size: ImVec2, flags: ImGuiDockNodeFlags, window_class: [*c]const ImGuiWindowClass) void { _ogDockSpace(id, size.x, size.y, flags, window_class); } pub fn ogImDrawList_AddQuad(draw_list: [*c]ImDrawList, p1: *ImVec2, p2: *ImVec2, p3: *ImVec2, p4: *ImVec2, col: ImU32, thickness: f32) void { _ogImDrawList_AddQuad(draw_list, p1, p2, p3, p4, col, thickness); } pub fn ogImDrawList_AddQuadFilled(draw_list: [*c]ImDrawList, p1: *ImVec2, p2: *ImVec2, p3: *ImVec2, p4: *ImVec2, col: ImU32) void { _ogImDrawList_AddQuadFilled(draw_list, p1, p2, p3, p4, col); } pub fn ogImDrawList_AddImage( draw_list: [*c]ImDrawList, id: ImTextureID, p_min: ImVec2, p_max: ImVec2, uv_min: ImVec2, uv_max: ImVec2, col: ImU32) void { _ogImDrawList_AddImage(draw_list, id, &p_min, &p_max, &uv_min, &uv_max, col); } /// adds a rect outline with possibly non-matched width/height to the draw list pub fn ogAddRect(draw_list: [*c]ImDrawList, tl: ImVec2, size: ImVec2, col: ImU32, thickness: f32) void { _ogImDrawList_AddQuad(draw_list, &ImVec2{ .x = tl.x, .y = tl.y }, &ImVec2{ .x = tl.x + size.x, .y = tl.y }, &ImVec2{ .x = tl.x + size.x, .y = tl.y + size.y }, &ImVec2{ .x = tl.x, .y = tl.y + size.y }, col, thickness); } pub fn ogImDrawList_AddLine(draw_list: [*c]ImDrawList, p1: ImVec2, p2: ImVec2, col: ImU32, thickness: f32) void { _ogImDrawList_AddLine(draw_list, &p1, &p2, col, thickness); } pub fn ogSetCursorScreenPos(pos: ImVec2) void { _ogSetCursorScreenPos(&pos); } pub fn ogListBoxHeaderVec2(label: [*c]const u8, size: ImVec2) bool { return _ogListBoxHeaderVec2(label, &size); } // just plain helper methods pub fn ogOpenPopup(str_id: [*c]const u8) void { igOpenPopup(str_id); } pub fn ogColoredButton(color: ImU32, label: [*c]const u8) bool { return ogColoredButtonEx(color, label, .{}); } pub fn ogColoredButtonEx(color: ImU32, label: [*c]const u8, size: ImVec2) bool { igPushStyleColorU32(ImGuiCol_Button, color); defer igPopStyleColor(1); return ogButtonEx(label, size); } pub fn ogPushIDUsize(id: usize) void { igPushIDInt(@intCast(c_int, id)); } /// helper to shorten disabling controls via ogPushDisabled; defer ogPopDisabled; due to defer not working inside the if block. pub fn ogPushDisabled(should_push: bool) void { if (should_push) { igPushItemFlag(ImGuiItemFlags_Disabled, true); igPushStyleVarFloat(ImGuiStyleVar_Alpha, 0.7); } } pub fn ogPopDisabled(should_pop: bool) void { if (should_pop) { igPopItemFlag(); igPopStyleVar(1); } } /// only true if down this frame and not down the previous frame pub fn ogKeyPressed(key: usize) bool { return igGetIO().KeysDown[key] and igGetIO().KeysDownDuration[key] == 0; } /// true the entire time the key is down pub fn ogKeyDown(key: usize) bool { return igGetIO().KeysDown[key]; } /// true only the frame the key is released pub fn ogKeyUp(key: usize) bool { return !igGetIO().KeysDown[key] and igGetIO().KeysDownDuration[key] == -1 and igGetIO().KeysDownDurationPrev[key] >= 0; } pub fn ogGetCursorScreenPos() ImVec2 { var pos = ImVec2{}; igGetCursorScreenPos(&pos); return pos; } pub fn ogGetCursorPos() ImVec2 { var pos = ImVec2{}; igGetCursorPos(&pos); return pos; } pub fn ogGetWindowSize() ImVec2 { var pos = ImVec2{}; igGetWindowSize(&pos); return pos; } pub fn ogGetWindowPos() ImVec2 { var pos = ImVec2{}; igGetWindowPos(&pos); return pos; } pub fn ogGetItemRectSize() ImVec2 { var size = ImVec2{}; igGetItemRectSize(&size); return size; } pub fn ogGetItemRectMax() ImVec2 { var size = ImVec2{}; igGetItemRectMax(&size); return size; } pub fn ogGetMouseDragDelta(button: ImGuiMouseButton, lock_threshold: f32) ImVec2 { var pos = ImVec2{}; igGetMouseDragDelta(&pos, button, lock_threshold); return pos; } /// returns the drag delta of the mouse buttons that is dragging pub fn ogGetAnyMouseDragDelta() ImVec2 { var drag_delta = ImVec2{}; if (igIsMouseDragging(ImGuiMouseButton_Left, 0)) { igGetMouseDragDelta(&drag_delta, ImGuiMouseButton_Left, 0); } else { igGetMouseDragDelta(&drag_delta, ImGuiMouseButton_Right, 0); } return drag_delta; } /// returns true if any mouse is dragging pub fn ogIsAnyMouseDragging() bool { return igIsMouseDragging(ImGuiMouseButton_Left, 0) or igIsMouseDragging(ImGuiMouseButton_Right, 0); } pub fn ogIsAnyMouseDown() bool { return igIsMouseDown(ImGuiMouseButton_Left) or igIsMouseDown(ImGuiMouseButton_Right); } pub fn ogIsAnyMouseReleased() bool { return igIsMouseReleased(ImGuiMouseButton_Left) or igIsMouseReleased(ImGuiMouseButton_Right); } pub fn ogGetContentRegionAvail() ImVec2 { var pos = ImVec2{}; igGetContentRegionAvail(&pos); return pos; } pub fn ogGetWindowContentRegionMax() ImVec2 { var max = ImVec2{}; igGetWindowContentRegionMax(&max); return max; } pub fn ogGetWindowCenter() ImVec2 { var max = ogGetWindowContentRegionMax(); max.x /= 2; max.y /= 2; return max; } pub fn ogAddQuad(draw_list: [*c]ImDrawList, tl: ImVec2, size: f32, col: ImU32, thickness: f32) void { ogImDrawList_AddQuad(draw_list, &ImVec2{ .x = tl.x, .y = tl.y }, &ImVec2{ .x = tl.x + size, .y = tl.y }, &ImVec2{ .x = tl.x + size, .y = tl.y + size }, &ImVec2{ .x = tl.x, .y = tl.y + size }, col, thickness); } pub fn ogAddQuadFilled(draw_list: [*c]ImDrawList, tl: ImVec2, size: f32, col: ImU32) void { ogImDrawList_AddQuadFilled(draw_list, &ImVec2{ .x = tl.x, .y = tl.y }, &ImVec2{ .x = tl.x + size, .y = tl.y }, &ImVec2{ .x = tl.x + size, .y = tl.y + size }, &ImVec2{ .x = tl.x, .y = tl.y + size }, col); } /// adds a rect with possibly non-matched width/height to the draw list pub fn ogAddRectFilled(draw_list: [*c]ImDrawList, tl: ImVec2, size: ImVec2, col: ImU32) void { ogImDrawList_AddQuadFilled(draw_list, &ImVec2{ .x = tl.x, .y = tl.y }, &ImVec2{ .x = tl.x + size.x, .y = tl.y }, &ImVec2{ .x = tl.x + size.x, .y = tl.y + size.y }, &ImVec2{ .x = tl.x, .y = tl.y + size.y }, col); } pub fn ogInputText(label: [*c]const u8, buf: [*c]u8, buf_size: usize) bool { return igInputText(label, buf, buf_size, ImGuiInputTextFlags_None, null, null); } pub fn ogInputTextEnter(label: [*c]const u8, buf: [*c]u8, buf_size: usize) bool { return igInputText(label, buf, buf_size, ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll, null, null); } /// adds an unformatted (igTextUnformatted) tooltip with a specific wrap width pub fn ogUnformattedTooltip(text_wrap_pos: f32, text: [*c]const u8) void { if (igIsItemHovered(ImGuiHoveredFlags_None)) { igBeginTooltip(); defer igEndTooltip(); igPushTextWrapPos(igGetFontSize() * text_wrap_pos); igTextUnformatted(text, null); igPopTextWrapPos(); } } pub fn ogDrag(comptime T: type, label: [*c]const u8, p_data: *T, v_speed: f32, p_min: T, p_max: T) bool { if (std.meta.trait.isUnsignedInt(T)) { return ogDragUnsignedFormat(T, label, p_data, v_speed, p_min, p_max, "%u"); } else if (T == f32) { return ogDragSigned(T, label, p_data, v_speed, p_min, p_max); } return ogDragSigned(T, label, p_data, v_speed, p_min, p_max); } pub fn ogDragUnsignedFormat(comptime T: type, label: [*c]const u8, p_data: *T, v_speed: f32, p_min: T, p_max: T, format: [*c]const u8) bool { std.debug.assert(std.meta.trait.isUnsignedInt(T)); var min = p_min; var max = p_max; const data_type = switch (T) { u8 => ImGuiDataType_U8, u16 => ImGuiDataType_U16, u32 => ImGuiDataType_U32, usize => ImGuiDataType_U64, else => unreachable, }; return igDragScalar(label, data_type, p_data, v_speed, &min, &max, format, 1); } pub fn ogDragSigned(comptime T: type, label: [*c]const u8, p_data: *T, v_speed: f32, p_min: T, p_max: T) bool { var min = p_min; var max = p_max; const data_type = switch (T) { i16 => ImGuiDataType_S16, i32 => ImGuiDataType_S32, f32 => ImGuiDataType_Float, else => unreachable, }; return igDragScalar(label, data_type, p_data, v_speed, &min, &max, "%.2f", 1); } pub fn ogDragSignedFormat(comptime T: type, label: [*c]const u8, p_data: *T, v_speed: f32, p_min: T, p_max: T, format: [*c]const u8) bool { var min = p_min; var max = p_max; const data_type = switch (T) { i16 => ImGuiDataType_S16, i32 => ImGuiDataType_S32, f32 => ImGuiDataType_Float, else => unreachable, }; return igDragScalar(label, data_type, p_data, v_speed, &min, &max, format, 1); } pub fn ogColorConvertU32ToFloat4(in: ImU32) ImVec4 { var col = ImVec4{}; igColorConvertU32ToFloat4(&col, in); return col; } pub fn ogColorConvertFloat4ToU32 (in: ImVec4) ImU32 { return _ogColorConvertFloat4ToU32(&in); }
src/deps/imgui/wrapper.zig
const std = @import("std"); const root = @import("root"); const req = @import("request.zig"); const resp = @import("response.zig"); const net = std.net; const atomic = std.atomic; const log = std.log.scoped(.apple_pie); const Response = resp.Response; const Request = req.Request; const Allocator = std.mem.Allocator; const Queue = atomic.Queue; /// User API function signature of a request handler pub const RequestHandler = fn handle(*Response, Request) anyerror!void; /// Allows users to set the max buffer size before we allocate memory on the heap to store our data const max_buffer_size: usize = if (@hasField(root, "buffer_size")) root.buffer_size else 4096; /// Allows users to set the max request header buffer size before we return error.RequestTooLarge. const max_request_size: usize = if (@hasField(root, "request_buffer_size")) root.request_buffer_size else 4096; /// Creates a new `Server` instance and starts listening to new connections /// Afterwards cleans up any resources. /// /// This creates a `Server` with default options, meaning it uses 4096 bytes /// max for parsing request headers and 4096 bytes as a stack buffer before it /// will allocate any memory /// /// If the server needs the ability to be shutdown on command, use `Server.init()` /// and then start it by calling `run()`. pub fn listenAndServe( /// Memory allocator, for general usage. /// Will be used to setup an arena to free any request/response data. gpa: *Allocator, /// Address the server is listening at address: net.Address, /// User defined `Request`/`Response` handler comptime handler: RequestHandler, ) !void { try (Server.init()).run(gpa, address, handler); } pub const Server = struct { should_quit: atomic.Bool, /// Initializes a new `Server` instance pub fn init() Server { return .{ .should_quit = atomic.Bool.init(false) }; } /// Starts listening to new connections and serves the responses /// Cleans up any resources that were allocated during the connection pub fn run( self: *Server, /// Memory allocator, for general usage. /// Will be used to setup an arena to free any request/response data. gpa: *Allocator, /// Address the server is listening at address: net.Address, /// User defined `Request`/`Response` handler comptime handler: RequestHandler, ) !void { var stream = net.StreamServer.init(.{ .reuse_address = true }); defer stream.deinit(); // client queue to clean up clients after connection is broken/finished const Client = ClientFn(handler); var clients = Queue(*Client).init(); // Force clean up any remaining clients that are still connected // if an error occured defer while (clients.get()) |node| { const data = node.data; data.stream.close(); gpa.destroy(data); }; try stream.listen(address); while (!self.should_quit.load(.SeqCst)) { var connection = stream.accept() catch |err| switch (err) { error.ConnectionResetByPeer, error.ConnectionAborted => { log.err("Could not accept connection: '{s}'", .{@errorName(err)}); continue; }, else => return err, }; // setup client connection and handle it const client = try gpa.create(Client); client.* = Client{ .stream = connection.stream, .node = .{ .data = client }, .frame = async client.run(gpa, &clients), }; while (clients.get()) |node| { const data = node.data; await data.frame; gpa.destroy(data); } } } /// Tells the server to shutdown pub fn shutdown(self: *Server) void { self.should_quit.store(true, .SeqCst); } }; /// Generic Client handler wrapper around the given `T` of `RequestHandler`. /// Allows us to wrap our client connection base around the given user defined handler /// without allocating data on the heap for it fn ClientFn(comptime handler: RequestHandler) type { return struct { const Self = @This(); /// Frame of the client, used to ensure its lifetime along the Client's frame: @Frame(run), /// Streaming connection to the peer stream: net.Stream, /// Node used to cleanup itself after a connection is finished node: Queue(*Self).Node, /// Handles the client connection. First parses the client into a `Request`, and then calls the user defined /// client handler defined in `T`, and finally sends the final `Response` to the client. /// If the connection is below version HTTP1/1, the connection will be broken and no keep-alive is supported. /// Same for blocking instances, to ensure multiple clients can connect (synchronously). /// NOTE: This is a wrapper function around `handle` so we can catch any errors and handle them accordingly /// as we do not want to crash the server when an error occurs. fn run(self: *Self, gpa: *Allocator, clients: *Queue(*Self)) void { self.handle(gpa, clients) catch |err| { log.err("An error occured handling request: '{s}'", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } }; } fn handle(self: *Self, gpa: *Allocator, clients: *Queue(*Self)) !void { defer { self.stream.close(); clients.put(&self.node); } while (true) { var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); var stack_allocator = std.heap.stackFallback(max_buffer_size, &arena.allocator); var body = std.ArrayList(u8).init(gpa); defer body.deinit(); var response = Response{ .headers = resp.Headers.init(stack_allocator.get()), .buffered_writer = std.io.bufferedWriter(self.stream.writer()), .is_flushed = false, .body = body.writer(), }; var buffer: [max_request_size]u8 = undefined; const parsed_request = req.parse( stack_allocator.get(), self.stream.reader(), &buffer, ) catch |err| switch (err) { // not an error, client disconnected error.EndOfStream, error.ConnectionResetByPeer => return, error.HeadersTooLarge => return response.writeHeader(.request_header_fields_too_large), else => return response.writeHeader(.bad_request), }; try handler(&response, parsed_request); if (parsed_request.protocol == .http1_1 and parsed_request.host == null) { return response.writeHeader(.bad_request); } if (!response.is_flushed) try response.flush(); // ensure data is flushed if (parsed_request.should_close) return; // close connection if (!std.io.is_async) return; // io_mode = blocking } } }; } test "Basic server test" { if (std.builtin.single_threaded) return error.SkipZigTest; const alloc = std.testing.allocator; const test_message = "Hello, Apple pie!"; const address = try net.Address.parseIp("0.0.0.0", 8080); var server = Server.init(); const server_thread = struct { var _addr: net.Address = undefined; fn index(response: *Response, request: Request) !void { try response.writer().writeAll(test_message); } fn runServer(context: *Server) !void { try context.run(alloc, _addr, index); } }; server_thread._addr = address; const thread = try std.Thread.spawn(&server, server_thread.runServer); errdefer server.shutdown(); var stream = while (true) { var conn = net.tcpConnectToAddress(address) catch |err| switch (err) { error.ConnectionRefused => continue, else => return err, }; break conn; } else unreachable; errdefer stream.close(); // tell server to shutdown // fill finish current request and then shutdown server.shutdown(); try stream.writer().writeAll("GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"); var buf: [512]u8 = undefined; const len = try stream.reader().read(&buf); stream.close(); thread.wait(); const index = std.mem.indexOf(u8, buf[0..len], "\r\n\r\n") orelse return error.Unexpected; const answer = buf[index + 4 .. len]; std.testing.expectEqualStrings(test_message, answer); }
src/server.zig
pub fn isWhiteSpace(cp: u21) bool { if (cp < 0x9 or cp > 0x3000) return false; return switch (cp) { 0x9...0xd => true, 0x20 => true, 0x85 => true, 0xa0 => true, 0x1680 => true, 0x2000...0x200a => true, 0x2028 => true, 0x2029 => true, 0x202f => true, 0x205f => true, 0x3000 => true, else => false, }; } pub fn isBidiControl(cp: u21) bool { if (cp < 0x61c or cp > 0x2069) return false; return switch (cp) { 0x61c => true, 0x200e...0x200f => true, 0x202a...0x202e => true, 0x2066...0x2069 => true, else => false, }; } pub fn isJoinControl(cp: u21) bool { if (cp < 0x200c or cp > 0x200d) return false; return switch (cp) { 0x200c...0x200d => true, else => false, }; } pub fn isDash(cp: u21) bool { if (cp < 0x2d or cp > 0x10ead) return false; return switch (cp) { 0x2d => true, 0x58a => true, 0x5be => true, 0x1400 => true, 0x1806 => true, 0x2010...0x2015 => true, 0x2053 => true, 0x207b => true, 0x208b => true, 0x2212 => true, 0x2e17 => true, 0x2e1a => true, 0x2e3a...0x2e3b => true, 0x2e40 => true, 0x2e5d => true, 0x301c => true, 0x3030 => true, 0x30a0 => true, 0xfe31...0xfe32 => true, 0xfe58 => true, 0xfe63 => true, 0xff0d => true, 0x10ead => true, else => false, }; } pub fn isHyphen(cp: u21) bool { if (cp < 0x2d or cp > 0xff65) return false; return switch (cp) { 0x2d => true, 0xad => true, 0x58a => true, 0x1806 => true, 0x2010...0x2011 => true, 0x2e17 => true, 0x30fb => true, 0xfe63 => true, 0xff0d => true, 0xff65 => true, else => false, }; } pub fn isQuotationMark(cp: u21) bool { if (cp < 0x22 or cp > 0xff63) return false; return switch (cp) { 0x22 => true, 0x27 => true, 0xab => true, 0xbb => true, 0x2018 => true, 0x2019 => true, 0x201a => true, 0x201b...0x201c => true, 0x201d => true, 0x201e => true, 0x201f => true, 0x2039 => true, 0x203a => true, 0x2e42 => true, 0x300c => true, 0x300d => true, 0x300e => true, 0x300f => true, 0x301d => true, 0x301e...0x301f => true, 0xfe41 => true, 0xfe42 => true, 0xfe43 => true, 0xfe44 => true, 0xff02 => true, 0xff07 => true, 0xff62 => true, 0xff63 => true, else => false, }; } pub fn isTerminalPunctuation(cp: u21) bool { if (cp < 0x21 or cp > 0x1da8a) return false; return switch (cp) { 0x21 => true, 0x2c => true, 0x2e => true, 0x3a...0x3b => true, 0x3f => true, 0x37e => true, 0x387 => true, 0x589 => true, 0x5c3 => true, 0x60c => true, 0x61b => true, 0x61d...0x61f => true, 0x6d4 => true, 0x700...0x70a => true, 0x70c => true, 0x7f8...0x7f9 => true, 0x830...0x83e => true, 0x85e => true, 0x964...0x965 => true, 0xe5a...0xe5b => true, 0xf08 => true, 0xf0d...0xf12 => true, 0x104a...0x104b => true, 0x1361...0x1368 => true, 0x166e => true, 0x16eb...0x16ed => true, 0x1735...0x1736 => true, 0x17d4...0x17d6 => true, 0x17da => true, 0x1802...0x1805 => true, 0x1808...0x1809 => true, 0x1944...0x1945 => true, 0x1aa8...0x1aab => true, 0x1b5a...0x1b5b => true, 0x1b5d...0x1b5f => true, 0x1b7d...0x1b7e => true, 0x1c3b...0x1c3f => true, 0x1c7e...0x1c7f => true, 0x203c...0x203d => true, 0x2047...0x2049 => true, 0x2e2e => true, 0x2e3c => true, 0x2e41 => true, 0x2e4c => true, 0x2e4e...0x2e4f => true, 0x2e53...0x2e54 => true, 0x3001...0x3002 => true, 0xa4fe...0xa4ff => true, 0xa60d...0xa60f => true, 0xa6f3...0xa6f7 => true, 0xa876...0xa877 => true, 0xa8ce...0xa8cf => true, 0xa92f => true, 0xa9c7...0xa9c9 => true, 0xaa5d...0xaa5f => true, 0xaadf => true, 0xaaf0...0xaaf1 => true, 0xabeb => true, 0xfe50...0xfe52 => true, 0xfe54...0xfe57 => true, 0xff01 => true, 0xff0c => true, 0xff0e => true, 0xff1a...0xff1b => true, 0xff1f => true, 0xff61 => true, 0xff64 => true, 0x1039f => true, 0x103d0 => true, 0x10857 => true, 0x1091f => true, 0x10a56...0x10a57 => true, 0x10af0...0x10af5 => true, 0x10b3a...0x10b3f => true, 0x10b99...0x10b9c => true, 0x10f55...0x10f59 => true, 0x10f86...0x10f89 => true, 0x11047...0x1104d => true, 0x110be...0x110c1 => true, 0x11141...0x11143 => true, 0x111c5...0x111c6 => true, 0x111cd => true, 0x111de...0x111df => true, 0x11238...0x1123c => true, 0x112a9 => true, 0x1144b...0x1144d => true, 0x1145a...0x1145b => true, 0x115c2...0x115c5 => true, 0x115c9...0x115d7 => true, 0x11641...0x11642 => true, 0x1173c...0x1173e => true, 0x11944 => true, 0x11946 => true, 0x11a42...0x11a43 => true, 0x11a9b...0x11a9c => true, 0x11aa1...0x11aa2 => true, 0x11c41...0x11c43 => true, 0x11c71 => true, 0x11ef7...0x11ef8 => true, 0x12470...0x12474 => true, 0x16a6e...0x16a6f => true, 0x16af5 => true, 0x16b37...0x16b39 => true, 0x16b44 => true, 0x16e97...0x16e98 => true, 0x1bc9f => true, 0x1da87...0x1da8a => true, else => false, }; } pub fn isOtherMath(cp: u21) bool { if (cp < 0x5e or cp > 0x1eebb) return false; return switch (cp) { 0x5e => true, 0x3d0...0x3d2 => true, 0x3d5 => true, 0x3f0...0x3f1 => true, 0x3f4...0x3f5 => true, 0x2016 => true, 0x2032...0x2034 => true, 0x2040 => true, 0x2061...0x2064 => true, 0x207d => true, 0x207e => true, 0x208d => true, 0x208e => true, 0x20d0...0x20dc => true, 0x20e1 => true, 0x20e5...0x20e6 => true, 0x20eb...0x20ef => true, 0x2102 => true, 0x2107 => true, 0x210a...0x2113 => true, 0x2115 => true, 0x2119...0x211d => true, 0x2124 => true, 0x2128 => true, 0x2129 => true, 0x212c...0x212d => true, 0x212f...0x2131 => true, 0x2133...0x2134 => true, 0x2135...0x2138 => true, 0x213c...0x213f => true, 0x2145...0x2149 => true, 0x2195...0x2199 => true, 0x219c...0x219f => true, 0x21a1...0x21a2 => true, 0x21a4...0x21a5 => true, 0x21a7 => true, 0x21a9...0x21ad => true, 0x21b0...0x21b1 => true, 0x21b6...0x21b7 => true, 0x21bc...0x21cd => true, 0x21d0...0x21d1 => true, 0x21d3 => true, 0x21d5...0x21db => true, 0x21dd => true, 0x21e4...0x21e5 => true, 0x2308 => true, 0x2309 => true, 0x230a => true, 0x230b => true, 0x23b4...0x23b5 => true, 0x23b7 => true, 0x23d0 => true, 0x23e2 => true, 0x25a0...0x25a1 => true, 0x25ae...0x25b6 => true, 0x25bc...0x25c0 => true, 0x25c6...0x25c7 => true, 0x25ca...0x25cb => true, 0x25cf...0x25d3 => true, 0x25e2 => true, 0x25e4 => true, 0x25e7...0x25ec => true, 0x2605...0x2606 => true, 0x2640 => true, 0x2642 => true, 0x2660...0x2663 => true, 0x266d...0x266e => true, 0x27c5 => true, 0x27c6 => true, 0x27e6 => true, 0x27e7 => true, 0x27e8 => true, 0x27e9 => true, 0x27ea => true, 0x27eb => true, 0x27ec => true, 0x27ed => true, 0x27ee => true, 0x27ef => true, 0x2983 => true, 0x2984 => true, 0x2985 => true, 0x2986 => true, 0x2987 => true, 0x2988 => true, 0x2989 => true, 0x298a => true, 0x298b => true, 0x298c => true, 0x298d => true, 0x298e => true, 0x298f => true, 0x2990 => true, 0x2991 => true, 0x2992 => true, 0x2993 => true, 0x2994 => true, 0x2995 => true, 0x2996 => true, 0x2997 => true, 0x2998 => true, 0x29d8 => true, 0x29d9 => true, 0x29da => true, 0x29db => true, 0x29fc => true, 0x29fd => true, 0xfe61 => true, 0xfe63 => true, 0xfe68 => true, 0xff3c => true, 0xff3e => true, 0x1d400...0x1d454 => true, 0x1d456...0x1d49c => true, 0x1d49e...0x1d49f => true, 0x1d4a2 => true, 0x1d4a5...0x1d4a6 => true, 0x1d4a9...0x1d4ac => true, 0x1d4ae...0x1d4b9 => true, 0x1d4bb => true, 0x1d4bd...0x1d4c3 => true, 0x1d4c5...0x1d505 => true, 0x1d507...0x1d50a => true, 0x1d50d...0x1d514 => true, 0x1d516...0x1d51c => true, 0x1d51e...0x1d539 => true, 0x1d53b...0x1d53e => true, 0x1d540...0x1d544 => true, 0x1d546 => true, 0x1d54a...0x1d550 => true, 0x1d552...0x1d6a5 => true, 0x1d6a8...0x1d6c0 => true, 0x1d6c2...0x1d6da => true, 0x1d6dc...0x1d6fa => true, 0x1d6fc...0x1d714 => true, 0x1d716...0x1d734 => true, 0x1d736...0x1d74e => true, 0x1d750...0x1d76e => true, 0x1d770...0x1d788 => true, 0x1d78a...0x1d7a8 => true, 0x1d7aa...0x1d7c2 => true, 0x1d7c4...0x1d7cb => true, 0x1d7ce...0x1d7ff => true, 0x1ee00...0x1ee03 => true, 0x1ee05...0x1ee1f => true, 0x1ee21...0x1ee22 => true, 0x1ee24 => true, 0x1ee27 => true, 0x1ee29...0x1ee32 => true, 0x1ee34...0x1ee37 => true, 0x1ee39 => true, 0x1ee3b => true, 0x1ee42 => true, 0x1ee47 => true, 0x1ee49 => true, 0x1ee4b => true, 0x1ee4d...0x1ee4f => true, 0x1ee51...0x1ee52 => true, 0x1ee54 => true, 0x1ee57 => true, 0x1ee59 => true, 0x1ee5b => true, 0x1ee5d => true, 0x1ee5f => true, 0x1ee61...0x1ee62 => true, 0x1ee64 => true, 0x1ee67...0x1ee6a => true, 0x1ee6c...0x1ee72 => true, 0x1ee74...0x1ee77 => true, 0x1ee79...0x1ee7c => true, 0x1ee7e => true, 0x1ee80...0x1ee89 => true, 0x1ee8b...0x1ee9b => true, 0x1eea1...0x1eea3 => true, 0x1eea5...0x1eea9 => true, 0x1eeab...0x1eebb => true, else => false, }; } pub fn isHexDigit(cp: u21) bool { if (cp < 0x30 or cp > 0xff46) return false; return switch (cp) { 0x30...0x39 => true, 0x41...0x46 => true, 0x61...0x66 => true, 0xff10...0xff19 => true, 0xff21...0xff26 => true, 0xff41...0xff46 => true, else => false, }; } pub fn isASCIIHexDigit(cp: u21) bool { if (cp < 0x30 or cp > 0x66) return false; return switch (cp) { 0x30...0x39 => true, 0x41...0x46 => true, 0x61...0x66 => true, else => false, }; } pub fn isOtherAlphabetic(cp: u21) bool { if (cp < 0x345 or cp > 0x1f189) return false; return switch (cp) { 0x345 => true, 0x5b0...0x5bd => true, 0x5bf => true, 0x5c1...0x5c2 => true, 0x5c4...0x5c5 => true, 0x5c7 => true, 0x610...0x61a => true, 0x64b...0x657 => true, 0x659...0x65f => true, 0x670 => true, 0x6d6...0x6dc => true, 0x6e1...0x6e4 => true, 0x6e7...0x6e8 => true, 0x6ed => true, 0x711 => true, 0x730...0x73f => true, 0x7a6...0x7b0 => true, 0x816...0x817 => true, 0x81b...0x823 => true, 0x825...0x827 => true, 0x829...0x82c => true, 0x8d4...0x8df => true, 0x8e3...0x8e9 => true, 0x8f0...0x902 => true, 0x903 => true, 0x93a => true, 0x93b => true, 0x93e...0x940 => true, 0x941...0x948 => true, 0x949...0x94c => true, 0x94e...0x94f => true, 0x955...0x957 => true, 0x962...0x963 => true, 0x981 => true, 0x982...0x983 => true, 0x9be...0x9c0 => true, 0x9c1...0x9c4 => true, 0x9c7...0x9c8 => true, 0x9cb...0x9cc => true, 0x9d7 => true, 0x9e2...0x9e3 => true, 0xa01...0xa02 => true, 0xa03 => true, 0xa3e...0xa40 => true, 0xa41...0xa42 => true, 0xa47...0xa48 => true, 0xa4b...0xa4c => true, 0xa51 => true, 0xa70...0xa71 => true, 0xa75 => true, 0xa81...0xa82 => true, 0xa83 => true, 0xabe...0xac0 => true, 0xac1...0xac5 => true, 0xac7...0xac8 => true, 0xac9 => true, 0xacb...0xacc => true, 0xae2...0xae3 => true, 0xafa...0xafc => true, 0xb01 => true, 0xb02...0xb03 => true, 0xb3e => true, 0xb3f => true, 0xb40 => true, 0xb41...0xb44 => true, 0xb47...0xb48 => true, 0xb4b...0xb4c => true, 0xb56 => true, 0xb57 => true, 0xb62...0xb63 => true, 0xb82 => true, 0xbbe...0xbbf => true, 0xbc0 => true, 0xbc1...0xbc2 => true, 0xbc6...0xbc8 => true, 0xbca...0xbcc => true, 0xbd7 => true, 0xc00 => true, 0xc01...0xc03 => true, 0xc3e...0xc40 => true, 0xc41...0xc44 => true, 0xc46...0xc48 => true, 0xc4a...0xc4c => true, 0xc55...0xc56 => true, 0xc62...0xc63 => true, 0xc81 => true, 0xc82...0xc83 => true, 0xcbe => true, 0xcbf => true, 0xcc0...0xcc4 => true, 0xcc6 => true, 0xcc7...0xcc8 => true, 0xcca...0xccb => true, 0xccc => true, 0xcd5...0xcd6 => true, 0xce2...0xce3 => true, 0xd00...0xd01 => true, 0xd02...0xd03 => true, 0xd3e...0xd40 => true, 0xd41...0xd44 => true, 0xd46...0xd48 => true, 0xd4a...0xd4c => true, 0xd57 => true, 0xd62...0xd63 => true, 0xd81 => true, 0xd82...0xd83 => true, 0xdcf...0xdd1 => true, 0xdd2...0xdd4 => true, 0xdd6 => true, 0xdd8...0xddf => true, 0xdf2...0xdf3 => true, 0xe31 => true, 0xe34...0xe3a => true, 0xe4d => true, 0xeb1 => true, 0xeb4...0xeb9 => true, 0xebb...0xebc => true, 0xecd => true, 0xf71...0xf7e => true, 0xf7f => true, 0xf80...0xf81 => true, 0xf8d...0xf97 => true, 0xf99...0xfbc => true, 0x102b...0x102c => true, 0x102d...0x1030 => true, 0x1031 => true, 0x1032...0x1036 => true, 0x1038 => true, 0x103b...0x103c => true, 0x103d...0x103e => true, 0x1056...0x1057 => true, 0x1058...0x1059 => true, 0x105e...0x1060 => true, 0x1062...0x1064 => true, 0x1067...0x106d => true, 0x1071...0x1074 => true, 0x1082 => true, 0x1083...0x1084 => true, 0x1085...0x1086 => true, 0x1087...0x108c => true, 0x108d => true, 0x108f => true, 0x109a...0x109c => true, 0x109d => true, 0x1712...0x1713 => true, 0x1732...0x1733 => true, 0x1752...0x1753 => true, 0x1772...0x1773 => true, 0x17b6 => true, 0x17b7...0x17bd => true, 0x17be...0x17c5 => true, 0x17c6 => true, 0x17c7...0x17c8 => true, 0x1885...0x1886 => true, 0x18a9 => true, 0x1920...0x1922 => true, 0x1923...0x1926 => true, 0x1927...0x1928 => true, 0x1929...0x192b => true, 0x1930...0x1931 => true, 0x1932 => true, 0x1933...0x1938 => true, 0x1a17...0x1a18 => true, 0x1a19...0x1a1a => true, 0x1a1b => true, 0x1a55 => true, 0x1a56 => true, 0x1a57 => true, 0x1a58...0x1a5e => true, 0x1a61 => true, 0x1a62 => true, 0x1a63...0x1a64 => true, 0x1a65...0x1a6c => true, 0x1a6d...0x1a72 => true, 0x1a73...0x1a74 => true, 0x1abf...0x1ac0 => true, 0x1acc...0x1ace => true, 0x1b00...0x1b03 => true, 0x1b04 => true, 0x1b35 => true, 0x1b36...0x1b3a => true, 0x1b3b => true, 0x1b3c => true, 0x1b3d...0x1b41 => true, 0x1b42 => true, 0x1b43 => true, 0x1b80...0x1b81 => true, 0x1b82 => true, 0x1ba1 => true, 0x1ba2...0x1ba5 => true, 0x1ba6...0x1ba7 => true, 0x1ba8...0x1ba9 => true, 0x1bac...0x1bad => true, 0x1be7 => true, 0x1be8...0x1be9 => true, 0x1bea...0x1bec => true, 0x1bed => true, 0x1bee => true, 0x1bef...0x1bf1 => true, 0x1c24...0x1c2b => true, 0x1c2c...0x1c33 => true, 0x1c34...0x1c35 => true, 0x1c36 => true, 0x1de7...0x1df4 => true, 0x24b6...0x24e9 => true, 0x2de0...0x2dff => true, 0xa674...0xa67b => true, 0xa69e...0xa69f => true, 0xa802 => true, 0xa80b => true, 0xa823...0xa824 => true, 0xa825...0xa826 => true, 0xa827 => true, 0xa880...0xa881 => true, 0xa8b4...0xa8c3 => true, 0xa8c5 => true, 0xa8ff => true, 0xa926...0xa92a => true, 0xa947...0xa951 => true, 0xa952 => true, 0xa980...0xa982 => true, 0xa983 => true, 0xa9b4...0xa9b5 => true, 0xa9b6...0xa9b9 => true, 0xa9ba...0xa9bb => true, 0xa9bc...0xa9bd => true, 0xa9be...0xa9bf => true, 0xa9e5 => true, 0xaa29...0xaa2e => true, 0xaa2f...0xaa30 => true, 0xaa31...0xaa32 => true, 0xaa33...0xaa34 => true, 0xaa35...0xaa36 => true, 0xaa43 => true, 0xaa4c => true, 0xaa4d => true, 0xaa7b => true, 0xaa7c => true, 0xaa7d => true, 0xaab0 => true, 0xaab2...0xaab4 => true, 0xaab7...0xaab8 => true, 0xaabe => true, 0xaaeb => true, 0xaaec...0xaaed => true, 0xaaee...0xaaef => true, 0xaaf5 => true, 0xabe3...0xabe4 => true, 0xabe5 => true, 0xabe6...0xabe7 => true, 0xabe8 => true, 0xabe9...0xabea => true, 0xfb1e => true, 0x10376...0x1037a => true, 0x10a01...0x10a03 => true, 0x10a05...0x10a06 => true, 0x10a0c...0x10a0f => true, 0x10d24...0x10d27 => true, 0x10eab...0x10eac => true, 0x11000 => true, 0x11001 => true, 0x11002 => true, 0x11038...0x11045 => true, 0x11073...0x11074 => true, 0x11082 => true, 0x110b0...0x110b2 => true, 0x110b3...0x110b6 => true, 0x110b7...0x110b8 => true, 0x110c2 => true, 0x11100...0x11102 => true, 0x11127...0x1112b => true, 0x1112c => true, 0x1112d...0x11132 => true, 0x11145...0x11146 => true, 0x11180...0x11181 => true, 0x11182 => true, 0x111b3...0x111b5 => true, 0x111b6...0x111be => true, 0x111bf => true, 0x111ce => true, 0x111cf => true, 0x1122c...0x1122e => true, 0x1122f...0x11231 => true, 0x11232...0x11233 => true, 0x11234 => true, 0x11237 => true, 0x1123e => true, 0x112df => true, 0x112e0...0x112e2 => true, 0x112e3...0x112e8 => true, 0x11300...0x11301 => true, 0x11302...0x11303 => true, 0x1133e...0x1133f => true, 0x11340 => true, 0x11341...0x11344 => true, 0x11347...0x11348 => true, 0x1134b...0x1134c => true, 0x11357 => true, 0x11362...0x11363 => true, 0x11435...0x11437 => true, 0x11438...0x1143f => true, 0x11440...0x11441 => true, 0x11443...0x11444 => true, 0x11445 => true, 0x114b0...0x114b2 => true, 0x114b3...0x114b8 => true, 0x114b9 => true, 0x114ba => true, 0x114bb...0x114be => true, 0x114bf...0x114c0 => true, 0x114c1 => true, 0x115af...0x115b1 => true, 0x115b2...0x115b5 => true, 0x115b8...0x115bb => true, 0x115bc...0x115bd => true, 0x115be => true, 0x115dc...0x115dd => true, 0x11630...0x11632 => true, 0x11633...0x1163a => true, 0x1163b...0x1163c => true, 0x1163d => true, 0x1163e => true, 0x11640 => true, 0x116ab => true, 0x116ac => true, 0x116ad => true, 0x116ae...0x116af => true, 0x116b0...0x116b5 => true, 0x1171d...0x1171f => true, 0x11720...0x11721 => true, 0x11722...0x11725 => true, 0x11726 => true, 0x11727...0x1172a => true, 0x1182c...0x1182e => true, 0x1182f...0x11837 => true, 0x11838 => true, 0x11930...0x11935 => true, 0x11937...0x11938 => true, 0x1193b...0x1193c => true, 0x11940 => true, 0x11942 => true, 0x119d1...0x119d3 => true, 0x119d4...0x119d7 => true, 0x119da...0x119db => true, 0x119dc...0x119df => true, 0x119e4 => true, 0x11a01...0x11a0a => true, 0x11a35...0x11a38 => true, 0x11a39 => true, 0x11a3b...0x11a3e => true, 0x11a51...0x11a56 => true, 0x11a57...0x11a58 => true, 0x11a59...0x11a5b => true, 0x11a8a...0x11a96 => true, 0x11a97 => true, 0x11c2f => true, 0x11c30...0x11c36 => true, 0x11c38...0x11c3d => true, 0x11c3e => true, 0x11c92...0x11ca7 => true, 0x11ca9 => true, 0x11caa...0x11cb0 => true, 0x11cb1 => true, 0x11cb2...0x11cb3 => true, 0x11cb4 => true, 0x11cb5...0x11cb6 => true, 0x11d31...0x11d36 => true, 0x11d3a => true, 0x11d3c...0x11d3d => true, 0x11d3f...0x11d41 => true, 0x11d43 => true, 0x11d47 => true, 0x11d8a...0x11d8e => true, 0x11d90...0x11d91 => true, 0x11d93...0x11d94 => true, 0x11d95 => true, 0x11d96 => true, 0x11ef3...0x11ef4 => true, 0x11ef5...0x11ef6 => true, 0x16f4f => true, 0x16f51...0x16f87 => true, 0x16f8f...0x16f92 => true, 0x16ff0...0x16ff1 => true, 0x1bc9e => true, 0x1e000...0x1e006 => true, 0x1e008...0x1e018 => true, 0x1e01b...0x1e021 => true, 0x1e023...0x1e024 => true, 0x1e026...0x1e02a => true, 0x1e947 => true, 0x1f130...0x1f149 => true, 0x1f150...0x1f169 => true, 0x1f170...0x1f189 => true, else => false, }; } pub fn isIdeographic(cp: u21) bool { if (cp < 0x3006 or cp > 0x3134a) return false; return switch (cp) { 0x3006 => true, 0x3007 => true, 0x3021...0x3029 => true, 0x3038...0x303a => true, 0x3400...0x4dbf => true, 0x4e00...0x9fff => true, 0xf900...0xfa6d => true, 0xfa70...0xfad9 => true, 0x16fe4 => true, 0x17000...0x187f7 => true, 0x18800...0x18cd5 => true, 0x18d00...0x18d08 => true, 0x1b170...0x1b2fb => true, 0x20000...0x2a6df => true, 0x2a700...0x2b738 => true, 0x2b740...0x2b81d => true, 0x2b820...0x2cea1 => true, 0x2ceb0...0x2ebe0 => true, 0x2f800...0x2fa1d => true, 0x30000...0x3134a => true, else => false, }; } pub fn isDiacritic(cp: u21) bool { if (cp < 0x5e or cp > 0x1e94a) return false; return switch (cp) { 0x5e => true, 0x60 => true, 0xa8 => true, 0xaf => true, 0xb4 => true, 0xb7 => true, 0xb8 => true, 0x2b0...0x2c1 => true, 0x2c2...0x2c5 => true, 0x2c6...0x2d1 => true, 0x2d2...0x2df => true, 0x2e0...0x2e4 => true, 0x2e5...0x2eb => true, 0x2ec => true, 0x2ed => true, 0x2ee => true, 0x2ef...0x2ff => true, 0x300...0x34e => true, 0x350...0x357 => true, 0x35d...0x362 => true, 0x374 => true, 0x375 => true, 0x37a => true, 0x384...0x385 => true, 0x483...0x487 => true, 0x559 => true, 0x591...0x5a1 => true, 0x5a3...0x5bd => true, 0x5bf => true, 0x5c1...0x5c2 => true, 0x5c4 => true, 0x64b...0x652 => true, 0x657...0x658 => true, 0x6df...0x6e0 => true, 0x6e5...0x6e6 => true, 0x6ea...0x6ec => true, 0x730...0x74a => true, 0x7a6...0x7b0 => true, 0x7eb...0x7f3 => true, 0x7f4...0x7f5 => true, 0x818...0x819 => true, 0x898...0x89f => true, 0x8c9 => true, 0x8ca...0x8d2 => true, 0x8e3...0x8fe => true, 0x93c => true, 0x94d => true, 0x951...0x954 => true, 0x971 => true, 0x9bc => true, 0x9cd => true, 0xa3c => true, 0xa4d => true, 0xabc => true, 0xacd => true, 0xafd...0xaff => true, 0xb3c => true, 0xb4d => true, 0xb55 => true, 0xbcd => true, 0xc3c => true, 0xc4d => true, 0xcbc => true, 0xccd => true, 0xd3b...0xd3c => true, 0xd4d => true, 0xdca => true, 0xe47...0xe4c => true, 0xe4e => true, 0xeba => true, 0xec8...0xecc => true, 0xf18...0xf19 => true, 0xf35 => true, 0xf37 => true, 0xf39 => true, 0xf3e...0xf3f => true, 0xf82...0xf84 => true, 0xf86...0xf87 => true, 0xfc6 => true, 0x1037 => true, 0x1039...0x103a => true, 0x1063...0x1064 => true, 0x1069...0x106d => true, 0x1087...0x108c => true, 0x108d => true, 0x108f => true, 0x109a...0x109b => true, 0x135d...0x135f => true, 0x1714 => true, 0x1715 => true, 0x17c9...0x17d3 => true, 0x17dd => true, 0x1939...0x193b => true, 0x1a75...0x1a7c => true, 0x1a7f => true, 0x1ab0...0x1abd => true, 0x1abe => true, 0x1ac1...0x1acb => true, 0x1b34 => true, 0x1b44 => true, 0x1b6b...0x1b73 => true, 0x1baa => true, 0x1bab => true, 0x1c36...0x1c37 => true, 0x1c78...0x1c7d => true, 0x1cd0...0x1cd2 => true, 0x1cd3 => true, 0x1cd4...0x1ce0 => true, 0x1ce1 => true, 0x1ce2...0x1ce8 => true, 0x1ced => true, 0x1cf4 => true, 0x1cf7 => true, 0x1cf8...0x1cf9 => true, 0x1d2c...0x1d6a => true, 0x1dc4...0x1dcf => true, 0x1df5...0x1dff => true, 0x1fbd => true, 0x1fbf...0x1fc1 => true, 0x1fcd...0x1fcf => true, 0x1fdd...0x1fdf => true, 0x1fed...0x1fef => true, 0x1ffd...0x1ffe => true, 0x2cef...0x2cf1 => true, 0x2e2f => true, 0x302a...0x302d => true, 0x302e...0x302f => true, 0x3099...0x309a => true, 0x309b...0x309c => true, 0x30fc => true, 0xa66f => true, 0xa67c...0xa67d => true, 0xa67f => true, 0xa69c...0xa69d => true, 0xa6f0...0xa6f1 => true, 0xa700...0xa716 => true, 0xa717...0xa71f => true, 0xa720...0xa721 => true, 0xa788 => true, 0xa789...0xa78a => true, 0xa7f8...0xa7f9 => true, 0xa8c4 => true, 0xa8e0...0xa8f1 => true, 0xa92b...0xa92d => true, 0xa92e => true, 0xa953 => true, 0xa9b3 => true, 0xa9c0 => true, 0xa9e5 => true, 0xaa7b => true, 0xaa7c => true, 0xaa7d => true, 0xaabf => true, 0xaac0 => true, 0xaac1 => true, 0xaac2 => true, 0xaaf6 => true, 0xab5b => true, 0xab5c...0xab5f => true, 0xab69 => true, 0xab6a...0xab6b => true, 0xabec => true, 0xabed => true, 0xfb1e => true, 0xfe20...0xfe2f => true, 0xff3e => true, 0xff40 => true, 0xff70 => true, 0xff9e...0xff9f => true, 0xffe3 => true, 0x102e0 => true, 0x10780...0x10785 => true, 0x10787...0x107b0 => true, 0x107b2...0x107ba => true, 0x10ae5...0x10ae6 => true, 0x10d22...0x10d23 => true, 0x10d24...0x10d27 => true, 0x10f46...0x10f50 => true, 0x10f82...0x10f85 => true, 0x11046 => true, 0x11070 => true, 0x110b9...0x110ba => true, 0x11133...0x11134 => true, 0x11173 => true, 0x111c0 => true, 0x111ca...0x111cc => true, 0x11235 => true, 0x11236 => true, 0x112e9...0x112ea => true, 0x1133c => true, 0x1134d => true, 0x11366...0x1136c => true, 0x11370...0x11374 => true, 0x11442 => true, 0x11446 => true, 0x114c2...0x114c3 => true, 0x115bf...0x115c0 => true, 0x1163f => true, 0x116b6 => true, 0x116b7 => true, 0x1172b => true, 0x11839...0x1183a => true, 0x1193d => true, 0x1193e => true, 0x11943 => true, 0x119e0 => true, 0x11a34 => true, 0x11a47 => true, 0x11a99 => true, 0x11c3f => true, 0x11d42 => true, 0x11d44...0x11d45 => true, 0x11d97 => true, 0x16af0...0x16af4 => true, 0x16b30...0x16b36 => true, 0x16f8f...0x16f92 => true, 0x16f93...0x16f9f => true, 0x16ff0...0x16ff1 => true, 0x1aff0...0x1aff3 => true, 0x1aff5...0x1affb => true, 0x1affd...0x1affe => true, 0x1cf00...0x1cf2d => true, 0x1cf30...0x1cf46 => true, 0x1d167...0x1d169 => true, 0x1d16d...0x1d172 => true, 0x1d17b...0x1d182 => true, 0x1d185...0x1d18b => true, 0x1d1aa...0x1d1ad => true, 0x1e130...0x1e136 => true, 0x1e2ae => true, 0x1e2ec...0x1e2ef => true, 0x1e8d0...0x1e8d6 => true, 0x1e944...0x1e946 => true, 0x1e948...0x1e94a => true, else => false, }; } pub fn isExtender(cp: u21) bool { if (cp < 0xb7 or cp > 0x1e946) return false; return switch (cp) { 0xb7 => true, 0x2d0...0x2d1 => true, 0x640 => true, 0x7fa => true, 0xb55 => true, 0xe46 => true, 0xec6 => true, 0x180a => true, 0x1843 => true, 0x1aa7 => true, 0x1c36 => true, 0x1c7b => true, 0x3005 => true, 0x3031...0x3035 => true, 0x309d...0x309e => true, 0x30fc...0x30fe => true, 0xa015 => true, 0xa60c => true, 0xa9cf => true, 0xa9e6 => true, 0xaa70 => true, 0xaadd => true, 0xaaf3...0xaaf4 => true, 0xff70 => true, 0x10781...0x10782 => true, 0x1135d => true, 0x115c6...0x115c8 => true, 0x11a98 => true, 0x16b42...0x16b43 => true, 0x16fe0...0x16fe1 => true, 0x16fe3 => true, 0x1e13c...0x1e13d => true, 0x1e944...0x1e946 => true, else => false, }; } pub fn isOtherLowercase(cp: u21) bool { if (cp < 0xaa or cp > 0x107ba) return false; return switch (cp) { 0xaa => true, 0xba => true, 0x2b0...0x2b8 => true, 0x2c0...0x2c1 => true, 0x2e0...0x2e4 => true, 0x345 => true, 0x37a => true, 0x1d2c...0x1d6a => true, 0x1d78 => true, 0x1d9b...0x1dbf => true, 0x2071 => true, 0x207f => true, 0x2090...0x209c => true, 0x2170...0x217f => true, 0x24d0...0x24e9 => true, 0x2c7c...0x2c7d => true, 0xa69c...0xa69d => true, 0xa770 => true, 0xa7f8...0xa7f9 => true, 0xab5c...0xab5f => true, 0x10780 => true, 0x10783...0x10785 => true, 0x10787...0x107b0 => true, 0x107b2...0x107ba => true, else => false, }; } pub fn isOtherUppercase(cp: u21) bool { if (cp < 0x2160 or cp > 0x1f189) return false; return switch (cp) { 0x2160...0x216f => true, 0x24b6...0x24cf => true, 0x1f130...0x1f149 => true, 0x1f150...0x1f169 => true, 0x1f170...0x1f189 => true, else => false, }; } pub fn isNoncharacterCodePoint(cp: u21) bool { if (cp < 0xfdd0 or cp > 0x10ffff) return false; return switch (cp) { 0xfdd0...0xfdef => true, 0xfffe...0xffff => true, 0x1fffe...0x1ffff => true, 0x2fffe...0x2ffff => true, 0x3fffe...0x3ffff => true, 0x4fffe...0x4ffff => true, 0x5fffe...0x5ffff => true, 0x6fffe...0x6ffff => true, 0x7fffe...0x7ffff => true, 0x8fffe...0x8ffff => true, 0x9fffe...0x9ffff => true, 0xafffe...0xaffff => true, 0xbfffe...0xbffff => true, 0xcfffe...0xcffff => true, 0xdfffe...0xdffff => true, 0xefffe...0xeffff => true, 0xffffe...0xfffff => true, 0x10fffe...0x10ffff => true, else => false, }; } pub fn isOtherGraphemeExtend(cp: u21) bool { if (cp < 0x9be or cp > 0xe007f) return false; return switch (cp) { 0x9be => true, 0x9d7 => true, 0xb3e => true, 0xb57 => true, 0xbbe => true, 0xbd7 => true, 0xcc2 => true, 0xcd5...0xcd6 => true, 0xd3e => true, 0xd57 => true, 0xdcf => true, 0xddf => true, 0x1b35 => true, 0x200c => true, 0x302e...0x302f => true, 0xff9e...0xff9f => true, 0x1133e => true, 0x11357 => true, 0x114b0 => true, 0x114bd => true, 0x115af => true, 0x11930 => true, 0x1d165 => true, 0x1d16e...0x1d172 => true, 0xe0020...0xe007f => true, else => false, }; } pub fn isIDSBinaryOperator(cp: u21) bool { if (cp < 0x2ff0 or cp > 0x2ffb) return false; return switch (cp) { 0x2ff0...0x2ff1 => true, 0x2ff4...0x2ffb => true, else => false, }; } pub fn isIDSTrinaryOperator(cp: u21) bool { if (cp < 0x2ff2 or cp > 0x2ff3) return false; return switch (cp) { 0x2ff2...0x2ff3 => true, else => false, }; } pub fn isRadical(cp: u21) bool { if (cp < 0x2e80 or cp > 0x2fd5) return false; return switch (cp) { 0x2e80...0x2e99 => true, 0x2e9b...0x2ef3 => true, 0x2f00...0x2fd5 => true, else => false, }; } pub fn isUnifiedIdeograph(cp: u21) bool { if (cp < 0x3400 or cp > 0x3134a) return false; return switch (cp) { 0x3400...0x4dbf => true, 0x4e00...0x9fff => true, 0xfa0e...0xfa0f => true, 0xfa11 => true, 0xfa13...0xfa14 => true, 0xfa1f => true, 0xfa21 => true, 0xfa23...0xfa24 => true, 0xfa27...0xfa29 => true, 0x20000...0x2a6df => true, 0x2a700...0x2b738 => true, 0x2b740...0x2b81d => true, 0x2b820...0x2cea1 => true, 0x2ceb0...0x2ebe0 => true, 0x30000...0x3134a => true, else => false, }; } pub fn isOtherDefaultIgnorableCodePoint(cp: u21) bool { if (cp < 0x34f or cp > 0xe0fff) return false; return switch (cp) { 0x34f => true, 0x115f...0x1160 => true, 0x17b4...0x17b5 => true, 0x2065 => true, 0x3164 => true, 0xffa0 => true, 0xfff0...0xfff8 => true, 0xe0000 => true, 0xe0002...0xe001f => true, 0xe0080...0xe00ff => true, 0xe01f0...0xe0fff => true, else => false, }; } pub fn isDeprecated(cp: u21) bool { if (cp < 0x149 or cp > 0xe0001) return false; return switch (cp) { 0x149 => true, 0x673 => true, 0xf77 => true, 0xf79 => true, 0x17a3...0x17a4 => true, 0x206a...0x206f => true, 0x2329 => true, 0x232a => true, 0xe0001 => true, else => false, }; } pub fn isSoftDotted(cp: u21) bool { if (cp < 0x69 or cp > 0x1df1a) return false; return switch (cp) { 0x69...0x6a => true, 0x12f => true, 0x249 => true, 0x268 => true, 0x29d => true, 0x2b2 => true, 0x3f3 => true, 0x456 => true, 0x458 => true, 0x1d62 => true, 0x1d96 => true, 0x1da4 => true, 0x1da8 => true, 0x1e2d => true, 0x1ecb => true, 0x2071 => true, 0x2148...0x2149 => true, 0x2c7c => true, 0x1d422...0x1d423 => true, 0x1d456...0x1d457 => true, 0x1d48a...0x1d48b => true, 0x1d4be...0x1d4bf => true, 0x1d4f2...0x1d4f3 => true, 0x1d526...0x1d527 => true, 0x1d55a...0x1d55b => true, 0x1d58e...0x1d58f => true, 0x1d5c2...0x1d5c3 => true, 0x1d5f6...0x1d5f7 => true, 0x1d62a...0x1d62b => true, 0x1d65e...0x1d65f => true, 0x1d692...0x1d693 => true, 0x1df1a => true, else => false, }; } pub fn isLogicalOrderException(cp: u21) bool { if (cp < 0xe40 or cp > 0xaabc) return false; return switch (cp) { 0xe40...0xe44 => true, 0xec0...0xec4 => true, 0x19b5...0x19b7 => true, 0x19ba => true, 0xaab5...0xaab6 => true, 0xaab9 => true, 0xaabb...0xaabc => true, else => false, }; } pub fn isOtherIDStart(cp: u21) bool { if (cp < 0x1885 or cp > 0x309c) return false; return switch (cp) { 0x1885...0x1886 => true, 0x2118 => true, 0x212e => true, 0x309b...0x309c => true, else => false, }; } pub fn isOtherIDContinue(cp: u21) bool { if (cp < 0xb7 or cp > 0x19da) return false; return switch (cp) { 0xb7 => true, 0x387 => true, 0x1369...0x1371 => true, 0x19da => true, else => false, }; } pub fn isSentenceTerminal(cp: u21) bool { if (cp < 0x21 or cp > 0x1da88) return false; return switch (cp) { 0x21 => true, 0x2e => true, 0x3f => true, 0x589 => true, 0x61d...0x61f => true, 0x6d4 => true, 0x700...0x702 => true, 0x7f9 => true, 0x837 => true, 0x839 => true, 0x83d...0x83e => true, 0x964...0x965 => true, 0x104a...0x104b => true, 0x1362 => true, 0x1367...0x1368 => true, 0x166e => true, 0x1735...0x1736 => true, 0x1803 => true, 0x1809 => true, 0x1944...0x1945 => true, 0x1aa8...0x1aab => true, 0x1b5a...0x1b5b => true, 0x1b5e...0x1b5f => true, 0x1b7d...0x1b7e => true, 0x1c3b...0x1c3c => true, 0x1c7e...0x1c7f => true, 0x203c...0x203d => true, 0x2047...0x2049 => true, 0x2e2e => true, 0x2e3c => true, 0x2e53...0x2e54 => true, 0x3002 => true, 0xa4ff => true, 0xa60e...0xa60f => true, 0xa6f3 => true, 0xa6f7 => true, 0xa876...0xa877 => true, 0xa8ce...0xa8cf => true, 0xa92f => true, 0xa9c8...0xa9c9 => true, 0xaa5d...0xaa5f => true, 0xaaf0...0xaaf1 => true, 0xabeb => true, 0xfe52 => true, 0xfe56...0xfe57 => true, 0xff01 => true, 0xff0e => true, 0xff1f => true, 0xff61 => true, 0x10a56...0x10a57 => true, 0x10f55...0x10f59 => true, 0x10f86...0x10f89 => true, 0x11047...0x11048 => true, 0x110be...0x110c1 => true, 0x11141...0x11143 => true, 0x111c5...0x111c6 => true, 0x111cd => true, 0x111de...0x111df => true, 0x11238...0x11239 => true, 0x1123b...0x1123c => true, 0x112a9 => true, 0x1144b...0x1144c => true, 0x115c2...0x115c3 => true, 0x115c9...0x115d7 => true, 0x11641...0x11642 => true, 0x1173c...0x1173e => true, 0x11944 => true, 0x11946 => true, 0x11a42...0x11a43 => true, 0x11a9b...0x11a9c => true, 0x11c41...0x11c42 => true, 0x11ef7...0x11ef8 => true, 0x16a6e...0x16a6f => true, 0x16af5 => true, 0x16b37...0x16b38 => true, 0x16b44 => true, 0x16e98 => true, 0x1bc9f => true, 0x1da88 => true, else => false, }; } pub fn isVariationSelector(cp: u21) bool { if (cp < 0x180b or cp > 0xe01ef) return false; return switch (cp) { 0x180b...0x180d => true, 0x180f => true, 0xfe00...0xfe0f => true, 0xe0100...0xe01ef => true, else => false, }; } pub fn isPatternWhiteSpace(cp: u21) bool { if (cp < 0x9 or cp > 0x2029) return false; return switch (cp) { 0x9...0xd => true, 0x20 => true, 0x85 => true, 0x200e...0x200f => true, 0x2028 => true, 0x2029 => true, else => false, }; } pub fn isPatternSyntax(cp: u21) bool { if (cp < 0x21 or cp > 0xfe46) return false; return switch (cp) { 0x21...0x23 => true, 0x24 => true, 0x25...0x27 => true, 0x28 => true, 0x29 => true, 0x2a => true, 0x2b => true, 0x2c => true, 0x2d => true, 0x2e...0x2f => true, 0x3a...0x3b => true, 0x3c...0x3e => true, 0x3f...0x40 => true, 0x5b => true, 0x5c => true, 0x5d => true, 0x5e => true, 0x60 => true, 0x7b => true, 0x7c => true, 0x7d => true, 0x7e => true, 0xa1 => true, 0xa2...0xa5 => true, 0xa6 => true, 0xa7 => true, 0xa9 => true, 0xab => true, 0xac => true, 0xae => true, 0xb0 => true, 0xb1 => true, 0xb6 => true, 0xbb => true, 0xbf => true, 0xd7 => true, 0xf7 => true, 0x2010...0x2015 => true, 0x2016...0x2017 => true, 0x2018 => true, 0x2019 => true, 0x201a => true, 0x201b...0x201c => true, 0x201d => true, 0x201e => true, 0x201f => true, 0x2020...0x2027 => true, 0x2030...0x2038 => true, 0x2039 => true, 0x203a => true, 0x203b...0x203e => true, 0x2041...0x2043 => true, 0x2044 => true, 0x2045 => true, 0x2046 => true, 0x2047...0x2051 => true, 0x2052 => true, 0x2053 => true, 0x2055...0x205e => true, 0x2190...0x2194 => true, 0x2195...0x2199 => true, 0x219a...0x219b => true, 0x219c...0x219f => true, 0x21a0 => true, 0x21a1...0x21a2 => true, 0x21a3 => true, 0x21a4...0x21a5 => true, 0x21a6 => true, 0x21a7...0x21ad => true, 0x21ae => true, 0x21af...0x21cd => true, 0x21ce...0x21cf => true, 0x21d0...0x21d1 => true, 0x21d2 => true, 0x21d3 => true, 0x21d4 => true, 0x21d5...0x21f3 => true, 0x21f4...0x22ff => true, 0x2300...0x2307 => true, 0x2308 => true, 0x2309 => true, 0x230a => true, 0x230b => true, 0x230c...0x231f => true, 0x2320...0x2321 => true, 0x2322...0x2328 => true, 0x2329 => true, 0x232a => true, 0x232b...0x237b => true, 0x237c => true, 0x237d...0x239a => true, 0x239b...0x23b3 => true, 0x23b4...0x23db => true, 0x23dc...0x23e1 => true, 0x23e2...0x2426 => true, 0x2427...0x243f => true, 0x2440...0x244a => true, 0x244b...0x245f => true, 0x2500...0x25b6 => true, 0x25b7 => true, 0x25b8...0x25c0 => true, 0x25c1 => true, 0x25c2...0x25f7 => true, 0x25f8...0x25ff => true, 0x2600...0x266e => true, 0x266f => true, 0x2670...0x2767 => true, 0x2768 => true, 0x2769 => true, 0x276a => true, 0x276b => true, 0x276c => true, 0x276d => true, 0x276e => true, 0x276f => true, 0x2770 => true, 0x2771 => true, 0x2772 => true, 0x2773 => true, 0x2774 => true, 0x2775 => true, 0x2794...0x27bf => true, 0x27c0...0x27c4 => true, 0x27c5 => true, 0x27c6 => true, 0x27c7...0x27e5 => true, 0x27e6 => true, 0x27e7 => true, 0x27e8 => true, 0x27e9 => true, 0x27ea => true, 0x27eb => true, 0x27ec => true, 0x27ed => true, 0x27ee => true, 0x27ef => true, 0x27f0...0x27ff => true, 0x2800...0x28ff => true, 0x2900...0x2982 => true, 0x2983 => true, 0x2984 => true, 0x2985 => true, 0x2986 => true, 0x2987 => true, 0x2988 => true, 0x2989 => true, 0x298a => true, 0x298b => true, 0x298c => true, 0x298d => true, 0x298e => true, 0x298f => true, 0x2990 => true, 0x2991 => true, 0x2992 => true, 0x2993 => true, 0x2994 => true, 0x2995 => true, 0x2996 => true, 0x2997 => true, 0x2998 => true, 0x2999...0x29d7 => true, 0x29d8 => true, 0x29d9 => true, 0x29da => true, 0x29db => true, 0x29dc...0x29fb => true, 0x29fc => true, 0x29fd => true, 0x29fe...0x2aff => true, 0x2b00...0x2b2f => true, 0x2b30...0x2b44 => true, 0x2b45...0x2b46 => true, 0x2b47...0x2b4c => true, 0x2b4d...0x2b73 => true, 0x2b74...0x2b75 => true, 0x2b76...0x2b95 => true, 0x2b96 => true, 0x2b97...0x2bff => true, 0x2e00...0x2e01 => true, 0x2e02 => true, 0x2e03 => true, 0x2e04 => true, 0x2e05 => true, 0x2e06...0x2e08 => true, 0x2e09 => true, 0x2e0a => true, 0x2e0b => true, 0x2e0c => true, 0x2e0d => true, 0x2e0e...0x2e16 => true, 0x2e17 => true, 0x2e18...0x2e19 => true, 0x2e1a => true, 0x2e1b => true, 0x2e1c => true, 0x2e1d => true, 0x2e1e...0x2e1f => true, 0x2e20 => true, 0x2e21 => true, 0x2e22 => true, 0x2e23 => true, 0x2e24 => true, 0x2e25 => true, 0x2e26 => true, 0x2e27 => true, 0x2e28 => true, 0x2e29 => true, 0x2e2a...0x2e2e => true, 0x2e2f => true, 0x2e30...0x2e39 => true, 0x2e3a...0x2e3b => true, 0x2e3c...0x2e3f => true, 0x2e40 => true, 0x2e41 => true, 0x2e42 => true, 0x2e43...0x2e4f => true, 0x2e50...0x2e51 => true, 0x2e52...0x2e54 => true, 0x2e55 => true, 0x2e56 => true, 0x2e57 => true, 0x2e58 => true, 0x2e59 => true, 0x2e5a => true, 0x2e5b => true, 0x2e5c => true, 0x2e5d => true, 0x2e5e...0x2e7f => true, 0x3001...0x3003 => true, 0x3008 => true, 0x3009 => true, 0x300a => true, 0x300b => true, 0x300c => true, 0x300d => true, 0x300e => true, 0x300f => true, 0x3010 => true, 0x3011 => true, 0x3012...0x3013 => true, 0x3014 => true, 0x3015 => true, 0x3016 => true, 0x3017 => true, 0x3018 => true, 0x3019 => true, 0x301a => true, 0x301b => true, 0x301c => true, 0x301d => true, 0x301e...0x301f => true, 0x3020 => true, 0x3030 => true, 0xfd3e => true, 0xfd3f => true, 0xfe45...0xfe46 => true, else => false, }; } pub fn isPrependedConcatenationMark(cp: u21) bool { if (cp < 0x600 or cp > 0x110cd) return false; return switch (cp) { 0x600...0x605 => true, 0x6dd => true, 0x70f => true, 0x890...0x891 => true, 0x8e2 => true, 0x110bd => true, 0x110cd => true, else => false, }; } pub fn isRegionalIndicator(cp: u21) bool { if (cp < 0x1f1e6 or cp > 0x1f1ff) return false; return switch (cp) { 0x1f1e6...0x1f1ff => true, else => false, }; }
src/components/autogen/PropList.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); } fn is_nice1(s: []const u8) bool { const voyelles = "aeiou"; var nbvoy: u32 = 0; var hasdouble = false; var hasforbidden = false; var prev: u8 = 0; for (s) |c| { for (voyelles) |v| { if (c == v) nbvoy += 1; } if (prev == c) hasdouble = true; if (prev == 'a' and c == 'b') hasforbidden = true; if (prev == 'c' and c == 'd') hasforbidden = true; if (prev == 'p' and c == 'q') hasforbidden = true; if (prev == 'x' and c == 'y') hasforbidden = true; prev = c; } return (!hasforbidden and hasdouble and nbvoy >= 3); } fn is_nice2(s: []const u8) bool { var hasrepeat = false; var tri = [3]u8{ 0, 0, 0 }; for (s) |c| { tri[0] = tri[1]; tri[1] = tri[2]; tri[2] = c; if (tri[0] == tri[2]) hasrepeat = true; } var hasrepeatpair = false; var pair = [2]u8{ 0, 0 }; for (s) |c, i| { pair[0] = pair[1]; pair[1] = c; var pair2 = [2]u8{ 1, 1 }; for (s[i + 1 ..]) |c2| { pair2[0] = pair2[1]; pair2[1] = c2; if (pair2[0] == pair[0] and pair2[1] == pair[1]) hasrepeatpair = true; } } return (hasrepeatpair and hasrepeat); } pub fn main() anyerror!void { 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, "day5.txt", limit); var nb_nice: u32 = 0; var it = std.mem.split(u8, text, "\n"); while (it.next()) |line| { const trimmed = std.mem.trim(u8, line, " \n\r\t"); if (is_nice2(trimmed)) nb_nice += 1; } const out = std.io.getStdOut().writer(); try out.print("nices={} \n", nb_nice); // return error.SolutionNotFound; }
2015/day5.zig
const ImageReader = zigimg.ImageReader; const ImageSeekStream = zigimg.ImageSeekStream; const PixelFormat = zigimg.PixelFormat; const assert = std.debug.assert; const color = zigimg.color; const errors = zigimg.errors; const png = zigimg.png; const std = @import("std"); const testing = std.testing; const zigimg = @import("zigimg"); usingnamespace @import("../helpers.zig"); test "Read s01i3p01 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s01i3p01.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 1); expectEq(pngFile.header.height, 1); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp1); expectEq(pixels.Bpp1.palette.len, 2); const firstColor = pixels.Bpp1.palette[0].toIntegerColor8(); expectEq(firstColor.R, 0); expectEq(firstColor.G, 0); expectEq(firstColor.B, 255); const secondColor = pixels.Bpp1.palette[1].toIntegerColor8(); expectEq(secondColor.R, 0); expectEq(secondColor.G, 0); expectEq(secondColor.B, 0); expectEq(pixels.Bpp1.indices[0], 0); } } test "Read s01n3p01 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s01n3p01.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 1); expectEq(pngFile.header.height, 1); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp1); expectEq(pixels.Bpp1.palette.len, 2); const firstColor = pixels.Bpp1.palette[0].toIntegerColor8(); expectEq(firstColor.R, 0); expectEq(firstColor.G, 0); expectEq(firstColor.B, 255); const secondColor = pixels.Bpp1.palette[1].toIntegerColor8(); expectEq(secondColor.R, 0); expectEq(secondColor.G, 0); expectEq(secondColor.B, 0); expectEq(pixels.Bpp1.indices[0], 0); } } test "Read s02i3p01 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s02i3p01.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 2); expectEq(pngFile.header.height, 2); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp1); expectEq(pixels.Bpp1.palette.len, 2); const firstColor = pixels.Bpp1.palette[0].toIntegerColor8(); expectEq(firstColor.R, 0); expectEq(firstColor.G, 255); expectEq(firstColor.B, 255); const secondColor = pixels.Bpp1.palette[1].toIntegerColor8(); expectEq(secondColor.R, 0); expectEq(secondColor.G, 0); expectEq(secondColor.B, 0); expectEq(pixels.Bpp1.indices.len, 4); expectEq(pixels.Bpp1.indices[0], 0); expectEq(pixels.Bpp1.indices[1], 0); expectEq(pixels.Bpp1.indices[2], 0); expectEq(pixels.Bpp1.indices[3], 0); } } test "Read s02n3p01 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s02n3p01.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 2); expectEq(pngFile.header.height, 2); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp1); expectEq(pixels.Bpp1.palette.len, 2); const firstColor = pixels.Bpp1.palette[0].toIntegerColor8(); expectEq(firstColor.R, 0); expectEq(firstColor.G, 255); expectEq(firstColor.B, 255); const secondColor = pixels.Bpp1.palette[1].toIntegerColor8(); expectEq(secondColor.R, 0); expectEq(secondColor.G, 0); expectEq(secondColor.B, 0); expectEq(pixels.Bpp1.indices.len, 4); expectEq(pixels.Bpp1.indices[0], 0); expectEq(pixels.Bpp1.indices[1], 0); expectEq(pixels.Bpp1.indices[2], 0); expectEq(pixels.Bpp1.indices[3], 0); } } test "Read s03i3p01 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s03i3p01.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 3); expectEq(pngFile.header.height, 3); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp1); expectEq(pixels.Bpp1.palette.len, 2); const firstColor = pixels.Bpp1.palette[0].toIntegerColor8(); expectEq(firstColor.R, 0); expectEq(firstColor.G, 255); expectEq(firstColor.B, 0); const secondColor = pixels.Bpp1.palette[1].toIntegerColor8(); expectEq(secondColor.R, 0xFF); expectEq(secondColor.G, 0x77); expectEq(secondColor.B, 0); expectEq(pixels.Bpp1.indices.len, 3 * 3); var index: usize = 0; while (index < 3 * 3) : (index += 1) { if (index == 1 * pngFile.header.width + 1) { expectEq(pixels.Bpp1.indices[index], 1); } else { expectEq(pixels.Bpp1.indices[index], 0); } } } } test "Read s03n3p01 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s03n3p01.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 3); expectEq(pngFile.header.height, 3); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp1); expectEq(pixels.Bpp1.palette.len, 2); const firstColor = pixels.Bpp1.palette[0].toIntegerColor8(); expectEq(firstColor.R, 0); expectEq(firstColor.G, 255); expectEq(firstColor.B, 0); const secondColor = pixels.Bpp1.palette[1].toIntegerColor8(); expectEq(secondColor.R, 0xFF); expectEq(secondColor.G, 0x77); expectEq(secondColor.B, 0); expectEq(pixels.Bpp1.indices.len, 3 * 3); var index: usize = 0; while (index < 3 * 3) : (index += 1) { if (index == 1 * pngFile.header.width + 1) { expectEq(pixels.Bpp1.indices[index], 1); } else { expectEq(pixels.Bpp1.indices[index], 0); } } } } test "Read s04i3p01 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s04i3p01.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 4); expectEq(pngFile.header.height, 4); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp1); expectEq(pixels.Bpp1.palette.len, 2); const firstColor = pixels.Bpp1.palette[0].toIntegerColor8(); expectEq(firstColor.R, 255); expectEq(firstColor.G, 0); expectEq(firstColor.B, 119); const secondColor = pixels.Bpp1.palette[1].toIntegerColor8(); expectEq(secondColor.R, 255); expectEq(secondColor.G, 255); expectEq(secondColor.B, 0); expectEq(pixels.Bpp1.indices.len, 4 * 4); const expected = [_]u8{ 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, }; var index: usize = 0; while (index < 4 * 4) : (index += 1) { expectEq(pixels.Bpp1.indices[index], @intCast(u1, expected[index])); } } } test "Read s04n3p01 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s04n3p01.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 4); expectEq(pngFile.header.height, 4); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp1); expectEq(pixels.Bpp1.palette.len, 2); const firstColor = pixels.Bpp1.palette[0].toIntegerColor8(); expectEq(firstColor.R, 255); expectEq(firstColor.G, 0); expectEq(firstColor.B, 119); const secondColor = pixels.Bpp1.palette[1].toIntegerColor8(); expectEq(secondColor.R, 255); expectEq(secondColor.G, 255); expectEq(secondColor.B, 0); expectEq(pixels.Bpp1.indices.len, 4 * 4); const expected = [_]u8{ 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, }; var index: usize = 0; while (index < 4 * 4) : (index += 1) { expectEq(pixels.Bpp1.indices[index], @intCast(u1, expected[index])); } } } test "Read s05i3p02 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s05i3p02.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 5); expectEq(pngFile.header.height, 5); const total_size = 5 * 5; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp2); expectEq(pixels.Bpp2.palette.len, 4); const color0 = pixels.Bpp2.palette[0].toIntegerColor8(); expectEq(color0.R, 0); expectEq(color0.G, 255); expectEq(color0.B, 255); const color1 = pixels.Bpp2.palette[1].toIntegerColor8(); expectEq(color1.R, 119); expectEq(color1.G, 0); expectEq(color1.B, 255); const color2 = pixels.Bpp2.palette[2].toIntegerColor8(); expectEq(color2.R, 255); expectEq(color2.G, 0); expectEq(color2.B, 0); expectEq(pixels.Bpp2.indices.len, total_size); const expected = [_]u8{ 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 0, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, }; var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp2.indices[index], @intCast(u2, expected[index])); } } } test "Read s05n3p02 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s05n3p02.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 5); expectEq(pngFile.header.height, 5); const total_size = 5 * 5; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp2); expectEq(pixels.Bpp2.palette.len, 4); const color0 = pixels.Bpp2.palette[0].toIntegerColor8(); expectEq(color0.R, 0); expectEq(color0.G, 255); expectEq(color0.B, 255); const color1 = pixels.Bpp2.palette[1].toIntegerColor8(); expectEq(color1.R, 119); expectEq(color1.G, 0); expectEq(color1.B, 255); const color2 = pixels.Bpp2.palette[2].toIntegerColor8(); expectEq(color2.R, 255); expectEq(color2.G, 0); expectEq(color2.B, 0); expectEq(pixels.Bpp2.indices.len, total_size); const expected = [_]u8{ 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 0, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, }; var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp2.indices[index], @intCast(u2, expected[index])); } } } test "Read s06i3p02 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s06i3p02.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 6); expectEq(pngFile.header.height, 6); const total_size = 6 * 6; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp2); expectEq(pixels.Bpp2.palette.len, 4); const color0 = pixels.Bpp2.palette[0].toIntegerColor8(); expectEq(color0.R, 0); expectEq(color0.G, 255); expectEq(color0.B, 0); const color1 = pixels.Bpp2.palette[1].toIntegerColor8(); expectEq(color1.R, 0); expectEq(color1.G, 119); expectEq(color1.B, 255); const color2 = pixels.Bpp2.palette[2].toIntegerColor8(); expectEq(color2.R, 255); expectEq(color2.G, 0); expectEq(color2.B, 255); expectEq(pixels.Bpp2.indices.len, total_size); const expected = [_]u8{ 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 1, 0, 0, 1, 2, 2, 1, 0, 0, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, }; var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp2.indices[index], @intCast(u2, expected[index])); } } } test "Read s06n3p02 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s06n3p02.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 6); expectEq(pngFile.header.height, 6); const total_size = 6 * 6; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp2); expectEq(pixels.Bpp2.palette.len, 4); const color0 = pixels.Bpp2.palette[0].toIntegerColor8(); expectEq(color0.R, 0); expectEq(color0.G, 255); expectEq(color0.B, 0); const color1 = pixels.Bpp2.palette[1].toIntegerColor8(); expectEq(color1.R, 0); expectEq(color1.G, 119); expectEq(color1.B, 255); const color2 = pixels.Bpp2.palette[2].toIntegerColor8(); expectEq(color2.R, 255); expectEq(color2.G, 0); expectEq(color2.B, 255); expectEq(pixels.Bpp2.indices.len, total_size); const expected = [_]u8{ 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 1, 0, 0, 1, 2, 2, 1, 0, 0, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, }; var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp2.indices[index], @intCast(u2, expected[index])); } } } test "Read s07i3p02 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s07i3p02.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 7); expectEq(pngFile.header.height, 7); const total_size = 7 * 7; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp2); expectEq(pixels.Bpp2.palette.len, 4); const color0 = pixels.Bpp2.palette[0].toIntegerColor8(); expectEq(color0.R, 255); expectEq(color0.G, 0); expectEq(color0.B, 119); const color1 = pixels.Bpp2.palette[1].toIntegerColor8(); expectEq(color1.R, 0); expectEq(color1.G, 255); expectEq(color1.B, 119); const color2 = pixels.Bpp2.palette[2].toIntegerColor8(); expectEq(color2.R, 255); expectEq(color2.G, 255); expectEq(color2.B, 0); const color3 = pixels.Bpp2.palette[3].toIntegerColor8(); expectEq(color3.R, 0); expectEq(color3.G, 0); expectEq(color3.B, 255); expectEq(pixels.Bpp2.indices.len, total_size); const expected = [_]u8{ 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 3, 3, 1, 2, 2, 2, 1, 3, 3, 1, 2, 0, 2, 1, 3, 3, 1, 2, 2, 2, 1, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, }; var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp2.indices[index], @intCast(u2, expected[index])); } } } test "Read s07n3p02 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s07n3p02.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 7); expectEq(pngFile.header.height, 7); const total_size = 7 * 7; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp2); expectEq(pixels.Bpp2.palette.len, 4); const color0 = pixels.Bpp2.palette[0].toIntegerColor8(); expectEq(color0.R, 255); expectEq(color0.G, 0); expectEq(color0.B, 119); const color1 = pixels.Bpp2.palette[1].toIntegerColor8(); expectEq(color1.R, 0); expectEq(color1.G, 255); expectEq(color1.B, 119); const color2 = pixels.Bpp2.palette[2].toIntegerColor8(); expectEq(color2.R, 255); expectEq(color2.G, 255); expectEq(color2.B, 0); const color3 = pixels.Bpp2.palette[3].toIntegerColor8(); expectEq(color3.R, 0); expectEq(color3.G, 0); expectEq(color3.B, 255); expectEq(pixels.Bpp2.indices.len, total_size); const expected = [_]u8{ 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 3, 3, 1, 2, 2, 2, 1, 3, 3, 1, 2, 0, 2, 1, 3, 3, 1, 2, 2, 2, 1, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, }; var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp2.indices[index], @intCast(u2, expected[index])); } } } test "Read s08i3p02 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s08i3p02.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 8); expectEq(pngFile.header.height, 8); const total_size = 8 * 8; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp2); expectEq(pixels.Bpp2.palette.len, 4); const color0 = pixels.Bpp2.palette[0].toIntegerColor8(); expectEq(color0.R, 0); expectEq(color0.G, 255); expectEq(color0.B, 255); const color1 = pixels.Bpp2.palette[1].toIntegerColor8(); expectEq(color1.R, 119); expectEq(color1.G, 0); expectEq(color1.B, 255); const color2 = pixels.Bpp2.palette[2].toIntegerColor8(); expectEq(color2.R, 119); expectEq(color2.G, 255); expectEq(color2.B, 0); const color3 = pixels.Bpp2.palette[3].toIntegerColor8(); expectEq(color3.R, 255); expectEq(color3.G, 0); expectEq(color3.B, 0); expectEq(pixels.Bpp2.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 2, 3, 3, 3, 3, 2, 0, 0, 2, 3, 1, 1, 3, 2, 0, 0, 2, 3, 1, 1, 3, 2, 0, 0, 2, 3, 3, 3, 3, 2, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp2.indices[index], @intCast(u2, expected[index])); } } } test "Read s08n3p02 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s08n3p02.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 8); expectEq(pngFile.header.height, 8); const total_size = 8 * 8; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp2); expectEq(pixels.Bpp2.palette.len, 4); const color0 = pixels.Bpp2.palette[0].toIntegerColor8(); expectEq(color0.R, 0); expectEq(color0.G, 255); expectEq(color0.B, 255); const color1 = pixels.Bpp2.palette[1].toIntegerColor8(); expectEq(color1.R, 119); expectEq(color1.G, 0); expectEq(color1.B, 255); const color2 = pixels.Bpp2.palette[2].toIntegerColor8(); expectEq(color2.R, 119); expectEq(color2.G, 255); expectEq(color2.B, 0); const color3 = pixels.Bpp2.palette[3].toIntegerColor8(); expectEq(color3.R, 255); expectEq(color3.G, 0); expectEq(color3.B, 0); expectEq(pixels.Bpp2.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 2, 3, 3, 3, 3, 2, 0, 0, 2, 3, 1, 1, 3, 2, 0, 0, 2, 3, 1, 1, 3, 2, 0, 0, 2, 3, 3, 3, 3, 2, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp2.indices[index], @intCast(u2, expected[index])); } } } test "Read s09i3p02 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s09i3p02.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 9); expectEq(pngFile.header.height, 9); const total_size = 9 * 9; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp2); expectEq(pixels.Bpp2.palette.len, 4); const color0 = pixels.Bpp2.palette[0].toIntegerColor8(); expectEq(color0.R, 0); expectEq(color0.G, 255); expectEq(color0.B, 0); const color1 = pixels.Bpp2.palette[1].toIntegerColor8(); expectEq(color1.R, 0); expectEq(color1.G, 119); expectEq(color1.B, 255); const color2 = pixels.Bpp2.palette[2].toIntegerColor8(); expectEq(color2.R, 255); expectEq(color2.G, 0); expectEq(color2.B, 255); const color3 = pixels.Bpp2.palette[3].toIntegerColor8(); expectEq(color3.R, 255); expectEq(color3.G, 119); expectEq(color3.B, 0); expectEq(pixels.Bpp2.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 2, 2, 2, 2, 2, 3, 0, 0, 3, 2, 1, 1, 1, 2, 3, 0, 0, 3, 2, 1, 0, 1, 2, 3, 0, 0, 3, 2, 1, 1, 1, 2, 3, 0, 0, 3, 2, 2, 2, 2, 2, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp2.indices[index], @intCast(u2, expected[index])); } } } test "Read s09n3p02 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s09n3p02.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 9); expectEq(pngFile.header.height, 9); const total_size = 9 * 9; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp2); expectEq(pixels.Bpp2.palette.len, 4); const color0 = pixels.Bpp2.palette[0].toIntegerColor8(); expectEq(color0.R, 0); expectEq(color0.G, 255); expectEq(color0.B, 0); const color1 = pixels.Bpp2.palette[1].toIntegerColor8(); expectEq(color1.R, 0); expectEq(color1.G, 119); expectEq(color1.B, 255); const color2 = pixels.Bpp2.palette[2].toIntegerColor8(); expectEq(color2.R, 255); expectEq(color2.G, 0); expectEq(color2.B, 255); const color3 = pixels.Bpp2.palette[3].toIntegerColor8(); expectEq(color3.R, 255); expectEq(color3.G, 119); expectEq(color3.B, 0); expectEq(pixels.Bpp2.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 2, 2, 2, 2, 2, 3, 0, 0, 3, 2, 1, 1, 1, 2, 3, 0, 0, 3, 2, 1, 0, 1, 2, 3, 0, 0, 3, 2, 1, 1, 1, 2, 3, 0, 0, 3, 2, 2, 2, 2, 2, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp2.indices[index], @intCast(u2, expected[index])); } } } test "Read s32i3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s32i3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 32); expectEq(pngFile.header.height, 32); const total_size = 32 * 32; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 0, 0, 0, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 0, 0, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 0, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 0, 0, 0, 0, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 0, 11, 10, 6, 3, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 8, 11, 10, 6, 3, 9, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 8, 11, 10, 6, 3, 9, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 0, 0, 0, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 0, 0, 0, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 0, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 0, 0, 0, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s32n3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s32n3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 32); expectEq(pngFile.header.height, 32); const total_size = 32 * 32; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 0, 0, 0, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 0, 0, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 0, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 0, 0, 0, 0, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 0, 11, 10, 6, 3, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 8, 11, 10, 6, 3, 9, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 8, 11, 10, 6, 3, 9, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 0, 0, 0, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 0, 0, 0, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 0, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 0, 0, 0, 10, 6, 3, 9, 2, 5, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s33i3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s33i3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 33); expectEq(pngFile.header.height, 33); const total_size = 33 * 33; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 6, 6, 6, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 0, 0, 5, 5, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 11, 11, 11, 11, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 5, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 0, 0, 0, 8, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 9, 9, 9, 9, 9, 9, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 5, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 0, 0, 0, 12, 12, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s33n3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s33n3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 33); expectEq(pngFile.header.height, 33); const total_size = 33 * 33; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 6, 6, 6, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 0, 0, 5, 5, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 11, 11, 11, 11, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 5, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 0, 0, 0, 8, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 9, 9, 9, 9, 9, 9, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 5, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 0, 0, 0, 12, 12, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s34i3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s34i3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 34); expectEq(pngFile.header.height, 34); const total_size = 34 * 34; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 0, 0, 0, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 0, 0, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 0, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 0, 0, 0, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 0, 0, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 0, 0, 0, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 0, 0, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 0, 6, 3, 9, 0, 0, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 10, 6, 3, 9, 0, 0, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 10, 6, 3, 9, 0, 0, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s34n3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s34n3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 34); expectEq(pngFile.header.height, 34); const total_size = 34 * 34; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 0, 0, 0, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 0, 0, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 0, 0, 0, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 0, 0, 0, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 0, 0, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 0, 0, 0, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 0, 0, 6, 3, 9, 2, 5, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 0, 6, 3, 9, 0, 0, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 10, 6, 3, 9, 0, 0, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 10, 6, 3, 9, 0, 0, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s35i3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s35i3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 35); expectEq(pngFile.header.height, 35); const total_size = 35 * 35; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 6, 6, 6, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 0, 0, 5, 5, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 11, 11, 11, 11, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 0, 0, 11, 0, 0, 0, 0, 0, 0, 11, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 0, 0, 0, 0, 6, 6, 6, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 5, 5, 5, 5, 5, 5, 0, 0, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 12, 12, 12, 12, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 7, 7, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s35n3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s35n3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 35); expectEq(pngFile.header.height, 35); const total_size = 35 * 35; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 6, 6, 6, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 0, 0, 5, 5, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 11, 11, 11, 11, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 0, 0, 11, 0, 0, 0, 0, 0, 0, 11, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 0, 0, 0, 0, 6, 6, 6, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 5, 5, 5, 5, 5, 5, 0, 0, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 12, 12, 12, 12, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 7, 7, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s36i3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s36i3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 36); expectEq(pngFile.header.height, 36); const total_size = 36 * 36; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 0, 0, 0, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 0, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 9, 2, 5, 12, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 0, 2, 5, 12, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 9, 2, 5, 12, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 0, 0, 0, 7, 1, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s36n3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s36n3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 36); expectEq(pngFile.header.height, 36); const total_size = 36 * 36; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 0, 0, 0, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 0, 0, 0, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 9, 2, 5, 12, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 0, 2, 5, 12, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 9, 2, 5, 12, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 0, 0, 0, 7, 1, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s37i3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s37i3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 37); expectEq(pngFile.header.height, 37); const total_size = 37 * 37; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 6, 6, 6, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 0, 0, 5, 5, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 11, 11, 11, 11, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 10, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 0, 0, 0, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 9, 9, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 5, 5, 5, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 0, 0, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 7, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s37n3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s37n3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 37); expectEq(pngFile.header.height, 37); const total_size = 37 * 37; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 6, 6, 6, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 0, 0, 5, 5, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 11, 11, 11, 11, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 10, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 0, 0, 0, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 9, 9, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 5, 5, 5, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 0, 0, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 7, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s38i3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s38i3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 38); expectEq(pngFile.header.height, 38); const total_size = 38 * 38; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 0, 0, 0, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 0, 0, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 0, 0, 0, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 0, 0, 0, 0, 0, 0, 0, 0, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 0, 0, 0, 0, 0, 0, 0, 0, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 0, 0, 0, 0, 0, 0, 0, 0, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 0, 0, 0, 0, 0, 0, 0, 0, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 0, 0, 0, 8, 11, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s38n3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s38n3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 38); expectEq(pngFile.header.height, 38); const total_size = 38 * 38; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 0, 0, 0, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 0, 0, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 10, 6, 3, 9, 2, 5, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 0, 0, 0, 6, 3, 9, 2, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 0, 0, 0, 0, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 0, 0, 0, 8, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 0, 0, 0, 0, 0, 0, 0, 0, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 0, 0, 0, 0, 0, 0, 0, 0, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 0, 0, 0, 0, 0, 0, 0, 0, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 5, 12, 4, 7, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 0, 0, 0, 0, 0, 0, 0, 0, 11, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 0, 0, 0, 8, 11, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s39i3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s39i3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 39); expectEq(pngFile.header.height, 39); const total_size = 39 * 39; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 6, 6, 6, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 0, 0, 5, 5, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 11, 11, 11, 11, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 8, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 0, 0, 0, 11, 11, 11, 11, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 10, 10, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 0, 0, 6, 6, 6, 6, 6, 6, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 9, 9, 9, 9, 9, 9, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 0, 0, 12, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 8, 8, 8, 8, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 0, 0, 0, 0, 0, 0, 0, 0, 11, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 10, 10, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s39n3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s39n3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 39); expectEq(pngFile.header.height, 39); const total_size = 39 * 39; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 6, 6, 6, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 0, 0, 5, 5, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 11, 11, 11, 11, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 8, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 0, 0, 0, 11, 11, 11, 11, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 10, 10, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 0, 0, 6, 6, 6, 6, 6, 6, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 9, 9, 9, 9, 9, 9, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 0, 0, 12, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 8, 8, 8, 8, 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 0, 0, 0, 0, 0, 0, 0, 0, 11, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 10, 10, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s40i3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s40i3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 40); expectEq(pngFile.header.height, 40); const total_size = 40 * 40; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 0, 0, 0, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 0, 0, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 0, 0, 0, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 0, 0, 0, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 0, 0, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 0, 0, 0, 0, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 4, 7, 1, 8, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 0, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 0, 0, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 0, 0, 0, 11, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 0, 0, 0, 8, 11, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 0, 0, 1, 8, 11, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 0, 7, 1, 8, 11, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 4, 7, 1, 8, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 0, 0, 0, 0, 10, 6, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } } test "Read s40n3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/s40n3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pngFile.header.width, 40); expectEq(pngFile.header.height, 40); const total_size = 40 * 40; testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == PixelFormat.Bpp4); expectEq(pixels.Bpp4.palette.len, 16); const palette = [_]u32{ 0x000000, 0xff0077, 0x00ffff, 0x00ff00, 0x7700ff, 0x0077ff, 0x77ff00, 0xff00ff, 0xff0000, 0x00ff77, 0xffff00, 0xff7700, 0x0000ff, }; for (palette) |raw_color, i| { const expected = color.IntegerColor8.fromHtmlHex(raw_color); expectEq(pixels.Bpp4.palette[i].toIntegerColor8(), expected); } expectEq(pixels.Bpp4.indices.len, total_size); const expected = [_]u8{ 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 0, 0, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 0, 0, 0, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 0, 0, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 0, 0, 0, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 0, 0, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 0, 0, 0, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 0, 0, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 0, 0, 0, 0, 10, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 4, 7, 1, 8, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 0, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 0, 0, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 0, 0, 0, 11, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 0, 0, 0, 8, 11, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 0, 0, 1, 8, 11, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 0, 7, 1, 8, 11, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 4, 7, 1, 8, 11, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 12, 4, 7, 1, 8, 11, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 0, 0, 0, 4, 7, 1, 8, 0, 0, 0, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 12, 4, 7, 1, 8, 11, 10, 6, 3, 9, 2, 5, 0, 0, 0, 0, 0, 0, 10, 6, }; expectEq(pixels.Bpp4.indices.len, expected.len); var index: usize = 0; while (index < total_size) : (index += 1) { expectEq(pixels.Bpp4.indices[index], @intCast(u4, expected[index])); } } }
tests/formats/png_odd_sizes_test.zig
const std = @import("std"); const assert = std.debug.assert; comptime { assert(@alignOf(i8) == 1); assert(@alignOf(u8) == 1); assert(@alignOf(i16) == 2); assert(@alignOf(u16) == 2); assert(@alignOf(i32) == 4); assert(@alignOf(u32) == 4); // assert(@alignOf(i64) == 8); // assert(@alignOf(u64) == 8); } pub const F_OK = 0; pub const X_OK = 1; pub const W_OK = 2; pub const R_OK = 4; pub const iovec_t = std.os.iovec; pub const ciovec_t = std.os.iovec_const; pub extern "wasi_snapshot_preview1" fn args_get(argv: [*][*:0]u8, argv_buf: [*]u8) errno_t; pub extern "wasi_snapshot_preview1" fn args_sizes_get(argc: *usize, argv_buf_size: *usize) errno_t; pub extern "wasi_snapshot_preview1" fn clock_res_get(clock_id: clockid_t, resolution: *timestamp_t) errno_t; pub extern "wasi_snapshot_preview1" fn clock_time_get(clock_id: clockid_t, precision: timestamp_t, timestamp: *timestamp_t) errno_t; pub extern "wasi_snapshot_preview1" fn environ_get(environ: [*][*:0]u8, environ_buf: [*]u8) errno_t; pub extern "wasi_snapshot_preview1" fn environ_sizes_get(environ_count: *usize, environ_buf_size: *usize) errno_t; pub extern "wasi_snapshot_preview1" fn fd_advise(fd: fd_t, offset: filesize_t, len: filesize_t, advice: advice_t) errno_t; pub extern "wasi_snapshot_preview1" fn fd_allocate(fd: fd_t, offset: filesize_t, len: filesize_t) errno_t; pub extern "wasi_snapshot_preview1" fn fd_close(fd: fd_t) errno_t; pub extern "wasi_snapshot_preview1" fn fd_datasync(fd: fd_t) errno_t; pub extern "wasi_snapshot_preview1" fn fd_pread(fd: fd_t, iovs: [*]const iovec_t, iovs_len: usize, offset: filesize_t, nread: *usize) errno_t; pub extern "wasi_snapshot_preview1" fn fd_pwrite(fd: fd_t, iovs: [*]const ciovec_t, iovs_len: usize, offset: filesize_t, nwritten: *usize) errno_t; pub extern "wasi_snapshot_preview1" fn fd_read(fd: fd_t, iovs: [*]const iovec_t, iovs_len: usize, nread: *usize) errno_t; pub extern "wasi_snapshot_preview1" fn fd_readdir(fd: fd_t, buf: [*]u8, buf_len: usize, cookie: dircookie_t, bufused: *usize) errno_t; pub extern "wasi_snapshot_preview1" fn fd_renumber(from: fd_t, to: fd_t) errno_t; pub extern "wasi_snapshot_preview1" fn fd_seek(fd: fd_t, offset: filedelta_t, whence: whence_t, newoffset: *filesize_t) errno_t; pub extern "wasi_snapshot_preview1" fn fd_sync(fd: fd_t) errno_t; pub extern "wasi_snapshot_preview1" fn fd_tell(fd: fd_t, newoffset: *filesize_t) errno_t; pub extern "wasi_snapshot_preview1" fn fd_write(fd: fd_t, iovs: [*]const ciovec_t, iovs_len: usize, nwritten: *usize) errno_t; pub extern "wasi_snapshot_preview1" fn fd_fdstat_get(fd: fd_t, buf: *fdstat_t) errno_t; pub extern "wasi_snapshot_preview1" fn fd_fdstat_set_flags(fd: fd_t, flags: fdflags_t) errno_t; pub extern "wasi_snapshot_preview1" fn fd_fdstat_set_rights(fd: fd_t, fs_rights_base: rights_t, fs_rights_inheriting: rights_t) errno_t; pub extern "wasi_snapshot_preview1" fn fd_filestat_get(fd: fd_t, buf: *filestat_t) errno_t; pub extern "wasi_snapshot_preview1" fn fd_filestat_set_size(fd: fd_t, st_size: filesize_t) errno_t; pub extern "wasi_snapshot_preview1" fn fd_filestat_set_times(fd: fd_t, st_atim: timestamp_t, st_mtim: timestamp_t, fstflags: fstflags_t) errno_t; pub extern "wasi_snapshot_preview1" fn fd_prestat_get(fd: fd_t, buf: *prestat_t) errno_t; pub extern "wasi_snapshot_preview1" fn fd_prestat_dir_name(fd: fd_t, path: [*]u8, path_len: usize) errno_t; pub extern "wasi_snapshot_preview1" fn path_create_directory(fd: fd_t, path: [*]const u8, path_len: usize) errno_t; pub extern "wasi_snapshot_preview1" fn path_filestat_get(fd: fd_t, flags: lookupflags_t, path: [*]const u8, path_len: usize, buf: *filestat_t) errno_t; pub extern "wasi_snapshot_preview1" fn path_filestat_set_times(fd: fd_t, flags: lookupflags_t, path: [*]const u8, path_len: usize, st_atim: timestamp_t, st_mtim: timestamp_t, fstflags: fstflags_t) errno_t; pub extern "wasi_snapshot_preview1" fn path_link(old_fd: fd_t, old_flags: lookupflags_t, old_path: [*]const u8, old_path_len: usize, new_fd: fd_t, new_path: [*]const u8, new_path_len: usize) errno_t; pub extern "wasi_snapshot_preview1" fn path_open(dirfd: fd_t, dirflags: lookupflags_t, path: [*]const u8, path_len: usize, oflags: oflags_t, fs_rights_base: rights_t, fs_rights_inheriting: rights_t, fs_flags: fdflags_t, fd: *fd_t) errno_t; pub extern "wasi_snapshot_preview1" fn path_readlink(fd: fd_t, path: [*]const u8, path_len: usize, buf: [*]u8, buf_len: usize, bufused: *usize) errno_t; pub extern "wasi_snapshot_preview1" fn path_remove_directory(fd: fd_t, path: [*]const u8, path_len: usize) errno_t; pub extern "wasi_snapshot_preview1" fn path_rename(old_fd: fd_t, old_path: [*]const u8, old_path_len: usize, new_fd: fd_t, new_path: [*]const u8, new_path_len: usize) errno_t; pub extern "wasi_snapshot_preview1" fn path_symlink(old_path: [*]const u8, old_path_len: usize, fd: fd_t, new_path: [*]const u8, new_path_len: usize) errno_t; pub extern "wasi_snapshot_preview1" fn path_unlink_file(fd: fd_t, path: [*]const u8, path_len: usize) errno_t; pub extern "wasi_snapshot_preview1" fn poll_oneoff(in: *const subscription_t, out: *event_t, nsubscriptions: usize, nevents: *usize) errno_t; pub extern "wasi_snapshot_preview1" fn proc_exit(rval: exitcode_t) noreturn; pub extern "wasi_snapshot_preview1" fn random_get(buf: [*]u8, buf_len: usize) errno_t; pub extern "wasi_snapshot_preview1" fn sched_yield() errno_t; pub extern "wasi_snapshot_preview1" fn sock_recv(sock: fd_t, ri_data: *const iovec_t, ri_data_len: usize, ri_flags: riflags_t, ro_datalen: *usize, ro_flags: *roflags_t) errno_t; pub extern "wasi_snapshot_preview1" fn sock_send(sock: fd_t, si_data: *const ciovec_t, si_data_len: usize, si_flags: siflags_t, so_datalen: *usize) errno_t; pub extern "wasi_snapshot_preview1" fn sock_shutdown(sock: fd_t, how: sdflags_t) errno_t; /// Get the errno from a syscall return value, or 0 for no error. pub fn getErrno(r: errno_t) errno_t { return r; } pub const STDIN_FILENO = 0; pub const STDOUT_FILENO = 1; pub const STDERR_FILENO = 2; pub const mode_t = u32; pub const time_t = i64; // match https://github.com/CraneStation/wasi-libc pub const timespec = extern struct { tv_sec: time_t, tv_nsec: isize, pub fn fromTimestamp(tm: timestamp_t) timespec { const tv_sec: timestamp_t = tm / 1_000_000_000; const tv_nsec = tm - tv_sec * 1_000_000_000; return timespec{ .tv_sec = @intCast(time_t, tv_sec), .tv_nsec = @intCast(isize, tv_nsec), }; } pub fn toTimestamp(ts: timespec) timestamp_t { const tm = @intCast(timestamp_t, ts.tv_sec * 1_000_000_000) + @intCast(timestamp_t, ts.tv_nsec); return tm; } }; pub const Stat = struct { dev: device_t, ino: inode_t, mode: mode_t, filetype: filetype_t, nlink: linkcount_t, size: filesize_t, atim: timespec, mtim: timespec, ctim: timespec, const Self = @This(); pub fn fromFilestat(stat: filestat_t) Self { return Self{ .dev = stat.dev, .ino = stat.ino, .mode = 0, .filetype = stat.filetype, .nlink = stat.nlink, .size = stat.size, .atim = stat.atime(), .mtim = stat.mtime(), .ctim = stat.ctime(), }; } pub fn atime(self: Self) timespec { return self.atim; } pub fn mtime(self: Self) timespec { return self.mtim; } pub fn ctime(self: Self) timespec { return self.ctim; } }; pub const IOV_MAX = 1024; pub const AT = struct { pub const REMOVEDIR: u32 = 0x4; pub const FDCWD: fd_t = -2; }; // As defined in the wasi_snapshot_preview1 spec file: // https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/witx/typenames.witx pub const advice_t = u8; pub const ADVICE_NORMAL: advice_t = 0; pub const ADVICE_SEQUENTIAL: advice_t = 1; pub const ADVICE_RANDOM: advice_t = 2; pub const ADVICE_WILLNEED: advice_t = 3; pub const ADVICE_DONTNEED: advice_t = 4; pub const ADVICE_NOREUSE: advice_t = 5; pub const clockid_t = u32; pub const CLOCK = struct { pub const REALTIME: clockid_t = 0; pub const MONOTONIC: clockid_t = 1; pub const PROCESS_CPUTIME_ID: clockid_t = 2; pub const THREAD_CPUTIME_ID: clockid_t = 3; }; pub const device_t = u64; pub const dircookie_t = u64; pub const DIRCOOKIE_START: dircookie_t = 0; pub const dirnamlen_t = u32; pub const dirent_t = extern struct { d_next: dircookie_t, d_ino: inode_t, d_namlen: dirnamlen_t, d_type: filetype_t, }; pub const errno_t = enum(u16) { SUCCESS = 0, @"2BIG" = 1, ACCES = 2, ADDRINUSE = 3, ADDRNOTAVAIL = 4, AFNOSUPPORT = 5, /// This is also the error code used for `WOULDBLOCK`. AGAIN = 6, ALREADY = 7, BADF = 8, BADMSG = 9, BUSY = 10, CANCELED = 11, CHILD = 12, CONNABORTED = 13, CONNREFUSED = 14, CONNRESET = 15, DEADLK = 16, DESTADDRREQ = 17, DOM = 18, DQUOT = 19, EXIST = 20, FAULT = 21, FBIG = 22, HOSTUNREACH = 23, IDRM = 24, ILSEQ = 25, INPROGRESS = 26, INTR = 27, INVAL = 28, IO = 29, ISCONN = 30, ISDIR = 31, LOOP = 32, MFILE = 33, MLINK = 34, MSGSIZE = 35, MULTIHOP = 36, NAMETOOLONG = 37, NETDOWN = 38, NETRESET = 39, NETUNREACH = 40, NFILE = 41, NOBUFS = 42, NODEV = 43, NOENT = 44, NOEXEC = 45, NOLCK = 46, NOLINK = 47, NOMEM = 48, NOMSG = 49, NOPROTOOPT = 50, NOSPC = 51, NOSYS = 52, NOTCONN = 53, NOTDIR = 54, NOTEMPTY = 55, NOTRECOVERABLE = 56, NOTSOCK = 57, /// This is also the code used for `NOTSUP`. OPNOTSUPP = 58, NOTTY = 59, NXIO = 60, OVERFLOW = 61, OWNERDEAD = 62, PERM = 63, PIPE = 64, PROTO = 65, PROTONOSUPPORT = 66, PROTOTYPE = 67, RANGE = 68, ROFS = 69, SPIPE = 70, SRCH = 71, STALE = 72, TIMEDOUT = 73, TXTBSY = 74, XDEV = 75, NOTCAPABLE = 76, _, }; pub const E = errno_t; pub const event_t = extern struct { userdata: userdata_t, @"error": errno_t, @"type": eventtype_t, fd_readwrite: eventfdreadwrite_t, }; pub const eventfdreadwrite_t = extern struct { nbytes: filesize_t, flags: eventrwflags_t, }; pub const eventrwflags_t = u16; pub const EVENT_FD_READWRITE_HANGUP: eventrwflags_t = 0x0001; pub const eventtype_t = u8; pub const EVENTTYPE_CLOCK: eventtype_t = 0; pub const EVENTTYPE_FD_READ: eventtype_t = 1; pub const EVENTTYPE_FD_WRITE: eventtype_t = 2; pub const exitcode_t = u32; pub const fd_t = i32; pub const fdflags_t = u16; pub const FDFLAG = struct { pub const APPEND: fdflags_t = 0x0001; pub const DSYNC: fdflags_t = 0x0002; pub const NONBLOCK: fdflags_t = 0x0004; pub const RSYNC: fdflags_t = 0x0008; pub const SYNC: fdflags_t = 0x0010; }; pub const fdstat_t = extern struct { fs_filetype: filetype_t, fs_flags: fdflags_t, fs_rights_base: rights_t, fs_rights_inheriting: rights_t, }; pub const filedelta_t = i64; pub const filesize_t = u64; pub const filestat_t = extern struct { dev: device_t, ino: inode_t, filetype: filetype_t, nlink: linkcount_t, size: filesize_t, atim: timestamp_t, mtim: timestamp_t, ctim: timestamp_t, pub fn atime(self: filestat_t) timespec { return timespec.fromTimestamp(self.atim); } pub fn mtime(self: filestat_t) timespec { return timespec.fromTimestamp(self.mtim); } pub fn ctime(self: filestat_t) timespec { return timespec.fromTimestamp(self.ctim); } }; /// Also known as `FILETYPE`. pub const filetype_t = enum(u8) { UNKNOWN, BLOCK_DEVICE, CHARACTER_DEVICE, DIRECTORY, REGULAR_FILE, SOCKET_DGRAM, SOCKET_STREAM, SYMBOLIC_LINK, _, }; pub const fstflags_t = u16; pub const FILESTAT_SET_ATIM: fstflags_t = 0x0001; pub const FILESTAT_SET_ATIM_NOW: fstflags_t = 0x0002; pub const FILESTAT_SET_MTIM: fstflags_t = 0x0004; pub const FILESTAT_SET_MTIM_NOW: fstflags_t = 0x0008; pub const inode_t = u64; pub const ino_t = inode_t; pub const linkcount_t = u64; pub const lookupflags_t = u32; pub const LOOKUP_SYMLINK_FOLLOW: lookupflags_t = 0x00000001; pub const oflags_t = u16; pub const O = struct { pub const CREAT: oflags_t = 0x0001; pub const DIRECTORY: oflags_t = 0x0002; pub const EXCL: oflags_t = 0x0004; pub const TRUNC: oflags_t = 0x0008; }; pub const preopentype_t = u8; pub const PREOPENTYPE_DIR: preopentype_t = 0; pub const prestat_t = extern struct { pr_type: preopentype_t, u: prestat_u_t, }; pub const prestat_dir_t = extern struct { pr_name_len: usize, }; pub const prestat_u_t = extern union { dir: prestat_dir_t, }; pub const riflags_t = u16; pub const roflags_t = u16; pub const SOCK = struct { pub const RECV_PEEK: riflags_t = 0x0001; pub const RECV_WAITALL: riflags_t = 0x0002; pub const RECV_DATA_TRUNCATED: roflags_t = 0x0001; }; pub const rights_t = u64; pub const RIGHT = struct { pub const FD_DATASYNC: rights_t = 0x0000000000000001; pub const FD_READ: rights_t = 0x0000000000000002; pub const FD_SEEK: rights_t = 0x0000000000000004; pub const FD_FDSTAT_SET_FLAGS: rights_t = 0x0000000000000008; pub const FD_SYNC: rights_t = 0x0000000000000010; pub const FD_TELL: rights_t = 0x0000000000000020; pub const FD_WRITE: rights_t = 0x0000000000000040; pub const FD_ADVISE: rights_t = 0x0000000000000080; pub const FD_ALLOCATE: rights_t = 0x0000000000000100; pub const PATH_CREATE_DIRECTORY: rights_t = 0x0000000000000200; pub const PATH_CREATE_FILE: rights_t = 0x0000000000000400; pub const PATH_LINK_SOURCE: rights_t = 0x0000000000000800; pub const PATH_LINK_TARGET: rights_t = 0x0000000000001000; pub const PATH_OPEN: rights_t = 0x0000000000002000; pub const FD_READDIR: rights_t = 0x0000000000004000; pub const PATH_READLINK: rights_t = 0x0000000000008000; pub const PATH_RENAME_SOURCE: rights_t = 0x0000000000010000; pub const PATH_RENAME_TARGET: rights_t = 0x0000000000020000; pub const PATH_FILESTAT_GET: rights_t = 0x0000000000040000; pub const PATH_FILESTAT_SET_SIZE: rights_t = 0x0000000000080000; pub const PATH_FILESTAT_SET_TIMES: rights_t = 0x0000000000100000; pub const FD_FILESTAT_GET: rights_t = 0x0000000000200000; pub const FD_FILESTAT_SET_SIZE: rights_t = 0x0000000000400000; pub const FD_FILESTAT_SET_TIMES: rights_t = 0x0000000000800000; pub const PATH_SYMLINK: rights_t = 0x0000000001000000; pub const PATH_REMOVE_DIRECTORY: rights_t = 0x0000000002000000; pub const PATH_UNLINK_FILE: rights_t = 0x0000000004000000; pub const POLL_FD_READWRITE: rights_t = 0x0000000008000000; pub const SOCK_SHUTDOWN: rights_t = 0x0000000010000000; pub const ALL: rights_t = FD_DATASYNC | FD_READ | FD_SEEK | FD_FDSTAT_SET_FLAGS | FD_SYNC | FD_TELL | FD_WRITE | FD_ADVISE | FD_ALLOCATE | PATH_CREATE_DIRECTORY | PATH_CREATE_FILE | PATH_LINK_SOURCE | PATH_LINK_TARGET | PATH_OPEN | FD_READDIR | PATH_READLINK | PATH_RENAME_SOURCE | PATH_RENAME_TARGET | PATH_FILESTAT_GET | PATH_FILESTAT_SET_SIZE | PATH_FILESTAT_SET_TIMES | FD_FILESTAT_GET | FD_FILESTAT_SET_SIZE | FD_FILESTAT_SET_TIMES | PATH_SYMLINK | PATH_REMOVE_DIRECTORY | PATH_UNLINK_FILE | POLL_FD_READWRITE | SOCK_SHUTDOWN; }; pub const sdflags_t = u8; pub const SHUT = struct { pub const RD: sdflags_t = 0x01; pub const WR: sdflags_t = 0x02; }; pub const siflags_t = u16; pub const signal_t = u8; pub const SIGNONE: signal_t = 0; pub const SIGHUP: signal_t = 1; pub const SIGINT: signal_t = 2; pub const SIGQUIT: signal_t = 3; pub const SIGILL: signal_t = 4; pub const SIGTRAP: signal_t = 5; pub const SIGABRT: signal_t = 6; pub const SIGBUS: signal_t = 7; pub const SIGFPE: signal_t = 8; pub const SIGKILL: signal_t = 9; pub const SIGUSR1: signal_t = 10; pub const SIGSEGV: signal_t = 11; pub const SIGUSR2: signal_t = 12; pub const SIGPIPE: signal_t = 13; pub const SIGALRM: signal_t = 14; pub const SIGTERM: signal_t = 15; pub const SIGCHLD: signal_t = 16; pub const SIGCONT: signal_t = 17; pub const SIGSTOP: signal_t = 18; pub const SIGTSTP: signal_t = 19; pub const SIGTTIN: signal_t = 20; pub const SIGTTOU: signal_t = 21; pub const SIGURG: signal_t = 22; pub const SIGXCPU: signal_t = 23; pub const SIGXFSZ: signal_t = 24; pub const SIGVTALRM: signal_t = 25; pub const SIGPROF: signal_t = 26; pub const SIGWINCH: signal_t = 27; pub const SIGPOLL: signal_t = 28; pub const SIGPWR: signal_t = 29; pub const SIGSYS: signal_t = 30; pub const subclockflags_t = u16; pub const SUBSCRIPTION_CLOCK_ABSTIME: subclockflags_t = 0x0001; pub const subscription_t = extern struct { userdata: userdata_t, u: subscription_u_t, }; pub const subscription_clock_t = extern struct { id: clockid_t, timeout: timestamp_t, precision: timestamp_t, flags: subclockflags_t, }; pub const subscription_fd_readwrite_t = extern struct { fd: fd_t, }; pub const subscription_u_t = extern struct { tag: eventtype_t, u: subscription_u_u_t, }; pub const subscription_u_u_t = extern union { clock: subscription_clock_t, fd_read: subscription_fd_readwrite_t, fd_write: subscription_fd_readwrite_t, }; pub const timestamp_t = u64; pub const userdata_t = u64; /// Also known as `WHENCE`. pub const whence_t = enum(u8) { SET, CUR, END }; pub const S = struct { pub const IEXEC = @compileError("TODO audit this"); pub const IFBLK = 0x6000; pub const IFCHR = 0x2000; pub const IFDIR = 0x4000; pub const IFIFO = 0xc000; pub const IFLNK = 0xa000; pub const IFMT = IFBLK | IFCHR | IFDIR | IFIFO | IFLNK | IFREG | IFSOCK; pub const IFREG = 0x8000; // There's no concept of UNIX domain socket but we define this value here in order to line with other OSes. pub const IFSOCK = 0x1; }; pub const LOCK = struct { pub const SH = 0x1; pub const EX = 0x2; pub const NB = 0x4; pub const UN = 0x8; };
lib/std/os/wasi.zig
const __floatundidf = @import("floatundidf.zig").__floatundidf; const testing = @import("std").testing; fn test__floatundidf(a: u64, expected: f64) void { const r = __floatundidf(a); testing.expect(r == expected); } test "floatundidf" { test__floatundidf(0, 0.0); test__floatundidf(1, 1.0); test__floatundidf(2, 2.0); test__floatundidf(20, 20.0); test__floatundidf(0x7FFFFF8000000000, 0x1.FFFFFEp+62); test__floatundidf(0x7FFFFFFFFFFFF800, 0x1.FFFFFFFFFFFFEp+62); test__floatundidf(0x7FFFFF0000000000, 0x1.FFFFFCp+62); test__floatundidf(0x7FFFFFFFFFFFF000, 0x1.FFFFFFFFFFFFCp+62); test__floatundidf(0x8000008000000000, 0x1.000001p+63); test__floatundidf(0x8000000000000800, 0x1.0000000000001p+63); test__floatundidf(0x8000010000000000, 0x1.000002p+63); test__floatundidf(0x8000000000001000, 0x1.0000000000002p+63); test__floatundidf(0x8000000000000000, 0x1p+63); test__floatundidf(0x8000000000000001, 0x1p+63); test__floatundidf(0x0007FB72E8000000, 0x1.FEDCBAp+50); test__floatundidf(0x0007FB72EA000000, 0x1.FEDCBA8p+50); test__floatundidf(0x0007FB72EB000000, 0x1.FEDCBACp+50); test__floatundidf(0x0007FB72EBFFFFFF, 0x1.FEDCBAFFFFFFCp+50); test__floatundidf(0x0007FB72EC000000, 0x1.FEDCBBp+50); test__floatundidf(0x0007FB72E8000001, 0x1.FEDCBA0000004p+50); test__floatundidf(0x0007FB72E6000000, 0x1.FEDCB98p+50); test__floatundidf(0x0007FB72E7000000, 0x1.FEDCB9Cp+50); test__floatundidf(0x0007FB72E7FFFFFF, 0x1.FEDCB9FFFFFFCp+50); test__floatundidf(0x0007FB72E4000001, 0x1.FEDCB90000004p+50); test__floatundidf(0x0007FB72E4000000, 0x1.FEDCB9p+50); test__floatundidf(0x023479FD0E092DC0, 0x1.1A3CFE870496Ep+57); test__floatundidf(0x023479FD0E092DA1, 0x1.1A3CFE870496Dp+57); test__floatundidf(0x023479FD0E092DB0, 0x1.1A3CFE870496Ep+57); test__floatundidf(0x023479FD0E092DB8, 0x1.1A3CFE870496Ep+57); test__floatundidf(0x023479FD0E092DB6, 0x1.1A3CFE870496Ep+57); test__floatundidf(0x023479FD0E092DBF, 0x1.1A3CFE870496Ep+57); test__floatundidf(0x023479FD0E092DC1, 0x1.1A3CFE870496Ep+57); test__floatundidf(0x023479FD0E092DC7, 0x1.1A3CFE870496Ep+57); test__floatundidf(0x023479FD0E092DC8, 0x1.1A3CFE870496Ep+57); test__floatundidf(0x023479FD0E092DCF, 0x1.1A3CFE870496Ep+57); test__floatundidf(0x023479FD0E092DD0, 0x1.1A3CFE870496Ep+57); test__floatundidf(0x023479FD0E092DD1, 0x1.1A3CFE870496Fp+57); test__floatundidf(0x023479FD0E092DD8, 0x1.1A3CFE870496Fp+57); test__floatundidf(0x023479FD0E092DDF, 0x1.1A3CFE870496Fp+57); test__floatundidf(0x023479FD0E092DE0, 0x1.1A3CFE870496Fp+57); }
lib/std/special/compiler_rt/floatundidf_test.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const ArrayListUnmanaged = std.ArrayListUnmanaged; const assert = std.debug.assert; const expect = std.testing.expect; fn FindResultType(comptime Node: type) type { return struct { parent: ?*const Node, index: usize, key: []const Node.Part, pub fn wasFound(self: @This()) bool { return self.key.len == 0; } pub fn get(self: @This()) ?Node.Value { return if (self.wasFound()) self.parent.?.value(self.index) else null; } pub fn getPtr(self: @This()) ?*Node.Value { return if (self.wasFound()) self.parent.?.valuePtr(self.index) else null; } }; } pub fn PrefixTreeMapUnmanaged(comptime K: type, comptime V: type, comptime cmpFn: fn (lhs: K, rhs: K) std.math.Order) type { return struct { const Self = @This(); pub const Part = K; pub const Value = V; pub const FindResult = FindResultType(Self); // https://github.com/ziglang/zig/issues/4562 const S = struct { s: ?*Self }; parts: ArrayListUnmanaged(K) = ArrayListUnmanaged(K){}, values: ArrayListUnmanaged(V) = ArrayListUnmanaged(V){}, child_nodes: ArrayListUnmanaged(S) = ArrayListUnmanaged(S){}, fn clear(self: *Self, allocator: *Allocator) void { self.parts.deinit(allocator); self.values.deinit(allocator); self.child_nodes.deinit(allocator); } pub fn deinit(self: *Self, allocator: *Allocator, stack: []*Self) void { var count: usize = 0; for (self.child_nodes.items) |child_node, i| { if (child_node.s) |n| { stack[count] = n; count += 1; } } while (count > 0) { const node = stack[count - 1]; count -= 1; for (node.child_nodes.items) |child_node| { if (child_node.s) |n| { stack[count] = n; count += 1; } } node.clear(allocator); allocator.destroy(node); } self.clear(allocator); } pub fn deinitRecursive(self: *Self, allocator: *Allocator) void { const impl = struct { fn f(node: *Self, a: *Allocator) void { for (node.child_nodes.items) |child_node| { if (child_node.s) |n| f(n, a); } node.clear(a); a.destroy(node); } }.f; for (self.child_nodes.items) |child_node| { if (child_node.s) |n| { impl(n, allocator); } } self.clear(allocator); } pub fn part(self: Self, index: usize) K { return self.parts.items[index]; } pub fn value(self: Self, index: usize) V { return self.values.items[index]; } pub fn valuePtr(self: Self, index: usize) *V { return &self.values.items[index]; } pub fn child(self: Self, index: usize) ?*Self { return self.child_nodes.items[index].s; } pub fn numChildren(self: Self) usize { return self.child_nodes.items.len; } pub fn hasPart(self: Self, p: K) bool { return self.indexOf(p) != null; } pub fn find(self: *const Self, key: []const K) FindResult { assert(key.len > 0); var result = FindResult{ .parent = null, .index = undefined, .key = key, }; var next = self; for (key) |p| { const child_index = next.indexOf(p) orelse break; result = FindResult{ .parent = next, .index = child_index, .key = result.key[1..], }; next = next.child(child_index) orelse break; } return result; } pub fn exists(self: *const Self, key: []const K) bool { return self.find(key).wasFound(); } pub fn get(self: *const Self, key: []const K) ?V { return self.find(key).get(); } pub fn getPtr(self: *const Self, key: []const K) ?*V { return self.find(key).getPtr(); } /// Inserts a new key-value pair into the tree, filling any newly created intermediate /// key-value pairs with `filler`. If there was already a value associated with the key, /// it is returned. pub fn insert(self: *Self, allocator: *Allocator, key: []const K, val: V, filler: V) !?V { return insertWithFind(self, allocator, self.find(key), val, filler); } /// Inserts a new key-value pair into the tree, filling any newly created intermediate /// key-value pairs with `filler`. If there was already a value associated with the key, /// it is returned. A `FindResult` is used to skip traversing some of the tree. pub fn insertWithFind(self: *Self, allocator: *Allocator, find_result: FindResult, val: V, filler: V) !?V { if (find_result.wasFound()) { const ptr = find_result.getPtr().?; const old = ptr.*; ptr.* = val; return old; } else if (find_result.parent == null) { try insertBranch(self, allocator, find_result.key, val, filler); return null; } else { try insertMaybeCreateChildNode(allocator, find_result, val, filler); return null; } } fn insertMaybeCreateChildNode(allocator: *Allocator, find_result: FindResult, val: V, filler: V) !void { const child_node_ptr = &find_result.parent.?.child_nodes.items[find_result.index].s; if (child_node_ptr.*) |child_node| { try insertBranch(child_node, allocator, find_result.key, val, filler); } else { const child_node = try allocator.create(Self); errdefer allocator.destroy(child_node); child_node.* = Self{}; try insertBranch(child_node, allocator, find_result.key, val, filler); child_node_ptr.* = child_node; } } fn insertBranch(parent: *Self, allocator: *Allocator, key: []const K, val: V, filler: V) !void { if (key.len == 1) { _ = try newEdge(parent, allocator, key[0], val, null); } else { const branch = try newBranch(allocator, key[1..], val, filler); errdefer deleteBranch(branch, allocator); _ = try newEdge(parent, allocator, key[0], filler, branch); } } fn indexOf(self: Self, p: K) ?usize { const cmp = struct { fn f(ctx: void, lhs: K, rhs: K) std.math.Order { return cmpFn(lhs, rhs); } }.f; return std.sort.binarySearch(K, p, self.parts.items, {}, cmp); } /// Stolen from std.sort.binarySearch. fn searchForInsertPosition( key: K, parts: []const K, ) usize { var left: usize = 0; var right: usize = parts.len; while (left < right) { // Avoid overflowing in the midpoint calculation const mid = left + (right - left) / 2; // Compare the key with the midpoint element switch (cmpFn(key, parts[mid])) { .eq => unreachable, .gt => left = mid + 1, .lt => right = mid, } } return left; } fn newEdge(self: *Self, allocator: *Allocator, p: K, val: V, child_node: ?*Self) !usize { assert(!self.hasPart(p)); // Edge already exists. const index = searchForInsertPosition(p, self.parts.items); try self.parts.insert(allocator, index, p); errdefer _ = self.parts.orderedRemove(index); try self.values.insert(allocator, index, val); errdefer _ = self.values.orderedRemove(index); try self.child_nodes.insert(allocator, index, .{ .s = child_node }); errdefer _ = self.child_nodes.orderedRemove(index); return index; } fn newBranch(allocator: *Allocator, key: []const K, val: V, filler: V) !*Self { var top = try allocator.create(Self); top.* = Self{}; errdefer deleteBranch(top, allocator); _ = try top.newEdge(allocator, key[0], filler, null); var previous = top; for (key[1..]) |p| { var current = try allocator.create(Self); current.* = Self{}; errdefer allocator.destroy(current); _ = try current.newEdge(allocator, p, filler, null); previous.child_nodes.items[0].s = current; previous = current; } previous.valuePtr(0).* = val; return top; } fn deleteBranch(branch: *Self, allocator: *Allocator) void { var current = branch; while (current.child(0)) |next| { current.clear(allocator); allocator.destroy(current); current = next; } } }; } test "sample tree" { const cmpFn = (struct { fn f(lhs: u8, rhs: u8) std.math.Order { return std.math.order(lhs, rhs); } }).f; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer expect(!gpa.deinit()); const allocator = &gpa.allocator; const Tree = PrefixTreeMapUnmanaged(u8, i32, cmpFn); var stack = @as([3]*Tree, undefined); var tree = Tree{}; defer tree.deinit(allocator, &stack); expect(!tree.exists("a")); expect((try tree.insert(allocator, "a", -64, 0)) == null); expect((try tree.insert(allocator, "b", 100, 0)) == null); expect((try tree.insert(allocator, "ab", 42, 0)) == null); expect(tree.exists("a")); expect(tree.exists("b")); expect(tree.exists("ab")); expect(!tree.exists("c")); expect(!tree.exists("ba")); expect(!tree.exists("abc")); expect(tree.get("a").? == -64); expect(tree.get("b").? == 100); expect(tree.get("ab").? == 42); expect((try tree.insert(allocator, "zyx", 1729, 1)) == null); expect(tree.exists("zyx")); expect(tree.exists("zy")); expect(tree.exists("z")); expect(tree.get("zyx").? == 1729); expect(tree.get("zy").? == 1); expect(tree.get("z").? == 1); tree.getPtr("z").?.* = 5; expect(tree.get("z").? == 5); } test "empty tree" { const cmpFn = (struct { fn f(lhs: u8, rhs: u8) std.math.Order { return std.math.order(lhs, rhs); } }).f; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer expect(!gpa.deinit()); const allocator = &gpa.allocator; const Tree = PrefixTreeMapUnmanaged(u8, i32, cmpFn); var stack = @as([3]*Tree, undefined); var tree = Tree{}; defer tree.deinit(allocator, &stack); var tree2 = Tree{}; defer tree2.deinitRecursive(allocator); } test "void tree" { if (false) { const cmpFn = (struct { fn f(lhs: u8, rhs: u8) std.math.Order { return std.math.order(lhs, rhs); } }).f; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer expect(!gpa.deinit()); const allocator = &gpa.allocator; const Tree = PrefixTreeMapUnmanaged(u8, void, cmpFn); var tree = Tree{}; defer tree.deinitRecursive(allocator); _ = try tree.insert(allocator, "a", {}, {}); expect(tree.exists("a")); expect(tree.get("a").? == {}); } }
source/prefix_tree_map.zig
const std = @import("std"); const mem = std.mem; const maxInt = std.math.maxInt; const Error = std.crypto.Error; // RFC 2898 Section 5.2 // // FromSpec: // // PBKDF2 applies a pseudorandom function (see Appendix B.1 for an // example) to derive keys. The length of the derived key is essentially // unbounded. (However, the maximum effective search space for the // derived key may be limited by the structure of the underlying // pseudorandom function. See Appendix B.1 for further discussion.) // PBKDF2 is recommended for new applications. // // PBKDF2 (P, S, c, dk_len) // // Options: PRF underlying pseudorandom function (h_len // denotes the length in octets of the // pseudorandom function output) // // Input: P password, an octet string // S salt, an octet string // c iteration count, a positive integer // dk_len intended length in octets of the derived // key, a positive integer, at most // (2^32 - 1) * h_len // // Output: DK derived key, a dk_len-octet string // Based on Apple's CommonKeyDerivation, based originally on code by <NAME>. /// Apply PBKDF2 to generate a key from a password. /// /// PBKDF2 is defined in RFC 2898, and is a recommendation of NIST SP 800-132. /// /// dk: Slice of appropriate size for generated key. Generally 16 or 32 bytes in length. /// May be uninitialized. All bytes will be overwritten. /// Maximum size is `maxInt(u32) * Hash.digest_length` /// It is a programming error to pass buffer longer than the maximum size. /// /// password: Arbitrary sequence of bytes of any length, including empty. /// /// salt: Arbitrary sequence of bytes of any length, including empty. A common length is 8 bytes. /// /// rounds: Iteration count. Must be greater than 0. Common values range from 1,000 to 100,000. /// Larger iteration counts improve security by increasing the time required to compute /// the dk. It is common to tune this parameter to achieve approximately 100ms. /// /// Prf: Pseudo-random function to use. A common choice is `std.crypto.auth.hmac.HmacSha256`. pub fn pbkdf2(dk: []u8, password: []const u8, salt: []const u8, rounds: u32, comptime Prf: type) Error!void { if (rounds < 1) return error.WeakParameters; const dk_len = dk.len; const h_len = Prf.mac_length; comptime std.debug.assert(h_len >= 1); // FromSpec: // // 1. If dk_len > maxInt(u32) * h_len, output "derived key too long" and // stop. // if (dk_len / h_len >= maxInt(u32)) { // Counter starts at 1 and is 32 bit, so if we have to return more blocks, we would overflow return error.OutputTooLong; } // FromSpec: // // 2. Let l be the number of h_len-long blocks of bytes in the derived key, // rounding up, and let r be the number of bytes in the last // block // const blocks_count = @intCast(u32, std.math.divCeil(usize, dk_len, h_len) catch unreachable); var r = dk_len % h_len; if (r == 0) { r = h_len; } // FromSpec: // // 3. For each block of the derived key apply the function F defined // below to the password P, the salt S, the iteration count c, and // the block index to compute the block: // // T_1 = F (P, S, c, 1) , // T_2 = F (P, S, c, 2) , // ... // T_l = F (P, S, c, l) , // // where the function F is defined as the exclusive-or sum of the // first c iterates of the underlying pseudorandom function PRF // applied to the password P and the concatenation of the salt S // and the block index i: // // F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c // // where // // U_1 = PRF (P, S || INT (i)) , // U_2 = PRF (P, U_1) , // ... // U_c = PRF (P, U_{c-1}) . // // Here, INT (i) is a four-octet encoding of the integer i, most // significant octet first. // // 4. Concatenate the blocks and extract the first dk_len octets to // produce a derived key DK: // // DK = T_1 || T_2 || ... || T_l<0..r-1> var block: u32 = 0; while (block < blocks_count) : (block += 1) { var prev_block: [h_len]u8 = undefined; var new_block: [h_len]u8 = undefined; // U_1 = PRF (P, S || INT (i)) const block_index = mem.toBytes(mem.nativeToBig(u32, block + 1)); // Block index starts at 0001 var ctx = Prf.init(password); ctx.update(salt); ctx.update(block_index[0..]); ctx.final(prev_block[0..]); // Choose portion of DK to write into (T_n) and initialize const offset = block * h_len; const block_len = if (block != blocks_count - 1) h_len else r; const dk_block: []u8 = dk[offset..][0..block_len]; mem.copy(u8, dk_block, prev_block[0..dk_block.len]); var i: u32 = 1; while (i < rounds) : (i += 1) { // U_c = PRF (P, U_{c-1}) Prf.create(&new_block, prev_block[0..], password); mem.copy(u8, prev_block[0..], new_block[0..]); // F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c for (dk_block) |_, j| { dk_block[j] ^= new_block[j]; } } } } const htest = @import("test.zig"); const HmacSha1 = std.crypto.auth.hmac.HmacSha1; // RFC 6070 PBKDF2 HMAC-SHA1 Test Vectors test "RFC 6070 one iteration" { const p = "password"; const s = "<PASSWORD>"; const c = 1; const dk_len = 20; var dk: [dk_len]u8 = undefined; try pbkdf2(&dk, p, s, c, HmacSha1); const expected = "0c60c80f961f0e71f3a9b524af6012062fe037a6"; htest.assertEqual(expected, dk[0..]); } test "RFC 6070 two iterations" { const p = "password"; const s = "<PASSWORD>"; const c = 2; const dk_len = 20; var dk: [dk_len]u8 = undefined; try pbkdf2(&dk, p, s, c, HmacSha1); const expected = "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"; htest.assertEqual(expected, dk[0..]); } test "RFC 6070 4096 iterations" { const p = "password"; const s = "<PASSWORD>"; const c = 4096; const dk_len = 20; var dk: [dk_len]u8 = undefined; try pbkdf2(&dk, p, s, c, HmacSha1); const expected = "4b007901b765489abead49d926f721d065a429c1"; htest.assertEqual(expected, dk[0..]); } test "RFC 6070 16,777,216 iterations" { // These iteration tests are slow so we always skip them. Results have been verified. if (true) { return error.SkipZigTest; } const p = "password"; const s = "<PASSWORD>"; const c = 16777216; const dk_len = 20; var dk = [_]u8{0} ** dk_len; try pbkdf2(&dk, p, s, c, HmacSha1); const expected = "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984"; htest.assertEqual(expected, dk[0..]); } test "RFC 6070 multi-block salt and password" { const p = "<PASSWORD>password"; const s = "saltSALTsaltSALTsaltSALTsaltSALTsalt"; const c = 4096; const dk_len = 25; var dk: [dk_len]u8 = undefined; try pbkdf2(&dk, p, s, c, HmacSha1); const expected = "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"; htest.assertEqual(expected, dk[0..]); } test "RFC 6070 embedded NUL" { const p = "<PASSWORD>"; const s = "sa\x00lt"; const c = 4096; const dk_len = 16; var dk: [dk_len]u8 = undefined; try pbkdf2(&dk, p, s, c, HmacSha1); const expected = "56fa6aa75548099dcc37d7f03425e0c3"; htest.assertEqual(expected, dk[0..]); } test "Very large dk_len" { // This test allocates 8GB of memory and is expected to take several hours to run. if (true) { return error.SkipZigTest; } const p = "password"; const s = "<PASSWORD>"; const c = 1; const dk_len = 1 << 33; var dk = try std.testing.allocator.alloc(u8, dk_len); defer { std.testing.allocator.free(dk); } // Just verify this doesn't crash with an overflow try pbkdf2(dk, p, s, c, HmacSha1); }
lib/std/crypto/pbkdf2.zig
const std = @import("std"); const lpc = @import("lpc1768"); const F_CPU = 100_000_000; comptime { // Provides the initialization routines _ = @import("boot.zig"); } const LED1 = GPIO(1, 18); const LED2 = GPIO(1, 20); const LED3 = GPIO(1, 21); const LED4 = GPIO(1, 23); const SD_SELECT = GPIO(0, 16); // DIP14 const pinConfig = comptime blk: { var cfg = PinConfig{}; cfg.configure(0, 10, .Func01, .PullUp, false); // P28 TXD2 cfg.configure(0, 11, .Func01, .PullUp, false); // P27 RXD2 cfg.configure(0, 16, .Func00, .PullUp, false); // P14 GPIO / SD_SELECT | CH0 | Blue cfg.configure(0, 15, .Func10, .PullUp, false); // P13 SCK | CH1 | Green cfg.configure(0, 17, .Func10, .PullUp, false); // P12 MISO0 | CH2 | Yellow cfg.configure(0, 18, .Func10, .PullUp, false); // P11 MOSI0 | CH3 | Orange break :blk cfg; }; pub fn main() !void { //pinConfig.apply(); LED1.setDirection(.out); LED2.setDirection(.out); LED3.setDirection(.out); LED4.setDirection(.out); // SD_SELECT.setDirection(.out); LED1.clear(); LED2.clear(); LED3.set(); LED4.set(); // SD_SELECT.setTo(.high); while (true) { asm volatile ("wfi"); } // // Enable PLL & serial for debug output // PLL.init(); // Serial.init(115_200); // SPI.init(); // var sync_serial = Serial.syncWriter(); // try sync_serial.writeAll("Serial port initialized.\r\n"); // SysTick.init(1_000); // try sync_serial.writeAll("SysTick initialized.\r\n"); // EventLoop.init(); // try sync_serial.writeAll("Starting event loop...\r\n"); // LED4.set(); // var core_loop = async coreMain(); // var blinky_frame = async doBlinkyLoop(); // EventLoop.run(); // try nosuspend await core_loop; // nosuspend await blinky_frame; // try sync_serial.writeAll("Event loop finished!\r\n"); } fn doBlinkyLoop() void { while (true) { LED1.set(); EventLoop.waitForMillis(250); LED1.clear(); EventLoop.waitForMillis(750); } } fn coreMain() !void { var serin = Serial.reader(); var serout = Serial.writer(); while (true) { var cmd = try serin.readByte(); LED2.set(); switch (std.ascii.toLower(cmd)) { 's' => { SD_SELECT.setTo(.low); try serout.writeAll("select chip\r\n"); }, 'u' => { SD_SELECT.setTo(.high); try serout.writeAll("unselect chip\r\n"); }, 't' => { try serout.writeAll("write test burst...\r\n"); var i: u32 = 0; while (i < 256) : (i += 1) { SPI.write(@truncate(u8, i)); } try serout.writeAll("done!\r\n"); }, 'i' => { try serout.writeAll("initialize sd card...\r\n"); if (SDCard.get()) |maybe_card| { try serout.print("found card: {}\r\n", .{maybe_card}); if (maybe_card) |card| { try serout.print(" status: {}\r\n", .{ try card.getStatus(), }); const T = struct { var boot_block: [512]u8 = undefined; }; try card.readBlock(0, &T.boot_block); try serout.writeAll(" boot block:\r\n"); var offset: usize = 0; while (offset < T.boot_block.len) : (offset += 32) { const line = T.boot_block[offset..][0..32]; try serout.print(" {} |", .{std.fmt.fmtSliceHexUpper(line)}); for (line) |c| { if (c >= 0x20 and c < 0x7F) { try serout.print("{c}", .{c}); } else { try serout.writeAll("."); } } try serout.writeAll("|\r\n"); } } } else |err| { try serout.print("could not detect card: {}\r\n", .{err}); } }, else => try serout.print("Unknown command '{c}'\r\n", .{cmd}), } LED2.clear(); } } const SDCard = struct { const Self = @This(); const Type = enum { mmc, sd1, sd2, sdhc, }; type: Type, fn range(comptime size: usize) [size]void { return [_]void{{}} ** size; } fn get() !?Self { assertCard(); for (range(10)) |_| _ = readRawByte(); deassertCard(); for (range(10)) |_| { cmdGoIdleState() catch |err| switch (err) { error.NotInitialized => break, else => continue, }; } else return null; // no card present var card = Self{ .type = undefined, }; if (sendInterfaceCondition(.standard_3v3, 0x55)) |supported_voltages| { if (supported_voltages != .standard_3v3) { return error.VoltageMismatch; } card.type = .sd2; const ocr = try readOcr(); if ((ocr & ((1 << 20) | (1 << 21))) == 0) { return error.VoltageMismatch; } } else |err| { if (err != error.IllegalCommand) return err; card.type = .sd1; } if (card.type == .sd2) { for (range(10)) |_| { const r1 = try sdSendOpCond(true); r1.throw() catch continue; break; } else return error.Timeout; const ocr2 = try readOcr(); if ((ocr2 & 0x4000_0000) != 0) { card.type = .sdhc; } } else { if (sdSendOpCond(false)) |_| { // Success card.type = .sd1; } else |_| { try sendOpCond(false); card.type = .mmc; } } // try setBlockLength(512); return card; } pub fn getStatus(self: Self) !R2Response { return try sendStatus(); } pub fn readBlock(self: Self, block_index: u32, buffer: *[512]u8) !void { defer deassertCard(); const index = if (self.type == .sdhc) block_index else 512 * block_index; const r1 = try writeR1Command(.CMD17, index, false); try r1.throw(); for (range(0xFF)) |_| { const start_token = readRawByte(); if (start_token == 0xFE) break; } else return error.Timeout; for (buffer) |*b| { b.* = readRawByte(); } var crc16_buf: [2]u8 = undefined; crc16_buf[0] = readRawByte(); crc16_buf[1] = readRawByte(); // TODO: Verify CRC16 } const Command = enum(u6) { CMD0 = 0, // R1 GO_IDLE_STATE CMD1 = 1, // R1 SEND_OP_COND CMD5 = 5, // R1 ?? CMD6 = 6, // R1 SWITCH_FUNC CMD8 = 8, // R7 SEND_IF_COND CMD9 = 9, // R1 SEND_CSD CMD10 = 10, // R1 SEND_CID CMD12 = 12, // R1b STOP_TRANSMISSION CMD13 = 13, // R2 SEND_STATUS CMD16 = 16, // R1 SET_BLOCKLEN CMD17 = 17, // R1 READ_SINGLE_BLOCK CMD18 = 18, // R1 READ_MULTIPLE_BLOCK CMD24 = 24, // R1 WRITE_BLOCK CMD25 = 25, // R1 WRITE_MULTIPLE_BLOCK CMD27 = 27, // R1 PROGRAM_CSD CMD28 = 28, // R1b SET_WRITE_PROT CMD29 = 29, // R1b CLR_WRITE_PRO CMD30 = 30, // R1 SEND_WRITE_PROT CMD32 = 32, // R1 ERASE_WR_BL_START_ADDR CMD33 = 33, // R1 ERASE_WR_BLK_END_ADDR CMD34 = 34, // ?? CMD35 = 35, // ?? CMD36 = 36, // ?? CMD37 = 37, // ?? CMD38 = 38, // R1b ERASE CMD42 = 42, // R1 LOCK_UNLOCK CMD50 = 50, // ?? CMD52 = 52, // ?? CMD53 = 53, // ?? CMD55 = 55, // R1 APP_CMD CMD56 = 56, // R1 GEN_CMD CMD57 = 57, // ?? CMD58 = 58, // R3 READ_OCR CMD59 = 59, // R3 CRC_ON_OFF }; const AppCommand = enum(u6) { ACMD13 = 13, // R2 SD_STATUS ACMD22 = 22, // R1 SEND_NUM_WR_BLOCKS ACMD23 = 23, // R1 SET_WR_BLK_ERASE_COUNT ACMD41 = 41, // R1 SD_SEND_OP_COND ACMD42 = 42, // R1 SET_CLR_CARD_DETECT ACMD51 = 51, // R1 SEND_SCR }; fn cmdGoIdleState() !void { return (try writeR1Command(.CMD0, 0, true)).throw(); } fn sendOpCond(high_capacity_support: bool) !void { const erg = try writeR1Command( .CMD1, if (high_capacity_support) 0x4000_0000 else 0x0000_0000, true, ); return erg.throw(); } fn switchFunc() !void { @panic("switchFunc not implemented yet!"); // try writeR1Command(.CMD6, 0,true); } fn sendCsd() !void { try writeR1Command(.CMD9, 0, true); } fn sendCid() !void { try writeR1Command(.CMD10, 0, true); } fn setBlockLength(block_length: u32) !void { try (try writeR1Command(.CMD16, block_length, true)).throw(); } fn programCsd() !void { try writeR1Command(.CMD27, 0, true); } fn sendWriteProt(address: u32) !void { try writeR1Command(.CMD30, address, true); } fn eraseWrBlStartAddr(address: u32) !void { try writeR1Command(.CMD32, address, true); } fn eraseWrBlkEndAddr(address: u32) !void { try writeR1Command(.CMD33, address, true); } fn lockUnlock() !void { try writeR1Command(.CMD42, 0, true); } fn appCmd() !void { try writeR1Command(.CMD55, 0, true); } fn genCmd(write: bool) !void { try writeR1Command(.CMD56, if (write) 0 else 1, true); } // R1b commands: fn stopTransmission() !void { try writeR1bCommand(.CMD12, 0); } fn setWriteProt(address: u32) !void { try writeR1bCommand(.CMD28, address); } fn clrWritePro(address: u32) !void { try writeR1bCommand(.CMD29, address); } fn erase() !void { try writeR1bCommand(.CMD38, 0); } // R2 commands: fn sendStatus() !R2Response { return try writeR2Command(.CMD13, 0); } // R3 commands: fn readOcr() !u32 { const ocr = try writeR3Command(.CMD58, 0); ocr.r1.throw() catch |err| switch (err) { error.NotInitialized => {}, else => return err, }; return ocr.value; } fn crcOnOff(enabled: bool) !void { const ocr = try writeR3Command(.CMD59, if (enabled) 1 else 0); try ocr.r1.throw(); } // R7 commands: const VoltageRange = enum(u4) { standard_3v3 = 0b0001, low_voltage_range = 0b0010, reserved0 = 0b0100, reserved1 = 0b1000, _, }; fn sendInterfaceCondition(voltage_support: VoltageRange, pattern: u8) !VoltageRange { const arg = (@as(u32, @enumToInt(voltage_support)) << 8) | (@as(u32, pattern)); const response = try writeR7Command(.CMD8, arg); response.r1.throw() catch |err| switch (err) { error.NotInitialized => {}, else => return err, }; if ((response.value & 0xFF) != pattern) return error.PatternMismatch; return @intToEnum(VoltageRange, @truncate(u4, response.value >> 8)); } // app commands: fn sdSendOpCond(high_capacity_support: bool) !ResponseBits { assertCard(); defer deassertCard(); writeRawCommand(Command.CMD55, 0); _ = try readResponseR1(); deassertCard(); _ = readRawByte(); assertCard(); writeRawCommand(AppCommand.ACMD41, @as(u32, if (high_capacity_support) 0x4000_0000 else 0x0000_0000)); return try readResponseR1(); } // raw interface: fn writeR1Command(cmd: Command, arg: u32, deassert: bool) !ResponseBits { assertCard(); defer if (deassert) deassertCard(); writeRawCommand(cmd, arg); return readResponseR1(); } fn writeR1bCommand(cmd: Command, arg: u32) !ResponseBits { assertCard(); defer deassertCard(); writeRawCommand(cmd, arg); return try readResponseR1b(); } fn writeR2Command(cmd: Command, arg: u32) !R2Response { assertCard(); defer deassertCard(); writeRawCommand(cmd, arg); return try readResponseR2(); } fn writeR3Command(cmd: Command, arg: u32) !R3Response { assertCard(); defer deassertCard(); writeRawCommand(cmd, arg); return readResponseR3(); } fn writeR7Command(cmd: Command, arg: u32) !R7Response { assertCard(); defer deassertCard(); writeRawCommand(cmd, arg); return readResponseR7(); } fn assertCard() void { SD_SELECT.setTo(.low); // Give card some time _ = readRawByte(); } fn deassertCard() void { // Give card some time _ = readRawByte(); SD_SELECT.setTo(.high); } // //SD card accepts byte address while SDHC accepts block address in multiples of 512 // //so, if it's SD card we need to convert block address into corresponding byte address by // //multipying it with 512. which is equivalent to shifting it left 9 times // //following 'if' loop does that // const arg = if (self.sdhc) // arg_ro // else switch (cmd) { // .READ_SINGLE_BLOCK, // .READ_MULTIPLE_BLOCKS, // .WRITE_SINGLE_BLOCK, // .WRITE_MULTIPLE_BLOCKS, // .ERASE_BLOCK_START_ADDR, // .ERASE_BLOCK_END_ADDR, // => arg_ro << 9, // else => arg_ro, // }; fn writeRawCommand(cmd: anytype, arg: u32) void { Serial.syncWriter().writeAll(@tagName(cmd)) catch {}; Serial.syncWriter().writeAll("\r\n") catch {}; var msg: [6]u8 = undefined; msg[0] = @enumToInt(cmd) | @as(u8, 0b01000000); std.mem.writeIntBig(u32, msg[1..5], arg); msg[5] = (@as(u8, CRC7.compute(msg[0..5])) << 1) | 1; writeRaw(&msg); } const ResponseBits = packed struct { idle: bool, erase_reset: bool, illegal_command: bool, com_crc_error: bool, erase_sequence_error: bool, address_error: bool, parameter_error: bool, must_be_zero: u1, fn throw(self: @This()) !void { if (self.illegal_command) return error.IllegalCommand; if (self.address_error) return error.AddressError; if (self.com_crc_error) return error.CrcError; if (self.erase_sequence_error) return error.EraseSequenceError; if (self.parameter_error) return error.ParameterError; if (self.idle) return error.NotInitialized; } }; fn readResponseR1() !ResponseBits { for (range(0x10)) |_| { const byte = readRawByte(); if (byte == 0xFF) continue; return @bitCast(ResponseBits, byte); } else return error.Timeout; } fn readResponseR1b() !ResponseBits { for (range(0xFF)) |_| { const byte = readRawByte(); if (byte == 0x00) continue; if (byte == 0xFF) continue; return @bitCast(ResponseBits, byte); } else return error.Timeout; } const R2Response = packed struct { card_is_locked: bool, wp_erase_skip_or_lock_unlock_cmd_failed: bool, @"error": bool, cc_error: bool, card_ecc_failed: bool, wp_violation: bool, erase_param: bool, out_of_range_csd_overwrite: bool, in_idle_state: bool, erase_reset: bool, illegal_command: bool, com_crc_error: bool, erase_sequence_error: bool, address_error: bool, parameter_error: bool, zero: u1 = 0, }; fn readResponseR2() !R2Response { var resp: [2]u8 = undefined; for (range(20)) |_| { resp[0] = readRawByte(); if (resp[0] != 0xFF) break; } else return error.Timeout; resp[1] = readRawByte(); return @bitCast(R2Response, resp); } const R3Response = struct { r1: ResponseBits, value: u32, }; fn readResponseR3() !R3Response { var result: R3Response = undefined; result.r1 = try readResponseR1(); var buf: [4]u8 = undefined; readRaw(&buf); result.value = std.mem.readIntBig(u32, &buf); return result; } const R7Response = struct { r1: ResponseBits, value: u32, }; fn readResponseR7() !R7Response { var result: R7Response = undefined; result.r1 = try readResponseR1(); var resp: [4]u8 = undefined; readRaw(&resp); result.value = std.mem.readIntBig(u32, &resp); return result; } fn writeRaw(buffer: []const u8) void { for (buffer) |b| writeRawByte(b); } fn writeRawByte(val: u8) void { try Serial.syncWriter().print("→ 0x{X:0>2}\r\n", .{val}); _ = SPI.xmit(val); } fn readRawByte() u8 { const res = @intCast(u8, SPI.xmit(0xFF)); try Serial.syncWriter().print("← 0x{X:0>2}\r\n", .{res}); return res; } fn readRaw(buf: []u8) void { for (buf) |*b| b.* = readRawByte(); } }; // Implemented after https://github.com/hazelnusse/crc7/blob/master/crc7.cc const CRC7 = struct { const table = blk: { @setEvalBranchQuota(10_000); var items: [256]u8 = undefined; const poly: u8 = 0x89; // the value of our CRC-7 polynomial // generate a table value for all 256 possible byte values for (items) |*item, i| { item.* = if ((i & 0x80) != 0) i ^ poly else i; var j: usize = 1; while (j < 8) : (j += 1) { item.* <<= 1; if ((item.* & 0x80) != 0) item.* ^= poly; } } break :blk items; }; // adds a message byte to the current CRC-7 to get a the new CRC-7 fn add(crc: u8, message_byte: u8) u8 { return table[(crc << 1) ^ message_byte]; } // returns the CRC-7 for a message of "length" bytes fn compute(message: []const u8) u7 { var crc: u8 = 0; for (message) |byte| { crc = add(crc, byte); } return @intCast(u7, crc); } }; // Three examples from the SD spec test "CRC7" { { var crc = compute(&[_]u8{ 0b01000000, 0x00, 0x00, 0x00, 0x00, }); std.debug.assert(crc == 0b1001010); } { var crc = compute(&[_]u8{ 0b01010001, 0x00, 0x00, 0x00, 0x00, }); std.debug.assert(crc == 0b0101010); } { var crc = compute(&[_]u8{ 0b00010001, 0b00000000, 0b00000000, 0b00001001, 0b00000000, }); std.debug.assert(crc == 0b0110011); } } pub fn panic(message: []const u8, maybe_stack_trace: ?*std.builtin.StackTrace) noreturn { lpc.__disable_irq(); LED1.set(); LED2.set(); LED3.set(); LED4.clear(); var serial = Serial.syncWriter(); serial.print("reached panic: {s}\r\n", .{message}) catch unreachable; if (maybe_stack_trace) |stack_trace| printStackTrace(stack_trace); while (true) { lpc.__disable_irq(); lpc.__disable_fault_irq(); lpc.__WFE(); } } fn printStackTrace(stack_trace: *std.builtin.StackTrace) void { var serial = Serial.syncWriter(); 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]; serial.print("[{d}] 0x{X}\r\n", .{ frames_left, return_address, }) catch unreachable; } } const PinDirection = enum { in, out }; fn GPIO(comptime portIndex: u32, comptime index: u32) type { return struct { const port_number = port_index; const pin_number = index; const pin_mask: u32 = (1 << index); const io = @intToPtr(*volatile lpc.LPC_GPIO_TypeDef, lpc.GPIO_BASE + 0x00020 * portIndex); fn setDirection(d: PinDirection) void { switch (d) { .out => io.FIODIR |= pin_mask, .in => io.FIODIR &= ~pin_mask, } } fn direction() PinDirection { return if ((io.FIODIR & pin_mask) != 0) .out else .in; } fn getValue() bool { return (io.FIOPIN & pin_mask) != 0; } fn clear() void { io.FIOCLR = pin_mask; } fn set() void { io.FIOSET = pin_mask; } const Level = enum { high, low }; fn setTo(level: Level) void { if (level == .high) { set(); } else { clear(); } } fn toggle() void { if (getValue()) { clear(); } else { set(); } } }; } const PLL = struct { fn init() void { reset_overclocking(); } fn reset_overclocking() void { overclock_flash(5); // 5 cycles access time overclock_pll(3); // 100 MHz } fn overclock_flash(timing: u8) void { lpc.sc.FLASHCFG = (@as(u32, timing - 1) << 12) | (lpc.sc.FLASHCFG & 0xFFFF0FFF); } fn feed_pll() callconv(.Inline) void { lpc.sc.PLL0FEED = 0xAA; // mit anschliessendem FEED lpc.sc.PLL0FEED = 0x55; } fn overclock_pll(divider: u8) void { // PLL einrichten für RC lpc.sc.PLL0CON = 0; // PLL disconnect feed_pll(); lpc.sc.CLKSRCSEL = 0x00; // RC-Oszillator als Quelle lpc.sc.PLL0CFG = ((1 << 16) | 74); // SysClk = (4MHz / 2) * (2 * 75) = 300 MHz lpc.sc.CCLKCFG = divider - 1; // CPU Takt = SysClk / divider feed_pll(); lpc.sc.PLL0CON = 1; // PLL einschalten feed_pll(); var i: usize = 0; while (i < 1_000) : (i += 1) { lpc.__NOP(); } lpc.sc.PLL0CON = 3; // PLL connecten feed_pll(); } }; const PinConfig = struct { const Function = enum(u2) { Func00 = 0, Func01 = 1, Func10 = 2, Func11 = 3, }; const Mode = enum(u2) { PullUp = 0, Repeater = 1, Floating = 2, PullDown = 3, }; // contain the register values if any selector: [10]?u32 = [1]?u32{null} ** 10, pinmode: [10]?u32 = [1]?u32{null} ** 10, opendrain: [5]?u32 = [1]?u32{null} ** 5, fn setup(val: *?u32, mask: u32, value: u32) void { if (val.* == null) val.* = 0; val.*.? = (val.*.? & ~mask) | (value & mask); } fn selectFunction(cfg: *PinConfig, port: u32, pin: u32, function: Function) void { const offset = (pin / 16); const index = @intCast(u5, (pin % 16) << 1); const mask = (@as(u32, 3) << index); const value = @as(u32, @enumToInt(function)) << index; setup(&cfg.selector[2 * port + offset], mask, value); } fn setMode(cfg: *PinConfig, port: u32, pin: u32, mode: Mode) void { const offset = (pin / 16); const index = @intCast(u5, pin % 16); const mask = (@as(u32, 3) << (2 * index)); const value = (@as(u32, @enumToInt(mode)) << (2 * index)); setup(&cfg.pinmode[2 * port + offset], mask, value); // P0.0 } fn setOpenDrain(cfg: *PinConfig, port: u32, pin: u32, enabled: bool) void { const index = @intCast(u5, pin % 16); const mask = (@as(u32, 1) << index); const value = if (enabled) mask else 0; setup(&cfg.opendrain[port], mask, value); } fn configure(cfg: *PinConfig, port: u32, pin: u32, func: Function, mode: Mode, open_drain: bool) void { cfg.selectFunction(port, pin, func); cfg.setMode(port, pin, mode); cfg.setOpenDrain(port, pin, open_drain); } fn apply(cfg: PinConfig) void { for (cfg.selector) |opt_value, i| { if (opt_value) |value| { lpc.pincon.PINSEL[i] = value; } } for (cfg.pinmode) |opt_value, i| { if (opt_value) |value| { lpc.pincon.PINMODE[i] = value; } } for (cfg.opendrain) |opt_value, i| { if (opt_value) |value| { lpc.pincon.PINMODE_OD[i] = value; } } } }; const DynamicPinConfig = struct { const Function = enum(u2) { Func00 = 0, Func01 = 1, Func10 = 2, Func11 = 3, }; const Mode = enum(u2) { PullUp = 0, Repeater = 1, Floating = 2, PullDown = 3, }; fn setup(val: *volatile u32, mask: u32, value: u32) callconv(.Inline) void { val.* = (val.* & ~mask) | (value & mask); } fn selectFunction(port: u32, pin: u32, function: Function) callconv(.Inline) void { const offset = (pin / 16); const index = @intCast(u5, (pin % 16) << 1); const mask = (@as(u32, 3) << index); const value = @as(u32, @enumToInt(function)) << index; setup(&@ptrCast([*]volatile u32, &lpc.pincon.PINSEL0)[2 * port + offset], mask, value); // P0.0 } fn setMode(port: u32, pin: u32, mode: Mode) callconv(.Inline) void { const offset = (pin / 16); const index = @intCast(u5, pin % 16); const mask = (@as(u32, 3) << (2 * index)); const value = (@as(u32, @enumToInt(mode)) << (2 * index)); setup(&@ptrCast([*]volatile u32, &lpc.pincon.PINMODE0)[2 * port + offset], mask, value); // P0.0 } fn setOpenDrain(port: u32, pin: u32, enabled: bool) callconv(.Inline) void { const index = @intCast(u5, pin % 16); const mask = (@as(u32, 1) << index); const value = if (enabled) mask else 0; setup(&@ptrCast([*]volatile u32, &lpc.pincon.PINMODE_OD0)[port], mask, value); // P0.0 } fn configure(port: u32, pin: u32, func: Function, mode: Mode, open_drain: bool) callconv(.Inline) void { selectFunction(port, pin, func); setMode(port, pin, mode); setOpenDrain(port, pin, open_drain); } }; const Serial = struct { const port = lpc.uart2; const Error = error{}; const SyncWriter = std.io.Writer(void, Error, writeSync); fn syncWriter() SyncWriter { return SyncWriter{ .context = {} }; } const SyncReader = std.io.Reader(void, Error, readSync); fn syncReader() SyncReader { return SyncReader{ .context = {} }; } const AsyncWriter = std.io.Writer(void, Error, writeAsync); fn writer() AsyncWriter { return AsyncWriter{ .context = {} }; } const AsyncReader = std.io.Reader(void, Error, readAsync); fn reader() AsyncReader { return AsyncReader{ .context = {} }; } fn init(comptime baudrate: u32) void { lpc.sc.setPeripherialPower(.uart2, .on); lpc.sc.PCLKSEL0 &= ~@as(u32, 0xC0); lpc.sc.PCLKSEL0 |= @as(u32, 0x00); // UART0 PCLK = SysClock / 4 port.LCR = 0x83; // enable DLAB, 8N1 port.unnamed_2.FCR = 0x00; // disable any fifoing const pclk = F_CPU / 4; const regval = (pclk / (16 * baudrate)); port.unnamed_0.DLL = @truncate(u8, regval >> 0x00); port.unnamed_1.DLM = @truncate(u8, regval >> 0x08); port.LCR &= ~@as(u8, 0x80); // disable DLAB } fn tx(ch: u8) void { while ((port.LSR & (1 << 5)) == 0) {} // Wait for Previous transmission port.unnamed_0.THR = ch; // Load the data to be transmitted } fn available() bool { return (port.LSR & (1 << 0)) != 0; } fn rx() u8 { while ((port.LSR & (1 << 0)) == 0) {} // Wait till the data is received return @truncate(u8, port.unnamed_0.RBR); // Read received data } fn writeSync(context: void, data: []const u8) Error!usize { for (data) |c| { tx(c); } return data.len; } fn readSync(context: void, data: []u8) Error!usize { for (data) |*c| { c.* = rx(); } return data.len; } fn writeAsync(context: void, data: []const u8) Error!usize { for (data) |c| { EventLoop.waitForRegister(u8, &port.LSR, (1 << 5), (1 << 5)); std.debug.assert((port.LSR & (1 << 5)) != 0); port.unnamed_0.THR = c; // Load the data to be transmitted } return data.len; } fn readAsync(context: void, data: []u8) Error!usize { for (data) |*c| { EventLoop.waitForRegister(u8, &port.LSR, (1 << 0), (1 << 0)); std.debug.assert((port.LSR & (1 << 0)) != 0); c.* = @truncate(u8, port.unnamed_0.RBR); // Read received data } return data.len; } }; const SysTick = struct { var counter: u32 = 0; fn init(comptime freq: u32) void { lpc.NVIC_SetHandler(.SysTick, SysTickHandler); lpc.SysTick_Config(F_CPU / freq) catch unreachable; } fn get() u32 { return @atomicLoad(u32, &SysTick.counter, .SeqCst); } fn SysTickHandler() callconv(.C) void { _ = @atomicRmw(u32, &counter, .Add, 1, .SeqCst); } }; const EventLoop = struct { const Fairness = enum { prefer_current, prefer_others, }; const fairness: Fairness = .prefer_current; const SuspendedTask = struct { frame: anyframe, condition: WaitCondition, }; const WaitCondition = union(enum) { register8: Register(u8), register16: Register(u16), register32: Register(u32), time: u32, fn Register(comptime T: type) type { return struct { register: *volatile T, mask: T, value: T, }; } fn isMet(cond: @This()) bool { return switch (cond) { .register8 => |reg| (reg.register.* & reg.mask) == reg.value, .register16 => |reg| (reg.register.* & reg.mask) == reg.value, .register32 => |reg| (reg.register.* & reg.mask) == reg.value, .time => |time| SysTick.get() >= time, }; } }; var tasks: [64]SuspendedTask = undefined; var task_count: usize = 0; fn waitFor(condition: WaitCondition) void { // don't suspend if we already meet the condition if (fairness == .prefer_current) { if (condition.isMet()) return; } std.debug.assert(task_count < tasks.len); var offset = task_count; tasks[offset] = SuspendedTask{ .frame = @frame(), .condition = condition, }; task_count += 1; suspend; } fn waitForRegister(comptime Type: type, register: *volatile Type, mask: Type, value: Type) void { std.debug.assert((mask & value) == value); var reg = WaitCondition.Register(Type){ .register = register, .mask = mask, .value = value, }; waitFor(switch (Type) { u8 => WaitCondition{ .register8 = reg, }, u16 => WaitCondition{ .register16 = reg, }, u32 => WaitCondition{ .register32 = reg, }, else => @compileError("Type must be u8, u16 or u32!"), }); } fn waitForMillis(delta: u32) void { waitFor(WaitCondition{ .time = SysTick.get() + delta, }); } fn init() void { task_count = 0; } fn run() void { while (task_count > 0) { std.debug.assert(task_count <= tasks.len); var i: usize = 0; while (i < task_count) : (i += 1) { if (tasks[i].condition.isMet()) { var frame = tasks[i].frame; if (i < (task_count - 1)) { std.mem.swap(SuspendedTask, &tasks[i], &tasks[task_count - 1]); } task_count -= 1; LED3.set(); resume frame; LED3.clear(); break; } } } } }; const SPI = struct { const Mode = enum { @"async", sync, fast, }; const mode: Mode = .@"async"; const TFE = (1 << 0); const TNF = (1 << 1); const RNE = (1 << 2); const RFF = (1 << 3); const BSY = (1 << 4); fn init() void { lpc.sc.setPeripherialPower(.ssp0, .on); // SSP0 prescaler = 1 (CCLK) // lpc.sc.PCLKSEL1 &= ~@as(u32, 3 << 10); // lpc.sc.PCLKSEL1 |= @as(u32, 1 << 10); lpc.ssp0.CR0 = 0x0007; // kein SPI-CLK Teiler, CPHA=0, CPOL=0, SPI, 8 bit lpc.ssp0.CR1 = 0x02; // SSP0 an Bus aktiv setPrescaler(2); } fn xmit(value: u16) u16 { switch (mode) { .@"async" => EventLoop.waitForRegister(u32, &lpc.ssp0.SR, BSY, 0), .sync => while ((lpc.ssp0.SR & BSY) != 0) {}, // while not transmit fifo empty .fast => {}, } lpc.ssp0.DR = value & 0x1FF; switch (mode) { .@"async" => EventLoop.waitForRegister(u32, &lpc.ssp0.SR, BSY, 0), .sync => while ((lpc.ssp0.SR & BSY) != 0) {}, // while not transmit fifo empty .fast => {}, } return @intCast(u16, lpc.ssp0.DR); } fn write(value: u16) void { switch (mode) { .@"async" => EventLoop.waitForRegister(u32, &lpc.ssp0.SR, TNF, TNF), .@"sync" => while ((lpc.ssp0.SR & TNF) == 0) {}, // while transmit fifo is full .fast => {}, } lpc.ssp0.DR = value & 0x1FF; } fn setPrescaler(prescaler: u32) void { lpc.ssp0.CPSR = prescaler; } }; const Color = packed struct { b: u5, g: u6, r: u5, pub const red = Color{ .r = 0x1F, .g = 0x00, .b = 0x00 }; pub const green = Color{ .r = 0x00, .g = 0x3F, .b = 0x00 }; pub const blue = Color{ .r = 0x00, .g = 0x00, .b = 0x1F }; pub const yellow = Color{ .r = 0x1F, .g = 0x3F, .b = 0x00 }; pub const magenta = Color{ .r = 0x1F, .g = 0x00, .b = 0x1F }; pub const cyan = Color{ .r = 0x00, .g = 0x3F, .b = 0x1F }; pub const black = Color{ .r = 0x00, .g = 0x00, .b = 0x00 }; pub const white = Color{ .r = 0x1F, .g = 0x3F, .b = 0x1F }; }; comptime { std.debug.assert(@sizeOf(Color) == 2); } const Display = struct { const width = 320; const height = 240; const MajorIncrement = enum { column_major, row_major, }; const IncrementDirection = enum { decrement, increment, }; const GCTRL_RAMWR = 0x22; // Set or get GRAM data const GCTRL_RAMRD = 0x22; // Set or get GRAM data const GCTRL_DISP_CTRL = 0x07; const GCTRL_DEVICE_CODE = 0x00; // rd only const GCTRL_V_WIN_ADR = 0x44; // Vertical range address end,begin const GCTRL_H_WIN_ADR_STRT = 0x45; // begin const GCTRL_H_WIN_ADR_END = 0x46; // end const GCTRL_RAM_ADR_X = 0x4E; // Set GRAM address x const GCTRL_RAM_ADR_Y = 0x4F; // Set GRAM address y // GCTRL_DISP_CTRL */ const GDISP_ON = 0x0033; const GDISP_OFF = 0x0030; const GDISP_WRITE_PIXEL = 0x22; const DisplayCommand = struct { index: u8, value: u16, fn init(index: u8, value: u16) DisplayCommand { return DisplayCommand{ .index = index, .value = value, }; } }; // Array of configuration descriptors, the registers are initialized in the order given in the table const init_commands = [_]DisplayCommand{ // DLC-Parameter START DisplayCommand.init(0x28, 0x0006), // set SS and SM bit DisplayCommand.init(0x00, 0x0001), // start oscillator DisplayCommand.init(0x10, 0x0000), // sleep mode = 0 DisplayCommand.init(0x07, 0x0033), // Resize register DisplayCommand.init(0x02, 0x0600), // RGB interface setting DisplayCommand.init(0x03, 0xaaae), // Frame marker Position 0x686a DisplayCommand.init(0x01, 0x30F0), // RGB interface polarity 70ef, setup BGR // *************Power On sequence **************** DisplayCommand.init(0x0f, 0x0000), // SAP, BT[3:0], AP, DSTB, SLP, STB DisplayCommand.init(0x0b, 0x5208), // VREG1OUT voltage 0x5408 DisplayCommand.init(0x0c, 0x0004), // VDV[4:0] for VCOM amplitude DisplayCommand.init(0x2a, 0x09d5), DisplayCommand.init(0x0d, 0x000e), // SAP, BT[3:0], AP, DSTB, SLP, STB DisplayCommand.init(0x0e, 0x2700), // DC1[2:0], DC0[2:0], VC[2:0] 0X3200 DisplayCommand.init(0x1e, 0x00ad), // Internal reference voltage= Vci; ac //set window DisplayCommand.init(0x44, 0xef00), // Set VDV[4:0] for VCOM amplitude DisplayCommand.init(0x45, 0x0000), // Set VCM[5:0] for VCOMH DisplayCommand.init(0x46, 0x013f), // Set Frame Rate DisplayCommand.init(0x4e, 0x0000), DisplayCommand.init(0x4f, 0x0000), //--------------- Gamma control---------------// DisplayCommand.init(0x30, 0x0100), // GRAM horizontal Address DisplayCommand.init(0x31, 0x0000), // GRAM Vertical Address DisplayCommand.init(0x32, 0x0106), DisplayCommand.init(0x33, 0x0000), DisplayCommand.init(0x34, 0x0000), DisplayCommand.init(0x35, 0x0403), DisplayCommand.init(0x36, 0x0000), DisplayCommand.init(0x37, 0x0000), DisplayCommand.init(0x3a, 0x1100), DisplayCommand.init(0x3b, 0x0009), DisplayCommand.init(0x25, 0xf000), // DC1[2:0], DC0[2:0], VC[2:0] e000 DisplayCommand.init(0x26, 0x3800), //18 30 // DLC-Parameter ENDE // {GCTRL_DISP_CTRL, 0, GDISP_ON} /* Reg 0x0007, turn disp on, to ease debug */ DisplayCommand.init(GCTRL_DISP_CTRL, GDISP_OFF), // Reg 0x0007, turn dispoff during ram clear }; var cursor_x: u16 = 0; var cursor_y: u16 = 0; var cursor_dx: IncrementDirection = undefined; var cursor_dy: IncrementDirection = undefined; var horiz_incr: bool = false; pub fn init() void { IO_DISP_RST.setDirection(.out); IO_DISP_OE.setDirection(.out); enable(false); EventLoop.waitForMillis(100); reset(); EventLoop.waitForMillis(100); enable(true); for (init_commands) |cmd| { exec(cmd.index, cmd.value); } set_entry_mode(.row_major, .increment, .increment); on(); write_cmd(GDISP_WRITE_PIXEL); force_move(0, 0); } pub fn reset() void { IO_DISP_RST.clear(); EventLoop.waitForMillis(1); IO_DISP_RST.set(); } pub fn on() callconv(.Inline) void { exec(GCTRL_DISP_CTRL, GDISP_ON); } pub fn off() callconv(.Inline) void { exec(GCTRL_DISP_CTRL, GDISP_OFF); } pub fn enable(enabled: bool) void { IO_DISP_OE.setTo(enabled); } const ColorCmd = struct { lower: u9, upper: u9, fn writeToDisplay(self: @This()) void { SPI.write(self.upper); SPI.write(self.lower); } }; fn decodeColor(color: Color) callconv(.Inline) ColorCmd { const bits = @bitCast(u16, color); return ColorCmd{ .upper = 0x100 | @as(u9, @truncate(u8, bits >> 8)), .lower = 0x100 | @as(u9, @truncate(u8, bits)), }; } pub fn fill(color: Color) void { const cmd = decodeColor(color); write_cmd(GDISP_WRITE_PIXEL); var i: usize = 0; while (i < width * height) : (i += 1) { cmd.writeToDisplay(); } } pub fn set(x: u16, y: u16, color: Color) void { if (move(x, y)) write_cmd(GDISP_WRITE_PIXEL); decodeColor(color).writeToDisplay(); } /// Moves the draw cursor to (x,y). /// This function lazily moves the cursor and only updates /// Returns `true` when the display received pub fn move(x: u16, y: u16) bool { force_move(x, y); return true; // // rotate 180° // // x = Display::width - x - 1; // // y = Display::height - y - 1; // if((x != cursor_x) or (y != cursor_y)) // { // force_move(x, y); // if(horiz_incr) // { // cursor_x = switch(cursor_dx) { // .decrement => if(cursor_x == 0) width - 1 else cursor_x - 1, // .increment => if(cursor_x == width - 1) 0 else cursor_x + 1, // else => unreachable, // } // if(cursor_x < 0 || cursor_x >= width) // cursor_y += cursor_dy; // } // else // { // cursor_y += cursor_dy; // if(cursor_x < 0 || cursor_x >= width) // cursor_x += cursor_dx; // } // cursor_x = (cursor_x + width) % width; // cursor_y = (cursor_y + height) % height; // return true; // } // else // { // return false; // } } pub fn set_entry_mode(major_increment: MajorIncrement, horizontal_dir: IncrementDirection, vertical_dir: IncrementDirection) void { // set entry mode, use vertical writing when COLUMN_MAJOR var cmd = DisplayCommand{ .index = 0x11, .value = 0x6200, }; if (major_increment == .column_major) cmd.value |= (1 << 3); // vertical first, horizontal second if (horizontal_dir == .increment) cmd.value |= (1 << 4); // inc x if (vertical_dir == .increment) cmd.value |= (1 << 5); exec(cmd.index, cmd.value); cursor_dx = horizontal_dir; cursor_dy = vertical_dir; horiz_incr = major_increment == .column_major; } /// Moves the display cursor. This will not use auto-increment buffering, /// but will always issue a command to the display. pub fn force_move(x: u16, y: u16) void { exec(GCTRL_RAM_ADR_X, x); exec(GCTRL_RAM_ADR_Y, y); cursor_x = x; cursor_y = y; } /// Low level display API: /// Writes a "write pixel data" command, but without pixel data. pub fn begin_put() void { write_cmd(GDISP_WRITE_PIXEL); } /// Low level display API: /// Writes raw pixel data to the display. Make sure the display /// is in "write pixel data" mode! pub fn put(color: Color) void { decodeColor(color).writeToDisplay(); } fn write_cmd(value: u8) callconv(.Inline) void { SPI.write(value); } fn write_data(value: u8) callconv(.Inline) void { SPI.write(0x100 | @as(u16, value)); } fn exec(cmd: u8, value: u16) callconv(.Inline) void { write_cmd(cmd); write_data(@truncate(u8, value >> 8)); write_data(@truncate(u8, value & 0xFF)); } };
research-chamber/src/main.zig
const std = @import("std"); const bitjuggle = @import("bitjuggle"); const Csr = @import("csr.zig").Csr; const Mstatus = @import("csr.zig").Mstatus; const MCause = @import("csr.zig").MCause; const Mtvec = @import("csr.zig").Mtvec; const Stvec = @import("csr.zig").Stvec; const SCause = @import("csr.zig").SCause; const Satp = @import("csr.zig").Satp; const InstructionType = @import("instruction.zig").InstructionType; const Instruction = @import("instruction.zig").Instruction; const PrivilegeLevel = @import("types.zig").PrivilegeLevel; const IntegerRegister = @import("types.zig").IntegerRegister; const ExceptionCode = @import("types.zig").ExceptionCode; const ContextStatus = @import("types.zig").ContextStatus; const VectorMode = @import("types.zig").VectorMode; const AddressTranslationMode = @import("types.zig").AddressTranslationMode; const CpuState = @import("CpuState.zig"); pub const CpuOptions = struct { writer_type: type = void, unrecognised_instruction_is_fatal: bool = true, unrecognised_csr_is_fatal: bool = true, ebreak_is_fatal: bool = false, execution_out_of_bounds_is_fatal: bool = true, /// this option is only taken into account if a writer is given always_print_pc: bool = true, }; pub fn Cpu(comptime options: CpuOptions) type { return struct { pub usingnamespace if (isWriter(options.writer_type)) struct { pub fn run(state: *CpuState, writer: options.writer_type) !void { while (true) { try step(state, writer); } } pub fn step(state: *CpuState, writer: options.writer_type) !void { // This is not 100% compatible with extension C, as the very last 16 bits of memory could be a compressed instruction const instruction: Instruction = blk: { if (options.execution_out_of_bounds_is_fatal) { break :blk Instruction{ .backing = try loadMemory(state, 32, state.pc) }; } else { const backing = loadMemory(state, 32, state.pc) catch |err| switch (err) { error.ExecutionOutOfBounds => { try throw(state, .InstructionAccessFault, 0, writer); return; }, else => |e| return e, }; break :blk Instruction{ .backing = backing }; } }; if (options.always_print_pc) { try writer.print("pc: {x:0>16}\n", .{state.pc}); } try execute(instruction, state, writer, options); } } else struct { pub fn run(state: *CpuState) !void { while (true) { try step(state); } } pub fn step(state: *CpuState) !void { const instruction: Instruction = blk: { if (options.execution_out_of_bounds_is_fatal) { break :blk Instruction{ .backing = try loadMemory(state, 32, state.pc) }; } else { const backing = loadMemory(state, 32, state.pc) catch |err| switch (err) { error.ExecutionOutOfBounds => { try throw(state, .InstructionAccessFault, 0, {}); return; }, else => |e| return e, }; break :blk Instruction{ .backing = backing }; } }; try execute(instruction, state, {}, options); } }; }; } const LoadError = error{ ExecutionOutOfBounds, Unimplemented, }; fn loadMemory(state: *CpuState, comptime number_of_bits: comptime_int, address: u64) LoadError!std.meta.Int(.unsigned, number_of_bits) { const MemoryType = std.meta.Int(.unsigned, number_of_bits); if (address + @sizeOf(MemoryType) >= state.memory.len) { return LoadError.ExecutionOutOfBounds; } switch (state.address_translation_mode) { .Bare => { return std.mem.readIntSlice(MemoryType, state.memory[address..], .Little); }, else => { std.log.emerg("Unimplemented address translation mode", .{}); return LoadError.Unimplemented; }, } } const StoreError = error{ ExecutionOutOfBounds, Unimplemented, }; fn storeMemory( state: *CpuState, comptime number_of_bits: comptime_int, address: u64, value: std.meta.Int(.unsigned, number_of_bits), ) StoreError!void { const MemoryType = std.meta.Int(.unsigned, number_of_bits); const number_of_bytes = @divExact(@typeInfo(MemoryType).Int.bits, 8); if (address + @sizeOf(MemoryType) >= state.memory.len) { return StoreError.ExecutionOutOfBounds; } switch (state.address_translation_mode) { .Bare => { var result: [number_of_bytes]u8 = undefined; std.mem.writeInt(MemoryType, &result, value, .Little); std.mem.copy(u8, state.memory[address..], &result); }, else => { std.log.emerg("Unimplemented address translation mode", .{}); return StoreError.Unimplemented; }, } } fn execute( instruction: Instruction, state: *CpuState, writer: anytype, comptime options: CpuOptions, ) !void { const has_writer = comptime isWriter(@TypeOf(writer)); const instruction_type = if (comptime options.unrecognised_instruction_is_fatal) try instruction.decode(options.unrecognised_instruction_is_fatal) else blk: { break :blk instruction.decode(options.unrecognised_instruction_is_fatal) catch { try throw(state, .IllegalInstruction, instruction.backing, writer); return; }; }; switch (instruction_type) { // 32I .LUI => { // U-type const rd = instruction.rd(); if (rd != .zero) { const imm = instruction.u_imm.read(); if (has_writer) { try writer.print( \\LUI - dest: {}, value: 0x{x} \\ setting {} to 0x{x} \\ , .{ rd, imm, rd, imm, }); } state.x[@enumToInt(rd)] = @bitCast(u64, imm); } else { if (has_writer) { const imm = instruction.u_imm.read(); try writer.print( \\LUI - dest: {}, value: 0x{x} \\ nop \\ , .{ rd, imm, }); } } state.pc += 4; }, .AUIPC => { // U-type const rd = instruction.rd(); if (rd != .zero) { const imm = instruction.u_imm.read(); if (has_writer) { try writer.print( \\AUIPC - dest: {}, offset: 0x{x} \\ setting {} to current pc (0x{x}) + 0x{x} \\ , .{ rd, imm, rd, state.pc, imm, }); } state.x[@enumToInt(rd)] = addSignedToUnsignedWrap(state.pc, imm); } else { if (has_writer) { const imm = instruction.u_imm.read(); try writer.print( \\AUIPC - dest: {}, offset: 0x{x} \\ nop \\ , .{ rd, imm, }); } } state.pc += 4; }, .JAL => { // J-type const rd = instruction.rd(); const imm = instruction.j_imm.read(); if (rd != .zero) { if (has_writer) { try writer.print( \\JAL - dest: {}, offset: 0x{x} \\ setting {} to current pc (0x{x}) + 0x4 \\ setting pc to current pc (0x{x}) + 0x{x} \\ , .{ rd, imm, rd, state.pc, state.pc, imm, }); } state.x[@enumToInt(rd)] = state.pc + 4; } else { if (has_writer) { try writer.print( \\JAL - dest: {}, offset: 0x{x} \\ setting pc to current pc (0x{x}) + 0x{x} \\ , .{ rd, imm, state.pc, imm, }); } } state.pc = addSignedToUnsignedWrap(state.pc, imm); }, .JALR => { // I-type const imm = instruction.i_imm.read(); const rs1 = instruction.rs1(); const rd = instruction.rd(); const rs1_inital = state.x[@enumToInt(rs1)]; if (rd != .zero) { if (has_writer) { try writer.print( \\JALR - dest: {}, base: {}, offset: 0x{x} \\ setting {} to current pc (0x{x}) + 0x4 \\ setting pc to {} + 0x{x} \\ , .{ rd, rs1, imm, rd, state.pc, rs1, imm, }); } state.x[@enumToInt(rd)] = state.pc + 4; } else { if (has_writer) { try writer.print( \\JALR - dest: {}, base: {}, offset: 0x{x} \\ setting pc to {} + 0x{x} \\ , .{ rd, rs1, imm, rs1, imm, }); } } state.pc = addSignedToUnsignedWrap(rs1_inital, imm) & ~@as(u64, 1); }, .BEQ => { // B-type const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (state.x[@enumToInt(rs1)] == state.x[@enumToInt(rs2)]) { const imm = instruction.b_imm.read(); if (has_writer) { try writer.print( \\BEQ - src1: {}, src2: {}, offset: 0x{x} \\ true \\ setting pc to current pc (0x{x}) + 0x{x} \\ , .{ rs1, rs2, imm, state.pc, imm, }); } state.pc = addSignedToUnsignedWrap(state.pc, imm); } else { if (has_writer) { const imm = instruction.b_imm.read(); try writer.print( \\BEQ - src1: {}, src2: {}, offset: 0x{x} \\ false \\ , .{ rs1, rs2, imm, }); } state.pc += 4; } }, .BNE => { // B-type const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (state.x[@enumToInt(rs1)] != state.x[@enumToInt(rs2)]) { const imm = instruction.b_imm.read(); if (has_writer) { try writer.print( \\BNE - src1: {}, src2: {}, offset: 0x{x} \\ true \\ setting pc to current pc (0x{x}) + 0x{x} \\ , .{ rs1, rs2, imm, state.pc, imm, }); } state.pc = addSignedToUnsignedWrap(state.pc, imm); } else { if (has_writer) { const imm = instruction.b_imm.read(); try writer.print( \\BNE - src1: {}, src2: {}, offset: 0x{x} \\ false \\ , .{ rs1, rs2, imm, }); } state.pc += 4; } }, .BLT => { // B-type const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (@bitCast(i64, state.x[@enumToInt(rs1)]) < @bitCast(i64, state.x[@enumToInt(rs2)])) { const imm = instruction.b_imm.read(); if (has_writer) { try writer.print( \\BLT - src1: {}, src2: {}, offset: 0x{x} \\ true \\ setting pc to current pc (0x{x}) + 0x{x} \\ , .{ rs1, rs2, imm, state.pc, imm, }); } state.pc = addSignedToUnsignedWrap(state.pc, imm); } else { if (has_writer) { const imm = instruction.b_imm.read(); try writer.print( \\BLT - src1: {}, src2: {}, offset: 0x{x} \\ false \\ , .{ rs1, rs2, imm, }); } state.pc += 4; } }, .BGE => { // B-type const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (@bitCast(i64, state.x[@enumToInt(rs1)]) >= @bitCast(i64, state.x[@enumToInt(rs2)])) { const imm = instruction.b_imm.read(); if (has_writer) { try writer.print( \\BGE - src1: {}, src2: {}, offset: 0x{x} \\ true \\ setting pc to current pc (0x{x}) + 0x{x} \\ , .{ rs1, rs2, imm, state.pc, imm, }); } state.pc = addSignedToUnsignedWrap(state.pc, imm); } else { if (has_writer) { const imm = instruction.b_imm.read(); try writer.print( \\BGE - src1: {}, src2: {}, offset: 0x{x} \\ false \\ , .{ rs1, rs2, imm, }); } state.pc += 4; } }, .BLTU => { // B-type const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (state.x[@enumToInt(rs1)] < state.x[@enumToInt(rs2)]) { const imm = instruction.b_imm.read(); if (has_writer) { try writer.print( \\BLTU - src1: {}, src2: {}, offset: 0x{x} \\ true \\ setting pc to current pc (0x{x}) + 0x{x} \\ , .{ rs1, rs2, imm, state.pc, imm, }); } state.pc = addSignedToUnsignedWrap(state.pc, imm); } else { if (has_writer) { const imm = instruction.b_imm.read(); try writer.print( \\BLTU - src1: {}, src2: {}, offset: 0x{x} \\ false \\ , .{ rs1, rs2, imm, }); } state.pc += 4; } }, .BGEU => { // B-type const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (state.x[@enumToInt(rs1)] >= state.x[@enumToInt(rs2)]) { const imm = instruction.b_imm.read(); if (has_writer) { try writer.print( \\BGEU - src1: {}, src2: {}, offset: 0x{x} \\ true \\ setting pc to current pc (0x{x}) + 0x{x} \\ , .{ rs1, rs2, imm, state.pc, imm, }); } state.pc = addSignedToUnsignedWrap(state.pc, imm); } else { if (has_writer) { const imm = instruction.b_imm.read(); try writer.print( \\BGEU - src1: {}, src2: {}, offset: 0x{x} \\ false \\ , .{ rs1, rs2, imm, }); } state.pc += 4; } }, .LB => { // I-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); if (has_writer) { try writer.print( \\LB - base: {}, dest: {}, imm: 0x{x} \\ load 1 byte sign extended into {} from memory {} + 0x{x} \\ , .{ rs1, rd, imm, rd, rs1, imm, }); } const address = addSignedToUnsignedWrap(state.x[@enumToInt(rs1)], imm); const memory = if (options.execution_out_of_bounds_is_fatal) try loadMemory(state, 8, address) else blk: { break :blk loadMemory(state, 8, address) catch |err| switch (err) { LoadError.ExecutionOutOfBounds => { try throw(state, .LoadAccessFault, 0, writer); return; }, else => |e| return e, }; }; state.x[@enumToInt(rd)] = signExtend8bit(memory); } else { if (has_writer) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); try writer.print( \\LB - base: {}, dest: {}, imm: 0x{x} \\ nop \\ , .{ rs1, rd, imm, }); } } state.pc += 4; }, .LH => { // I-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); if (has_writer) { try writer.print( \\LH - base: {}, dest: {}, imm: 0x{x} \\ load 2 bytes sign extended into {} from memory {} + 0x{x} \\ , .{ rs1, rd, imm, rd, rs1, imm, }); } const address = addSignedToUnsignedWrap(state.x[@enumToInt(rs1)], imm); const memory = if (options.execution_out_of_bounds_is_fatal) try loadMemory(state, 16, address) else blk: { break :blk loadMemory(state, 16, address) catch |err| switch (err) { LoadError.ExecutionOutOfBounds => { try throw(state, .LoadAccessFault, 0, writer); return; }, else => |e| return e, }; }; state.x[@enumToInt(rd)] = signExtend16bit(memory); } else { if (has_writer) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); try writer.print( \\LH - base: {}, dest: {}, imm: 0x{x} \\ nop \\ , .{ rs1, rd, imm, }); } } state.pc += 4; }, .LW => { // I-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); if (has_writer) { try writer.print( \\LW - base: {}, dest: {}, imm: 0x{x} \\ load 4 bytes sign extended into {} from memory {} + 0x{x} \\ , .{ rs1, rd, imm, rd, rs1, imm, }); } const address = addSignedToUnsignedWrap(state.x[@enumToInt(rs1)], imm); const memory = if (options.execution_out_of_bounds_is_fatal) try loadMemory(state, 32, address) else blk: { break :blk loadMemory(state, 32, address) catch |err| switch (err) { LoadError.ExecutionOutOfBounds => { try throw(state, .LoadAccessFault, 0, writer); return; }, else => |e| return e, }; }; state.x[@enumToInt(rd)] = signExtend32bit(memory); } else { if (has_writer) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); try writer.print( \\LW - base: {}, dest: {}, imm: 0x{x} \\ nop \\ , .{ rs1, rd, imm, }); } } state.pc += 4; }, .LBU => { // I-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); if (has_writer) { try writer.print( \\LBU - base: {}, dest: {}, imm: 0x{x} \\ load 1 byte into {} from memory {} + 0x{x} \\ , .{ rs1, rd, imm, rd, rs1, imm, }); } const address = addSignedToUnsignedWrap(state.x[@enumToInt(rs1)], imm); const memory = if (options.execution_out_of_bounds_is_fatal) try loadMemory(state, 8, address) else blk: { break :blk loadMemory(state, 8, address) catch |err| switch (err) { LoadError.ExecutionOutOfBounds => { try throw(state, .LoadAccessFault, 0, writer); return; }, else => |e| return e, }; }; state.x[@enumToInt(rd)] = memory; } else { if (has_writer) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); try writer.print( \\LBU - base: {}, dest: {}, imm: 0x{x} \\ nop \\ , .{ rs1, rd, imm, }); } } state.pc += 4; }, .LHU => { // I-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); if (has_writer) { try writer.print( \\LHU - base: {}, dest: {}, imm: 0x{x} \\ load 2 bytes into {} from memory {} + 0x{x} \\ , .{ rs1, rd, imm, rd, rs1, imm, }); } const address = addSignedToUnsignedWrap(state.x[@enumToInt(rs1)], imm); const memory = if (options.execution_out_of_bounds_is_fatal) try loadMemory(state, 16, address) else blk: { break :blk loadMemory(state, 16, address) catch |err| switch (err) { LoadError.ExecutionOutOfBounds => { try throw(state, .LoadAccessFault, 0, writer); return; }, else => |e| return e, }; }; state.x[@enumToInt(rd)] = memory; } else { if (has_writer) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); try writer.print( \\LHU - base: {}, dest: {}, imm: 0x{x} \\ nop \\ , .{ rs1, rd, imm, }); } } state.pc += 4; }, .SB => { // S-type const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); const imm = instruction.s_imm.read(); if (has_writer) { try writer.print( \\SB - base: {}, src: {}, imm: 0x{x} \\ store 1 byte from {} into memory {} + 0x{x} \\ , .{ rs1, rs2, imm, rs2, rs1, imm, }); } const address = addSignedToUnsignedWrap(state.x[@enumToInt(rs1)], imm); if (options.execution_out_of_bounds_is_fatal) { try storeMemory(state, 8, address, @truncate(u8, state.x[@enumToInt(rs2)])); } else { storeMemory(state, 8, address, @truncate(u8, state.x[@enumToInt(rs2)])) catch |err| switch (err) { StoreError.ExecutionOutOfBounds => { try throw(state, .@"Store/AMOAccessFault", 0, writer); return; }, else => |e| return e, }; } state.pc += 4; }, .SH => { // S-type const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); const imm = instruction.s_imm.read(); if (has_writer) { try writer.print( \\SH - base: {}, src: {}, imm: 0x{x} \\ store 2 bytes from {} into memory {} + 0x{x} \\ , .{ rs1, rs2, imm, rs2, rs1, imm, }); } const address = addSignedToUnsignedWrap(state.x[@enumToInt(rs1)], imm); if (options.execution_out_of_bounds_is_fatal) { try storeMemory(state, 16, address, @truncate(u16, state.x[@enumToInt(rs2)])); } else { storeMemory(state, 16, address, @truncate(u16, state.x[@enumToInt(rs2)])) catch |err| switch (err) { StoreError.ExecutionOutOfBounds => { try throw(state, .@"Store/AMOAccessFault", 0, writer); return; }, else => |e| return e, }; } state.pc += 4; }, .SW => { // S-type const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); const imm = instruction.s_imm.read(); if (has_writer) { try writer.print( \\SW - base: {}, src: {}, imm: 0x{x} \\ store 4 bytes from {} into memory {} + 0x{x} \\ , .{ rs1, rs2, imm, rs2, rs1, imm, }); } const address = addSignedToUnsignedWrap(state.x[@enumToInt(rs1)], imm); if (options.execution_out_of_bounds_is_fatal) { try storeMemory(state, 32, address, @truncate(u32, state.x[@enumToInt(rs2)])); } else { storeMemory(state, 32, address, @truncate(u32, state.x[@enumToInt(rs2)])) catch |err| switch (err) { StoreError.ExecutionOutOfBounds => { try throw(state, .@"Store/AMOAccessFault", 0, writer); return; }, else => |e| return e, }; } state.pc += 4; }, .SD => { // S-type const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); const imm = instruction.s_imm.read(); if (has_writer) { try writer.print( \\SD - base: {}, src: {}, imm: 0x{x} \\ store 8 bytes from {} into memory {} + 0x{x} \\ , .{ rs1, rs2, imm, rs2, rs1, imm, }); } const address = addSignedToUnsignedWrap(state.x[@enumToInt(rs1)], imm); if (options.execution_out_of_bounds_is_fatal) { try storeMemory(state, 64, address, state.x[@enumToInt(rs2)]); } else { storeMemory(state, 64, address, state.x[@enumToInt(rs2)]) catch |err| switch (err) { StoreError.ExecutionOutOfBounds => { try throw(state, .@"Store/AMOAccessFault", 0, writer); return; }, else => |e| return e, }; } state.pc += 4; }, .ADDI => { // I-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); if (has_writer) { try writer.print( \\ADDI - src: {}, dest: {}, imm: 0x{x} \\ set {} to {} + 0x{x} \\ , .{ rs1, rd, imm, rd, rs1, imm, }); } state.x[@enumToInt(rd)] = addSignedToUnsignedIgnoreOverflow(state.x[@enumToInt(rs1)], imm); } else { if (has_writer) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); try writer.print( \\ADDI - src: {}, dest: {}, imm: 0x{x} \\ nop \\ , .{ rs1, rd, imm, }); } } state.pc += 4; }, .SLTI => { // I-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); if (has_writer) { try writer.print( \\SLTI - src: {}, dest: {}, imm: 0x{x} \\ set {} to {} < 0x{x} ? 1 : 0 \\ , .{ rs1, rd, imm, rd, rs1, imm, }); } state.x[@enumToInt(rd)] = @boolToInt(@bitCast(i64, state.x[@enumToInt(rs1)]) < imm); } else { if (has_writer) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); try writer.print( \\SLTI - src: {}, dest: {}, imm: 0x{x} \\ nop \\ , .{ rs1, rd, imm, }); } } state.pc += 4; }, .SLTIU => { // I-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); if (has_writer) { try writer.print( \\SLTIU - src: {}, dest: {}, imm: 0x{x} \\ set {} to {} < 0x{x} ? 1 : 0 \\ , .{ rs1, rd, imm, rd, rs1, imm, }); } state.x[@enumToInt(rd)] = @boolToInt(state.x[@enumToInt(rs1)] < @bitCast(u64, imm)); } else { if (has_writer) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); try writer.print( \\SLTIU - src: {}, dest: {}, imm: 0x{x} \\ nop \\ , .{ rs1, rd, imm, }); } } state.pc += 4; }, .XORI => { // I-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); if (has_writer) { try writer.print( \\XORI - src: {}, dest: {}, imm: 0x{x} \\ set {} to {} ^ 0x{x} \\ , .{ rs1, rd, imm, rd, rs1, imm, }); } state.x[@enumToInt(rd)] = state.x[@enumToInt(rs1)] ^ @bitCast(u64, imm); } else { if (has_writer) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); try writer.print( \\XORI - src: {}, dest: {}, imm: 0x{x} \\ nop \\ , .{ rs1, rd, imm, }); } } state.pc += 4; }, .ORI => { // I-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); if (has_writer) { try writer.print( \\ORI - src: {}, dest: {}, imm: 0x{x} \\ set {} to {} | 0x{x} \\ , .{ rs1, rd, imm, rd, rs1, imm, }); } state.x[@enumToInt(rd)] = state.x[@enumToInt(rs1)] | @bitCast(u64, imm); } else { if (has_writer) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); try writer.print( \\ORI - src: {}, dest: {}, imm: 0x{x} \\ nop \\ , .{ rs1, rd, imm, }); } } state.pc += 4; }, .ANDI => { // I-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); if (has_writer) { try writer.print( \\ANDI - src: {}, dest: {}, imm: 0x{x} \\ set {} to {} & 0x{x} \\ , .{ rs1, rd, imm, rd, rs1, imm, }); } state.x[@enumToInt(rd)] = state.x[@enumToInt(rs1)] & @bitCast(u64, imm); } else { if (has_writer) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); try writer.print( \\ANDI - src: {}, dest: {}, imm: 0x{x} \\ nop \\ , .{ rs1, rd, imm, }); } } state.pc += 4; }, .SLLI => { // I-type specialization const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const shmt = instruction.i_specialization.fullShift(); if (has_writer) { try writer.print( \\SLLI - src: {}, dest: {}, shmt: {} \\ set {} to {} << {} \\ , .{ rs1, rd, shmt, rd, rs1, shmt, }); } state.x[@enumToInt(rd)] = state.x[@enumToInt(rs1)] << shmt; } else { if (has_writer) { const rs1 = instruction.rs1(); const shmt = instruction.i_specialization.fullShift(); try writer.print( \\SLLI - src: {}, dest: {}, shmt: {} \\ nop \\ , .{ rs1, rd, shmt, }); } } state.pc += 4; }, .SRLI => { // I-type specialization const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const shmt = instruction.i_specialization.fullShift(); if (has_writer) { try writer.print( \\SRLI - src: {}, dest: {}, shmt: {} \\ set {} to {} >> {} \\ , .{ rs1, rd, shmt, rd, rs1, shmt, }); } state.x[@enumToInt(rd)] = state.x[@enumToInt(rs1)] >> shmt; } else { if (has_writer) { const rs1 = instruction.rs1(); const shmt = instruction.i_specialization.fullShift(); try writer.print( \\SRLI - src: {}, dest: {}, shmt: {} \\ nop \\ , .{ rs1, rd, shmt, }); } } state.pc += 4; }, .SRAI => { // I-type specialization const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const shmt = instruction.i_specialization.fullShift(); if (has_writer) { try writer.print( \\SRAI - src: {}, dest: {}, shmt: {} \\ set {} to {} >> arithmetic {} \\ , .{ rs1, rd, shmt, rd, rs1, shmt, }); } state.x[@enumToInt(rd)] = @bitCast(u64, @bitCast(i64, state.x[@enumToInt(rs1)]) >> shmt); } else { if (has_writer) { const rs1 = instruction.rs1(); const shmt = instruction.i_specialization.fullShift(); try writer.print( \\SRAI - src: {}, dest: {}, shmt: {} \\ nop \\ , .{ rs1, rd, shmt, }); } } state.pc += 4; }, .ADD => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\ADD - src1: {}, src2: {}, dest: {} \\ set {} to {} + {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } _ = @addWithOverflow(u64, state.x[@enumToInt(rs1)], state.x[@enumToInt(rs2)], &state.x[@enumToInt(rd)]); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\ADD - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .SUB => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\ADD - src1: {}, src2: {}, dest: {} \\ set {} to {} - {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } _ = @subWithOverflow(u64, state.x[@enumToInt(rs1)], state.x[@enumToInt(rs2)], &state.x[@enumToInt(rd)]); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\ADD - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .SLL => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\SLL - src1: {}, src2: {}, dest: {} \\ set {} to {} << {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } state.x[@enumToInt(rd)] = state.x[@enumToInt(rs1)] << @truncate(u6, state.x[@enumToInt(rs2)]); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\SLL - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .SLT => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\SLT - src1: {}, src2: {}, dest: {} \\ set {} to {} < {} ? 1 : 0 \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } state.x[@enumToInt(rd)] = @boolToInt(@bitCast(i64, state.x[@enumToInt(rs1)]) < @bitCast(i64, state.x[@enumToInt(rs2)])); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\SLT - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .SLTU => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\SLT - src1: {}, src2: {}, dest: {} \\ set {} to {} < {} ? 1 : 0 \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } state.x[@enumToInt(rd)] = @boolToInt(state.x[@enumToInt(rs1)] < state.x[@enumToInt(rs2)]); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\SLT - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .XOR => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\XOR - src1: {}, src2: {}, dest: {} \\ set {} to {} ^ {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } state.x[@enumToInt(rd)] = state.x[@enumToInt(rs1)] ^ state.x[@enumToInt(rs2)]; } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\XOR - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .SRL => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\SRL - src1: {}, src2: {}, dest: {} \\ set {} to {} >> {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } state.x[@enumToInt(rd)] = state.x[@enumToInt(rs1)] >> @truncate(u6, state.x[@enumToInt(rs2)]); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\SRL - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .SRA => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\SRA - src1: {}, src2: {}, dest: {} \\ set {} to {} >> {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } state.x[@enumToInt(rd)] = @bitCast(u64, @bitCast(i64, state.x[@enumToInt(rs1)]) >> @truncate(u6, state.x[@enumToInt(rs2)])); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\SRA - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .AND => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\AND - src1: {}, src2: {}, dest: {} \\ set {} to {} & {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } state.x[@enumToInt(rd)] = state.x[@enumToInt(rs1)] & state.x[@enumToInt(rs2)]; } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\AND - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .OR => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\OR - src1: {}, src2: {}, dest: {} \\ set {} to {} | {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } state.x[@enumToInt(rd)] = state.x[@enumToInt(rs1)] | state.x[@enumToInt(rs2)]; } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\OR - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .FENCE => { if (has_writer) { try writer.print("FENCE\n", .{}); } state.pc += 4; }, .ECALL => { // I-type if (has_writer) { try writer.print("ECALL\n", .{}); } switch (state.privilege_level) { .User => try throw(state, .EnvironmentCallFromUMode, 0, writer), .Supervisor => try throw(state, .EnvironmentCallFromSMode, 0, writer), .Machine => try throw(state, .EnvironmentCallFromMMode, 0, writer), } }, .EBREAK => { // I-type if (has_writer) { try writer.print("EBREAK\n", .{}); } if (options.ebreak_is_fatal) return error.EBreak; try throw(state, .Breakpoint, 0, writer); }, // 64I .LWU => { // I-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); if (has_writer) { try writer.print( \\LWU - base: {}, dest: {}, imm: 0x{x} \\ load 4 bytes into {} from memory {} + 0x{x} \\ , .{ rs1, rd, imm, rd, rs1, imm, }); } const address = addSignedToUnsignedWrap(state.x[@enumToInt(rs1)], imm); const memory = if (options.execution_out_of_bounds_is_fatal) try loadMemory(state, 32, address) else blk: { break :blk loadMemory(state, 32, address) catch |err| switch (err) { LoadError.ExecutionOutOfBounds => { try throw(state, .LoadAccessFault, 0, writer); return; }, else => |e| return e, }; }; state.x[@enumToInt(rd)] = memory; } else { if (has_writer) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); try writer.print( \\LWU - base: {}, dest: {}, imm: 0x{x} \\ nop \\ , .{ rs1, rd, imm, }); } } state.pc += 4; }, .LD => { // I-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); if (has_writer) { try writer.print( \\LD - base: {}, dest: {}, imm: 0x{x} \\ load 8 bytes into {} from memory {} + 0x{x} \\ , .{ rs1, rd, imm, rd, rs1, imm, }); } const address = addSignedToUnsignedWrap(state.x[@enumToInt(rs1)], imm); const memory = if (options.execution_out_of_bounds_is_fatal) try loadMemory(state, 64, address) else blk: { break :blk loadMemory(state, 64, address) catch |err| switch (err) { LoadError.ExecutionOutOfBounds => { try throw(state, .LoadAccessFault, 0, writer); return; }, else => |e| return e, }; }; state.x[@enumToInt(rd)] = memory; } else { if (has_writer) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); try writer.print( \\LD - base: {}, dest: {}, imm: 0x{x} \\ nop \\ , .{ rs1, rd, imm, }); } } state.pc += 4; }, .ADDIW => { // I-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); if (has_writer) { try writer.print( \\ADDIW - src: {}, dest: {}, imm: 0x{x} \\ 32bit set {} to {} + 0x{x} \\ , .{ rs1, rd, imm, rd, rs1, imm, }); } const addition_result_32bit = addSignedToUnsignedIgnoreOverflow(state.x[@enumToInt(rs1)], imm) & 0xFFFFFFFF; state.x[@enumToInt(rd)] = signExtend32bit(addition_result_32bit); } else { if (has_writer) { const rs1 = instruction.rs1(); const imm = instruction.i_imm.read(); try writer.print( \\ADDIW - src: {}, dest: {}, imm: 0x{x} \\ nop \\ , .{ rs1, rd, imm, }); } } state.pc += 4; }, .SLLIW => { // I-type specialization const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const shmt = instruction.i_specialization.smallShift(); if (has_writer) { try writer.print( \\SLLIW - src: {}, dest: {}, shmt: {} \\ set {} to {} << {} \\ , .{ rs1, rd, shmt, rd, rs1, shmt, }); } state.x[@enumToInt(rd)] = signExtend32bit(@truncate(u32, state.x[@enumToInt(rs1)]) << shmt); } else { if (has_writer) { const rs1 = instruction.rs1(); const shmt = instruction.i_specialization.fullShift(); try writer.print( \\SLLIW - src: {}, dest: {}, shmt: {} \\ nop \\ , .{ rs1, rd, shmt, }); } } state.pc += 4; }, .SRLIW => { // I-type specialization const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const shmt = instruction.i_specialization.smallShift(); if (has_writer) { try writer.print( \\SRLIW - src: {}, dest: {}, shmt: {} \\ 32 bit set {} to {} >> {} \\ , .{ rs1, rd, shmt, rd, rs1, shmt, }); } state.x[@enumToInt(rd)] = signExtend32bit(@truncate(u32, state.x[@enumToInt(rs1)]) >> shmt); } else { if (has_writer) { const rs1 = instruction.rs1(); const shmt = instruction.i_specialization.fullShift(); try writer.print( \\SRLIW - src: {}, dest: {}, shmt: {} \\ nop \\ , .{ rs1, rd, shmt, }); } } state.pc += 4; }, .SRAIW => { // I-type specialization const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const shmt = instruction.i_specialization.smallShift(); if (has_writer) { try writer.print( \\SRAI - src: {}, dest: {}, shmt: {} \\ set {} to {} >> arithmetic {} \\ , .{ rs1, rd, shmt, rd, rs1, shmt, }); } state.x[@enumToInt(rd)] = signExtend32bit(@bitCast(u32, @bitCast(i32, @truncate(u32, state.x[@enumToInt(rs1)])) >> shmt)); } else { if (has_writer) { const rs1 = instruction.rs1(); const shmt = instruction.i_specialization.fullShift(); try writer.print( \\SRAI - src: {}, dest: {}, shmt: {} \\ nop \\ , .{ rs1, rd, shmt, }); } } state.pc += 4; }, .ADDW => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\ADDW - src1: {}, src2: {}, dest: {} \\ 32 bit set {} to {} + {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } var result: u32 = undefined; _ = @addWithOverflow(u32, @truncate(u32, state.x[@enumToInt(rs1)]), @truncate(u32, state.x[@enumToInt(rs2)]), &result); state.x[@enumToInt(rd)] = signExtend32bit(result); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\ADDW - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .SUBW => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\SUBW - src1: {}, src2: {}, dest: {} \\ 32 bit set {} to {} - {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } var result: u32 = undefined; _ = @subWithOverflow(u32, @truncate(u32, state.x[@enumToInt(rs1)]), @truncate(u32, state.x[@enumToInt(rs2)]), &result); state.x[@enumToInt(rd)] = signExtend32bit(result); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\SUBW - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .SLLW => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\SLLW - src1: {}, src2: {}, dest: {} \\ 32 bit set {} to {} << {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } state.x[@enumToInt(rd)] = signExtend32bit(@truncate(u32, state.x[@enumToInt(rs1)]) << @truncate(u5, state.x[@enumToInt(rs2)])); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\SLLW - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .SRLW => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\SRLW - src1: {}, src2: {}, dest: {} \\ 32 bit set {} to {} >> {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } state.x[@enumToInt(rd)] = signExtend32bit(@truncate(u32, state.x[@enumToInt(rs1)]) >> @truncate(u5, state.x[@enumToInt(rs2)])); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\SRLW - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .SRAW => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\SRAW - src1: {}, src2: {}, dest: {} \\ 32 bit set {} to {} >> {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } state.x[@enumToInt(rd)] = signExtend32bit(@bitCast(u32, @bitCast(i32, @truncate(u32, state.x[@enumToInt(rs1)])) >> @truncate(u5, state.x[@enumToInt(rs2)]))); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\SRAW - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, // Zicsr .CSRRW => { // I-type const csr = if (comptime options.unrecognised_csr_is_fatal) try Csr.getCsr(instruction.csr.read()) else blk: { break :blk Csr.getCsr(instruction.csr.read()) catch { try throw(state, .IllegalInstruction, instruction.backing, writer); return; }; }; const rd = instruction.rd(); const rs1 = instruction.rs1(); if (rd != .zero) { if (has_writer) { try writer.print( \\CSRRW - csr: {s}, dest: {}, source: {} \\ read csr {s} into {} \\ set csr {s} to {} \\ , .{ @tagName(csr), rd, rs1, @tagName(csr), rd, @tagName(csr), rs1, }); } if (!csr.canWrite(state.privilege_level)) { try throw(state, .IllegalInstruction, instruction.backing, writer); return; } const initial_rs1 = state.x[@enumToInt(rs1)]; const initial_csr = readCsr(state, csr); try writeCsr(state, csr, initial_rs1); state.x[@enumToInt(rd)] = initial_csr; } else { if (has_writer) { try writer.print( \\CSRRW - csr: {s}, dest: {}, source: {} \\ set csr {s} to {} \\ , .{ @tagName(csr), rd, rs1, @tagName(csr), rs1, }); } if (!csr.canWrite(state.privilege_level)) { try throw(state, .IllegalInstruction, instruction.backing, writer); return; } try writeCsr(state, csr, state.x[@enumToInt(rs1)]); } state.pc += 4; }, .CSRRS => { // I-type const csr = if (comptime options.unrecognised_csr_is_fatal) try Csr.getCsr(instruction.csr.read()) else blk: { break :blk Csr.getCsr(instruction.csr.read()) catch { try throw(state, .IllegalInstruction, instruction.backing, writer); return; }; }; const rd = instruction.rd(); const rs1 = instruction.rs1(); if (rs1 != .zero and rd != .zero) { if (has_writer) { try writer.print( \\CSRRS - csr: {s}, dest: {}, source: {} \\ read csr {s} into {} \\ set bits in csr {s} using mask in {} \\ , .{ @tagName(csr), rd, rs1, @tagName(csr), rd, @tagName(csr), rs1, }); } if (!csr.canWrite(state.privilege_level)) { try throw(state, .IllegalInstruction, instruction.backing, writer); return; } const initial_rs1 = state.x[@enumToInt(rs1)]; const initial_csr_value = readCsr(state, csr); try writeCsr(state, csr, initial_csr_value | initial_rs1); state.x[@enumToInt(rd)] = initial_csr_value; } else if (rs1 != .zero) { if (has_writer) { try writer.print( \\CSRRS - csr: {s}, dest: {}, source: {} \\ set bits in csr {s} using mask in {} \\ , .{ @tagName(csr), rd, rs1, @tagName(csr), rs1, }); } if (!csr.canWrite(state.privilege_level)) { try throw(state, .IllegalInstruction, instruction.backing, writer); return; } try writeCsr(state, csr, readCsr(state, csr) | state.x[@enumToInt(rs1)]); } else if (rd != .zero) { if (has_writer) { try writer.print( \\CSRRS - csr: {s}, dest: {}, source: {} \\ read csr {s} into {} \\ , .{ @tagName(csr), rd, rs1, @tagName(csr), rd, }); } if (!csr.canRead(state.privilege_level)) { try throw(state, .IllegalInstruction, instruction.backing, writer); return; } state.x[@enumToInt(rd)] = readCsr(state, csr); } else { if (has_writer) { try writer.print( \\CSRRS - csr: {s}, dest: {}, source: {} \\ nop \\ , .{ @tagName(csr), rd, rs1, }); } } state.pc += 4; }, .CSRRC => { // I-type const csr = if (comptime options.unrecognised_csr_is_fatal) try Csr.getCsr(instruction.csr.read()) else blk: { break :blk Csr.getCsr(instruction.csr.read()) catch { try throw(state, .IllegalInstruction, instruction.backing, writer); return; }; }; const rd = instruction.rd(); const rs1 = instruction.rs1(); if (rs1 != .zero and rd != .zero) { if (has_writer) { try writer.print( \\CSRRC - csr: {s}, dest: {}, source: {} \\ read csr {s} into {} \\ clear bits in csr {s} using mask in {} \\ , .{ @tagName(csr), rd, rs1, @tagName(csr), rd, @tagName(csr), rs1, }); } if (!csr.canWrite(state.privilege_level)) { try throw(state, .IllegalInstruction, instruction.backing, writer); return; } const initial_rs1 = state.x[@enumToInt(rs1)]; const initial_csr_value = readCsr(state, csr); try writeCsr(state, csr, initial_csr_value & ~initial_rs1); state.x[@enumToInt(rd)] = initial_csr_value; } else if (rs1 != .zero) { if (has_writer) { try writer.print( \\CSRRC - csr: {s}, dest: {}, source: {} \\ clear bits in csr {s} using mask in {} \\ , .{ @tagName(csr), rd, rs1, @tagName(csr), rs1, }); } if (!csr.canWrite(state.privilege_level)) { try throw(state, .IllegalInstruction, instruction.backing, writer); return; } try writeCsr(state, csr, readCsr(state, csr) & ~state.x[@enumToInt(rs1)]); } else if (rd != .zero) { if (has_writer) { try writer.print( \\CSRRC - csr: {s}, dest: {}, source: {} \\ read csr {s} into {} \\ , .{ @tagName(csr), rd, rs1, @tagName(csr), rd, }); } if (!csr.canRead(state.privilege_level)) { try throw(state, .IllegalInstruction, instruction.backing, writer); return; } state.x[@enumToInt(rd)] = readCsr(state, csr); } else { if (has_writer) { try writer.print( \\CSRRC - csr: {s}, dest: {}, source: {} \\ nop \\ , .{ @tagName(csr), rd, rs1, }); } } state.pc += 4; }, .CSRRWI => { // I-type const csr = if (comptime options.unrecognised_csr_is_fatal) try Csr.getCsr(instruction.csr.read()) else blk: { break :blk Csr.getCsr(instruction.csr.read()) catch { try throw(state, .IllegalInstruction, instruction.backing, writer); return; }; }; const rd = instruction.rd(); const rs1 = instruction.rs1(); if (rd != .zero) { if (has_writer) { try writer.print( \\CSRRWI - csr: {s}, dest: {}, imm: 0{} \\ read csr {s} into {} \\ set csr {s} to 0{} \\ , .{ @tagName(csr), rd, rs1, @tagName(csr), rd, @tagName(csr), rs1, }); } if (!csr.canWrite(state.privilege_level)) { try throw(state, .IllegalInstruction, instruction.backing, writer); return; } const initial_csr_value = readCsr(state, csr); try writeCsr(state, csr, @enumToInt(rs1)); state.x[@enumToInt(rd)] = initial_csr_value; } else { if (has_writer) { try writer.print( \\CSRRWI - csr: {s}, dest: {}, imm: 0{} \\ set csr {s} to 0{} \\ , .{ @tagName(csr), rd, rs1, @tagName(csr), rs1, }); } if (!csr.canWrite(state.privilege_level)) { try throw(state, .IllegalInstruction, instruction.backing, writer); return; } try writeCsr(state, csr, @enumToInt(rs1)); } state.pc += 4; }, // 32M .MUL => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\MUL - src1: {}, src2: {}, dest: {} \\ set {} to {} * {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } var result: u64 = undefined; _ = @mulWithOverflow(u64, state.x[@enumToInt(rs1)], state.x[@enumToInt(rs2)], &result); state.x[@enumToInt(rd)] = result; } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\MUL - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .MULH => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\MULH - src1: {}, src2: {}, dest: {} \\ set {} to {} * {} high bits \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } const mul = signExtend64bit(state.x[@enumToInt(rs1)]) * signExtend64bit(state.x[@enumToInt(rs2)]); state.x[@enumToInt(rd)] = @truncate(u64, @bitCast(u128, mul) >> 64); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\MULH - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .MULHSU => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\MULHSU - src1: {}, src2: {}, dest: {} \\ set {} to {} * {} high bits \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } const mul = signExtend64bit(state.x[@enumToInt(rs1)]) * state.x[@enumToInt(rs2)]; state.x[@enumToInt(rd)] = @truncate(u64, @bitCast(u128, mul) >> 64); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\MULHSU - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .MULHU => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\MULHU - src1: {}, src2: {}, dest: {} \\ set {} to {} * {} high bits \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } const mul = @as(u128, state.x[@enumToInt(rs1)]) * @as(u128, state.x[@enumToInt(rs2)]); state.x[@enumToInt(rd)] = @truncate(u64, @bitCast(u128, mul) >> 64); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\MULHU - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .DIV => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\DIV - src1: {}, src2: {}, dest: {} \\ set {} to {} / {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } state.x[@enumToInt(rd)] = @bitCast( u64, std.math.divTrunc( i64, @bitCast(i64, state.x[@enumToInt(rs1)]), @bitCast(i64, state.x[@enumToInt(rs2)]), ) catch |err| switch (err) { error.DivisionByZero => @as(i64, -1), error.Overflow => @as(i64, std.math.minInt(i64)), }, ); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\DIV - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .DIVU => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\DIVU - src1: {}, src2: {}, dest: {} \\ set {} to {} / {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } state.x[@enumToInt(rd)] = std.math.divTrunc( u64, state.x[@enumToInt(rs1)], state.x[@enumToInt(rs2)], ) catch |err| switch (err) { error.DivisionByZero => @bitCast(u64, @as(i64, -1)), }; } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\DIVU - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .REM => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\REM - src1: {}, src2: {}, dest: {} \\ set {} to {} % {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } const numerator = @bitCast(i64, state.x[@enumToInt(rs1)]); const denominator = @bitCast(i64, state.x[@enumToInt(rs2)]); state.x[@enumToInt(rd)] = @bitCast( u64, remNegativeDenominator( i64, numerator, denominator, ) catch |err| switch (err) { error.DivisionByZero => numerator, error.Overflow => @as(i64, 0), }, ); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\REM - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .REMU => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\REMU - src1: {}, src2: {}, dest: {} \\ set {} to {} % {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } const numerator = state.x[@enumToInt(rs1)]; const denominator = state.x[@enumToInt(rs2)]; state.x[@enumToInt(rd)] = std.math.rem(u64, numerator, denominator) catch |err| switch (err) { error.DivisionByZero => numerator, }; } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\REMU - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, // 64M .MULW => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\MULW - src1: {}, src2: {}, dest: {} \\ 32 bit set {} to {} * {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } var result: u32 = undefined; _ = @mulWithOverflow(u32, @truncate(u32, state.x[@enumToInt(rs1)]), @truncate(u32, state.x[@enumToInt(rs2)]), &result); state.x[@enumToInt(rd)] = signExtend32bit(result); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\MULW - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .DIVW => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\DIVW - src1: {}, src2: {}, dest: {} \\ 32 bit set {} to {} / {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } state.x[@enumToInt(rd)] = signExtend32bit( @bitCast( u32, std.math.divTrunc( i32, @bitCast(i32, @truncate(u32, state.x[@enumToInt(rs1)])), @bitCast(i32, @truncate(u32, state.x[@enumToInt(rs2)])), ) catch |err| switch (err) { error.DivisionByZero => @as(i32, -1), error.Overflow => @as(i32, std.math.minInt(i32)), }, ), ); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\DIVW - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .DIVUW => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\DIVUW - src1: {}, src2: {}, dest: {} \\ 32 bit set {} to {} / {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } state.x[@enumToInt(rd)] = signExtend32bit( std.math.divTrunc( u32, @truncate(u32, state.x[@enumToInt(rs1)]), @truncate(u32, state.x[@enumToInt(rs2)]), ) catch |err| switch (err) { error.DivisionByZero => @bitCast(u32, @as(i32, -1)), }, ); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\DIVUW - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .REMW => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\REMW - src1: {}, src2: {}, dest: {} \\ 32 bit set {} to {} % {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } const numerator = @bitCast(i32, @truncate(u32, state.x[@enumToInt(rs1)])); const denominator = @bitCast(i32, @truncate(u32, state.x[@enumToInt(rs2)])); state.x[@enumToInt(rd)] = signExtend32bit( @bitCast( u32, remNegativeDenominator( i32, numerator, denominator, ) catch |err| switch (err) { error.DivisionByZero => numerator, error.Overflow => @as(i32, 0), }, ), ); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\REMW - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, .REMUW => { // R-type const rd = instruction.rd(); if (rd != .zero) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); if (has_writer) { try writer.print( \\REMUW - src1: {}, src2: {}, dest: {} \\ 32 bit set {} to {} % {} \\ , .{ rs1, rs2, rd, rd, rs1, rs2, }); } const numerator = @truncate(u32, state.x[@enumToInt(rs1)]); const denominator = @truncate(u32, state.x[@enumToInt(rs2)]); state.x[@enumToInt(rd)] = signExtend32bit( std.math.rem(u32, numerator, denominator) catch |err| switch (err) { error.DivisionByZero => numerator, }, ); } else { if (has_writer) { const rs1 = instruction.rs1(); const rs2 = instruction.rs2(); try writer.print( \\REMUW - src1: {}, src2: {}, dest: {} \\ nop \\ , .{ rs1, rs2, rd, }); } } state.pc += 4; }, // Privilege .MRET => { if (has_writer) { try writer.print("MRET\n", .{}); } if (state.privilege_level != .Machine) { try throw(state, .IllegalInstruction, instruction.backing, writer); return; } if (state.machine_previous_privilege_level != .Machine) state.modify_privilege = false; state.machine_interrupts_enabled = state.machine_interrupts_enabled_prior; state.privilege_level = state.machine_previous_privilege_level; state.machine_interrupts_enabled_prior = true; state.machine_previous_privilege_level = .User; state.pc = state.mepc; }, } } pub fn remNegativeDenominator(comptime T: type, numerator: T, denominator: T) !T { @setRuntimeSafety(false); if (denominator == 0) return error.DivisionByZero; if (@typeInfo(T) == .Int and @typeInfo(T).Int.signedness == .signed and numerator == std.math.minInt(T) and denominator == -1) return error.Overflow; if (denominator < 0) { var temp: T = undefined; if (@mulWithOverflow(T, @divTrunc(numerator, denominator), denominator, &temp)) return error.Overflow; return numerator - temp; } return @rem(numerator, denominator); } fn throw( state: *CpuState, exception: ExceptionCode, val: u64, writer: anytype, ) !void { const has_writer = comptime isWriter(@TypeOf(writer)); if (state.privilege_level != .Machine and isExceptionDelegated(state, exception)) { if (has_writer) { try writer.print("exception {s} caught in {s} jumping to {s}\n", .{ @tagName(exception), @tagName(state.privilege_level), @tagName(PrivilegeLevel.Supervisor), }); } state.scause.code.write(@enumToInt(exception)); state.scause.interrupt.write(0); state.stval = val; state.supervisor_previous_privilege_level = state.privilege_level; state.mstatus.spp.write(@truncate(u1, @enumToInt(state.privilege_level))); state.privilege_level = .Supervisor; state.supervisor_interrupts_enabled_prior = state.supervisor_interrupts_enabled; state.mstatus.spie.write(@boolToInt(state.supervisor_interrupts_enabled)); state.supervisor_interrupts_enabled = false; state.mstatus.sie.write(0); state.sepc = state.pc; state.pc = state.supervisor_vector_base_address; return; } if (has_writer) { try writer.print("Exception {s} caught in {s} jumping to {s}\n", .{ @tagName(exception), @tagName(state.privilege_level), @tagName(PrivilegeLevel.Machine), }); } state.mcause.code.write(@enumToInt(exception)); state.mcause.interrupt.write(0); state.mtval = val; state.machine_previous_privilege_level = state.privilege_level; state.mstatus.mpp.write(@enumToInt(state.privilege_level)); state.privilege_level = .Machine; state.machine_interrupts_enabled_prior = state.machine_interrupts_enabled; state.mstatus.mpie.write(@boolToInt(state.machine_interrupts_enabled)); state.machine_interrupts_enabled = false; state.mstatus.mie.write(0); state.mepc = state.pc; state.pc = state.machine_vector_base_address; } fn isExceptionDelegated(state: *const CpuState, exception: ExceptionCode) bool { return switch (exception) { .InstructionAddressMisaligned => bitjuggle.getBit(state.medeleg, 0) != 0, .InstructionAccessFault => bitjuggle.getBit(state.medeleg, 1) != 0, .IllegalInstruction => bitjuggle.getBit(state.medeleg, 2) != 0, .Breakpoint => bitjuggle.getBit(state.medeleg, 3) != 0, .LoadAddressMisaligned => bitjuggle.getBit(state.medeleg, 4) != 0, .LoadAccessFault => bitjuggle.getBit(state.medeleg, 5) != 0, .@"Store/AMOAddressMisaligned" => bitjuggle.getBit(state.medeleg, 6) != 0, .@"Store/AMOAccessFault" => bitjuggle.getBit(state.medeleg, 7) != 0, .EnvironmentCallFromUMode => bitjuggle.getBit(state.medeleg, 8) != 0, .EnvironmentCallFromSMode => bitjuggle.getBit(state.medeleg, 9) != 0, .EnvironmentCallFromMMode => bitjuggle.getBit(state.medeleg, 11) != 0, .InstructionPageFault => bitjuggle.getBit(state.medeleg, 12) != 0, .LoadPageFault => bitjuggle.getBit(state.medeleg, 13) != 0, .Store_AMOPageFault => bitjuggle.getBit(state.medeleg, 15) != 0, }; } fn readCsr(state: *const CpuState, csr: Csr) u64 { return switch (csr) { .mhartid => state.mhartid, .mtvec => state.mtvec.backing, .stvec => state.stvec.backing, .satp => state.satp.backing, .medeleg => state.medeleg, .mideleg => state.mideleg, .mie => state.mie, .mip => state.mip, .mstatus => state.mstatus.backing, .mepc => state.mepc, .mcause => state.mcause.backing, .mtval => state.mtval, .sepc => state.sepc, .scause => state.scause.backing, .stval => state.stval, .pmpcfg0, .pmpcfg2, .pmpcfg4, .pmpcfg6, .pmpcfg8, .pmpcfg10, .pmpcfg12, .pmpcfg14, .pmpaddr0, .pmpaddr1, .pmpaddr2, .pmpaddr3, .pmpaddr4, .pmpaddr5, .pmpaddr6, .pmpaddr7, .pmpaddr8, .pmpaddr9, .pmpaddr10, .pmpaddr11, .pmpaddr12, .pmpaddr13, .pmpaddr14, .pmpaddr15, .pmpaddr16, .pmpaddr17, .pmpaddr18, .pmpaddr19, .pmpaddr20, .pmpaddr21, .pmpaddr22, .pmpaddr23, .pmpaddr24, .pmpaddr25, .pmpaddr26, .pmpaddr27, .pmpaddr28, .pmpaddr29, .pmpaddr30, .pmpaddr31, .pmpaddr32, .pmpaddr33, .pmpaddr34, .pmpaddr35, .pmpaddr36, .pmpaddr37, .pmpaddr38, .pmpaddr39, .pmpaddr40, .pmpaddr41, .pmpaddr42, .pmpaddr43, .pmpaddr44, .pmpaddr45, .pmpaddr46, .pmpaddr47, .pmpaddr48, .pmpaddr49, .pmpaddr50, .pmpaddr51, .pmpaddr52, .pmpaddr53, .pmpaddr54, .pmpaddr55, .pmpaddr56, .pmpaddr57, .pmpaddr58, .pmpaddr59, .pmpaddr60, .pmpaddr61, .pmpaddr62, .pmpaddr63 => 0, }; } fn writeCsr(state: *CpuState, csr: Csr, value: u64) !void { switch (csr) { .mhartid => state.mhartid = value, .mcause => state.mcause.backing = value, .mtval => state.mtval = value, .scause => state.scause.backing = value, .stval => state.stval = value, .sepc => state.sepc = value & ~@as(u64, 0), .mstatus => { const pending_mstatus = Mstatus{ .backing = state.mstatus.backing & Mstatus.unmodifiable_mask | value & Mstatus.modifiable_mask, }; const super_previous_level = try PrivilegeLevel.getPrivilegeLevel(pending_mstatus.spp.read()); const machine_previous_level = try PrivilegeLevel.getPrivilegeLevel(pending_mstatus.mpp.read()); const floating_point_state = try ContextStatus.getContextStatus(pending_mstatus.fs.read()); const extension_state = try ContextStatus.getContextStatus(pending_mstatus.xs.read()); state.supervisor_interrupts_enabled = pending_mstatus.sie.read() != 0; state.machine_interrupts_enabled = pending_mstatus.mie.read() != 0; state.supervisor_interrupts_enabled_prior = pending_mstatus.spie.read() != 0; state.machine_interrupts_enabled_prior = pending_mstatus.mpie.read() != 0; state.supervisor_previous_privilege_level = super_previous_level; state.machine_previous_privilege_level = machine_previous_level; state.floating_point_status = floating_point_state; state.extension_status = extension_state; state.modify_privilege = pending_mstatus.mprv.read() != 0; state.supervisor_user_memory_access = pending_mstatus.sum.read() != 0; state.executable_readable = pending_mstatus.mxr.read() != 0; state.trap_virtual_memory = pending_mstatus.tvm.read() != 0; state.timeout_wait = pending_mstatus.tw.read() != 0; state.trap_sret = pending_mstatus.tsr.read() != 0; state.state_dirty = pending_mstatus.sd.read() != 0; state.mstatus = pending_mstatus; }, .mepc => state.mepc = value & ~@as(u64, 0), .mtvec => { const pending_mtvec = Mtvec{ .backing = value }; state.machine_vector_mode = try VectorMode.getVectorMode(pending_mtvec.mode.read()); state.machine_vector_base_address = pending_mtvec.base.read() << 2; state.mtvec = pending_mtvec; }, .stvec => { const pending_stvec = Stvec{ .backing = value }; state.supervisor_vector_mode = try VectorMode.getVectorMode(pending_stvec.mode.read()); state.supervisor_vector_base_address = pending_stvec.base.read() << 2; state.stvec = pending_stvec; }, .satp => { const pending_satp = Satp{ .backing = value }; const address_translation_mode = try AddressTranslationMode.getAddressTranslationMode(pending_satp.mode.read()); if (address_translation_mode != .Bare) { std.log.emerg("unsupported address_translation_mode given: {s}", .{@tagName(address_translation_mode)}); return error.UnsupportedAddressTranslationMode; } state.address_translation_mode = address_translation_mode; state.asid = pending_satp.asid.read(); state.ppn_address = pending_satp.ppn.read() * 4096; state.satp = pending_satp; }, .medeleg => state.medeleg = value, .mideleg => state.mideleg = value, .mip => state.mip = value, .mie => state.mie = value, .pmpcfg0, .pmpcfg2, .pmpcfg4, .pmpcfg6, .pmpcfg8, .pmpcfg10, .pmpcfg12, .pmpcfg14, .pmpaddr0, .pmpaddr1, .pmpaddr2, .pmpaddr3, .pmpaddr4, .pmpaddr5, .pmpaddr6, .pmpaddr7, .pmpaddr8, .pmpaddr9, .pmpaddr10, .pmpaddr11, .pmpaddr12, .pmpaddr13, .pmpaddr14, .pmpaddr15, .pmpaddr16, .pmpaddr17, .pmpaddr18, .pmpaddr19, .pmpaddr20, .pmpaddr21, .pmpaddr22, .pmpaddr23, .pmpaddr24, .pmpaddr25, .pmpaddr26, .pmpaddr27, .pmpaddr28, .pmpaddr29, .pmpaddr30, .pmpaddr31, .pmpaddr32, .pmpaddr33, .pmpaddr34, .pmpaddr35, .pmpaddr36, .pmpaddr37, .pmpaddr38, .pmpaddr39, .pmpaddr40, .pmpaddr41, .pmpaddr42, .pmpaddr43, .pmpaddr44, .pmpaddr45, .pmpaddr46, .pmpaddr47, .pmpaddr48, .pmpaddr49, .pmpaddr50, .pmpaddr51, .pmpaddr52, .pmpaddr53, .pmpaddr54, .pmpaddr55, .pmpaddr56, .pmpaddr57, .pmpaddr58, .pmpaddr59, .pmpaddr60, .pmpaddr61, .pmpaddr62, .pmpaddr63 => {}, } } inline fn isWriter(comptime T: type) bool { return std.meta.trait.hasFn("print")(T); } inline fn addSignedToUnsignedWrap(unsigned: u64, signed: i64) u64 { return if (signed < 0) unsigned -% @bitCast(u64, -signed) else unsigned +% @bitCast(u64, signed); } test "addSignedToUnsignedWrap" { try std.testing.expectEqual( @as(u64, 0), addSignedToUnsignedWrap(@as(u64, std.math.maxInt(u64)), 1), ); try std.testing.expectEqual( @as(u64, std.math.maxInt(u64)), addSignedToUnsignedWrap(0, -1), ); } inline fn addSignedToUnsignedIgnoreOverflow(unsigned: u64, signed: i64) u64 { var result = unsigned; if (signed < 0) { _ = @subWithOverflow(u64, unsigned, @bitCast(u64, -signed), &result); } else { _ = @addWithOverflow(u64, unsigned, @bitCast(u64, signed), &result); } return result; } test "addSignedToUnsignedIgnoreOverflow" { try std.testing.expectEqual( @as(u64, 42), addSignedToUnsignedIgnoreOverflow(@as(u64, std.math.maxInt(u64)), 43), ); try std.testing.expectEqual( @as(u64, std.math.maxInt(u64)), addSignedToUnsignedIgnoreOverflow(5, -6), ); } inline fn signExtend64bit(value: u64) i128 { return @bitCast(i128, @as(u128, value) << 64) >> 64; } inline fn signExtend32bit(value: u64) u64 { return @bitCast(u64, @bitCast(i64, value << 32) >> 32); } inline fn signExtend16bit(value: u64) u64 { return @bitCast(u64, @bitCast(i64, value << 48) >> 48); } inline fn signExtend8bit(value: u64) u64 { return @bitCast(u64, @bitCast(i64, value << 56) >> 56); } comptime { std.testing.refAllDecls(@This()); }
lib/cpu.zig
const std = @import("std"); const clap = @import("clap"); pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer std.debug.assert(gpa.deinit() == false); const allocator = gpa.allocator(); const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display this help and exit.") catch unreachable, clap.parseParam("-o, --output <PATH> Output file path (stdout is used if not specified).") catch unreachable, clap.parseParam("-s, --string Specifies that the input is a Zig string literal.\nOutput will be the parsed string.") catch unreachable, clap.parseParam("<INPUT> ") catch unreachable, }; const parsers = comptime .{ .PATH = clap.parsers.string, .INPUT = clap.parsers.string, }; var diag = clap.Diagnostic{}; var argres = clap.parse(clap.Help, &params, parsers, .{ .diagnostic = &diag, .allocator = allocator }) catch |err| { diag.report(std.io.getStdErr().writer(), err) catch {}; return err; }; defer argres.deinit(); if (argres.args.help) { const writer = std.io.getStdErr().writer(); try writer.writeAll("Usage: zigescape "); try clap.usage(writer, clap.Help, &params); try writer.writeAll("\n\n"); try writer.writeAll( \\<INPUT>: Either a path to a file or a Zig string literal (if using --string) \\ If <INPUT> is not specified, then stdin is used. ); try writer.writeAll("\n\n"); try writer.writeAll("Available options:\n\n"); try clap.help(writer, clap.Help, &params, .{ .markdown_lite = false, .description_on_new_line = false, .description_indent = 4, .indent = 0, .spacing_between_parameters = 1, }); return; } const outfile = outfile: { if (argres.args.output) |output_path| { break :outfile try std.fs.cwd().createFile(output_path, .{}); } else { break :outfile std.io.getStdOut(); } }; const writer = outfile.writer(); var data_allocated = false; const data = data: { if (argres.args.string and argres.positionals.len > 0) { break :data argres.positionals[0]; } const infile = infile: { if (argres.positionals.len > 0) { const path = argres.positionals[0]; break :infile try std.fs.cwd().openFile(path, .{}); } else { break :infile std.io.getStdIn(); } }; data_allocated = true; break :data try infile.readToEndAlloc(allocator, std.math.maxInt(usize)); }; defer if (data_allocated) allocator.free(data); if (argres.args.string) { var line = data; if (std.mem.indexOfAny(u8, line, "\r\n")) |line_end| { line = line[0..line_end]; } var line_allocated = false; // wrap in quotes if it's not already if (line.len < 2 or line[0] != '"' or line[line.len - 1] != '"') { var buf = try allocator.alloc(u8, line.len + 2); buf[0] = '"'; std.mem.copy(u8, buf[1..], line); buf[buf.len - 1] = '"'; line = buf; line_allocated = true; } defer if (line_allocated) allocator.free(line); const parsed = try std.zig.string_literal.parseAlloc(allocator, line); defer allocator.free(parsed); try writer.writeAll(parsed); } else { try writer.print("\"{}\"\n", .{std.zig.fmtEscapes(data)}); } }
src/main.zig
const std = @import("std"); const util = @import("util"); const input = @embedFile("4.txt"); pub fn main(n: util.Utils) !void { var num_complete: usize = 0; var num_valid: usize = 0; var batches = std.mem.split(input, "\n\n"); while (batches.next()) |batch| { const document = Document.parse(batch); if (document.isComplete()) { num_complete += 1; if (document.isValid()) num_valid += 1; } } try n.out.print("{}\n{}\n", .{ num_complete, num_valid }); } const Document = struct { byr: ?[]const u8 = null, iyr: ?[]const u8 = null, eyr: ?[]const u8 = null, hgt: ?[]const u8 = null, hcl: ?[]const u8 = null, ecl: ?[]const u8 = null, pid: ?[]const u8 = null, fn parse(str: []const u8) Document { var document = Document{}; var fields = std.mem.tokenize(str, " \n"); while (fields.next()) |field| { inline for (std.meta.fields(Document)) |info| { if (std.mem.eql(u8, field[0..3], info.name)) { @field(document, info.name) = field[4..]; } } } return document; } fn isComplete(self: Document) bool { inline for (std.meta.fields(Document)) |info| if (@field(self, info.name) == null) return false; return true; } fn isValid(self: Document) bool { @setEvalBranchQuota(3000); if (!validRange(self.byr.?, 1920, 2002)) return false; if (!validRange(self.iyr.?, 2010, 2020)) return false; if (!validRange(self.eyr.?, 2020, 2030)) return false; const hgt = self.hgt.?; if (std.mem.endsWith(u8, hgt, "cm")) { if (!validRange(hgt[0..(hgt.len - 2)], 150, 193)) return false; } else if (std.mem.endsWith(u8, hgt, "in")) { if (!validRange(hgt[0..(hgt.len - 2)], 59, 76)) return false; } else return false; if (!util.isMatch("#[0-9a-f]{6}", self.hcl.?)) return false; if (!util.isMatch("[0-9]{9}", self.pid.?)) return false; return util.isMatch("amb|blu|brn|gry|grn|hzl|oth", self.ecl.?); } fn validRange(str: []const u8, min: u32, max: u32) bool { const int = util.parseUint(u32, str) catch return false; return int >= min and int <= max; } };
2020/4.zig
const std = @import("std"); const math = std.math; const testing = std.testing; const Allocator = std.mem.Allocator; /// A list of strongly connected components. /// /// This is effectively [][]u64 for a DirectedGraph. The u64 value is the /// hash code, NOT the type T. You should use the lookup function to get the /// actual vertex. pub const StronglyConnectedComponents = struct { const Self = @This(); const Entry = std.ArrayList(u64); const List = std.ArrayList(Entry); /// The list of components. Do not access this directly. This type /// also owns all the items, so when deinit is called, all items in this /// list will also be deinit-ed. list: List, /// Iterator is used to iterate through the strongly connected components. pub const Iterator = struct { list: *const List, index: usize = 0, /// next returns the list of hash IDs for the vertex. This should be /// looked up again with the graph to get the actual vertex value. pub fn next(it: *Iterator) ?[]u64 { // If we're empty or at the end, we're done. if (it.list.items.len == 0 or it.list.items.len <= it.index) return null; // Bump the index, return our value defer it.index += 1; return it.list.items[it.index].items; } }; pub fn init(allocator: Allocator) Self { return Self{ .list = List.init(allocator), }; } pub fn deinit(self: *Self) void { for (self.list.items) |v| { v.deinit(); } self.list.deinit(); } /// Iterate over all the strongly connected components pub fn iterator(self: *const Self) Iterator { return .{ .list = &self.list }; } /// The number of distinct strongly connected components. pub fn count(self: *const Self) usize { return self.list.items.len; } }; /// Calculate the set of strongly connected components in the graph g. /// The argument g must be a DirectedGraph type. pub fn stronglyConnectedComponents( allocator: Allocator, g: anytype, ) StronglyConnectedComponents { var acc = sccAcc.init(allocator); defer acc.deinit(); var result = StronglyConnectedComponents.init(allocator); var iter = g.values.keyIterator(); while (iter.next()) |h| { if (!acc.map.contains(h.*)) { _ = stronglyConnectedStep(allocator, g, &acc, &result, h.*); } } return result; } fn stronglyConnectedStep( allocator: Allocator, g: anytype, acc: *sccAcc, result: *StronglyConnectedComponents, current: u64, ) u32 { // TODO(mitchellh): I don't like this unreachable here. const idx = acc.visit(current) catch unreachable; var minIdx = idx; var iter = g.adjOut.getPtr(current).?.keyIterator(); while (iter.next()) |targetPtr| { const target = targetPtr.*; const targetIdx = acc.map.get(target) orelse 0; if (targetIdx == 0) { minIdx = math.min( minIdx, stronglyConnectedStep(allocator, g, acc, result, target), ); } else if (acc.inStack(target)) { minIdx = math.min(minIdx, targetIdx); } } // If this is the vertex we started with then build our result. if (idx == minIdx) { var scc = std.ArrayList(u64).init(allocator); while (true) { const v = acc.pop(); scc.append(v) catch unreachable; if (v == current) { break; } } result.list.append(scc) catch unreachable; } return minIdx; } /// Internal accumulator used to calculate the strongly connected /// components. This should not be used publicly. pub const sccAcc = struct { const MapType = std.hash_map.AutoHashMap(u64, Size); const StackType = std.ArrayList(u64); next: Size, map: MapType, stack: StackType, // Size is the maximum number of vertices that could exist. Our graph // is limited to 32 bit numbers due to the underlying usage of HashMap. const Size = u32; const Self = @This(); pub fn init(allocator: Allocator) Self { return Self{ .next = 1, .map = MapType.init(allocator), .stack = StackType.init(allocator), }; } pub fn deinit(self: *Self) void { self.map.deinit(); self.stack.deinit(); self.* = undefined; } pub fn visit(self: *Self, v: u64) !Size { const idx = self.next; try self.map.put(v, idx); self.next += 1; try self.stack.append(v); return idx; } pub fn pop(self: *Self) u64 { return self.stack.pop(); } pub fn inStack(self: *Self, v: u64) bool { for (self.stack.items) |i| { if (i == v) { return true; } } return false; } }; test "sccAcc" { var acc = sccAcc.init(testing.allocator); defer acc.deinit(); // should start at nothing try testing.expect(acc.next == 1); try testing.expect(!acc.inStack(42)); // add vertex try testing.expect((try acc.visit(42)) == 1); try testing.expect(acc.next == 2); try testing.expect(acc.inStack(42)); const v = acc.pop(); try testing.expect(v == 42); } test "StronglyConnectedComponents" { var sccs = StronglyConnectedComponents.init(testing.allocator); defer sccs.deinit(); // Initially empty try testing.expect(sccs.count() == 0); // Build our entries var entries = StronglyConnectedComponents.Entry.init(testing.allocator); try entries.append(1); try entries.append(2); try entries.append(3); try sccs.list.append(entries); // Should have one try testing.expect(sccs.count() == 1); // Test iteration var iter = sccs.iterator(); var count: u8 = 0; while (iter.next()) |set| { const expect = [_]u64{ 1, 2, 3 }; try testing.expectEqual(set.len, 3); try testing.expectEqualSlices(u64, set, &expect); count += 1; } try testing.expect(count == 1); }
src/tarjan.zig
const std = @import("std"); const log = std.log; const testing = std.testing; pub const Token = struct { id: Id, loc: Loc, pub const Loc = struct { start: usize, end: usize, }; pub const keywords = std.ComptimeStringMap(Id, .{ .{ "enum", .keyword_enum }, .{ "message", .keyword_message }, .{ "repeated", .keyword_repeated }, .{ "oneof", .keyword_oneof }, .{ "syntax", .keyword_syntax }, .{ "package", .keyword_package }, .{ "import", .keyword_import }, }); pub fn getKeyword(bytes: []const u8) ?Id { return keywords.get(bytes); } pub const Id = enum { // zig fmt: off eof, invalid, l_brace, // { r_brace, // } l_sbrace, // [ r_sbrace, // ] l_paren, // ( r_paren, // ) dot, // . comma, // , semicolon, // ; equal, // = string_literal, // "something" int_literal, // 1 identifier, // ident keyword_enum, // enum { ... } keyword_message, // message { ... } keyword_repeated, // repeated Type field = 5; keyword_oneof, // oneof { ... } keyword_syntax, // syntax = "proto3"; keyword_package, // package my_pkg; keyword_import, // import "other.proto"; // zig fmt: on }; }; pub const TokenIndex = usize; pub const TokenIterator = struct { buffer: []const Token, pos: TokenIndex = 0, pub fn next(self: *TokenIterator) Token { const token = self.buffer[self.pos]; self.pos += 1; return token; } pub fn peek(self: TokenIterator) ?Token { if (self.pos >= self.buffer.len) return null; return self.buffer[self.pos]; } pub fn reset(self: *TokenIterator) void { self.pos = 0; } pub fn seekTo(self: *TokenIterator, pos: TokenIndex) void { self.pos = pos; } pub fn seekBy(self: *TokenIterator, offset: isize) void { const new_pos = @bitCast(isize, self.pos) + offset; if (new_pos < 0) { self.pos = 0; } else { self.pos = @intCast(usize, new_pos); } } }; pub const Tokenizer = struct { buffer: []const u8, index: usize = 0, pub fn next(self: *Tokenizer) Token { var result = Token{ .id = .eof, .loc = .{ .start = self.index, .end = undefined, }, }; var state: union(enum) { start, identifier, string_literal, int_literal, slash, line_comment, multiline_comment, multiline_comment_end, } = .start; while (self.index < self.buffer.len) : (self.index += 1) { const c = self.buffer[self.index]; switch (state) { .start => switch (c) { ' ', '\t', '\n', '\r' => { result.loc.start = self.index + 1; }, 'a'...'z', 'A'...'Z', '_' => { state = .identifier; result.id = .identifier; }, '{' => { result.id = .l_brace; self.index += 1; break; }, '}' => { result.id = .r_brace; self.index += 1; break; }, '[' => { result.id = .l_sbrace; self.index += 1; break; }, ']' => { result.id = .r_sbrace; self.index += 1; break; }, '(' => { result.id = .l_paren; self.index += 1; break; }, ')' => { result.id = .r_paren; self.index += 1; break; }, ';' => { result.id = .semicolon; self.index += 1; break; }, '.' => { result.id = .dot; self.index += 1; break; }, ',' => { result.id = .comma; self.index += 1; break; }, '0'...'9' => { state = .int_literal; result.id = .int_literal; }, '=' => { result.id = .equal; self.index += 1; break; }, '/' => { state = .slash; }, '"' => { result.id = .string_literal; state = .string_literal; }, else => { result.id = .invalid; result.loc.end = self.index; self.index += 1; return result; }, }, .slash => switch (c) { '/' => { state = .line_comment; }, '*' => { state = .multiline_comment; }, else => { result.id = .invalid; self.index += 1; break; }, }, .line_comment => switch (c) { '\n' => { state = .start; result.loc.start = self.index + 1; }, else => {}, }, .multiline_comment => switch (c) { '*' => { state = .multiline_comment_end; }, else => {}, }, .multiline_comment_end => switch (c) { '/' => { state = .start; result.loc.start = self.index + 1; }, else => { state = .multiline_comment; }, }, .identifier => switch (c) { 'a'...'z', 'A'...'Z', '_', '0'...'9' => {}, else => { if (Token.getKeyword(self.buffer[result.loc.start..self.index])) |id| { result.id = id; } break; }, }, .int_literal => switch (c) { '0'...'9' => {}, else => { break; }, }, .string_literal => switch (c) { '"' => { self.index += 1; break; }, else => {}, // TODO validate characters/encoding }, } } if (result.id == .eof) { result.loc.start = self.index; } result.loc.end = self.index; return result; } }; fn testExpected(source: []const u8, expected: []const Token.Id) !void { var tokenizer = Tokenizer{ .buffer = source, }; for (expected) |exp, i| { const token = tokenizer.next(); if (exp != token.id) { const stderr = std.io.getStdErr().writer(); try stderr.print("Tokens don't match: (exp) {} != (giv) {} at pos {d}\n", .{ exp, token.id, i + 1 }); return error.TestExpectedEqual; } try testing.expectEqual(exp, token.id); } } test "simple enum" { try testExpected( \\/* \\ * Some cool kind \\ */ \\enum SomeKind \\{ \\ // This generally means none \\ NONE = 0; \\ // This means A \\ // and only A \\ A = 1; \\ /* B * * * * */ \\ B = 2; \\ // And this one is just a C \\ C = 3; \\} , &[_]Token.Id{ // zig fmt: off .keyword_enum, .identifier, .l_brace, .identifier, .equal, .int_literal, .semicolon, .identifier, .equal, .int_literal, .semicolon, .identifier, .equal, .int_literal, .semicolon, .identifier, .equal, .int_literal, .semicolon, .r_brace, // zig fmt: on }); } test "simple enum - weird formatting" { try testExpected( \\enum SomeKind { NONE = 0; \\A = 1; \\ B = 2; C = 3; \\} , &[_]Token.Id{ // zig fmt: off .keyword_enum, .identifier, .l_brace, .identifier, .equal, .int_literal, .semicolon, .identifier, .equal, .int_literal, .semicolon, .identifier, .equal, .int_literal, .semicolon, .identifier, .equal, .int_literal, .semicolon, .r_brace, // zig fmt: on }); } test "simple message" { try testExpected( \\message MyMessage \\{ \\ Ptr ptr_field = 1; \\ int32 ptr_len = 2; \\} , &[_]Token.Id{ // zig fmt: off .keyword_message, .identifier, .l_brace, .identifier, .identifier, .equal, .int_literal, .semicolon, .identifier, .identifier, .equal, .int_literal, .semicolon, .r_brace, // zig fmt: on }); } test "full proto spec file" { try testExpected( \\// autogen by super_proto_gen.py \\ \\syntax = "proto3"; \\ \\package my_pkg; \\ \\import "another.proto"; \\ \\message MsgA { \\ int32 field_1 = 1; \\ repeated Msg msgs = 2 [(nanopb).type=FT_POINTER]; \\} \\ \\// Tagged union y'all! \\message Msg { \\ oneof msg { \\ MsgA msg_a = 1 [json_name="msg_a"]; \\ MsgB msg_b = 2 [ json_name = "msg_b" ]; \\ } \\} \\ \\/* \\ * Message B \\ */ \\message MsgB { \\ // Some kind \\ Kind kind = 1; \\ // If the message is valid \\ bool valid = 2; \\} \\ \\enum Kind { \\ KIND_NONE = 0; \\ KIND_A = 1; \\ KIND_B = 2; \\} , &[_]Token.Id{ // zig fmt: off .keyword_syntax, .equal, .string_literal, .semicolon, .keyword_package, .identifier, .semicolon, .keyword_import, .string_literal, .semicolon, .keyword_message, .identifier, .l_brace, .identifier, .identifier, .equal, .int_literal, .semicolon, .keyword_repeated, .identifier, .identifier, .equal, .int_literal, .l_sbrace, .l_paren, .identifier, .r_paren, .dot, .identifier, .equal, .identifier, .r_sbrace, .semicolon, .r_brace, .keyword_message, .identifier, .l_brace, .keyword_oneof, .identifier, .l_brace, .identifier, .identifier, .equal, .int_literal, .l_sbrace, .identifier, .equal, .string_literal, .r_sbrace, .semicolon, .identifier, .identifier, .equal, .int_literal, .l_sbrace, .identifier, .equal, .string_literal, .r_sbrace, .semicolon, .r_brace, .r_brace, .keyword_message, .identifier, .l_brace, .identifier, .identifier, .equal, .int_literal, .semicolon, .identifier, .identifier, .equal, .int_literal, .semicolon, .r_brace, .keyword_enum, .identifier, .l_brace, .identifier, .equal, .int_literal, .semicolon, .identifier, .equal, .int_literal, .semicolon, .identifier, .equal, .int_literal, .semicolon, .r_brace, // zig fmt: on }); }
src/tokenizer.zig
const std = @import("std"); const assert = std.debug.assert; const wren = @import("./wren.zig"); const Vm = @import("./vm.zig").Vm; const Configuration = @import("./vm.zig").Configuration; const ErrorType = @import("./vm.zig").ErrorType; const WrenError = @import("./error.zig").WrenError; const call = @import("./call.zig"); const Receiver = call.Receiver; const CallHandle = call.CallHandle; const Method = call.Method; const EmptyUserData = struct {}; const testing = std.testing; /// Handle for freestanding functions (function objects saved in variables). pub fn FunctionHandle(comptime module: []const u8, comptime function: []const u8, comptime Ret: anytype, comptime Args: anytype) type { return struct { const Self = @This(); const Function = Method(Ret, Args); method: Function, pub fn init(vm: *Vm) Self { const slot_index = 0; const fun = "call"; // Tradeoff: maximum signature length or dynamic allocation. I chose the former. var buffer: [64]u8 = undefined; assert(fun.len + 2 + 2 * Args.len - 1 < buffer.len); std.mem.copy(u8, buffer[0..], fun); // TODO: Don't eff this up. Write a patch for wren to detect '\0's in signatures. var index: u16 = fun.len; buffer[index] = '('; index += 1; // index += 1; inline for (Args) |a| { buffer[index] = '_'; buffer[index + 1] = ','; index += 2; } buffer[index - 1] = ')'; buffer[index] = 0; const receiver = Receiver.init(vm, module, function); const call_handle = CallHandle.init(vm, buffer[0..]); const method = Function.init(receiver, call_handle); return Self{ .method = method }; } pub fn deinit(self: Self) void { self.method.call_handle.deinit(); self.method.receiver.deinit(); } pub fn call(self: Self, args: anytype) !Ret { return self.method.call(args); } }; } fn printError(vm: *Vm, error_type: ErrorType, module: ?[]const u8, line: ?u32, message: []const u8) void { std.debug.print("error_type={}, module={}, line={}, message={}\n", .{ error_type, module, line, message }); } fn print(vm: *Vm, msg: []const u8) void { std.debug.print("{}", .{msg}); } test "function handle" { var config = Configuration{}; config.errorFn = printError; config.writeFn = print; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); try vm.interpret("test", \\var addTwo = Fn.new { |n| \\ return n + 2 \\} ); const signature = FunctionHandle("test", "addTwo", i32, .{i32}); const funcHandle = signature.init(&vm); defer funcHandle.deinit(); const res = try funcHandle.call(.{5}); testing.expectEqual(@as(i32, 7), res); } test "many parameters" { var config = Configuration{}; config.errorFn = printError; config.writeFn = print; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); try vm.interpret("test", \\var sum3 = Fn.new { |a, b, c| \\ return a + b + c \\} ); const signature = FunctionHandle("test", "sum3", f64, .{ i32, u32, f32 }); const funcHandle = signature.init(&vm); defer funcHandle.deinit(); const res = try funcHandle.call(.{ -3, 3, 23.5 }); testing.expectEqual(@as(f64, 23.5), res); } test "string parameters" { var config = Configuration{}; config.errorFn = printError; config.writeFn = print; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); try vm.interpret("test", \\var concat = Fn.new { |s1, s2| \\ return s1 + s2 \\} ); const signature = FunctionHandle("test", "concat", []const u8, .{ []const u8, []const u8 }); const funcHandle = signature.init(&vm); defer funcHandle.deinit(); const res = try funcHandle.call(.{ "kum", "quat" }); testing.expectEqualStrings("kumquat", res); }
src/zapata/function_handle.zig
const std = @import("std"); const CPU = @import("CPU.zig"); const PIO = @import("PIO.zig"); const CTC = @import("CTC.zig"); const Memory = @import("Memory.zig"); const Clock = @import("Clock.zig"); const Beeper = @import("Beeper.zig"); const KeyBuffer = @import("KeyBuffer.zig"); const KC85 = @This(); cpu: CPU, ctc: CTC, pio: PIO, pio_a: u8, // current PIO Port A value, used for bankswitching pio_b: u8, // current PIO Port B value, used for bankswitching io84: u8, // byte latch on port 0x84, only on KC85/4 io86: u8, // byte latch on port 0x86, only on KC85/4 blink_flag: bool, // foreground color blinking flag toggled by CTC h_count: usize, // video timing generator counter v_count: usize, clk: Clock, mem: Memory, kbd: KeyBuffer, beeper_1: Beeper, beeper_2: Beeper, exp: ExpansionSystem, pixel_buffer: []u32, audio_func: ?AudioFunc, num_samples: usize, sample_pos: usize, sample_buffer: [max_audio_samples]f32, patch_func: ?PatchFunc, ram: [max_ram_size]u8, irm: [max_irm_size]u8, rom_caos_c: [rom_c_size]u8, rom_caos_e: [rom_e_size]u8, rom_basic: [rom_basic_size]u8, exp_buf: [expansion_buffer_size]u8, pub const Model = enum { KC85_2, KC85_3, KC85_4, }; // expansion system module types pub const ModuleType = enum { NONE, M006_BASIC, // BASIC+CAOS 16K ROM module for the KC85/2 (id=0xFC) M011_64KBYTE, // 64 KB RAM expansion (id=0xF6) M012_TEXOR, // TEXOR text editing (ix=0xFB) M022_16KBYTE, // 16 KB RAM expansion (id=0xF4) M026_FORTH, // FORTH IDE (id=0xFB) M027_DEVELOPMENT, // Assembler IDE (id=0xFB) }; pub const Desc = struct { pixel_buffer: []u32, // must have room for 320x256 RGBA8 pixels audio_func: ?AudioFunc = null, audio_num_samples: usize = default_num_audio_samples, audio_sample_rate: u32 = 44100, audio_volume: f32 = 0.4, patch_func: ?PatchFunc = null, rom_caos22: ?[]const u8 = null, // CAOS 2.2 ROM image (used in KC85/2) rom_caos31: ?[]const u8 = null, // CAOS 3.1 ROM image (used in KC85/3) rom_caos42c: ?[]const u8 = null, // CAOS 4.2 at 0xC000 (KC85/4) rom_caos42e: ?[]const u8 = null, // CAOS 4.2 at 0xE000 (KC85/4) rom_kcbasic: ?[]const u8 = null, // same BASIC version for KC85/3 and KC85/4 }; // create a KC85 instance on the heap pub fn create(allocator: std.mem.Allocator, desc: KC85.Desc) !*KC85 { var self = try allocator.create(KC85); const freq_hz = switch (model) { .KC85_2, .KC85_3 => 1_750_000, .KC85_4 => 1_770_000, }; self.* = .{ .cpu = .{ // execution on powerup starts at address 0xF000 .PC = 0xF000, }, .ctc = .{}, .pio = .{ .in_func = .{ .func = pioIn, .userdata = @ptrToInt(self) }, .out_func = .{ .func = pioOut, .userdata = @ptrToInt(self) }, }, .pio_a = PIOABits.RAM | PIOABits.RAM_RO | PIOABits.IRM | PIOABits.CAOS_ROM, // initial memory map .pio_b = 0, .io84 = 0, .io86 = 0, .blink_flag = true, .h_count = 0, .v_count = 0, .mem = .{ }, .kbd = .{ .sticky_duration = 2 * 16667, }, .beeper_1 = Beeper.init(.{ .tick_hz = freq_hz, .sound_hz = desc.audio_sample_rate, .volume = desc.audio_volume }), .beeper_2 = Beeper.init(.{ .tick_hz = freq_hz, .sound_hz = desc.audio_sample_rate, .volume = desc.audio_volume }), .exp = .{ .slots = .{ .{ .addr = 0x08 }, .{ .addr = 0x0C }, } }, .clk = .{ .freq_hz = freq_hz }, .sample_pos = 0, .sample_buffer = [_]f32{0.0} ** max_audio_samples, .pixel_buffer = desc.pixel_buffer, .audio_func = desc.audio_func, .num_samples = desc.audio_num_samples, .patch_func = desc.patch_func, .ram = [_]u8{0} ** max_ram_size, .irm = [_]u8{0} ** max_irm_size, .rom_caos_c = switch(model) { .KC85_4 => desc.rom_caos42c.?[0..rom_c_size].*, else => [_]u8{0} ** rom_c_size, }, .rom_caos_e = switch(model) { .KC85_2 => desc.rom_caos22.?[0..rom_e_size].*, .KC85_3 => desc.rom_caos31.?[0..rom_e_size].*, .KC85_4 => desc.rom_caos42e.?[0..rom_e_size].*, }, .rom_basic = switch(model) { .KC85_3, .KC85_4 => desc.rom_kcbasic.?[0..rom_basic_size].*, else => [_]u8{0} ** rom_basic_size, }, .exp_buf = [_]u8{0} ** expansion_buffer_size, }; // on KC85/2 and KC85/3, memory is initially filled with random noise if (model != .KC85_4) { var r: u32 = 0x6D98302B; for (self.ram) |*ptr| { r = xorshift32(r); ptr.* = @truncate(u8, r); } for (self.irm) |*ptr| { r = xorshift32(r); ptr.* = @truncate(u8, r); } } // setup initial memory map self.updateMemoryMapping(); return self; } // destroy heap-allocated KC85 instance pub fn destroy(self: *KC85, allocator: std.mem.Allocator) void { allocator.destroy(self); } // reset KC85 instance pub fn reset(self: *KC85) void { // FIXME _ = self; unreachable; } // run emulation for given number of microseconds pub fn exec(self: *KC85, micro_secs: u32) void { const ticks_to_run = self.clk.ticksToRun(micro_secs); const ticks_executed = self.cpu.exec(ticks_to_run, CPU.TickFunc{ .func=tickFunc, .userdata=@ptrToInt(self) }); self.clk.ticksExecuted(ticks_executed); self.kbd.update(micro_secs); self.handleKeyboard(); } // send a key down pub fn keyDown(self: *KC85, key_code: u8) void { self.kbd.keyDown(key_code); } // send a key up pub fn keyUp(self: *KC85, key_code: u8) void { self.kbd.keyUp(key_code); } // insert a module into an expansion slot pub fn insertModule(self: *KC85, slot_addr: u8, mod_type: ModuleType, optional_rom_image: ?[]const u8) !void { try self.removeModule(slot_addr); if (moduleNeedsROMImage(mod_type) and (optional_rom_image == null)) { return error.ModuleTypeExpectsROMImage; } else if (!moduleNeedsROMImage(mod_type) and (optional_rom_image != null)) { return error.ModuleTypeDoesNotExpectROMImage; } if (self.slotByAddr(slot_addr)) |slot| { slot.module = switch (mod_type) { .M006_BASIC => .{ .type = mod_type, .id = 0xFC, .writable = false, .addr_mask = 0xC0, .size = 16 * 1024, }, .M011_64KBYTE => .{ .type = mod_type, .id = 0xF6, .writable = true, .addr_mask = 0xC0, .size = 64 * 1024, }, .M022_16KBYTE => .{ .type = mod_type, .id = 0xF4, .writable = true, .addr_mask = 0xC0, .size = 16 * 1024, }, .M012_TEXOR, .M026_FORTH, .M027_DEVELOPMENT => .{ .type = mod_type, .id = 0xFB, .writable = false, .addr_mask = 0xE0, .size = 8 * 1024, }, else => .{ } }; // allocate space in expansion buffer self.slotAlloc(slot) catch |err| { // not enough space left in buffer slot.module = .{ }; return err; }; // copy optional ROM image, or clear RAM if (moduleNeedsROMImage(mod_type)) { const rom = optional_rom_image.?; if (rom.len != slot.module.size) { return error.ModuleRomImageSizeMismatch; } else { for (rom) |byte,i| { self.exp_buf[slot.buf_offset + i] = byte; } } } else { for (self.exp_buf[slot.buf_offset .. slot.buf_offset+slot.module.size]) |*p| { p.* = 0; } } // also update memory mapping self.updateMemoryMapping(); } else |err| { return err; } } // remove a module from an expansion slot pub fn removeModule(self: *KC85, slot_addr: u8) !void { var slot = try self.slotByAddr(slot_addr); if (slot.module.type == .NONE) { return; } self.slotFree(slot); slot.module = .{ }; self.updateMemoryMapping(); } // load a KCC or TAP file image pub fn load(self: *KC85, data: []const u8) !void { if (checkKCTAPMagic(data)) { return self.loadKCTAP(data); } else { return self.loadKCC(data); } } const model: Model = switch (@import("build_options").kc85_model) { .KC85_2 => .KC85_2, .KC85_3 => .KC85_3, .KC85_4 => .KC85_4, }; const max_audio_samples = 1024; const default_num_audio_samples = 128; const max_tape_size = 1024; const num_expansion_slots = 2; // max number of expansion slots const expansion_buffer_size = num_expansion_slots * 64 * 1024; // expansion system buffer size (64 KB per slot) const max_ram_size = 4 * 0x4000; // up to 64 KB regular RAM const max_irm_size = 4 * 0x4000; // up to 64 KB video RAM const rom_c_size = 0x1000; const rom_e_size = 0x2000; const rom_basic_size = 0x2000; // IO bits const PIOABits = struct { const CAOS_ROM: u8 = 1<<0; const RAM: u8 = 1<<1; const IRM: u8 = 1<<2; const RAM_RO: u8 = 1<<3; const UNUSED: u8 = 1<<4; const TAPE_LED: u8 = 1<<5; const TAPE_MOTOR: u8 = 1<<6; const BASIC_ROM: u8 = 1<<7; }; const PIOBBits = struct { const VOLUME_MASK: u8 = (1<<5)-1; const RAM8: u8 = 1<<5; // KC85/4 only const RAM8_RO: u8 = 1<<6; // KC85/4 only const BLINK_ENABLED: u8 = 1<<7; }; // KC85/4 only: 8-bit latch at IO port 0x84 const IO84Bits = struct { const SEL_VIEW_IMG: u8 = 1<<0; // 0: display img0, 1: display img1 const SEL_CPU_COLOR: u8 = 1<<1; // 0: access pixel plane, 1: access color plane const SEL_CPU_IMG: u8 = 1<<2; // 0: access img0, 1: access img1 const HICOLOR: u8 = 1<<3; // 0: hicolor off, 1: hicolor on const SEL_RAM8: u8 = 1<<4; // select RAM8 block 0 or 1 const BLOCKSEL_RAM8: u8 = 1<<5; // FIXME: ??? }; // KC85/4 only: 8-bit latch at IO port 0x86 const IO86Bits = struct { const RAM4: u8 = 1<<0; const RAM4_RO: u8 = 1<<1; const CAOS_ROM_C: u8 = 1<<7; }; // expansion module attributes const Module = struct { type: ModuleType = .NONE, id: u8 = 0xFF, writable: bool = false, addr_mask: u8 = 0, size: u32 = 0, }; // an expansion system slot for inserting modules const Slot = struct { addr: u8, // slot address, 0x0C (left slot) or 0x08 (right slot) ctrl: u8 = 0, // current control byte buf_offset: u32 = 0, // byte offset in expansion system data buffer module: Module = .{}, // attributes of currently inserted module }; // expansion system state const ExpansionSystem = struct { slots: [num_expansion_slots]Slot, // KC85 main unit has 2 expansion slots builtin buf_top: u32 = 0, // top of buffer index in KC85.exp_buf }; // audio output callback, called to push samples into host audio backend const AudioFunc = struct { func: fn(samples: []const f32, userdata: usize) void, userdata: usize = 0, }; // callback to apply patches after a snapshot is loaded const PatchFunc = struct { func: fn(snapshot_name: []const u8, userdata: usize) void, userdata: usize = 0, }; // pseudo-rand helper function fn xorshift32(r: u32) u32 { var x = r; x ^= x<<13; x ^= x>>17; x ^= x<<5; return x; } // the system tick function is called from within the CPU emulation fn tickFunc(num_ticks: u64, pins_in: u64, userdata: usize) u64 { var self = @intToPtr(*KC85, userdata); var pins = pins_in; // memory and IO requests if (0 != (pins & CPU.MREQ)) { // a memory request machine cycle const addr = CPU.getAddr(pins); if (0 != (pins & CPU.RD)) { pins = CPU.setData(pins, self.mem.r8(addr)); } else if (0 != (pins & CPU.WR)) { self.mem.w8(addr, CPU.getData(pins)); } } else if (0 != (pins & CPU.IORQ)) { // IO request machine cycle // // on the KC85/3, the chips-select signals for the CTC and PIO // are generated through logic gates, on KC85/4 this is implemented // with a PROM chip (details are in the KC85/3 and KC85/4 service manuals) // // the I/O addresses are as follows: // // 0x88: PIO Port A, data // 0x89: PIO Port B, data // 0x8A: PIO Port A, control // 0x8B: PIO Port B, control // 0x8C: CTC Channel 0 // 0x8D: CTC Channel 1 // 0x8E: CTC Channel 2 // 0x8F: CTC Channel 3 // // 0x80: controls the expansion module system, the upper // 8-bits of the port number address the module slot // 0x84: (KC85/4 only) control the video memory bank switching // 0x86: (KC85/4 only) control RAM block at 0x4000 and ROM switching // check if any of the valid port number if addressed (0x80..0x8F) if (CPU.A7 == (pins & (CPU.A7|CPU.A6|CPU.A5|CPU.A4))) { // check if the PIO or CTC is addressed (0x88..0x8F) if (0 != (pins & CPU.A3)) { pins &= CPU.PinMask; // A2 selects PIO or CTC if (0 != (pins & CPU.A2)) { // a CTC IO request pins |= CTC.CE; if (0 != (pins & CPU.A0)) { pins |= CTC.CS0; } if (0 != (pins & CPU.A1)) { pins |= CTC.CS1; } pins = self.ctc.iorq(pins) & CPU.PinMask; } else { // a PIO IO request pins |= PIO.CE; if (0 != (pins & CPU.A0)) { pins |= PIO.BASEL; } if (0 != (pins & CPU.A1)) { pins |= PIO.CDSEL; } pins = self.pio.iorq(pins) & CPU.PinMask; } } else { // we're in IO port range 0x80..0x87 const data = CPU.getData(pins); switch (pins & (CPU.A2|CPU.A1|CPU.A0)) { 0x00 => { // port 0x80: expansion system control const slot_addr = @truncate(u8, CPU.getAddr(pins) >> 8); if (0 != (pins & CPU.WR)) { // write new module control byte and update memory mapping if (self.slotWriteCtrlByte(slot_addr, data)) { self.updateMemoryMapping(); } } else { // read module id in slot pins = CPU.setData(pins, self.slotModuleId(slot_addr)); } }, 0x04 => if (model == .KC85_4) { // KC85/4 specific port 0x84 if (0 != (pins & CPU.WR)) { self.io84 = data; self.updateMemoryMapping(); } }, 0x06 => if (model == .KC85_4) { // KC85/4 specific port 0x86 if (0 != (pins & CPU.WR)) { self.io86 = data; self.updateMemoryMapping(); } }, else => { } } } } } pins = self.tickVideo(num_ticks, pins); var tick: u64 = 0; while (tick < num_ticks): (tick += 1) { // tick the CTC pins = self.ctc.tick(pins); // CTC channels 0 and 1 control audio frequency if (0 != (pins & CTC.ZCTO0)) { // toggle beeper 1 self.beeper_1.toggle(); } if (0 != (pins & CTC.ZCTO1)) { self.beeper_2.toggle(); } // CTC channel 2 trigger controls video blink frequency if (0 != (pins & CTC.ZCTO2)) { self.blink_flag = !self.blink_flag; } pins &= CPU.PinMask; // tick beepers and update audio _ = self.beeper_1.tick(); if (self.beeper_2.tick()) { // new audio sample ready self.sample_buffer[self.sample_pos] = self.beeper_1.sample + self.beeper_2.sample; self.sample_pos += 1; if (self.sample_pos == self.num_samples) { // flush sample buffer to audio backend self.sample_pos = 0; if (self.audio_func) |audio_func| { audio_func.func(self.sample_buffer[0..self.num_samples], audio_func.userdata); } } } } // interrupt daisychain handling, the CTC is higher priority than the PIO if (0 != (pins & CPU.M1)) { pins |= CPU.IEIO; pins = self.ctc.int(pins); pins = self.pio.int(pins); pins &= ~CPU.RETI; } return pins & CPU.PinMask; } fn updateMemoryMapping(self: *KC85) void { self.mem.unmapBank(0); // all models have 16 KB builtin RAM at 0x0000 and 8 KB ROM at 0xE000 if (0 != (self.pio_a & PIOABits.RAM)) { // RAM may be write-protected const ram0 = self.ram[0..0x4000]; if (0 != (self.pio_a & PIOABits.RAM_RO)) { self.mem.mapRAM(0, 0x0000, ram0); } else { self.mem.mapROM(0, 0x0000, ram0); } } if (0 != (self.pio_a & PIOABits.CAOS_ROM)) { self.mem.mapROM(0, 0xE000, &self.rom_caos_e); } // KC85/3 and /4: builtin 8 KB BASIC ROM at 0xC000 if (model != .KC85_2) { if (0 != (self.pio_a & PIOABits.BASIC_ROM)) { self.mem.mapROM(0, 0xC000, &self.rom_basic); } } if (model != .KC85_4) { // KC 85/2, /3: 16 KB video ram at 0x8000 if (0 != (self.pio_a & PIOABits.IRM)) { self.mem.mapRAM(0, 0x8000, self.irm[0x0000..0x4000]); } } else { // KC85/4 has a much more complex memory map // 16 KB RAM at 0x4000, may be write-protected if (0 != (self.io86 & IO86Bits.RAM4)) { const ram4 = self.ram[0x4000..0x8000]; if (0 != (self.io86 & IO86Bits.RAM4_RO)) { self.mem.mapRAM(0, 0x4000, ram4); } else { self.mem.mapROM(0, 0x4000, ram4); } } // 16 KB RAM at 0x8000 (2 banks) if (0 != (self.pio_b & PIOBBits.RAM8)) { const ram8_start: usize = if (0 != (self.io84 & IO84Bits.SEL_RAM8)) 0xC000 else 0x8000; const ram8_end = ram8_start + 0x4000; const ram8 = self.ram[ram8_start .. ram8_end]; if (0 != (self.pio_b & PIOBBits.RAM8_RO)) { self.mem.mapRAM(0, 0x8000, ram8); } else { self.mem.mapROM(0, 0x8000, ram8); } } // KC85/4 video ram is 4 16KB banks, 2 for pixels, 2 for colors, // the area 0xA800 to 0xBFFF is always mapped to IRM0! if (0 != (self.pio_a & PIOABits.IRM)) { const irm_start = @as(usize, (self.io84 >> 1) & 3) * 0x4000; const irm_end = irm_start + 0x2800; self.mem.mapRAM(0, 0x8000, self.irm[irm_start..irm_end]); self.mem.mapRAM(0, 0xA800, self.irm[0x2800..0x4000]); } // 4 KB CAOS-C ROM at 0xC000 (on top of BASIC) if (0 != (self.io86 & IO86Bits.CAOS_ROM_C)) { self.mem.mapROM(0, 0xC000, &self.rom_caos_c); } } // expansion system memory mapping for (self.exp.slots) |*slot, slot_index| { // nothing to do if no module in slot if (slot.module.type == .NONE) { continue; } // each slot gets its own memory bank, bank 0 is used by the // computer base unit const bank_index = slot_index + 1; self.mem.unmapBank(bank_index); // module is only active if bit 0 in control byte is set if (0 != (slot.ctrl & 1)) { // compute CPU and host address const addr: u16 = @as(u16, (slot.ctrl & slot.module.addr_mask)) << 8; const host_start = slot.buf_offset; const host_end = host_start + slot.module.size; const host_slice = self.exp_buf[host_start .. host_end]; // RAM modules are only writable if bit 1 in control byte is set const writable = (0 != (slot.ctrl & 2)) and slot.module.writable; if (writable) { self.mem.mapRAM(bank_index, addr, host_slice); } else { self.mem.mapROM(bank_index, addr, host_slice); } } } } // PIO port input/output callbacks fn pioIn(port: u1, userdata: usize) u8 { _ = port; _ = userdata; return 0xFF; } fn pioOut(port: u1, data: u8, userdata: usize) void { var self = @intToPtr(*KC85, userdata); switch (port) { PIO.PA => self.pio_a = data, PIO.PB => self.pio_b = data, } self.updateMemoryMapping(); } // foreground colors const fg_pal = [16]u32 { 0xFF000000, // black 0xFFFF0000, // blue 0xFF0000FF, // red 0xFFFF00FF, // magenta 0xFF00FF00, // green 0xFFFFFF00, // cyan 0xFF00FFFF, // yellow 0xFFFFFFFF, // white 0xFF000000, // black #2 0xFFFF00A0, // violet 0xFF00A0FF, // orange 0xFFA000FF, // purple 0xFFA0FF00, // blueish green 0xFFFFA000, // greenish blue 0xFF00FFA0, // yellow-green 0xFFFFFFFF, // white #2 }; // background colors const bg_pal = [8]u32 { 0xFF000000, // black 0xFFA00000, // dark-blue 0xFF0000A0, // dark-red 0xFFA000A0, // dark-magenta 0xFF00A000, // dark-green 0xFFA0A000, // dark-cyan 0xFF00A0A0, // dark-yellow 0xFFA0A0A0, // gray }; fn decode8Pixels(dst: []u32, pixel_bits: u8, color_bits: u8, force_bg: bool) void { // select foreground- and background color: // bit 7: blinking // bits 6..3: foreground color // bits 2..0: background color // // index 0 is background color, index 1 is foreground color const bg_index = color_bits & 0x7; const fg_index = (color_bits >> 3) & 0xF; const bg = bg_pal[bg_index]; const fg = if (force_bg) bg else fg_pal[fg_index]; dst[0] = if (0 != (pixel_bits & 0x80)) fg else bg; dst[1] = if (0 != (pixel_bits & 0x40)) fg else bg; dst[2] = if (0 != (pixel_bits & 0x20)) fg else bg; dst[3] = if (0 != (pixel_bits & 0x10)) fg else bg; dst[4] = if (0 != (pixel_bits & 0x08)) fg else bg; dst[5] = if (0 != (pixel_bits & 0x04)) fg else bg; dst[6] = if (0 != (pixel_bits & 0x02)) fg else bg; dst[7] = if (0 != (pixel_bits & 0x01)) fg else bg; } fn tickVideoCounters(self: *KC85, in_pins: u64) u64 { var pins = in_pins; const h_width = if (model == .KC85_4) 113 else 112; self.h_count += 1; if (self.h_count >= h_width) { self.h_count = 0; self.v_count += 1; if (self.v_count >= 312) { self.v_count = 0; // vertical sync, trigger CTC CLKTRG2 input for video blinking effect pins |= CTC.CLKTRG2; } } return pins; } fn tickVideoKC8523(self: *KC85, num_ticks: u64, in_pins: u64) u64 { // FIXME: display needling var pins = in_pins; const blink_bg = self.blink_flag and (0 != (self.pio_b & PIOBBits.BLINK_ENABLED)); var tick: u64 = 0; while (tick < num_ticks): (tick += 1) { // every 2 ticks 8 pixels are decoded if (0 != (self.h_count & 1)) { // decode visible 8-pixel group const x = self.h_count / 2; const y = self.v_count; if ((y < 256) and (x < 40)) { const dst_index = y * 320 + x * 8; const dst = self.pixel_buffer[dst_index .. dst_index+8]; var pixel_offset: usize = undefined; var color_offset: usize = undefined; if (x < 0x20) { // left 256x256 area pixel_offset = x | (((y>>2)&0x3)<<5) | ((y&0x3)<<7) | (((y>>4)&0xF)<<9); color_offset = x | (((y>>2)&0x3f)<<5); } else { // right 64x256 area pixel_offset = 0x2000 + ((x&0x7) | (((y>>4)&0x3)<<3) | (((y>>2)&0x3)<<5) | ((y&0x3)<<7) | (((y>>6)&0x3)<<9)); color_offset = 0x0800 + ((x&0x7) | (((y>>4)&0x3)<<3) | (((y>>2)&0x3)<<5) | (((y>>6)&0x3)<<7)); } const pixel_bits = self.irm[pixel_offset]; const color_bits = self.irm[0x2800 + color_offset]; const force_bg = blink_bg and (0 != (color_bits & 0x80)); decode8Pixels(dst, pixel_bits, color_bits, force_bg); } } pins = self.tickVideoCounters(pins); } return pins; } fn tickVideoKC854Std(self: *KC85, num_ticks: u64, in_pins: u64) u64 { var pins = in_pins; const blink_bg = self.blink_flag and (0 != (self.pio_b & PIOBBits.BLINK_ENABLED)); var tick: u64 = 0; while (tick < num_ticks): (tick += 1) { if (0 != (self.h_count & 1)) { const x = self.h_count / 2; const y = self.v_count; if ((y < 256) and (x < 40)) { const dst_index = y * 320 + x * 8; const dst = self.pixel_buffer[dst_index .. dst_index+8]; const irm_bank_index: usize = (self.io84 & IO84Bits.SEL_VIEW_IMG) * 2; const irm_offset: usize = irm_bank_index * 0x4000 + x * 256 + y; const pixel_bits = self.irm[irm_offset]; const color_bits = self.irm[irm_offset + 0x4000]; const force_bg = blink_bg and (0 != (color_bits & 0x80)); decode8Pixels(dst, pixel_bits, color_bits, force_bg); } } pins = self.tickVideoCounters(pins); } return pins; } fn tickVideoKC854HiColor(self: *KC85, num_ticks: u64, pins: u64) u64 { // FIXME _ = self; _ = num_ticks; return pins; } fn tickVideoKC854(self: *KC85, num_ticks: u64, pins: u64) u64 { if (0 != (self.io84 & IO84Bits.HICOLOR)) { return self.tickVideoKC854Std(num_ticks, pins); } else { return self.tickVideoKC854HiColor(num_ticks, pins); } } fn tickVideo(self: *KC85, num_ticks: u64, pins: u64) u64 { return switch (model) { .KC85_2, .KC85_3 => self.tickVideoKC8523(num_ticks, pins), .KC85_4 => self.tickVideoKC854(num_ticks, pins), }; } // helper functions for keyboard handler to directly set and clear bits in memory fn clearBits(self: *KC85, addr: u16, mask: u8) void { self.mem.w8(addr, self.mem.r8(addr) & ~mask); } fn setBits(self: *KC85, addr: u16, mask: u8) void { self.mem.w8(addr, self.mem.r8(addr) | mask); } fn handleKeyboard(self: *KC85) void { // KEYBOARD INPUT // // this is a simplified version of the PIO-B interrupt service routine // which is normally triggered when the serial keyboard hardware // sends a new pulse (for details, see // https://github.com/floooh/yakc/blob/master/misc/kc85_3_kbdint.md ) // // we ignore the whole tricky serial decoding and patch the // keycode directly into the right memory locations // const ready_bit: u8 = (1<<0); const timeout_bit: u8 = (1<<3); const repeat_bit: u8 = (1<<4); const short_repeat_count: u8 = 8; const long_repeat_count: u8 = 60; // don't do anything if interrupts are disabled, IX might point // to the wrong base addess in this case! if (!self.cpu.iff1) { return; } // get the most recently pressed key const key_code = self.kbd.mostRecentKey(); // system base address, where CAOS stores important system variables // (like the currently pressed key) const ix = self.cpu.IX; const addr_keystatus = ix +% 0x8; const addr_keycode = ix +% 0xD; const addr_keyrepeat = ix +% 0xA; if (0 == key_code) { // if keycode is 0, this basically means the CTC3 timeout was hit self.setBits(addr_keystatus, timeout_bit); // clear current key code self.mem.w8(addr_keycode, 0); } else { // a valid keycode has been received, clear the timeout bit self.clearBits(addr_keystatus, timeout_bit); // check for key repeat if (key_code != self.mem.r8(addr_keycode)) { // no key repeat, write new keycode self.mem.w8(addr_keycode, key_code); // clear the key-repeat bit and set the key-ready bit self.clearBits(addr_keystatus, repeat_bit); self.setBits(addr_keystatus, ready_bit); // clear the repeat counter self.mem.w8(addr_keyrepeat, 0); } else { // handle key repeat // increment repeat-pause counter self.mem.w8(addr_keyrepeat, self.mem.r8(addr_keyrepeat) +% 1); if (0 != (self.mem.r8(addr_keystatus) & repeat_bit)) { // this is a followup, short key repeat if (self.mem.r8(addr_keyrepeat) < short_repeat_count) { // wait some more... return; } } else { // this is the first, long key repeat if (self.mem.r8(addr_keyrepeat) < long_repeat_count) { // wait some more... return; } else { // first key repeat pause over, set first-key-repeat flag self.setBits(addr_keystatus, repeat_bit); } } // key-repeat triggered, just set the key ready flag, and reset repeat count self.setBits(addr_keystatus, ready_bit); self.mem.w8(addr_keyrepeat, 0); } } } fn slotByAddr(self: *KC85, addr: u8) !*Slot { for (self.exp.slots) |*slot| { if (addr == slot.addr) { return slot; } } else { return error.InvalidSlotAddress; } } fn slotModuleId(self: *KC85, addr: u8) u8 { const slot = self.slotByAddr(addr) catch { return 0xFF; }; return slot.module.id; } fn slotWriteCtrlByte(self: *KC85, slot_addr: u8, ctrl_byte: u8) bool { var slot = self.slotByAddr(slot_addr) catch { return false; }; slot.ctrl = ctrl_byte; return true; } // allocate expansion buffer space for a module to be inserted // into a slot, updates exp.buf_top and slot.buf_offset fn slotAlloc(self: *KC85, slot: *Slot) !void { if ((slot.module.size + self.exp.buf_top) > expansion_buffer_size) { return error.ExpansionBufferFull; } slot.buf_offset = self.exp.buf_top; self.exp.buf_top += slot.module.size; } // free an allocation in the expansion and close the gap // updates: // exp.buf_top // exp_buf (gaps are closed) // for each slot behind the to be freed slot: // slot.buf_offset fn slotFree(self: *KC85, free_slot: *Slot) void { std.debug.assert(free_slot.module.size > 0); const bytes_to_free = free_slot.module.size; self.exp.buf_top -= bytes_to_free; for (self.exp.slots) |*slot| { // skip empty slots if (slot.module.type == .NONE) { continue; } // if slot is behind the to be freed slot: if (slot.buf_offset > free_slot.buf_offset) { // move data backward to close the hole const src_start = slot.buf_offset; const src_end = slot.buf_offset + bytes_to_free; const dst_start = slot.buf_offset - bytes_to_free; for (self.exp_buf[src_start..src_end]) |byte,i| { self.exp_buf[dst_start + i] = byte; } slot.buf_offset -= bytes_to_free; } } } fn moduleNeedsROMImage(mod_type: ModuleType) bool { return switch (mod_type) { .M011_64KBYTE, .M022_16KBYTE => false, else => true, }; } // common autostart function for all loaders fn loadStart(self: *KC85, exec_addr: u16) void { // reset register values self.cpu.setR8(CPU.A, 0); self.cpu.setR8(CPU.A, 0x10); self.cpu.setR16(CPU.BC, 0); self.cpu.setR16(CPU.DE, 0); self.cpu.setR16(CPU.HL, 0); self.cpu.ex[CPU.BC] = 0; self.cpu.ex[CPU.DE] = 0; self.cpu.ex[CPU.HL] = 0; self.cpu.ex[CPU.FA] = 0; var addr: u16 = 0xB200; while (addr < 0xB700): (addr += 1) { self.mem.w8(addr, 0); } self.mem.w8(0xB7A0, 0); if (model == .KC85_3) { _ = tickFunc(1, CPU.setAddrData(CPU.IORQ|CPU.WR, 0x0089, 0x9F), @ptrToInt(self)); self.mem.w16(self.cpu.SP, 0xF15C); } else if (model == .KC85_4) { _ = tickFunc(1, CPU.setAddrData(CPU.IORQ|CPU.WR, 0x0089, 0xFF), @ptrToInt(self)); self.mem.w16(self.cpu.SP, 0xF17E); } self.cpu.PC = exec_addr; } // FIXME: this should "packed struct", but this results in a struct size // of 135 bytes for some reason const KCCHeader = extern struct { name: [16]u8, num_addr: u8, load_addr_l: u8, load_addr_h: u8, end_addr_l: u8, end_addr_h: u8, exec_addr_l: u8, exec_addr_h: u8, pad: [105]u8, // pads to 128 byte }; const KCTAPHeader = extern struct { magic: [16]u8, // "\xC3KC-TAPE by AF. " type: u8, // 00: KCTAP_Z9001, 01: KCTAP_KC85, else KCTAP_SYS kcc: KCCHeader, }; // invoke the post-loading patch callback function fn invokePatchCallback(self: *KC85, header: *const KCCHeader) void { if (self.patch_func) |patch_func| { patch_func.func(header.name[0..], patch_func.userdata); } } fn makeU16(hi: u8, lo: u8) u16 { return (@as(u16, hi) << 8) | lo; } fn validateKCC(data: []const u8) !void { if (data.len < @sizeOf(KCCHeader)) { return error.KCCWrongHeaderSize; } const hdr = @ptrCast(*const KCCHeader, data); if (hdr.num_addr > 3) { return error.KCCNumAddrTooBig; } const load_addr = makeU16(hdr.load_addr_h, hdr.load_addr_l); const end_addr = makeU16(hdr.end_addr_h, hdr.end_addr_l); if (end_addr <= load_addr) { return error.KCCEndAddrBeforeLoadAddr; } if (hdr.num_addr > 2) { const exec_addr = makeU16(hdr.exec_addr_h, hdr.exec_addr_l); if ((exec_addr < load_addr) or (exec_addr > end_addr)) { return error.KCCExecAddrOutOfRange; } } const expected_data_size = (end_addr - load_addr) + @sizeOf(KCCHeader); if (expected_data_size > data.len) { return error.KCCNotEnoughData; } } fn loadKCC(self: *KC85, data: []const u8) !void { try validateKCC(data); const hdr = @ptrCast(*const KCCHeader, data); var addr = makeU16(hdr.load_addr_h, hdr.load_addr_l); const end_addr = makeU16(hdr.end_addr_h, hdr.end_addr_l); const payload = data[@sizeOf(KCCHeader)..]; for (payload) |byte| { if (addr < end_addr) { self.mem.w8(addr, byte); } addr +%= 1; } self.invokePatchCallback(hdr); // if file has an exec address, start the program if (hdr.num_addr > 2) { const exec_addr = makeU16(hdr.exec_addr_h, hdr.exec_addr_l); self.loadStart(exec_addr); } } // this only checks the KCTAP header fn checkKCTAPMagic(data: []const u8) bool { if (data.len <= @sizeOf(KCTAPHeader)) { return false; } const hdr = @ptrCast(*const KCTAPHeader, data); const magic = [16]u8 { 0xC3,'K','C','-','T','A','P','E',0x20,'b','y',0x20,'A','F','.',0x20 }; return std.mem.eql(u8, magic[0..], hdr.magic[0..]); } fn validateKCTAP(data: []const u8) !void { if (!checkKCTAPMagic(data)) { return error.NoKCTAPMagicNumber; } const hdr = @ptrCast(*const KCTAPHeader, data); if (hdr.kcc.num_addr > 3) { return error.KCTAPNumAddrTooBig; } const load_addr = makeU16(hdr.kcc.load_addr_h, hdr.kcc.load_addr_l); const end_addr = makeU16(hdr.kcc.end_addr_h, hdr.kcc.end_addr_l); if (end_addr <= load_addr) { return error.KCTAPEndAddrBeforeLoadAddr; } if (hdr.kcc.num_addr > 2) { const exec_addr = makeU16(hdr.kcc.exec_addr_h, hdr.kcc.exec_addr_l); if ((exec_addr < load_addr) or (exec_addr > end_addr)) { return error.KCTAPExecAddrOutOfRange; } } const expected_data_size = (end_addr - load_addr) + @sizeOf(KCTAPHeader); if (expected_data_size > data.len) { return error.KCCNotEnoughData; } } fn loadKCTAP(self: *KC85, data: []const u8) !void { try validateKCTAP(data); const hdr = @ptrCast(*const KCTAPHeader, data); var addr = makeU16(hdr.kcc.load_addr_h, hdr.kcc.load_addr_l); const end_addr = makeU16(hdr.kcc.end_addr_h, hdr.kcc.end_addr_l); const payload = data[@sizeOf(KCTAPHeader)..]; for (payload) |byte, i| { // each block is one lead byte and 128 byte data if ((i % 129) != 0) { if (addr < end_addr) { self.mem.w8(addr, byte); } addr +%= 1; } } self.invokePatchCallback(&hdr.kcc); // if file has an exec address, start the program if (hdr.kcc.num_addr > 2) { const exec_addr = makeU16(hdr.kcc.exec_addr_h, hdr.kcc.exec_addr_l); self.loadStart(exec_addr); } }
src/emu/KC85.zig
pub fn isPrepend(cp: u21) bool { if (cp < 0x600 or cp > 0x11d46) return false; return switch (cp) { 0x600...0x605 => true, 0x6dd => true, 0x70f => true, 0x890...0x891 => true, 0x8e2 => true, 0xd4e => true, 0x110bd => true, 0x110cd => true, 0x111c2...0x111c3 => true, 0x1193f => true, 0x11941 => true, 0x11a3a => true, 0x11a84...0x11a89 => true, 0x11d46 => true, else => false, }; } pub fn isCr(cp: u21) bool { return cp == 0xd; } pub fn isLf(cp: u21) bool { return cp == 0xa; } pub fn isControl(cp: u21) bool { if (cp < 0x0 or cp > 0xe0fff) return false; return switch (cp) { 0x0...0x9 => true, 0xb...0xc => true, 0xe...0x1f => true, 0x7f...0x9f => true, 0xad => true, 0x61c => true, 0x180e => true, 0x200b => true, 0x200e...0x200f => true, 0x2028 => true, 0x2029 => true, 0x202a...0x202e => true, 0x2060...0x2064 => true, 0x2065 => true, 0x2066...0x206f => true, 0xfeff => true, 0xfff0...0xfff8 => true, 0xfff9...0xfffb => true, 0x13430...0x13438 => true, 0x1bca0...0x1bca3 => true, 0x1d173...0x1d17a => true, 0xe0000 => true, 0xe0001 => true, 0xe0002...0xe001f => true, 0xe0080...0xe00ff => true, 0xe01f0...0xe0fff => true, else => false, }; } pub fn isExtend(cp: u21) bool { if (cp < 0x300 or cp > 0xe01ef) return false; return switch (cp) { 0x300...0x36f => true, 0x483...0x487 => true, 0x488...0x489 => true, 0x591...0x5bd => true, 0x5bf => true, 0x5c1...0x5c2 => true, 0x5c4...0x5c5 => true, 0x5c7 => true, 0x610...0x61a => true, 0x64b...0x65f => true, 0x670 => true, 0x6d6...0x6dc => true, 0x6df...0x6e4 => true, 0x6e7...0x6e8 => true, 0x6ea...0x6ed => true, 0x711 => true, 0x730...0x74a => true, 0x7a6...0x7b0 => true, 0x7eb...0x7f3 => true, 0x7fd => true, 0x816...0x819 => true, 0x81b...0x823 => true, 0x825...0x827 => true, 0x829...0x82d => true, 0x859...0x85b => true, 0x898...0x89f => true, 0x8ca...0x8e1 => true, 0x8e3...0x902 => true, 0x93a => true, 0x93c => true, 0x941...0x948 => true, 0x94d => true, 0x951...0x957 => true, 0x962...0x963 => true, 0x981 => true, 0x9bc => true, 0x9be => true, 0x9c1...0x9c4 => true, 0x9cd => true, 0x9d7 => true, 0x9e2...0x9e3 => true, 0x9fe => true, 0xa01...0xa02 => true, 0xa3c => true, 0xa41...0xa42 => true, 0xa47...0xa48 => true, 0xa4b...0xa4d => true, 0xa51 => true, 0xa70...0xa71 => true, 0xa75 => true, 0xa81...0xa82 => true, 0xabc => true, 0xac1...0xac5 => true, 0xac7...0xac8 => true, 0xacd => true, 0xae2...0xae3 => true, 0xafa...0xaff => true, 0xb01 => true, 0xb3c => true, 0xb3e => true, 0xb3f => true, 0xb41...0xb44 => true, 0xb4d => true, 0xb55...0xb56 => true, 0xb57 => true, 0xb62...0xb63 => true, 0xb82 => true, 0xbbe => true, 0xbc0 => true, 0xbcd => true, 0xbd7 => true, 0xc00 => true, 0xc04 => true, 0xc3c => true, 0xc3e...0xc40 => true, 0xc46...0xc48 => true, 0xc4a...0xc4d => true, 0xc55...0xc56 => true, 0xc62...0xc63 => true, 0xc81 => true, 0xcbc => true, 0xcbf => true, 0xcc2 => true, 0xcc6 => true, 0xccc...0xccd => true, 0xcd5...0xcd6 => true, 0xce2...0xce3 => true, 0xd00...0xd01 => true, 0xd3b...0xd3c => true, 0xd3e => true, 0xd41...0xd44 => true, 0xd4d => true, 0xd57 => true, 0xd62...0xd63 => true, 0xd81 => true, 0xdca => true, 0xdcf => true, 0xdd2...0xdd4 => true, 0xdd6 => true, 0xddf => true, 0xe31 => true, 0xe34...0xe3a => true, 0xe47...0xe4e => true, 0xeb1 => true, 0xeb4...0xebc => true, 0xec8...0xecd => true, 0xf18...0xf19 => true, 0xf35 => true, 0xf37 => true, 0xf39 => true, 0xf71...0xf7e => true, 0xf80...0xf84 => true, 0xf86...0xf87 => true, 0xf8d...0xf97 => true, 0xf99...0xfbc => true, 0xfc6 => true, 0x102d...0x1030 => true, 0x1032...0x1037 => true, 0x1039...0x103a => true, 0x103d...0x103e => true, 0x1058...0x1059 => true, 0x105e...0x1060 => true, 0x1071...0x1074 => true, 0x1082 => true, 0x1085...0x1086 => true, 0x108d => true, 0x109d => true, 0x135d...0x135f => true, 0x1712...0x1714 => true, 0x1732...0x1733 => true, 0x1752...0x1753 => true, 0x1772...0x1773 => true, 0x17b4...0x17b5 => true, 0x17b7...0x17bd => true, 0x17c6 => true, 0x17c9...0x17d3 => true, 0x17dd => true, 0x180b...0x180d => true, 0x180f => true, 0x1885...0x1886 => true, 0x18a9 => true, 0x1920...0x1922 => true, 0x1927...0x1928 => true, 0x1932 => true, 0x1939...0x193b => true, 0x1a17...0x1a18 => true, 0x1a1b => true, 0x1a56 => true, 0x1a58...0x1a5e => true, 0x1a60 => true, 0x1a62 => true, 0x1a65...0x1a6c => true, 0x1a73...0x1a7c => true, 0x1a7f => true, 0x1ab0...0x1abd => true, 0x1abe => true, 0x1abf...0x1ace => true, 0x1b00...0x1b03 => true, 0x1b34 => true, 0x1b35 => true, 0x1b36...0x1b3a => true, 0x1b3c => true, 0x1b42 => true, 0x1b6b...0x1b73 => true, 0x1b80...0x1b81 => true, 0x1ba2...0x1ba5 => true, 0x1ba8...0x1ba9 => true, 0x1bab...0x1bad => true, 0x1be6 => true, 0x1be8...0x1be9 => true, 0x1bed => true, 0x1bef...0x1bf1 => true, 0x1c2c...0x1c33 => true, 0x1c36...0x1c37 => true, 0x1cd0...0x1cd2 => true, 0x1cd4...0x1ce0 => true, 0x1ce2...0x1ce8 => true, 0x1ced => true, 0x1cf4 => true, 0x1cf8...0x1cf9 => true, 0x1dc0...0x1dff => true, 0x200c => true, 0x20d0...0x20dc => true, 0x20dd...0x20e0 => true, 0x20e1 => true, 0x20e2...0x20e4 => true, 0x20e5...0x20f0 => true, 0x2cef...0x2cf1 => true, 0x2d7f => true, 0x2de0...0x2dff => true, 0x302a...0x302d => true, 0x302e...0x302f => true, 0x3099...0x309a => true, 0xa66f => true, 0xa670...0xa672 => true, 0xa674...0xa67d => true, 0xa69e...0xa69f => true, 0xa6f0...0xa6f1 => true, 0xa802 => true, 0xa806 => true, 0xa80b => true, 0xa825...0xa826 => true, 0xa82c => true, 0xa8c4...0xa8c5 => true, 0xa8e0...0xa8f1 => true, 0xa8ff => true, 0xa926...0xa92d => true, 0xa947...0xa951 => true, 0xa980...0xa982 => true, 0xa9b3 => true, 0xa9b6...0xa9b9 => true, 0xa9bc...0xa9bd => true, 0xa9e5 => true, 0xaa29...0xaa2e => true, 0xaa31...0xaa32 => true, 0xaa35...0xaa36 => true, 0xaa43 => true, 0xaa4c => true, 0xaa7c => true, 0xaab0 => true, 0xaab2...0xaab4 => true, 0xaab7...0xaab8 => true, 0xaabe...0xaabf => true, 0xaac1 => true, 0xaaec...0xaaed => true, 0xaaf6 => true, 0xabe5 => true, 0xabe8 => true, 0xabed => true, 0xfb1e => true, 0xfe00...0xfe0f => true, 0xfe20...0xfe2f => true, 0xff9e...0xff9f => true, 0x101fd => true, 0x102e0 => true, 0x10376...0x1037a => true, 0x10a01...0x10a03 => true, 0x10a05...0x10a06 => true, 0x10a0c...0x10a0f => true, 0x10a38...0x10a3a => true, 0x10a3f => true, 0x10ae5...0x10ae6 => true, 0x10d24...0x10d27 => true, 0x10eab...0x10eac => true, 0x10f46...0x10f50 => true, 0x10f82...0x10f85 => true, 0x11001 => true, 0x11038...0x11046 => true, 0x11070 => true, 0x11073...0x11074 => true, 0x1107f...0x11081 => true, 0x110b3...0x110b6 => true, 0x110b9...0x110ba => true, 0x110c2 => true, 0x11100...0x11102 => true, 0x11127...0x1112b => true, 0x1112d...0x11134 => true, 0x11173 => true, 0x11180...0x11181 => true, 0x111b6...0x111be => true, 0x111c9...0x111cc => true, 0x111cf => true, 0x1122f...0x11231 => true, 0x11234 => true, 0x11236...0x11237 => true, 0x1123e => true, 0x112df => true, 0x112e3...0x112ea => true, 0x11300...0x11301 => true, 0x1133b...0x1133c => true, 0x1133e => true, 0x11340 => true, 0x11357 => true, 0x11366...0x1136c => true, 0x11370...0x11374 => true, 0x11438...0x1143f => true, 0x11442...0x11444 => true, 0x11446 => true, 0x1145e => true, 0x114b0 => true, 0x114b3...0x114b8 => true, 0x114ba => true, 0x114bd => true, 0x114bf...0x114c0 => true, 0x114c2...0x114c3 => true, 0x115af => true, 0x115b2...0x115b5 => true, 0x115bc...0x115bd => true, 0x115bf...0x115c0 => true, 0x115dc...0x115dd => true, 0x11633...0x1163a => true, 0x1163d => true, 0x1163f...0x11640 => true, 0x116ab => true, 0x116ad => true, 0x116b0...0x116b5 => true, 0x116b7 => true, 0x1171d...0x1171f => true, 0x11722...0x11725 => true, 0x11727...0x1172b => true, 0x1182f...0x11837 => true, 0x11839...0x1183a => true, 0x11930 => true, 0x1193b...0x1193c => true, 0x1193e => true, 0x11943 => true, 0x119d4...0x119d7 => true, 0x119da...0x119db => true, 0x119e0 => true, 0x11a01...0x11a0a => true, 0x11a33...0x11a38 => true, 0x11a3b...0x11a3e => true, 0x11a47 => true, 0x11a51...0x11a56 => true, 0x11a59...0x11a5b => true, 0x11a8a...0x11a96 => true, 0x11a98...0x11a99 => true, 0x11c30...0x11c36 => true, 0x11c38...0x11c3d => true, 0x11c3f => true, 0x11c92...0x11ca7 => true, 0x11caa...0x11cb0 => true, 0x11cb2...0x11cb3 => true, 0x11cb5...0x11cb6 => true, 0x11d31...0x11d36 => true, 0x11d3a => true, 0x11d3c...0x11d3d => true, 0x11d3f...0x11d45 => true, 0x11d47 => true, 0x11d90...0x11d91 => true, 0x11d95 => true, 0x11d97 => true, 0x11ef3...0x11ef4 => true, 0x16af0...0x16af4 => true, 0x16b30...0x16b36 => true, 0x16f4f => true, 0x16f8f...0x16f92 => true, 0x16fe4 => true, 0x1bc9d...0x1bc9e => true, 0x1cf00...0x1cf2d => true, 0x1cf30...0x1cf46 => true, 0x1d165 => true, 0x1d167...0x1d169 => true, 0x1d16e...0x1d172 => true, 0x1d17b...0x1d182 => true, 0x1d185...0x1d18b => true, 0x1d1aa...0x1d1ad => true, 0x1d242...0x1d244 => true, 0x1da00...0x1da36 => true, 0x1da3b...0x1da6c => true, 0x1da75 => true, 0x1da84 => true, 0x1da9b...0x1da9f => true, 0x1daa1...0x1daaf => true, 0x1e000...0x1e006 => true, 0x1e008...0x1e018 => true, 0x1e01b...0x1e021 => true, 0x1e023...0x1e024 => true, 0x1e026...0x1e02a => true, 0x1e130...0x1e136 => true, 0x1e2ae => true, 0x1e2ec...0x1e2ef => true, 0x1e8d0...0x1e8d6 => true, 0x1e944...0x1e94a => true, 0x1f3fb...0x1f3ff => true, 0xe0020...0xe007f => true, 0xe0100...0xe01ef => true, else => false, }; } pub fn isRegionalIndicator(cp: u21) bool { if (cp < 0x1f1e6 or cp > 0x1f1ff) return false; return switch (cp) { 0x1f1e6...0x1f1ff => true, else => false, }; } pub fn isSpacingmark(cp: u21) bool { if (cp < 0x903 or cp > 0x1d16d) return false; return switch (cp) { 0x903 => true, 0x93b => true, 0x93e...0x940 => true, 0x949...0x94c => true, 0x94e...0x94f => true, 0x982...0x983 => true, 0x9bf...0x9c0 => true, 0x9c7...0x9c8 => true, 0x9cb...0x9cc => true, 0xa03 => true, 0xa3e...0xa40 => true, 0xa83 => true, 0xabe...0xac0 => true, 0xac9 => true, 0xacb...0xacc => true, 0xb02...0xb03 => true, 0xb40 => true, 0xb47...0xb48 => true, 0xb4b...0xb4c => true, 0xbbf => true, 0xbc1...0xbc2 => true, 0xbc6...0xbc8 => true, 0xbca...0xbcc => true, 0xc01...0xc03 => true, 0xc41...0xc44 => true, 0xc82...0xc83 => true, 0xcbe => true, 0xcc0...0xcc1 => true, 0xcc3...0xcc4 => true, 0xcc7...0xcc8 => true, 0xcca...0xccb => true, 0xd02...0xd03 => true, 0xd3f...0xd40 => true, 0xd46...0xd48 => true, 0xd4a...0xd4c => true, 0xd82...0xd83 => true, 0xdd0...0xdd1 => true, 0xdd8...0xdde => true, 0xdf2...0xdf3 => true, 0xe33 => true, 0xeb3 => true, 0xf3e...0xf3f => true, 0xf7f => true, 0x1031 => true, 0x103b...0x103c => true, 0x1056...0x1057 => true, 0x1084 => true, 0x1715 => true, 0x1734 => true, 0x17b6 => true, 0x17be...0x17c5 => true, 0x17c7...0x17c8 => true, 0x1923...0x1926 => true, 0x1929...0x192b => true, 0x1930...0x1931 => true, 0x1933...0x1938 => true, 0x1a19...0x1a1a => true, 0x1a55 => true, 0x1a57 => true, 0x1a6d...0x1a72 => true, 0x1b04 => true, 0x1b3b => true, 0x1b3d...0x1b41 => true, 0x1b43...0x1b44 => true, 0x1b82 => true, 0x1ba1 => true, 0x1ba6...0x1ba7 => true, 0x1baa => true, 0x1be7 => true, 0x1bea...0x1bec => true, 0x1bee => true, 0x1bf2...0x1bf3 => true, 0x1c24...0x1c2b => true, 0x1c34...0x1c35 => true, 0x1ce1 => true, 0x1cf7 => true, 0xa823...0xa824 => true, 0xa827 => true, 0xa880...0xa881 => true, 0xa8b4...0xa8c3 => true, 0xa952...0xa953 => true, 0xa983 => true, 0xa9b4...0xa9b5 => true, 0xa9ba...0xa9bb => true, 0xa9be...0xa9c0 => true, 0xaa2f...0xaa30 => true, 0xaa33...0xaa34 => true, 0xaa4d => true, 0xaaeb => true, 0xaaee...0xaaef => true, 0xaaf5 => true, 0xabe3...0xabe4 => true, 0xabe6...0xabe7 => true, 0xabe9...0xabea => true, 0xabec => true, 0x11000 => true, 0x11002 => true, 0x11082 => true, 0x110b0...0x110b2 => true, 0x110b7...0x110b8 => true, 0x1112c => true, 0x11145...0x11146 => true, 0x11182 => true, 0x111b3...0x111b5 => true, 0x111bf...0x111c0 => true, 0x111ce => true, 0x1122c...0x1122e => true, 0x11232...0x11233 => true, 0x11235 => true, 0x112e0...0x112e2 => true, 0x11302...0x11303 => true, 0x1133f => true, 0x11341...0x11344 => true, 0x11347...0x11348 => true, 0x1134b...0x1134d => true, 0x11362...0x11363 => true, 0x11435...0x11437 => true, 0x11440...0x11441 => true, 0x11445 => true, 0x114b1...0x114b2 => true, 0x114b9 => true, 0x114bb...0x114bc => true, 0x114be => true, 0x114c1 => true, 0x115b0...0x115b1 => true, 0x115b8...0x115bb => true, 0x115be => true, 0x11630...0x11632 => true, 0x1163b...0x1163c => true, 0x1163e => true, 0x116ac => true, 0x116ae...0x116af => true, 0x116b6 => true, 0x11726 => true, 0x1182c...0x1182e => true, 0x11838 => true, 0x11931...0x11935 => true, 0x11937...0x11938 => true, 0x1193d => true, 0x11940 => true, 0x11942 => true, 0x119d1...0x119d3 => true, 0x119dc...0x119df => true, 0x119e4 => true, 0x11a39 => true, 0x11a57...0x11a58 => true, 0x11a97 => true, 0x11c2f => true, 0x11c3e => true, 0x11ca9 => true, 0x11cb1 => true, 0x11cb4 => true, 0x11d8a...0x11d8e => true, 0x11d93...0x11d94 => true, 0x11d96 => true, 0x11ef5...0x11ef6 => true, 0x16f51...0x16f87 => true, 0x16ff0...0x16ff1 => true, 0x1d166 => true, 0x1d16d => true, else => false, }; } pub fn isL(cp: u21) bool { if (cp < 0x1100 or cp > 0xa97c) return false; return switch (cp) { 0x1100...0x115f => true, 0xa960...0xa97c => true, else => false, }; } pub fn isV(cp: u21) bool { if (cp < 0x1160 or cp > 0xd7c6) return false; return switch (cp) { 0x1160...0x11a7 => true, 0xd7b0...0xd7c6 => true, else => false, }; } pub fn isT(cp: u21) bool { if (cp < 0x11a8 or cp > 0xd7fb) return false; return switch (cp) { 0x11a8...0x11ff => true, 0xd7cb...0xd7fb => true, else => false, }; } pub fn isLv(cp: u21) bool { if (cp < 0xac00 or cp > 0xd788) return false; return switch (cp) { 0xac00 => true, 0xac1c => true, 0xac38 => true, 0xac54 => true, 0xac70 => true, 0xac8c => true, 0xaca8 => true, 0xacc4 => true, 0xace0 => true, 0xacfc => true, 0xad18 => true, 0xad34 => true, 0xad50 => true, 0xad6c => true, 0xad88 => true, 0xada4 => true, 0xadc0 => true, 0xaddc => true, 0xadf8 => true, 0xae14 => true, 0xae30 => true, 0xae4c => true, 0xae68 => true, 0xae84 => true, 0xaea0 => true, 0xaebc => true, 0xaed8 => true, 0xaef4 => true, 0xaf10 => true, 0xaf2c => true, 0xaf48 => true, 0xaf64 => true, 0xaf80 => true, 0xaf9c => true, 0xafb8 => true, 0xafd4 => true, 0xaff0 => true, 0xb00c => true, 0xb028 => true, 0xb044 => true, 0xb060 => true, 0xb07c => true, 0xb098 => true, 0xb0b4 => true, 0xb0d0 => true, 0xb0ec => true, 0xb108 => true, 0xb124 => true, 0xb140 => true, 0xb15c => true, 0xb178 => true, 0xb194 => true, 0xb1b0 => true, 0xb1cc => true, 0xb1e8 => true, 0xb204 => true, 0xb220 => true, 0xb23c => true, 0xb258 => true, 0xb274 => true, 0xb290 => true, 0xb2ac => true, 0xb2c8 => true, 0xb2e4 => true, 0xb300 => true, 0xb31c => true, 0xb338 => true, 0xb354 => true, 0xb370 => true, 0xb38c => true, 0xb3a8 => true, 0xb3c4 => true, 0xb3e0 => true, 0xb3fc => true, 0xb418 => true, 0xb434 => true, 0xb450 => true, 0xb46c => true, 0xb488 => true, 0xb4a4 => true, 0xb4c0 => true, 0xb4dc => true, 0xb4f8 => true, 0xb514 => true, 0xb530 => true, 0xb54c => true, 0xb568 => true, 0xb584 => true, 0xb5a0 => true, 0xb5bc => true, 0xb5d8 => true, 0xb5f4 => true, 0xb610 => true, 0xb62c => true, 0xb648 => true, 0xb664 => true, 0xb680 => true, 0xb69c => true, 0xb6b8 => true, 0xb6d4 => true, 0xb6f0 => true, 0xb70c => true, 0xb728 => true, 0xb744 => true, 0xb760 => true, 0xb77c => true, 0xb798 => true, 0xb7b4 => true, 0xb7d0 => true, 0xb7ec => true, 0xb808 => true, 0xb824 => true, 0xb840 => true, 0xb85c => true, 0xb878 => true, 0xb894 => true, 0xb8b0 => true, 0xb8cc => true, 0xb8e8 => true, 0xb904 => true, 0xb920 => true, 0xb93c => true, 0xb958 => true, 0xb974 => true, 0xb990 => true, 0xb9ac => true, 0xb9c8 => true, 0xb9e4 => true, 0xba00 => true, 0xba1c => true, 0xba38 => true, 0xba54 => true, 0xba70 => true, 0xba8c => true, 0xbaa8 => true, 0xbac4 => true, 0xbae0 => true, 0xbafc => true, 0xbb18 => true, 0xbb34 => true, 0xbb50 => true, 0xbb6c => true, 0xbb88 => true, 0xbba4 => true, 0xbbc0 => true, 0xbbdc => true, 0xbbf8 => true, 0xbc14 => true, 0xbc30 => true, 0xbc4c => true, 0xbc68 => true, 0xbc84 => true, 0xbca0 => true, 0xbcbc => true, 0xbcd8 => true, 0xbcf4 => true, 0xbd10 => true, 0xbd2c => true, 0xbd48 => true, 0xbd64 => true, 0xbd80 => true, 0xbd9c => true, 0xbdb8 => true, 0xbdd4 => true, 0xbdf0 => true, 0xbe0c => true, 0xbe28 => true, 0xbe44 => true, 0xbe60 => true, 0xbe7c => true, 0xbe98 => true, 0xbeb4 => true, 0xbed0 => true, 0xbeec => true, 0xbf08 => true, 0xbf24 => true, 0xbf40 => true, 0xbf5c => true, 0xbf78 => true, 0xbf94 => true, 0xbfb0 => true, 0xbfcc => true, 0xbfe8 => true, 0xc004 => true, 0xc020 => true, 0xc03c => true, 0xc058 => true, 0xc074 => true, 0xc090 => true, 0xc0ac => true, 0xc0c8 => true, 0xc0e4 => true, 0xc100 => true, 0xc11c => true, 0xc138 => true, 0xc154 => true, 0xc170 => true, 0xc18c => true, 0xc1a8 => true, 0xc1c4 => true, 0xc1e0 => true, 0xc1fc => true, 0xc218 => true, 0xc234 => true, 0xc250 => true, 0xc26c => true, 0xc288 => true, 0xc2a4 => true, 0xc2c0 => true, 0xc2dc => true, 0xc2f8 => true, 0xc314 => true, 0xc330 => true, 0xc34c => true, 0xc368 => true, 0xc384 => true, 0xc3a0 => true, 0xc3bc => true, 0xc3d8 => true, 0xc3f4 => true, 0xc410 => true, 0xc42c => true, 0xc448 => true, 0xc464 => true, 0xc480 => true, 0xc49c => true, 0xc4b8 => true, 0xc4d4 => true, 0xc4f0 => true, 0xc50c => true, 0xc528 => true, 0xc544 => true, 0xc560 => true, 0xc57c => true, 0xc598 => true, 0xc5b4 => true, 0xc5d0 => true, 0xc5ec => true, 0xc608 => true, 0xc624 => true, 0xc640 => true, 0xc65c => true, 0xc678 => true, 0xc694 => true, 0xc6b0 => true, 0xc6cc => true, 0xc6e8 => true, 0xc704 => true, 0xc720 => true, 0xc73c => true, 0xc758 => true, 0xc774 => true, 0xc790 => true, 0xc7ac => true, 0xc7c8 => true, 0xc7e4 => true, 0xc800 => true, 0xc81c => true, 0xc838 => true, 0xc854 => true, 0xc870 => true, 0xc88c => true, 0xc8a8 => true, 0xc8c4 => true, 0xc8e0 => true, 0xc8fc => true, 0xc918 => true, 0xc934 => true, 0xc950 => true, 0xc96c => true, 0xc988 => true, 0xc9a4 => true, 0xc9c0 => true, 0xc9dc => true, 0xc9f8 => true, 0xca14 => true, 0xca30 => true, 0xca4c => true, 0xca68 => true, 0xca84 => true, 0xcaa0 => true, 0xcabc => true, 0xcad8 => true, 0xcaf4 => true, 0xcb10 => true, 0xcb2c => true, 0xcb48 => true, 0xcb64 => true, 0xcb80 => true, 0xcb9c => true, 0xcbb8 => true, 0xcbd4 => true, 0xcbf0 => true, 0xcc0c => true, 0xcc28 => true, 0xcc44 => true, 0xcc60 => true, 0xcc7c => true, 0xcc98 => true, 0xccb4 => true, 0xccd0 => true, 0xccec => true, 0xcd08 => true, 0xcd24 => true, 0xcd40 => true, 0xcd5c => true, 0xcd78 => true, 0xcd94 => true, 0xcdb0 => true, 0xcdcc => true, 0xcde8 => true, 0xce04 => true, 0xce20 => true, 0xce3c => true, 0xce58 => true, 0xce74 => true, 0xce90 => true, 0xceac => true, 0xcec8 => true, 0xcee4 => true, 0xcf00 => true, 0xcf1c => true, 0xcf38 => true, 0xcf54 => true, 0xcf70 => true, 0xcf8c => true, 0xcfa8 => true, 0xcfc4 => true, 0xcfe0 => true, 0xcffc => true, 0xd018 => true, 0xd034 => true, 0xd050 => true, 0xd06c => true, 0xd088 => true, 0xd0a4 => true, 0xd0c0 => true, 0xd0dc => true, 0xd0f8 => true, 0xd114 => true, 0xd130 => true, 0xd14c => true, 0xd168 => true, 0xd184 => true, 0xd1a0 => true, 0xd1bc => true, 0xd1d8 => true, 0xd1f4 => true, 0xd210 => true, 0xd22c => true, 0xd248 => true, 0xd264 => true, 0xd280 => true, 0xd29c => true, 0xd2b8 => true, 0xd2d4 => true, 0xd2f0 => true, 0xd30c => true, 0xd328 => true, 0xd344 => true, 0xd360 => true, 0xd37c => true, 0xd398 => true, 0xd3b4 => true, 0xd3d0 => true, 0xd3ec => true, 0xd408 => true, 0xd424 => true, 0xd440 => true, 0xd45c => true, 0xd478 => true, 0xd494 => true, 0xd4b0 => true, 0xd4cc => true, 0xd4e8 => true, 0xd504 => true, 0xd520 => true, 0xd53c => true, 0xd558 => true, 0xd574 => true, 0xd590 => true, 0xd5ac => true, 0xd5c8 => true, 0xd5e4 => true, 0xd600 => true, 0xd61c => true, 0xd638 => true, 0xd654 => true, 0xd670 => true, 0xd68c => true, 0xd6a8 => true, 0xd6c4 => true, 0xd6e0 => true, 0xd6fc => true, 0xd718 => true, 0xd734 => true, 0xd750 => true, 0xd76c => true, 0xd788 => true, else => false, }; } pub fn isLvt(cp: u21) bool { if (cp < 0xac01 or cp > 0xd7a3) return false; return switch (cp) { 0xac01...0xac1b => true, 0xac1d...0xac37 => true, 0xac39...0xac53 => true, 0xac55...0xac6f => true, 0xac71...0xac8b => true, 0xac8d...0xaca7 => true, 0xaca9...0xacc3 => true, 0xacc5...0xacdf => true, 0xace1...0xacfb => true, 0xacfd...0xad17 => true, 0xad19...0xad33 => true, 0xad35...0xad4f => true, 0xad51...0xad6b => true, 0xad6d...0xad87 => true, 0xad89...0xada3 => true, 0xada5...0xadbf => true, 0xadc1...0xaddb => true, 0xaddd...0xadf7 => true, 0xadf9...0xae13 => true, 0xae15...0xae2f => true, 0xae31...0xae4b => true, 0xae4d...0xae67 => true, 0xae69...0xae83 => true, 0xae85...0xae9f => true, 0xaea1...0xaebb => true, 0xaebd...0xaed7 => true, 0xaed9...0xaef3 => true, 0xaef5...0xaf0f => true, 0xaf11...0xaf2b => true, 0xaf2d...0xaf47 => true, 0xaf49...0xaf63 => true, 0xaf65...0xaf7f => true, 0xaf81...0xaf9b => true, 0xaf9d...0xafb7 => true, 0xafb9...0xafd3 => true, 0xafd5...0xafef => true, 0xaff1...0xb00b => true, 0xb00d...0xb027 => true, 0xb029...0xb043 => true, 0xb045...0xb05f => true, 0xb061...0xb07b => true, 0xb07d...0xb097 => true, 0xb099...0xb0b3 => true, 0xb0b5...0xb0cf => true, 0xb0d1...0xb0eb => true, 0xb0ed...0xb107 => true, 0xb109...0xb123 => true, 0xb125...0xb13f => true, 0xb141...0xb15b => true, 0xb15d...0xb177 => true, 0xb179...0xb193 => true, 0xb195...0xb1af => true, 0xb1b1...0xb1cb => true, 0xb1cd...0xb1e7 => true, 0xb1e9...0xb203 => true, 0xb205...0xb21f => true, 0xb221...0xb23b => true, 0xb23d...0xb257 => true, 0xb259...0xb273 => true, 0xb275...0xb28f => true, 0xb291...0xb2ab => true, 0xb2ad...0xb2c7 => true, 0xb2c9...0xb2e3 => true, 0xb2e5...0xb2ff => true, 0xb301...0xb31b => true, 0xb31d...0xb337 => true, 0xb339...0xb353 => true, 0xb355...0xb36f => true, 0xb371...0xb38b => true, 0xb38d...0xb3a7 => true, 0xb3a9...0xb3c3 => true, 0xb3c5...0xb3df => true, 0xb3e1...0xb3fb => true, 0xb3fd...0xb417 => true, 0xb419...0xb433 => true, 0xb435...0xb44f => true, 0xb451...0xb46b => true, 0xb46d...0xb487 => true, 0xb489...0xb4a3 => true, 0xb4a5...0xb4bf => true, 0xb4c1...0xb4db => true, 0xb4dd...0xb4f7 => true, 0xb4f9...0xb513 => true, 0xb515...0xb52f => true, 0xb531...0xb54b => true, 0xb54d...0xb567 => true, 0xb569...0xb583 => true, 0xb585...0xb59f => true, 0xb5a1...0xb5bb => true, 0xb5bd...0xb5d7 => true, 0xb5d9...0xb5f3 => true, 0xb5f5...0xb60f => true, 0xb611...0xb62b => true, 0xb62d...0xb647 => true, 0xb649...0xb663 => true, 0xb665...0xb67f => true, 0xb681...0xb69b => true, 0xb69d...0xb6b7 => true, 0xb6b9...0xb6d3 => true, 0xb6d5...0xb6ef => true, 0xb6f1...0xb70b => true, 0xb70d...0xb727 => true, 0xb729...0xb743 => true, 0xb745...0xb75f => true, 0xb761...0xb77b => true, 0xb77d...0xb797 => true, 0xb799...0xb7b3 => true, 0xb7b5...0xb7cf => true, 0xb7d1...0xb7eb => true, 0xb7ed...0xb807 => true, 0xb809...0xb823 => true, 0xb825...0xb83f => true, 0xb841...0xb85b => true, 0xb85d...0xb877 => true, 0xb879...0xb893 => true, 0xb895...0xb8af => true, 0xb8b1...0xb8cb => true, 0xb8cd...0xb8e7 => true, 0xb8e9...0xb903 => true, 0xb905...0xb91f => true, 0xb921...0xb93b => true, 0xb93d...0xb957 => true, 0xb959...0xb973 => true, 0xb975...0xb98f => true, 0xb991...0xb9ab => true, 0xb9ad...0xb9c7 => true, 0xb9c9...0xb9e3 => true, 0xb9e5...0xb9ff => true, 0xba01...0xba1b => true, 0xba1d...0xba37 => true, 0xba39...0xba53 => true, 0xba55...0xba6f => true, 0xba71...0xba8b => true, 0xba8d...0xbaa7 => true, 0xbaa9...0xbac3 => true, 0xbac5...0xbadf => true, 0xbae1...0xbafb => true, 0xbafd...0xbb17 => true, 0xbb19...0xbb33 => true, 0xbb35...0xbb4f => true, 0xbb51...0xbb6b => true, 0xbb6d...0xbb87 => true, 0xbb89...0xbba3 => true, 0xbba5...0xbbbf => true, 0xbbc1...0xbbdb => true, 0xbbdd...0xbbf7 => true, 0xbbf9...0xbc13 => true, 0xbc15...0xbc2f => true, 0xbc31...0xbc4b => true, 0xbc4d...0xbc67 => true, 0xbc69...0xbc83 => true, 0xbc85...0xbc9f => true, 0xbca1...0xbcbb => true, 0xbcbd...0xbcd7 => true, 0xbcd9...0xbcf3 => true, 0xbcf5...0xbd0f => true, 0xbd11...0xbd2b => true, 0xbd2d...0xbd47 => true, 0xbd49...0xbd63 => true, 0xbd65...0xbd7f => true, 0xbd81...0xbd9b => true, 0xbd9d...0xbdb7 => true, 0xbdb9...0xbdd3 => true, 0xbdd5...0xbdef => true, 0xbdf1...0xbe0b => true, 0xbe0d...0xbe27 => true, 0xbe29...0xbe43 => true, 0xbe45...0xbe5f => true, 0xbe61...0xbe7b => true, 0xbe7d...0xbe97 => true, 0xbe99...0xbeb3 => true, 0xbeb5...0xbecf => true, 0xbed1...0xbeeb => true, 0xbeed...0xbf07 => true, 0xbf09...0xbf23 => true, 0xbf25...0xbf3f => true, 0xbf41...0xbf5b => true, 0xbf5d...0xbf77 => true, 0xbf79...0xbf93 => true, 0xbf95...0xbfaf => true, 0xbfb1...0xbfcb => true, 0xbfcd...0xbfe7 => true, 0xbfe9...0xc003 => true, 0xc005...0xc01f => true, 0xc021...0xc03b => true, 0xc03d...0xc057 => true, 0xc059...0xc073 => true, 0xc075...0xc08f => true, 0xc091...0xc0ab => true, 0xc0ad...0xc0c7 => true, 0xc0c9...0xc0e3 => true, 0xc0e5...0xc0ff => true, 0xc101...0xc11b => true, 0xc11d...0xc137 => true, 0xc139...0xc153 => true, 0xc155...0xc16f => true, 0xc171...0xc18b => true, 0xc18d...0xc1a7 => true, 0xc1a9...0xc1c3 => true, 0xc1c5...0xc1df => true, 0xc1e1...0xc1fb => true, 0xc1fd...0xc217 => true, 0xc219...0xc233 => true, 0xc235...0xc24f => true, 0xc251...0xc26b => true, 0xc26d...0xc287 => true, 0xc289...0xc2a3 => true, 0xc2a5...0xc2bf => true, 0xc2c1...0xc2db => true, 0xc2dd...0xc2f7 => true, 0xc2f9...0xc313 => true, 0xc315...0xc32f => true, 0xc331...0xc34b => true, 0xc34d...0xc367 => true, 0xc369...0xc383 => true, 0xc385...0xc39f => true, 0xc3a1...0xc3bb => true, 0xc3bd...0xc3d7 => true, 0xc3d9...0xc3f3 => true, 0xc3f5...0xc40f => true, 0xc411...0xc42b => true, 0xc42d...0xc447 => true, 0xc449...0xc463 => true, 0xc465...0xc47f => true, 0xc481...0xc49b => true, 0xc49d...0xc4b7 => true, 0xc4b9...0xc4d3 => true, 0xc4d5...0xc4ef => true, 0xc4f1...0xc50b => true, 0xc50d...0xc527 => true, 0xc529...0xc543 => true, 0xc545...0xc55f => true, 0xc561...0xc57b => true, 0xc57d...0xc597 => true, 0xc599...0xc5b3 => true, 0xc5b5...0xc5cf => true, 0xc5d1...0xc5eb => true, 0xc5ed...0xc607 => true, 0xc609...0xc623 => true, 0xc625...0xc63f => true, 0xc641...0xc65b => true, 0xc65d...0xc677 => true, 0xc679...0xc693 => true, 0xc695...0xc6af => true, 0xc6b1...0xc6cb => true, 0xc6cd...0xc6e7 => true, 0xc6e9...0xc703 => true, 0xc705...0xc71f => true, 0xc721...0xc73b => true, 0xc73d...0xc757 => true, 0xc759...0xc773 => true, 0xc775...0xc78f => true, 0xc791...0xc7ab => true, 0xc7ad...0xc7c7 => true, 0xc7c9...0xc7e3 => true, 0xc7e5...0xc7ff => true, 0xc801...0xc81b => true, 0xc81d...0xc837 => true, 0xc839...0xc853 => true, 0xc855...0xc86f => true, 0xc871...0xc88b => true, 0xc88d...0xc8a7 => true, 0xc8a9...0xc8c3 => true, 0xc8c5...0xc8df => true, 0xc8e1...0xc8fb => true, 0xc8fd...0xc917 => true, 0xc919...0xc933 => true, 0xc935...0xc94f => true, 0xc951...0xc96b => true, 0xc96d...0xc987 => true, 0xc989...0xc9a3 => true, 0xc9a5...0xc9bf => true, 0xc9c1...0xc9db => true, 0xc9dd...0xc9f7 => true, 0xc9f9...0xca13 => true, 0xca15...0xca2f => true, 0xca31...0xca4b => true, 0xca4d...0xca67 => true, 0xca69...0xca83 => true, 0xca85...0xca9f => true, 0xcaa1...0xcabb => true, 0xcabd...0xcad7 => true, 0xcad9...0xcaf3 => true, 0xcaf5...0xcb0f => true, 0xcb11...0xcb2b => true, 0xcb2d...0xcb47 => true, 0xcb49...0xcb63 => true, 0xcb65...0xcb7f => true, 0xcb81...0xcb9b => true, 0xcb9d...0xcbb7 => true, 0xcbb9...0xcbd3 => true, 0xcbd5...0xcbef => true, 0xcbf1...0xcc0b => true, 0xcc0d...0xcc27 => true, 0xcc29...0xcc43 => true, 0xcc45...0xcc5f => true, 0xcc61...0xcc7b => true, 0xcc7d...0xcc97 => true, 0xcc99...0xccb3 => true, 0xccb5...0xcccf => true, 0xccd1...0xcceb => true, 0xcced...0xcd07 => true, 0xcd09...0xcd23 => true, 0xcd25...0xcd3f => true, 0xcd41...0xcd5b => true, 0xcd5d...0xcd77 => true, 0xcd79...0xcd93 => true, 0xcd95...0xcdaf => true, 0xcdb1...0xcdcb => true, 0xcdcd...0xcde7 => true, 0xcde9...0xce03 => true, 0xce05...0xce1f => true, 0xce21...0xce3b => true, 0xce3d...0xce57 => true, 0xce59...0xce73 => true, 0xce75...0xce8f => true, 0xce91...0xceab => true, 0xcead...0xcec7 => true, 0xcec9...0xcee3 => true, 0xcee5...0xceff => true, 0xcf01...0xcf1b => true, 0xcf1d...0xcf37 => true, 0xcf39...0xcf53 => true, 0xcf55...0xcf6f => true, 0xcf71...0xcf8b => true, 0xcf8d...0xcfa7 => true, 0xcfa9...0xcfc3 => true, 0xcfc5...0xcfdf => true, 0xcfe1...0xcffb => true, 0xcffd...0xd017 => true, 0xd019...0xd033 => true, 0xd035...0xd04f => true, 0xd051...0xd06b => true, 0xd06d...0xd087 => true, 0xd089...0xd0a3 => true, 0xd0a5...0xd0bf => true, 0xd0c1...0xd0db => true, 0xd0dd...0xd0f7 => true, 0xd0f9...0xd113 => true, 0xd115...0xd12f => true, 0xd131...0xd14b => true, 0xd14d...0xd167 => true, 0xd169...0xd183 => true, 0xd185...0xd19f => true, 0xd1a1...0xd1bb => true, 0xd1bd...0xd1d7 => true, 0xd1d9...0xd1f3 => true, 0xd1f5...0xd20f => true, 0xd211...0xd22b => true, 0xd22d...0xd247 => true, 0xd249...0xd263 => true, 0xd265...0xd27f => true, 0xd281...0xd29b => true, 0xd29d...0xd2b7 => true, 0xd2b9...0xd2d3 => true, 0xd2d5...0xd2ef => true, 0xd2f1...0xd30b => true, 0xd30d...0xd327 => true, 0xd329...0xd343 => true, 0xd345...0xd35f => true, 0xd361...0xd37b => true, 0xd37d...0xd397 => true, 0xd399...0xd3b3 => true, 0xd3b5...0xd3cf => true, 0xd3d1...0xd3eb => true, 0xd3ed...0xd407 => true, 0xd409...0xd423 => true, 0xd425...0xd43f => true, 0xd441...0xd45b => true, 0xd45d...0xd477 => true, 0xd479...0xd493 => true, 0xd495...0xd4af => true, 0xd4b1...0xd4cb => true, 0xd4cd...0xd4e7 => true, 0xd4e9...0xd503 => true, 0xd505...0xd51f => true, 0xd521...0xd53b => true, 0xd53d...0xd557 => true, 0xd559...0xd573 => true, 0xd575...0xd58f => true, 0xd591...0xd5ab => true, 0xd5ad...0xd5c7 => true, 0xd5c9...0xd5e3 => true, 0xd5e5...0xd5ff => true, 0xd601...0xd61b => true, 0xd61d...0xd637 => true, 0xd639...0xd653 => true, 0xd655...0xd66f => true, 0xd671...0xd68b => true, 0xd68d...0xd6a7 => true, 0xd6a9...0xd6c3 => true, 0xd6c5...0xd6df => true, 0xd6e1...0xd6fb => true, 0xd6fd...0xd717 => true, 0xd719...0xd733 => true, 0xd735...0xd74f => true, 0xd751...0xd76b => true, 0xd76d...0xd787 => true, 0xd789...0xd7a3 => true, else => false, }; } pub fn isZwj(cp: u21) bool { return cp == 0x200d; }
.gyro/ziglyph-jecolon-github.com-c37d93b6/pkg/src/autogen/grapheme_break_property.zig
const std = @import("std"); const stdx = @import("../stdx.zig"); const t = stdx.testing; const log = stdx.log.scoped(.rb_tree); const Color = enum(u1) { Black, Red, }; /// Based on Zig's rb node pointer based implementation: /// https://github.com/ziglang/std-lib-orphanage/blob/master/std/rb.zig /// Deletion logic was redone from https://www.youtube.com/watch?v=CTvfzU_uNKE as guidance. /// Correction for case 5 in the video: it should not have a parent black condition. /// Visualize: https://www.cs.usfca.edu/~galles/visualization/RedBlack.html pub fn RbTree(comptime Id: type, comptime Value: type, comptime Context: type, comptime Compare: fn (Value, Value, Context) std.math.Order) type { return struct { root: OptId, buf: stdx.ds.CompactUnorderedList(Id, Node), /// The current number of nodes. Does not count detached nodes. size: usize, ctx: Context, const Self = @This(); const OptId = Id; const NullId = stdx.ds.CompactNull(Id); const Node = struct { left: OptId, right: OptId, val: Value, parent: OptId, color: Color, fn getParentOpt(self: Node) ?Id { if (self.parent == NullId) { return null; } else { return self.parent; } } fn isRoot(self: Node) bool { return self.parent == NullId; } fn setChild(self: *Node, child: Id, is_left: bool) void { if (is_left) { self.left = child; } else { self.right = child; } } }; pub fn init(alloc: std.mem.Allocator, ctx: Context) Self { return .{ .root = NullId, .buf = stdx.ds.CompactUnorderedList(Id, Node).init(alloc), .size = 0, .ctx = ctx, }; } pub fn deinit(self: *Self) void { self.buf.deinit(); } pub fn clearRetainingCapacity(self: *Self) void { self.buf.clearRetainingCapacity(); self.root = NullId; self.size = 0; } /// Re-sorts a tree with a compare function. pub fn sort(self: *Self, ctx: anytype, cmp: fn (Value, Value, @TypeOf(ctx)) std.math.Order) !void { self.root = NullId; var iter = self.buf.iterator(); while (iter.next()) |node| { self.buf.remove(iter.cur_id); _ = try self.insertCustom(node.val, ctx, cmp); } } pub fn first(self: Self) ?Id { if (self.root == NullId) { return null; } var id = self.root; var node = self.buf.getNoCheck(id); while (node.left != NullId) { id = node.left; node = self.buf.getNoCheck(id); } return id; } pub fn firstFrom(self: Self, node_id: Id) Id { var id = node_id; var node = self.buf.getNoCheck(id); while (node.left != NullId) { id = node.left; node = self.buf.getNoCheck(id); } return id; } pub fn last(self: Self) ?Id { if (self.root == NullId) { return null; } var id = self.root; var node = self.buf.getNoCheck(id); while (node.right != NullId) { id = node.right; node = self.buf.getNoCheck(id); } return id; } pub fn allocValuesInOrder(self: Self, alloc: std.mem.Allocator) []const Value { var vals = std.ArrayList(Value).initCapacity(alloc, self.size) catch unreachable; var cur = self.first(); while (cur) |id| { vals.appendAssumeCapacity(self.get(id).?); cur = self.getNext(id); } return vals.toOwnedSlice(); } pub fn allocNodeIdsInOrder(self: Self, alloc: std.mem.Allocator) []const Id { var node_ids = std.ArrayList(Id).initCapacity(alloc, self.size) catch unreachable; var cur = self.first(); while (cur) |id| { node_ids.appendAssumeCapacity(id); cur = self.getNext(id); } return node_ids.toOwnedSlice(); } /// User code typically wouldn't need the node, but it is available for testing. pub fn getNode(self: Self, id: Id) ?Node { return self.buf.get(id); } pub fn get(self: Self, id: Id) ?Value { if (self.buf.get(id)) |node| { return node.val; } else return null; } pub fn getNoCheck(self: Self, id: Id) Value { return self.buf.getNoCheck(id).val; } pub fn getPtr(self: Self, id: Id) ?*Value { if (self.buf.getPtr(id)) |node| { return &node.val; } else return null; } pub fn getPtrNoCheck(self: Self, id: Id) *Value { return &self.buf.getPtrNoCheck(id).val; } fn getSibling(self: Self, parent: *Node, child_id: Id) OptId { _ = self; if (parent.left == child_id) { return parent.right; } else { return parent.left; } } // Replacement node (with it's children) are relinked in place of node . Node (with it's children) become detached from tree. fn transplant(self: *Self, node_id: Id, node: *Node, r_id: Id, mb_rnode: ?*Node) void { if (node_id == self.root) { self.root = r_id; } else { const parent = self.buf.getPtrNoCheck(node.parent); parent.setChild(r_id, parent.left == node_id); } if (mb_rnode) |rnode| { rnode.parent = node.parent; } } pub fn removeDetached(self: *Self, node_id: Id) void { self.buf.remove(node_id); } pub fn remove(self: *Self, node_id: Id) anyerror!void { try self.detach(node_id); self.buf.remove(node_id); } /// If node is not part of tree, error is returned. /// Detaches the node from the tree, rebalances tree, but does not remove it. The caller is responsible for calling removeDetached later on. pub fn detach(self: *Self, node_id: Id) anyerror!void { try self.detachInternal(node_id); self.size -= 1; } fn detachInternal(self: *Self, node_id: Id) anyerror!void { var node = self.buf.getPtr(node_id) orelse return error.DoesNotExist; var to_fix_nid: OptId = undefined; if (node.left == NullId) { const mb_rnode: ?*Node = if (node.right != NullId) self.buf.getPtrNoCheck(node.right) else null; self.transplant(node_id, node, node.right, mb_rnode); to_fix_nid = node.right; } else if (node.right == NullId) { const mb_rnode: ?*Node = if (node.left != NullId) self.buf.getPtrNoCheck(node.left) else null; self.transplant(node_id, node, node.left, mb_rnode); to_fix_nid = node.left; } else { const r_id = self.firstFrom(node.right); const r_node = self.buf.getPtrNoCheck(r_id); // Normally this would be a value copy but since ids are tied to their nodes, the replacement node is relinked in place of the target node. // Transplant only relinks parent of replacement node. const r_parent = r_node.parent; self.transplant(node_id, node, r_id, r_node); if (r_parent != node_id) { const rp = self.buf.getPtrNoCheck(r_parent); rp.setChild(node_id, rp.left == r_id); node.parent = r_parent; } else { node.parent = r_id; } // Swap colors. const tmp_color = r_node.color; r_node.color = node.color; node.color = tmp_color; // Copy r_node value to node; a recursive call to delete node will be called. var orig_val = node.val; node.val = r_node.val; defer { // Revert back to node's original val in case the user wanted to only detach the node (and not remove it). node.val = orig_val; } // Relink r_node left and node left. // Note: r_node shouldn't have a left child since firstFrom would have returned it the child instead. self.buf.getPtrNoCheck(node.left).parent = r_id; r_node.left = node.left; node.left = NullId; // Relink r_node right and node right. // Note: tmp_right can't be null since node should have two children. const tmp_right = node.right; if (r_node.right != NullId) { self.buf.getPtrNoCheck(r_node.right).parent = node_id; } node.right = r_node.right; if (tmp_right != r_id) { self.buf.getPtrNoCheck(tmp_right).parent = r_id; r_node.right = tmp_right; } // Reduced to zero or one children case. Recurse once. try self.detachInternal(node_id); return; } // If red was removed, it is done. if (node.color == .Red) { return; } else { // If black was removed and replacement is red. Paint replacement black and we are done. if (to_fix_nid == NullId) { // Double black. Perform fix. self.detachFixUp(to_fix_nid, node.parent); } else { const r_node = self.buf.getPtrNoCheck(to_fix_nid); if (r_node.color == .Red) { // Can mark black and be done since a black was removed. r_node.color = .Black; } else { // Double black. Perform fix. self.detachFixUp(to_fix_nid, r_node.parent); } } } } /// Handle double black cases. /// Assumes node is a double black. Since the node could be null, the current parent is also required. fn detachFixUp(self: *Self, node_id: OptId, parent_id: OptId) void { // Case 1: Root case. if (parent_id == NullId) { return; } const parent = self.buf.getPtrNoCheck(parent_id); const s_id = self.getSibling(parent, node_id); const is_right_sibling = parent.left == node_id; // Sibling must exist since node is a double black. const sibling = self.buf.getPtrNoCheck(s_id); const s_left: ?*Node = if (sibling.left != NullId) self.buf.getPtrNoCheck(sibling.left) else null; const s_right: ?*Node = if (sibling.right != NullId) self.buf.getPtrNoCheck(sibling.right) else null; const s_left_black = s_left == null or s_left.?.color == .Black; const s_right_black = s_right == null or s_right.?.color == .Black; if (parent.color == .Black and sibling.color == .Red) { if (s_left_black and s_right_black) { if (is_right_sibling) { // Case 2: parent is black, right sibling is red and has two black children. self.rotateLeft(parent_id, parent); } else { // Case 2: parent is black, left sibling is red and has two black children. self.rotateRight(parent_id, parent); } parent.color = .Red; sibling.color = .Black; self.detachFixUp(node_id, parent_id); return; } } if (parent.color == .Black and sibling.color == .Black) { // Case 3: left or right sibling with both black children. if (s_left_black and s_right_black) { sibling.color = .Red; // Recurse at parent. self.detachFixUp(parent_id, parent.parent); return; } } if (parent.color == .Red and sibling.color == .Black) { // Case 4: left or right sibling with both black children. if (s_left_black and s_right_black) { parent.color = .Black; sibling.color = .Red; return; } } if (sibling.color == .Black) { // Case 5: parent is black, right sibling is black, sibling has red left child and black right child. if (is_right_sibling and s_left != null and s_left.?.color == .Red and s_right_black) { self.rotateRight(s_id, sibling); sibling.color = .Red; s_left.?.color = .Black; // Call again to check for case 6. self.detachFixUp(node_id, parent_id); return; } // Case 5: parent is black, left sibiling is black, sibling has red right child and black left child. if (!is_right_sibling and s_right != null and s_right.?.color == .Red and s_left_black) { self.rotateLeft(s_id, sibling); sibling.color = .Red; s_right.?.color = .Black; // Call again to check for case 6. self.detachFixUp(node_id, parent_id); return; } // Case 6: right sibling with red right child. if (is_right_sibling and s_right != null and s_right.?.color == .Red) { self.rotateLeft(parent_id, parent); sibling.color = parent.color; parent.color = .Black; s_right.?.color = .Black; return; } // Case 6: left sibling with red left child. if (!is_right_sibling and s_left != null and s_left.?.color == .Red) { self.rotateRight(parent_id, parent); sibling.color = parent.color; parent.color = .Black; s_left.?.color = .Black; return; } } } pub fn insert(self: *Self, val: Value) !Id { return try self.insertCustom(val, self.ctx, Compare); } /// Duplicate keys are not allowed. pub fn insertCustom(self: *Self, val: Value, ctx: anytype, cmp: fn (Value, Value, @TypeOf(ctx)) std.math.Order) !Id { var maybe_id: ?Id = undefined; var maybe_parent: ?Id = undefined; var is_left: bool = undefined; maybe_id = self.doLookup(val, &maybe_parent, &is_left, ctx, cmp); if (maybe_id) |_| { return error.DuplicateKey; } const new_id = try self.buf.add(.{ .left = NullId, .right = NullId, .color = .Red, .parent = maybe_parent orelse NullId, .val = val, }); self.size += 1; if (maybe_parent) |parent| { self.buf.getPtrNoCheck(parent).setChild(new_id, is_left); } else { self.root = new_id; } var node_id = new_id; while (true) { var node = self.buf.getPtrNoCheck(node_id); const parent_id = node.getParentOpt() orelse break; var parent = self.buf.getPtrNoCheck(parent_id); if (parent.color == .Black) { // Current is red, parent is black. Nothing left to do. break; } // If parent is red, there must be a grand parent that is black. var grandpa_id = parent.getParentOpt() orelse unreachable; var grandpa = self.buf.getPtrNoCheck(grandpa_id); if (parent_id == grandpa.left) { var opt_psibling = grandpa.right; const mb_psibling: ?*Node = if (opt_psibling != NullId) self.buf.getPtrNoCheck(opt_psibling) else null; if (mb_psibling == null or mb_psibling.?.color == .Black) { // Case #5, parent is red, parent sibling is black, node is inner grandchild. Rotate left first. if (node_id == parent.right) { self.rotateLeft(parent_id, parent); // Make sure reattached right is black since parent is red. if (parent.right != NullId) { self.buf.getPtrNoCheck(parent.right).color = .Black; } parent = node; } parent.color = .Black; grandpa.color = .Red; self.rotateRight(grandpa_id, grandpa); // Make sure reattached left is black since grandpa is red. if (grandpa.left != NullId) { self.buf.getPtrNoCheck(grandpa.left).color = .Black; } } else { // parent and parent sibling are both red. Set both to black, and grand parent to red. parent.color = .Black; mb_psibling.?.color = .Black; grandpa.color = .Red; node_id = grandpa_id; } } else { var opt_psibling = grandpa.left; const mb_psibling: ?*Node = if (opt_psibling != NullId) self.buf.getPtrNoCheck(opt_psibling) else null; if (mb_psibling == null or mb_psibling.?.color == .Black) { // Case #5, parent is red, parent sibling is black, node is inner grandchild. Rotate right first. if (node_id == parent.left) { self.rotateRight(parent_id, parent); // Make sure reattached left is black since parent is red. if (parent.left != NullId) { self.buf.getPtrNoCheck(parent.left).color = .Black; } parent = node; } parent.color = .Black; grandpa.color = .Red; self.rotateLeft(grandpa_id, grandpa); // Make sure reattached right is black since grandpa is red. if (grandpa.right != NullId) { self.buf.getPtrNoCheck(grandpa.right).color = .Black; } } else { // parent and parent sibling are both red. Set both to black, and grand parent to red. parent.color = .Black; mb_psibling.?.color = .Black; grandpa.color = .Red; node_id = grandpa_id; } } } // This was an insert, there is at least one node. self.buf.getPtrNoCheck(self.root).color = .Black; return new_id; } /// lookup searches for the value of key, using binary search. It will /// return a pointer to the node if it is there, otherwise it will return null. /// Complexity guaranteed O(log n), where n is the number of nodes book-kept /// by tree. pub fn lookup(self: Self, val: Value) ?Id { var parent: ?Id = undefined; var is_left: bool = undefined; return self.doLookup(val, &parent, &is_left, self.ctx, Compare); } /// Lookup with a different compare function. pub fn lookupCustom(self: Self, val: Value, ctx: anytype, cmp: fn (Value, Value, @TypeOf(ctx)) std.math.Order) ?Id { var parent: ?Id = undefined; var is_left: bool = undefined; return self.doLookup(val, &parent, &is_left, ctx, cmp); } /// Lookup that also sets the parent and is_left to indicate where it was found or where it would be inserted. pub fn lookupCustomLoc(self: Self, val: Value, ctx: anytype, cmp: fn (Value, Value, @TypeOf(ctx)) std.math.Order, parent: *?Id, is_left: *bool) ?Id { return self.doLookup(val, parent, is_left, ctx, cmp); } /// If there is a match, the Id is returned. /// Otherwise, the insert slot is provided by pparent and is_left. fn doLookup(self: Self, val: Value, pparent: *?Id, is_left: *bool, ctx: anytype, cmp: fn (Value, Value, @TypeOf(ctx)) std.math.Order) ?Id { var opt_id = self.root; pparent.* = null; is_left.* = false; while (opt_id != NullId) { const node = self.buf.getNoCheck(opt_id); const res = cmp(val, node.val, ctx); if (res == .eq) { return opt_id; } pparent.* = opt_id; switch (res) { .lt => { is_left.* = true; opt_id = node.left; }, .gt => { is_left.* = false; opt_id = node.right; }, .eq => unreachable, // handled above } } return null; } /// e /// / /// (a) /// / \ /// b c /// / /// d /// Given a, rotate a to b and c to a. a's parent becomes c and right becomes d. c's parent bcomes e and left becomes a. fn rotateLeft(self: *Self, node_id: Id, node: *Node) void { if (node.right == NullId) { unreachable; } var right = self.buf.getPtrNoCheck(node.right); if (!node.isRoot()) { var parent = self.buf.getPtrNoCheck(node.parent); if (parent.left == node_id) { parent.left = node.right; } else { parent.right = node.right; } right.parent = node.parent; } else { self.root = node.right; right.parent = NullId; } node.parent = node.right; node.right = right.left; if (node.right != NullId) { self.buf.getPtrNoCheck(node.right).parent = node_id; } right.left = node_id; } /// Works similarily to rotateLeft for the right direction. fn rotateRight(self: *Self, node_id: Id, node: *Node) void { if (node.left == NullId) { unreachable; } var left = self.buf.getPtrNoCheck(node.left); if (!node.isRoot()) { var parent = self.buf.getPtrNoCheck(node.parent); if (parent.left == node_id) { parent.left = node.left; } else { parent.right = node.left; } left.parent = node.parent; } else { self.root = node.left; left.parent = NullId; } node.parent = node.left; node.left = left.right; if (node.left != NullId) { self.buf.getPtrNoCheck(node.left).parent = node_id; } left.right = node_id; } pub fn getPrev(self: Self, id: Id) ?Id { var node = self.buf.getNoCheck(id); if (node.left != NullId) { var cur = node.left; node = self.buf.getNoCheck(cur); while (node.right != NullId) { cur = node.right; node = self.buf.getNoCheck(cur); } return cur; } var cur = id; while (true) { if (node.parent != NullId) { var p = self.buf.getNoCheck(node.parent); if (cur != p.left) { return node.parent; } cur = node.parent; node = p; } else { return null; } } } pub fn getNext(self: Self, id: Id) ?Id { var node = self.buf.getNoCheck(id); if (node.right != NullId) { var cur = node.right; node = self.buf.getNoCheck(cur); while (node.left != NullId) { cur = node.left; node = self.buf.getNoCheck(cur); } return cur; } var cur = id; while (true) { if (node.parent != NullId) { var p = self.buf.getNoCheck(node.parent); if (cur != p.right) { return node.parent; } cur = node.parent; node = p; } else { return null; } } } /// Checks whether the tree is a valid red black tree. pub fn isValid(self: Self) bool { if (self.root == NullId) { return true; } const root = self.buf.getNoCheck(self.root); if (root.color != .Black) { return false; } var black_cnt: u32 = undefined; return self.isValid2(self.root, &black_cnt); } fn isValid2(self: Self, id: OptId, out_black_cnt: *u32) bool { if (id == NullId) { out_black_cnt.* = 1; return true; } const node = self.buf.getNoCheck(id); if (node.color == .Red) { // Red node. Both children must be black. if (node.left != NullId) { const left = self.buf.getNoCheck(node.left); if (left.color != .Black) { return false; } } if (node.right != NullId) { const right = self.buf.getNoCheck(node.right); if (right.color != .Black) { return false; } } } var left_black_cnt: u32 = undefined; if (!self.isValid2(node.left, &left_black_cnt)) { return false; } var right_black_cnt: u32 = undefined; if (!self.isValid2(node.right, &right_black_cnt)) { return false; } if (left_black_cnt != right_black_cnt) { return false; } if (node.color == .Black) { out_black_cnt.* = left_black_cnt + 1; } else { out_black_cnt.* = left_black_cnt; } return true; } fn dump(self: Self) void { self.dump2(self.root); } fn dump2(self: Self, id: Id) void { if (id == NullId) { return; } const node = self.buf.getNoCheck(id); log.debug("{}-{} -> {} {}", .{id, node.color, node.left, node.right}); self.dump2(node.left); self.dump2(node.right); } fn insertDetached(self: *Self, val: Value, color: Color) !Id { return try self.buf.add(.{ .left = NullId, .right = NullId, .color = color, .parent = NullId, .val = val, }); } fn attachLeft(self: *Self, attached_parent: Id, detached: Id) !void { const parent = self.buf.getPtrNoCheck(attached_parent); if (parent.left != NullId) { return error.CantAttach; } parent.left = detached; const left = self.buf.getPtrNoCheck(detached); left.parent = attached_parent; self.size += 1; } fn attachRight(self: *Self, attached_parent: Id, detached: Id) !void { const parent = self.buf.getPtrNoCheck(attached_parent); if (parent.right != NullId) { return error.CantAttach; } parent.right = detached; const right = self.buf.getPtrNoCheck(detached); right.parent = attached_parent; self.size += 1; } }; } fn testCompare(left: u32, right: u32, _: void) std.math.Order { if (left < right) { return .lt; } else if (left == right) { return .eq; } else if (left > right) { return .gt; } unreachable; } fn testCompareReverse(left: u32, right: u32, _: void) std.math.Order { return testCompare(right, left, {}); } test "getNext, getPrev" { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(10); const b = try tree.insert(5); const c = try tree.insert(15); try t.eq(tree.getNext(b).?, a); try t.eq(tree.getNext(a).?, c); try t.eq(tree.getNext(c), null); try t.eq(tree.getPrev(b), null); try t.eq(tree.getPrev(a).?, b); try t.eq(tree.getPrev(c).?, a); } test "Insert where rotations need to set reattached nodes to black." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(10); const b = try tree.insertDetached(9, .Black); const c = try tree.insertDetached(20, .Red); const d = try tree.insertDetached(8, .Red); const e = try tree.insertDetached(19, .Black); const f = try tree.insertDetached(21, .Black); const g = try tree.insertDetached(17, .Red); try tree.attachLeft(a, b); try tree.attachRight(a, c); try tree.attachLeft(b, d); try tree.attachLeft(c, e); try tree.attachRight(c, f); try tree.attachLeft(e, g); try t.eq(tree.isValid(), true); const h = try tree.insert(18); try t.eq(tree.isValid(), true); const vals = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(vals); try t.eqSlice(TestId, vals, &.{ d, b, a, g, h, e, c, f }); } test "Insert case #1: current node parent is black" { var tree = initTestTree(); defer tree.deinit(); const root = try tree.insert(10); const node = try tree.insert(9); try t.eq(tree.getNode(root).?.color, .Black); try t.eq(tree.getNode(root).?.left, node); try t.eq(tree.getNode(node).?.color, .Red); try t.eq(tree.getNode(node).?.parent, root); } test "Insert case #2/#3/#4: both parent and parent sibling are red" { var tree = initTestTree(); defer tree.deinit(); const root = try tree.insert(10); const parent = try tree.insert(9); const psibling = try tree.insert(11); const node = try tree.insert(8); try t.eq(tree.getNode(root).?.color, .Black); try t.eq(tree.getNode(root).?.left, parent); try t.eq(tree.getNode(root).?.right, psibling); try t.eq(tree.getNode(parent).?.color, .Black); try t.eq(tree.getNode(parent).?.left, node); try t.eq(tree.getNode(psibling).?.color, .Black); try t.eq(tree.getNode(node).?.color, .Red); try t.eq(tree.getNode(node).?.parent, parent); } test "Insert case #5: parent is red but parent sibling is black, node is inner grandchild" { var tree = initTestTree(); defer tree.deinit(); const root = try tree.insert(100); const parent = try tree.insert(50); _ = try tree.insert(150); _ = try tree.insert(25); const node = try tree.insert(75); _ = try tree.insert(80); _ = try tree.insert(70); _ = try tree.insert(60); try t.eq(tree.getNode(node).?.parent, TestNullId); try t.eq(tree.getNode(node).?.color, .Black); try t.eq(tree.getNode(node).?.right, root); try t.eq(tree.getNode(node).?.left, parent); try t.eq(tree.getNode(root).?.color, .Red); try t.eq(tree.getNode(root).?.parent, node); try t.eq(tree.getNode(parent).?.color, .Red); try t.eq(tree.getNode(parent).?.parent, node); } test "Insert case #6: parent is red but parent sibling is black, node is outer grandchild" { var tree = initTestTree(); defer tree.deinit(); const root = try tree.insert(100); const parent = try tree.insert(50); _ = try tree.insert(150); const node = try tree.insert(25); _ = try tree.insert(70); _ = try tree.insert(20); _ = try tree.insert(30); _ = try tree.insert(15); try t.eq(tree.getNode(parent).?.parent, TestNullId); try t.eq(tree.getNode(parent).?.color, .Black); try t.eq(tree.getNode(parent).?.right, root); try t.eq(tree.getNode(parent).?.left, node); try t.eq(tree.getNode(root).?.color, .Red); try t.eq(tree.getNode(root).?.parent, parent); try t.eq(tree.getNode(node).?.color, .Red); try t.eq(tree.getNode(node).?.parent, parent); } test "Insert in order." { var tree = initTestTree(); defer tree.deinit(); _ = try tree.insert(1); _ = try tree.insert(2); _ = try tree.insert(3); _ = try tree.insert(4); _ = try tree.insert(5); _ = try tree.insert(6); _ = try tree.insert(7); _ = try tree.insert(8); _ = try tree.insert(9); _ = try tree.insert(10); const vals = tree.allocValuesInOrder(t.alloc); defer t.alloc.free(vals); try t.eqSlice(TestId, vals, &.{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); } test "Insert in reverse order." { var tree = initTestTree(); defer tree.deinit(); _ = try tree.insert(10); _ = try tree.insert(9); _ = try tree.insert(8); _ = try tree.insert(7); _ = try tree.insert(6); _ = try tree.insert(5); _ = try tree.insert(4); _ = try tree.insert(3); _ = try tree.insert(2); _ = try tree.insert(1); const vals = tree.allocValuesInOrder(t.alloc); defer t.alloc.free(vals); try t.eqSlice(TestId, vals, &.{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); } test "inserting and looking up" { var tree = initTestTree(); defer tree.deinit(); const orig: u32 = 1000; const node_id = try tree.insert(orig); // Assert that identical value finds the same pointer try t.eq(tree.lookup(1000), node_id); // Assert that insert duplicate returns error. try t.expectError(tree.insert(1000), error.DuplicateKey); try t.eq(tree.lookup(1000), node_id); try t.eq(tree.get(node_id).?, orig); // Assert that if looking for a non-existing value, return null. try t.eq(tree.lookup(1234), null); } test "multiple inserts, followed by calling first and last" { // if (@import("builtin").arch == .aarch64) { // // TODO https://github.com/ziglang/zig/issues/3288 // return error.SkipZigTest; // } var tree = initTestTree(); defer tree.deinit(); _ = try tree.insert(0); _ = try tree.insert(1); _ = try tree.insert(2); const third_id = try tree.insert(3); try t.eq(tree.get(tree.first().?).?, 0); try t.eq(tree.get(tree.last().?).?, 3); try t.eq(tree.lookup(3), third_id); tree.sort({}, testCompareReverse) catch unreachable; try t.eq(tree.get(tree.first().?).?, 3); try t.eq(tree.get(tree.last().?).?, 0); try t.eq(tree.lookupCustom(3, {}, testCompareReverse), third_id); } test "Remove root with no children." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(10); try t.eq(tree.root, a); try tree.remove(a); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{}); } test "Remove root with left red child." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(10); const b = try tree.insert(5); try t.eq(tree.root, a); try t.eq(tree.getNode(a).?.left, b); try t.eq(tree.getNode(b).?.color, .Red); try tree.remove(a); try t.eq(tree.getNode(b).?.color, .Black); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ b }); } test "Remove root with right red child." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(10); const b = try tree.insert(15); try t.eq(tree.root, a); try t.eq(tree.getNode(a).?.right, b); try t.eq(tree.getNode(b).?.color, .Red); try tree.remove(a); try t.eq(tree.getNode(b).?.color, .Black); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ b }); } test "Remove root with two red children." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(10); const b = try tree.insert(5); const c = try tree.insert(15); try t.eq(tree.root, a); try t.eq(tree.getNode(a).?.left, b); try t.eq(tree.getNode(a).?.right, c); try t.eq(tree.getNode(b).?.color, .Red); try t.eq(tree.getNode(c).?.color, .Red); try tree.remove(a); try t.eq(tree.root, c); try t.eq(tree.getNode(c).?.color, .Black); try t.eq(tree.getNode(c).?.left, b); try t.eq(tree.getNode(b).?.color, .Red); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ b, c }); } test "Remove red non-root." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(10); const b = try tree.insert(5); try t.eq(tree.root, a); try t.eq(tree.getNode(a).?.left, b); try t.eq(tree.getNode(b).?.color, .Red); try tree.remove(b); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ a }); } test "Remove black non-root with left red child." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(3); const b = try tree.insert(2); const c = try tree.insert(4); const d = try tree.insert(1); try t.eq(tree.root, a); try t.eq(tree.getNode(b).?.color, .Black); try t.eq(tree.getNode(d).?.color, .Red); try tree.remove(b); try t.eq(tree.getNode(d).?.parent, a); try t.eq(tree.getNode(d).?.color, .Black); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ d, a, c }); } test "Remove black non-root with right red child." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(3); const b = try tree.insert(2); const c = try tree.insert(4); const d = try tree.insert(5); try t.eq(tree.root, a); try t.eq(tree.getNode(c).?.color, .Black); try t.eq(tree.getNode(d).?.color, .Red); try tree.remove(c); try t.eq(tree.getNode(d).?.parent, a); try t.eq(tree.getNode(d).?.color, .Black); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ b, a, d }); } test "Remove non-root with double black case: Parent is red, right sibling is black, and sibling's children are black." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(15); const b = try tree.insert(10); const c = try tree.insert(20); const d = try tree.insert(17); const e = try tree.insert(23); const f = try tree.insert(25); try tree.remove(f); try t.eq(tree.getNode(c).?.color, .Red); try t.eq(tree.getNode(d).?.color, .Black); try t.eq(tree.getNode(e).?.color, .Black); try t.eq(tree.getNode(e).?.left, TestNullId); try t.eq(tree.getNode(e).?.right, TestNullId); try tree.remove(d); try t.eq(tree.getNode(c).?.color, .Black); try t.eq(tree.getNode(c).?.left, TestNullId); try t.eq(tree.getNode(e).?.color, .Red); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ b, a, c, e }); } test "Remove non-root with double black case: Parent is red, left sibling is black, and sibling's children are black." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(15); const b = try tree.insert(10); const c = try tree.insert(20); const d = try tree.insert(13); const e = try tree.insert(7); const f = try tree.insert(5); try tree.remove(f); try t.eq(tree.getNode(b).?.color, .Red); try t.eq(tree.getNode(d).?.color, .Black); try t.eq(tree.getNode(e).?.color, .Black); try t.eq(tree.getNode(e).?.left, TestNullId); try t.eq(tree.getNode(e).?.right, TestNullId); try tree.remove(d); try t.eq(tree.getNode(b).?.color, .Black); try t.eq(tree.getNode(b).?.right, TestNullId); try t.eq(tree.getNode(e).?.color, .Red); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ e, b, a, c }); } test "Remove non-root with double black case: Right sibling is black, and sibling's right child is red." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(10); const b = try tree.insert(5); const c = try tree.insert(15); const d = try tree.insert(20); try t.eq(tree.getNode(b).?.color, .Black); try t.eq(tree.getNode(c).?.color, .Black); try t.eq(tree.getNode(c).?.right, d); try t.eq(tree.getNode(d).?.color, .Red); try tree.remove(b); try t.eq(tree.root, c); try t.eq(tree.getNode(a).?.color, .Black); try t.eq(tree.getNode(c).?.color, .Black); try t.eq(tree.getNode(d).?.color, .Black); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ a, c, d }); } test "Remove non-root with double black case: Left sibling is black, and sibling's left child is red." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(10); const b = try tree.insert(5); const c = try tree.insert(15); const d = try tree.insert(4); try t.eq(tree.getNode(c).?.color, .Black); try t.eq(tree.getNode(b).?.color, .Black); try t.eq(tree.getNode(b).?.left, d); try t.eq(tree.getNode(d).?.color, .Red); try tree.remove(c); try t.eq(tree.root, b); try t.eq(tree.getNode(a).?.color, .Black); try t.eq(tree.getNode(b).?.color, .Black); try t.eq(tree.getNode(d).?.color, .Black); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ d, b, a }); } test "Remove non-root case 5: parent is red, right sibling is black, sibling's left child is red, sibling's right child is black." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(10); const b = try tree.insertDetached(10, .Red); const c = try tree.insertDetached(10, .Black); const d = try tree.insertDetached(10, .Black); const e = try tree.insertDetached(10, .Black); const f = try tree.insertDetached(10, .Red); try tree.attachLeft(a, b); try tree.attachRight(a, c); try tree.attachLeft(b, d); try tree.attachRight(b, e); try tree.attachLeft(e, f); try t.eq(tree.isValid(), true); t.setLogLevel(.debug); try tree.remove(d); try t.eq(tree.isValid(), true); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ b, f, e, a, c }); } test "Remove non-root with double black case: Parent is black, right sibling is red, sibling's children are black" { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(10); const b = try tree.insert(5); const c = try tree.insert(15); const d = try tree.insert(20); const e = try tree.insert(25); const f = try tree.insert(30); try t.eq(tree.getNode(b).?.color, .Black); try t.eq(tree.getNode(a).?.color, .Black); try t.eq(tree.getNode(d).?.color, .Red); try t.eq(tree.getNode(d).?.left, c); try t.eq(tree.getNode(d).?.right, e); try t.eq(tree.getNode(c).?.color, .Black); try t.eq(tree.getNode(e).?.color, .Black); try tree.remove(b); try t.eq(tree.root, d); try t.eq(tree.getNode(c).?.color, .Red); try t.eq(tree.getNode(a).?.color, .Black); try t.eq(tree.getNode(d).?.color, .Black); try t.eq(tree.getNode(e).?.color, .Black); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ a, c, d, e, f }); } test "Remove non-root with double black case: Parent is black, left sibling is red, sibling's children are black" { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(10); const b = try tree.insert(5); const c = try tree.insert(15); const d = try tree.insert(4); const e = try tree.insert(3); const f = try tree.insert(2); try t.eq(tree.getNode(b).?.color, .Black); try t.eq(tree.getNode(a).?.color, .Black); try t.eq(tree.getNode(d).?.color, .Red); try t.eq(tree.getNode(d).?.left, e); try t.eq(tree.getNode(d).?.right, b); try t.eq(tree.getNode(e).?.color, .Black); try t.eq(tree.getNode(b).?.color, .Black); try tree.remove(c); try t.eq(tree.root, d); try t.eq(tree.getNode(b).?.color, .Red); try t.eq(tree.getNode(a).?.color, .Black); try t.eq(tree.getNode(d).?.color, .Black); try t.eq(tree.getNode(e).?.color, .Black); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ f, e, d, b, a }); } test "Remove non-root with double black case: Parent is black, right sibling is black, sibling's left child is red, sibling's right child is black." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(10); const b = try tree.insert(5); const c = try tree.insert(15); const d = try tree.insert(13); try t.eq(tree.getNode(b).?.color, .Black); try t.eq(tree.getNode(c).?.color, .Black); try t.eq(tree.getNode(c).?.left, d); try t.eq(tree.getNode(d).?.color, .Red); try tree.remove(b); try t.eq(tree.root, d); try t.eq(tree.getNode(c).?.color, .Black); try t.eq(tree.getNode(d).?.color, .Black); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ a, d, c }); } test "Remove non-root with double black case: Parent is black, left sibling is black, sibling's right child is red, sibling's left child is black." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(10); const b = try tree.insert(5); const c = try tree.insert(15); const d = try tree.insert(7); try t.eq(tree.getNode(c).?.color, .Black); try t.eq(tree.getNode(b).?.color, .Black); try t.eq(tree.getNode(b).?.right, d); try t.eq(tree.getNode(d).?.color, .Red); try tree.remove(c); try t.eq(tree.root, d); try t.eq(tree.getNode(b).?.color, .Black); try t.eq(tree.getNode(d).?.color, .Black); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ b, d, a }); } test "Remove non-root with double black case: Parent is black, right sibling is black, and sibling's children are black." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(15); const b = try tree.insert(10); const c = try tree.insert(20); const d = try tree.insert(5); try tree.remove(d); try t.eq(tree.getNode(a).?.color, .Black); try t.eq(tree.getNode(b).?.color, .Black); try t.eq(tree.getNode(c).?.color, .Black); try tree.remove(b); try t.eq(tree.root, a); try t.eq(tree.getNode(a).?.color, .Black); try t.eq(tree.getNode(c).?.color, .Red); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ a, c }); } test "Remove non-root with double black case: Parent is black, left sibling is black, and sibling's children are black." { var tree = initTestTree(); defer tree.deinit(); const a = try tree.insert(15); const b = try tree.insert(10); const c = try tree.insert(20); const d = try tree.insert(5); try tree.remove(d); try t.eq(tree.getNode(a).?.color, .Black); try t.eq(tree.getNode(b).?.color, .Black); try t.eq(tree.getNode(c).?.color, .Black); try tree.remove(c); try t.eq(tree.root, a); try t.eq(tree.getNode(a).?.color, .Black); try t.eq(tree.getNode(b).?.color, .Red); const node_ids = tree.allocNodeIdsInOrder(t.alloc); defer t.alloc.free(node_ids); try t.eqSlice(TestId, node_ids, &.{ b, a }); } fn initTestTree() RbTree(TestId, u32, void, testCompare) { return RbTree(TestId, u32, void, testCompare).init(t.alloc, {}); } const TestId = u32; const TestNullId = stdx.ds.CompactNull(TestId);
stdx/ds/rb_tree.zig
const kernel = @import("kernel.zig"); const PhysicalAddress = @This(); const Virtual = kernel.Virtual; const Physical = kernel.Physical; value: u64, pub var max: u64 = 0; pub var max_bit: u6 = 0; pub inline fn new(value: u64) PhysicalAddress { const physical_address = PhysicalAddress{ .value = value, }; if (!physical_address.is_valid()) { kernel.panic("physical address 0x{x} is invalid", .{physical_address.value}); } return physical_address; } pub inline fn identity_virtual_address(physical_address: PhysicalAddress) Virtual.Address { return physical_address.identity_virtual_address_extended(false); } pub inline fn identity_virtual_address_extended(physical_address: PhysicalAddress, comptime override: bool) Virtual.Address { if (!override and kernel.Virtual.initialized) kernel.TODO(@src()); return Virtual.Address.new(physical_address.value); } pub inline fn access_identity(physical_address: PhysicalAddress, comptime Ptr: type) Ptr { kernel.assert(@src(), !kernel.Virtual.initialized); return @intToPtr(Ptr, physical_address.identity_virtual_address().value); } pub inline fn access(physical_address: PhysicalAddress, comptime Ptr: type) Ptr { return if (kernel.Virtual.initialized) physical_address.access_higher_half(Ptr) else physical_address.access_identity(Ptr); } pub inline fn to_higher_half_virtual_address(physical_address: PhysicalAddress) Virtual.Address { return Virtual.Address.new(physical_address.value + kernel.higher_half_direct_map.value); } pub inline fn access_higher_half(physical_address: PhysicalAddress, comptime Ptr: type) Ptr { return @intToPtr(Ptr, physical_address.to_higher_half_virtual_address().value); } pub inline fn is_valid(physical_address: PhysicalAddress) bool { kernel.assert(@src(), physical_address.value != 0); kernel.assert(@src(), max_bit != 0); kernel.assert(@src(), max > 1000); return physical_address.value <= max; } pub inline fn page_up(physical_address: *PhysicalAddress) void { kernel.assert(@src(), physical_address.is_page_aligned()); physical_address.value += kernel.arch.page_size; } pub inline fn page_down(physical_address: *PhysicalAddress) void { kernel.assert(@src(), physical_address.is_page_aligned()); physical_address.value -= kernel.arch.page_size; } pub inline fn page_align_forward(physical_address: *PhysicalAddress) void { physical_address.value = kernel.align_forward(physical_address.value, kernel.arch.page_size); } pub inline fn page_align_backward(physical_address: *PhysicalAddress) void { physical_address.value = kernel.align_backward(physical_address.value, kernel.arch.page_size); } pub inline fn is_page_aligned(physical_address: PhysicalAddress) bool { return kernel.is_aligned(physical_address.value, kernel.arch.page_size); } pub inline fn belongs_to_region(physical_address: PhysicalAddress, region: Physical.Memory.Region) bool { return physical_address.value >= region.address.value and physical_address.value < region.address.value + region.size; } pub inline fn offset(physical_address: PhysicalAddress, asked_offset: u64) PhysicalAddress { return PhysicalAddress.new(physical_address.value + asked_offset); }
src/kernel/physical_address.zig
const std = @import("std"); const DW = std.dwarf; const assert = std.debug.assert; const testing = std.testing; // TODO: this is only tagged to facilitate the monstrosity. // Once packed structs work make it packed. pub const Instruction = union(enum) { R: packed struct { opcode: u7, rd: u5, funct3: u3, rs1: u5, rs2: u5, funct7: u7, }, I: packed struct { opcode: u7, rd: u5, funct3: u3, rs1: u5, imm0_11: u12, }, S: packed struct { opcode: u7, imm0_4: u5, funct3: u3, rs1: u5, rs2: u5, imm5_11: u7, }, B: packed struct { opcode: u7, imm11: u1, imm1_4: u4, funct3: u3, rs1: u5, rs2: u5, imm5_10: u6, imm12: u1, }, U: packed struct { opcode: u7, rd: u5, imm12_31: u20, }, J: packed struct { opcode: u7, rd: u5, imm12_19: u8, imm11: u1, imm1_10: u10, imm20: u1, }, // TODO: once packed structs work we can remove this monstrosity. pub fn toU32(self: Instruction) u32 { return switch (self) { .R => |v| @bitCast(u32, v), .I => |v| @bitCast(u32, v), .S => |v| @bitCast(u32, v), .B => |v| @intCast(u32, v.opcode) + (@intCast(u32, v.imm11) << 7) + (@intCast(u32, v.imm1_4) << 8) + (@intCast(u32, v.funct3) << 12) + (@intCast(u32, v.rs1) << 15) + (@intCast(u32, v.rs2) << 20) + (@intCast(u32, v.imm5_10) << 25) + (@intCast(u32, v.imm12) << 31), .U => |v| @bitCast(u32, v), .J => |v| @bitCast(u32, v), }; } fn rType(op: u7, fn3: u3, fn7: u7, rd: Register, r1: Register, r2: Register) Instruction { return Instruction{ .R = .{ .opcode = op, .funct3 = fn3, .funct7 = fn7, .rd = @enumToInt(rd), .rs1 = @enumToInt(r1), .rs2 = @enumToInt(r2), }, }; } // RISC-V is all signed all the time -- convert immediates to unsigned for processing fn iType(op: u7, fn3: u3, rd: Register, r1: Register, imm: i12) Instruction { const umm = @bitCast(u12, imm); return Instruction{ .I = .{ .opcode = op, .funct3 = fn3, .rd = @enumToInt(rd), .rs1 = @enumToInt(r1), .imm0_11 = umm, }, }; } fn sType(op: u7, fn3: u3, r1: Register, r2: Register, imm: i12) Instruction { const umm = @bitCast(u12, imm); return Instruction{ .S = .{ .opcode = op, .funct3 = fn3, .rs1 = @enumToInt(r1), .rs2 = @enumToInt(r2), .imm0_4 = @truncate(u5, umm), .imm5_11 = @truncate(u7, umm >> 5), }, }; } // Use significance value rather than bit value, same for J-type // -- less burden on callsite, bonus semantic checking fn bType(op: u7, fn3: u3, r1: Register, r2: Register, imm: i13) Instruction { const umm = @bitCast(u13, imm); assert(umm % 2 == 0); // misaligned branch target return Instruction{ .B = .{ .opcode = op, .funct3 = fn3, .rs1 = @enumToInt(r1), .rs2 = @enumToInt(r2), .imm1_4 = @truncate(u4, umm >> 1), .imm5_10 = @truncate(u6, umm >> 5), .imm11 = @truncate(u1, umm >> 11), .imm12 = @truncate(u1, umm >> 12), }, }; } // We have to extract the 20 bits anyway -- let's not make it more painful fn uType(op: u7, rd: Register, imm: i20) Instruction { const umm = @bitCast(u20, imm); return Instruction{ .U = .{ .opcode = op, .rd = @enumToInt(rd), .imm12_31 = umm, }, }; } fn jType(op: u7, rd: Register, imm: i21) Instruction { const umm = @bitCast(u21, imm); assert(umm % 2 == 0); // misaligned jump target return Instruction{ .J = .{ .opcode = op, .rd = @enumToInt(rd), .imm1_10 = @truncate(u10, umm >> 1), .imm11 = @truncate(u1, umm >> 11), .imm12_19 = @truncate(u8, umm >> 12), .imm20 = @truncate(u1, umm >> 20), }, }; } // The meat and potatoes. Arguments are in the order in which they would appear in assembly code. // Arithmetic/Logical, Register-Register pub fn add(rd: Register, r1: Register, r2: Register) Instruction { return rType(0b0110011, 0b000, 0b0000000, rd, r1, r2); } pub fn sub(rd: Register, r1: Register, r2: Register) Instruction { return rType(0b0110011, 0b000, 0b0100000, rd, r1, r2); } pub fn @"and"(rd: Register, r1: Register, r2: Register) Instruction { return rType(0b0110011, 0b111, 0b0000000, rd, r1, r2); } pub fn @"or"(rd: Register, r1: Register, r2: Register) Instruction { return rType(0b0110011, 0b110, 0b0000000, rd, r1, r2); } pub fn xor(rd: Register, r1: Register, r2: Register) Instruction { return rType(0b0110011, 0b100, 0b0000000, rd, r1, r2); } pub fn sll(rd: Register, r1: Register, r2: Register) Instruction { return rType(0b0110011, 0b001, 0b0000000, rd, r1, r2); } pub fn srl(rd: Register, r1: Register, r2: Register) Instruction { return rType(0b0110011, 0b101, 0b0000000, rd, r1, r2); } pub fn sra(rd: Register, r1: Register, r2: Register) Instruction { return rType(0b0110011, 0b101, 0b0100000, rd, r1, r2); } pub fn slt(rd: Register, r1: Register, r2: Register) Instruction { return rType(0b0110011, 0b010, 0b0000000, rd, r1, r2); } pub fn sltu(rd: Register, r1: Register, r2: Register) Instruction { return rType(0b0110011, 0b011, 0b0000000, rd, r1, r2); } // Arithmetic/Logical, Register-Register (32-bit) pub fn addw(rd: Register, r1: Register, r2: Register) Instruction { return rType(0b0111011, 0b000, rd, r1, r2); } pub fn subw(rd: Register, r1: Register, r2: Register) Instruction { return rType(0b0111011, 0b000, 0b0100000, rd, r1, r2); } pub fn sllw(rd: Register, r1: Register, r2: Register) Instruction { return rType(0b0111011, 0b001, 0b0000000, rd, r1, r2); } pub fn srlw(rd: Register, r1: Register, r2: Register) Instruction { return rType(0b0111011, 0b101, 0b0000000, rd, r1, r2); } pub fn sraw(rd: Register, r1: Register, r2: Register) Instruction { return rType(0b0111011, 0b101, 0b0100000, rd, r1, r2); } // Arithmetic/Logical, Register-Immediate pub fn addi(rd: Register, r1: Register, imm: i12) Instruction { return iType(0b0010011, 0b000, rd, r1, imm); } pub fn andi(rd: Register, r1: Register, imm: i12) Instruction { return iType(0b0010011, 0b111, rd, r1, imm); } pub fn ori(rd: Register, r1: Register, imm: i12) Instruction { return iType(0b0010011, 0b110, rd, r1, imm); } pub fn xori(rd: Register, r1: Register, imm: i12) Instruction { return iType(0b0010011, 0b100, rd, r1, imm); } pub fn slli(rd: Register, r1: Register, shamt: u6) Instruction { return iType(0b0010011, 0b001, rd, r1, shamt); } pub fn srli(rd: Register, r1: Register, shamt: u6) Instruction { return iType(0b0010011, 0b101, rd, r1, shamt); } pub fn srai(rd: Register, r1: Register, shamt: u6) Instruction { return iType(0b0010011, 0b101, rd, r1, (1 << 10) + shamt); } pub fn slti(rd: Register, r1: Register, imm: i12) Instruction { return iType(0b0010011, 0b010, rd, r1, imm); } pub fn sltiu(rd: Register, r1: Register, imm: u12) Instruction { return iType(0b0010011, 0b011, rd, r1, @bitCast(i12, imm)); } // Arithmetic/Logical, Register-Immediate (32-bit) pub fn addiw(rd: Register, r1: Register, imm: i12) Instruction { return iType(0b0011011, 0b000, rd, r1, imm); } pub fn slliw(rd: Register, r1: Register, shamt: u5) Instruction { return iType(0b0011011, 0b001, rd, r1, shamt); } pub fn srliw(rd: Register, r1: Register, shamt: u5) Instruction { return iType(0b0011011, 0b101, rd, r1, shamt); } pub fn sraiw(rd: Register, r1: Register, shamt: u5) Instruction { return iType(0b0011011, 0b101, rd, r1, (1 << 10) + shamt); } // Upper Immediate pub fn lui(rd: Register, imm: i20) Instruction { return uType(0b0110111, rd, imm); } pub fn auipc(rd: Register, imm: i20) Instruction { return uType(0b0010111, rd, imm); } // Load pub fn ld(rd: Register, offset: i12, base: Register) Instruction { return iType(0b0000011, 0b011, rd, base, offset); } pub fn lw(rd: Register, offset: i12, base: Register) Instruction { return iType(0b0000011, 0b010, rd, base, offset); } pub fn lwu(rd: Register, offset: i12, base: Register) Instruction { return iType(0b0000011, 0b110, rd, base, offset); } pub fn lh(rd: Register, offset: i12, base: Register) Instruction { return iType(0b0000011, 0b001, rd, base, offset); } pub fn lhu(rd: Register, offset: i12, base: Register) Instruction { return iType(0b0000011, 0b101, rd, base, offset); } pub fn lb(rd: Register, offset: i12, base: Register) Instruction { return iType(0b0000011, 0b000, rd, base, offset); } pub fn lbu(rd: Register, offset: i12, base: Register) Instruction { return iType(0b0000011, 0b100, rd, base, offset); } // Store pub fn sd(rs: Register, offset: i12, base: Register) Instruction { return sType(0b0100011, 0b011, base, rs, offset); } pub fn sw(rs: Register, offset: i12, base: Register) Instruction { return sType(0b0100011, 0b010, base, rs, offset); } pub fn sh(rs: Register, offset: i12, base: Register) Instruction { return sType(0b0100011, 0b001, base, rs, offset); } pub fn sb(rs: Register, offset: i12, base: Register) Instruction { return sType(0b0100011, 0b000, base, rs, offset); } // Fence // TODO: implement fence // Branch pub fn beq(r1: Register, r2: Register, offset: i13) Instruction { return bType(0b1100011, 0b000, r1, r2, offset); } pub fn bne(r1: Register, r2: Register, offset: i13) Instruction { return bType(0b1100011, 0b001, r1, r2, offset); } pub fn blt(r1: Register, r2: Register, offset: i13) Instruction { return bType(0b1100011, 0b100, r1, r2, offset); } pub fn bge(r1: Register, r2: Register, offset: i13) Instruction { return bType(0b1100011, 0b101, r1, r2, offset); } pub fn bltu(r1: Register, r2: Register, offset: i13) Instruction { return bType(0b1100011, 0b110, r1, r2, offset); } pub fn bgeu(r1: Register, r2: Register, offset: i13) Instruction { return bType(0b1100011, 0b111, r1, r2, offset); } // Jump pub fn jal(link: Register, offset: i21) Instruction { return jType(0b1101111, link, offset); } pub fn jalr(link: Register, offset: i12, base: Register) Instruction { return iType(0b1100111, 0b000, link, base, offset); } // System pub const ecall = iType(0b1110011, 0b000, .zero, .zero, 0x000); pub const ebreak = iType(0b1110011, 0b000, .zero, .zero, 0x001); }; // zig fmt: off pub const RawRegister = enum(u5) { x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22, x23, x24, x25, x26, x27, x28, x29, x30, x31, pub fn dwarfLocOp(reg: RawRegister) u8 { return @enumToInt(reg) + DW.OP_reg0; } }; pub const Register = enum(u5) { // 64 bit registers zero, // zero ra, // return address. caller saved sp, // stack pointer. callee saved. gp, // global pointer tp, // thread pointer t0, t1, t2, // temporaries. caller saved. s0, // s0/fp, callee saved. s1, // callee saved. a0, a1, // fn args/return values. caller saved. a2, a3, a4, a5, a6, a7, // fn args. caller saved. s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, // saved registers. callee saved. t3, t4, t5, t6, // caller saved pub fn parseRegName(name: []const u8) ?Register { if(std.meta.stringToEnum(Register, name)) |reg| return reg; if(std.meta.stringToEnum(RawRegister, name)) |rawreg| return @intToEnum(Register, @enumToInt(rawreg)); return null; } /// Returns the index into `callee_preserved_regs`. pub fn allocIndex(self: Register) ?u4 { inline for(callee_preserved_regs) |cpreg, i| { if(self == cpreg) return i; } return null; } pub fn dwarfLocOp(reg: Register) u8 { return @as(u8, @enumToInt(reg)) + DW.OP_reg0; } }; // zig fmt: on pub const callee_preserved_regs = [_]Register{ .s0, .s1, .s2, .s3, .s4, .s5, .s6, .s7, .s8, .s9, .s10, .s11, }; test "serialize instructions" { const Testcase = struct { inst: Instruction, expected: u32, }; const testcases = [_]Testcase{ .{ // add t6, zero, zero .inst = Instruction.add(.t6, .zero, .zero), .expected = 0b0000000_00000_00000_000_11111_0110011, }, .{ // sd s0, 0x7f(s0) .inst = Instruction.sd(.s0, 0x7f, .s0), .expected = 0b0000011_01000_01000_011_11111_0100011, }, .{ // bne s0, s1, 0x42 .inst = Instruction.bne(.s0, .s1, 0x42), .expected = 0b0_000010_01001_01000_001_0001_0_1100011, }, .{ // j 0x1a .inst = Instruction.jal(.zero, 0x1a), .expected = 0b0_0000001101_0_00000000_00000_1101111, }, .{ // ebreak .inst = Instruction.ebreak, .expected = 0b000000000001_00000_000_00000_1110011, }, }; for (testcases) |case| { const actual = case.inst.toU32(); testing.expectEqual(case.expected, actual); } }
src/codegen/riscv64.zig
const std = @import("std"); const gpa = std.heap.c_allocator; const fs = std.fs; const zig = std.zig; const known_folders = @import("known-folders"); const u = @import("./util/index.zig"); // // pub fn execute(args: [][]u8) !void { // const dir = try fs.path.join(gpa, &[_][]const u8{".zigmod", "deps"}); const top_module = try fetch_deps(dir, "zig.mod"); // const f = try fs.cwd().createFile("deps.zig", .{}); defer f.close(); const w = f.writer(); try w.writeAll("const std = @import(\"std\");\n"); try w.writeAll("const build = std.build;\n\n"); try w.print("const cache = \"{}\";\n\n", .{zig.fmtEscapes(dir)}); try w.writeAll( \\pub fn addAllTo(exe: *build.LibExeObjStep) void { \\ @setEvalBranchQuota(1_000_000); \\ for (packages) |pkg| { \\ exe.addPackage(pkg); \\ } \\ if (c_include_dirs.len > 0 or c_source_files.len > 0) { \\ exe.linkLibC(); \\ } \\ for (c_include_dirs) |dir| { \\ exe.addIncludeDir(dir); \\ } \\ inline for (c_source_files) |fpath| { \\ exe.addCSourceFile(fpath[1], @field(c_source_flags, fpath[0])); \\ } \\ for (system_libs) |lib| { \\ exe.linkSystemLibrary(lib); \\ } \\} \\ \\fn get_flags(comptime index: usize) []const u8 { \\ return @field(c_source_flags, _paths[index]); \\} \\ \\ ); const list = &std.ArrayList(u.Module).init(gpa); try collect_pkgs(top_module, list); try w.writeAll("pub const _ids = .{\n"); try print_ids(w, list.items); try w.writeAll("};\n\n"); try w.writeAll("pub const _paths = .{\n"); try print_paths(w, list.items); try w.writeAll("};\n\n"); try w.writeAll("pub const package_data = struct {\n"); const duped = &std.ArrayList(u.Module).init(gpa); for (list.items) |mod| { if (mod.main.len > 0 and mod.clean_path.len > 0) { try duped.append(mod); } } try print_pkg_data_to(w, duped, &std.ArrayList(u.Module).init(gpa)); try w.writeAll("};\n\n"); try w.writeAll("pub const packages = "); try print_deps(w, dir, top_module, 0, true); try w.writeAll(";\n\n"); try w.writeAll("pub const pkgs = "); try print_deps(w, dir, top_module, 0, false); try w.writeAll(";\n\n"); try w.writeAll("pub const c_include_dirs = &[_][]const u8{\n"); try print_incl_dirs_to(w, list.items); try w.writeAll("};\n\n"); try w.writeAll("pub const c_source_flags = struct {\n"); try print_csrc_flags_to(w, list.items); try w.writeAll("};\n\n"); try w.writeAll("pub const c_source_files = &[_][2][]const u8{\n"); try print_csrc_dirs_to(w, list.items); try w.writeAll("};\n\n"); try w.writeAll("pub const system_libs = &[_][]const u8{\n"); try print_sys_libs_to(w, list.items, &std.ArrayList([]const u8).init(gpa)); try w.writeAll("};\n\n"); } fn fetch_deps(dir: []const u8, mpath: []const u8) anyerror!u.Module { const m = try u.ModFile.init(gpa, mpath); const moduledeps = &std.ArrayList(u.Module).init(gpa); var moddir: []const u8 = undefined; for (m.deps) |d| { const p = try fs.path.join(gpa, &[_][]const u8{dir, try d.clean_path()}); const pv = try fs.path.join(gpa, &[_][]const u8{dir, try d.clean_path_v()}); u.print("fetch: {s}: {s}: {s}", .{m.name, @tagName(d.type), d.path}); moddir = p; switch (d.type) { .system_lib => { // no op }, .git => blk: { if (!try u.does_folder_exist(p)) { try d.type.pull(d.path, p); } else { try d.type.update(p, d.path); } if (d.version.len > 0) { const vers = u.parse_split(u.GitVersionType, "-").do(d.version) catch |e| switch (e) { error.IterEmpty => unreachable, error.NoMemberFound => { const vtype = d.version[0..std.mem.indexOf(u8, d.version, "-").?]; u.assert(false, "fetch: git: version type '{s}' is invalid.", .{vtype}); unreachable; }, }; if (try u.does_folder_exist(pv)) { if (vers.id == .branch) { try d.type.update(p, d.path); } moddir = pv; break :blk; } if ((try u.run_cmd(p, &[_][]const u8{"git", "checkout", vers.string})) > 0) { u.assert(false, "fetch: git: {s}: {s} {s} does not exist", .{d.path, @tagName(vers.id), vers.string}); } else { _ = try u.run_cmd(p, &[_][]const u8{"git", "checkout", "-"}); } try d.type.pull(d.path, pv); _ = try u.run_cmd(pv, &[_][]const u8{"git", "checkout", vers.string}); if (vers.id != .branch) { const pvd = try std.fs.cwd().openDir(pv, .{}); try pvd.deleteTree(".git"); } moddir = pv; } }, .hg => { if (!try u.does_folder_exist(p)) { try d.type.pull(d.path, p); } else { try d.type.update(p, d.path); } }, .http => blk: { if (try u.does_folder_exist(pv)) { moddir = pv; break :blk; } const file_name = try u.last(try u.split(d.path, "/")); if (d.version.len > 0) { const file_path = try std.fs.path.join(gpa, &[_][]const u8{pv, file_name}); try d.type.pull(d.path, pv); if (try u.validate_hash(try u.last(try u.split(pv, "/")), file_path)) { try std.fs.deleteFileAbsolute(file_path); moddir = pv; break :blk; } try u.rm_recv(pv); u.assert(false, "{s} does not match hash {s}", .{d.path, d.version}); break :blk; } if (try u.does_folder_exist(p)) { try u.rm_recv(p); } const file_path = try std.fs.path.join(gpa, &[_][]const u8{p, file_name}); try d.type.pull(d.path, p); try std.fs.deleteFileAbsolute(file_path); }, } switch (d.type) { .system_lib => { if (d.is_for_this()) try moduledeps.append(u.Module{ .is_sys_lib = true, .id = "", .name = d.path, .only_os = d.only_os, .except_os = d.except_os, .main = "", .c_include_dirs = &[_][]const u8{}, .c_source_flags = &[_][]const u8{}, .c_source_files = &[_][]const u8{}, .deps = &[_]u.Module{}, .clean_path = "", }); }, else => blk: { var dd = try fetch_deps(dir, try u.concat(&[_][]const u8{moddir, "/zig.mod"})) catch |e| switch (e) { error.FileNotFound => { if (d.main.len > 0 or d.c_include_dirs.len > 0 or d.c_source_files.len > 0) { var mod_from = try u.Module.from(d); mod_from.id = try u.random_string(48); mod_from.clean_path = u.trim_prefix(moddir, dir)[1..]; if (mod_from.is_for_this()) try moduledeps.append(mod_from); } break :blk; }, else => e, }; dd.clean_path = u.trim_prefix(moddir, dir)[1..]; if (dd.id.len == 0) dd.id = try u.random_string(48); if (d.name.len > 0) dd.name = d.name; if (d.main.len > 0) dd.main = d.main; if (d.c_include_dirs.len > 0) dd.c_include_dirs = d.c_include_dirs; if (d.c_source_flags.len > 0) dd.c_source_flags = d.c_source_flags; if (d.c_source_files.len > 0) dd.c_source_files = d.c_source_files; if (d.only_os.len > 0) dd.only_os = d.only_os; if (d.except_os.len > 0) dd.except_os = d.except_os; if (dd.is_for_this()) try moduledeps.append(dd); }, } } return u.Module{ .is_sys_lib = false, .id = m.id, .name = m.name, .main = m.main, .c_include_dirs = m.c_include_dirs, .c_source_flags = m.c_source_flags, .c_source_files = m.c_source_files, .deps = moduledeps.items, .clean_path = "", .only_os = &[_][]const u8{}, .except_os = &[_][]const u8{}, }; } fn print_ids(w: fs.File.Writer, list: []u.Module) !void { for (list) |mod| { if (mod.is_sys_lib) { continue; } if (mod.clean_path.len == 0) { try w.print(" \"\",\n", .{}); } else { try w.print(" \"{}\",\n", .{zig.fmtEscapes(mod.id)}); } } } fn print_paths(w: fs.File.Writer, list: []u.Module) !void { for (list) |mod| { if (mod.is_sys_lib) { continue; } if (mod.clean_path.len == 0) { try w.print(" \"\",\n", .{}); } else { const s = fs.path.sep_str; try w.print(" \"{}{}{}\",\n", .{zig.fmtEscapes(s), zig.fmtEscapes(mod.clean_path), zig.fmtEscapes(s)}); } } } fn print_deps(w: fs.File.Writer, dir: []const u8, m: u.Module, tabs: i32, array: bool) anyerror!void { if (m.has_no_zig_deps() and tabs > 0) { try w.print("null", .{}); return; } if (array) { try u.print_all(w, .{"&[_]build.Pkg{"}, true); } else { try u.print_all(w, .{"struct {"}, true); } const t = " "; const r = try u.repeat(t, tabs); for (m.deps) |d, i| { if (d.main.len == 0) { continue; } if (!array) { try w.print(" pub const {} = packages[{}];\n", .{zig.fmtId(d.name), i}); } else { try w.print(" package_data._{s},\n", .{d.id}); } } try w.writeAll(r); try w.writeAll("}"); } fn print_incl_dirs_to(w: fs.File.Writer, list: []u.Module) !void { for (list) |mod, i| { if (mod.is_sys_lib) { continue; } for (mod.c_include_dirs) |it| { if (i > 0) { try w.print(" cache ++ _paths[{}] ++ \"{}\",\n", .{i, zig.fmtEscapes(it)}); } else { try w.writeAll(" \"\",\n"); } } } } fn print_csrc_dirs_to(w: fs.File.Writer, list: []u.Module) !void { for (list) |mod, i| { if (mod.is_sys_lib) { continue; } for (mod.c_source_files) |it| { try w.writeAll(" [_][]const u8{"); if (i > 0) { try w.print("_ids[{}], cache ++ _paths[{}] ++ \"{}\"", .{i, i, zig.fmtEscapes(it)}); } else { try w.print("\"{}\", \".{}/{}\"", .{zig.fmtEscapes(mod.clean_path), zig.fmtEscapes(mod.clean_path), zig.fmtEscapes(it)}); } try w.writeAll("},\n"); } } } fn print_csrc_flags_to(w: fs.File.Writer, list: []u.Module) !void { for (list) |mod, i| { if (mod.is_sys_lib) { continue; } if (i == 0) { try w.writeAll(" pub const @\"\" = "); try w.writeAll("&[_][]const u8{};\n"); } else { try w.print(" pub const {} = ", .{zig.fmtId(mod.id)}); try w.writeAll("&[_][]const u8{"); for (mod.c_source_flags) |it| { try w.print("\"{}\",", .{zig.fmtEscapes(it)}); } try w.writeAll("};\n"); } } } fn print_sys_libs_to(w: fs.File.Writer, list: []u.Module, list2: *std.ArrayList([]const u8)) !void { for (list) |mod| { if (!mod.is_sys_lib) { continue; } try w.print(" \"{}\",\n", .{zig.fmtEscapes(mod.name)}); } } fn collect_pkgs(mod: u.Module, list: *std.ArrayList(u.Module)) anyerror!void { // if (u.list_contains_gen(u.Module, list, mod)) { return; } try list.append(mod); for (mod.deps) |d| { try collect_pkgs(d, list); } } fn print_pkg_data_to(w: fs.File.Writer, list: *std.ArrayList(u.Module), list2: *std.ArrayList(u.Module)) anyerror!void { var i: usize = 0; while (i < list.items.len) : (i += 1) { const mod = list.items[i]; if (contains_all(mod.deps, list2)) { try w.print(" pub const _{} = build.Pkg{{ .name = \"{}\", .path = cache ++ \"/{}/{}\", .dependencies = &[_]build.Pkg{{", .{mod.id, zig.fmtEscapes(mod.name), zig.fmtEscapes(mod.clean_path), zig.fmtEscapes(mod.main)}); for (mod.deps) |d| { if (d.main.len > 0) { try w.print(" _{},", .{d.id}); } } try w.writeAll(" } };\n"); try list2.append(mod); _ = list.orderedRemove(i); break; } } if (list.items.len > 0) { try print_pkg_data_to(w, list, list2); } } /// returns if all of the zig modules in needles are in haystack fn contains_all(needles: []u.Module, haystack: *std.ArrayList(u.Module)) bool { for (needles) |item| { if (item.main.len > 0 and !u.list_contains_gen(u.Module, haystack, item)) { return false; } } return true; }
src/cmd_fetch.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/day12.txt"); //const data = "start-A\nstart-b\nA-c\nA-b\nb-d\nA-end\nb-end"; //const data ="dc-end\nHN-start\nstart-kj\ndc-start\ndc-HN\nLN-dc\nHN-end\nkj-sa\nkj-HN\nkj-dc"; //const data = "fs-end\nhe-DX\nfs-he\nstart-DX\npj-DX\nend-zg\nzg-sl\nzg-pj\npj-he\nRW-he\nfs-DX\npj-RW\nzg-RW\nstart-pj\nhe-WI\nzg-he\npj-fs\nstart-RW"; const Size = enum { big, small, }; const Cave = struct { size: Size, name: []const u8, connections: []*Cave = undefined, visits: usize = 0, }; pub fn main() !void { // Scan the input to build a slice of caves var caves: []Cave = blk: { var lines = tokenize(u8, data, "\r\n-"); var map = StrMap(Cave).init(gpa); defer map.deinit(); while (lines.next()) |name| { const cave = Cave{ .size = if (name[0] >= 'a') .small else .big, .name = name, }; try map.put(name, cave); } var list = List(Cave).init(gpa); var iter = map.iterator(); while (iter.next()) |cave| { try list.append(cave.value_ptr.*); } break :blk list.toOwnedSlice(); }; // Put pointers to each cave into a hashmap indexed by name var cave_names = StrMap(*Cave).init(gpa); for (caves) |*cave| { try cave_names.put(cave.name, cave); } // For each cave, scan the input to populate the connections field for (caves) |*cave| { var cave_connection_list = List(*Cave).init(gpa); var lines = tokenize(u8, data, "\r\n"); while (lines.next()) |line| { var cols = tokenize(u8, line, "-"); const fst = cols.next().?; const snd = cols.next().?; if (std.mem.eql(u8, cave.name, fst)) { const cave_ptr = cave_names.get(snd).?; try cave_connection_list.append(cave_ptr); } else if (std.mem.eql(u8, cave.name, snd)) { const cave_ptr = cave_names.get(fst).?; try cave_connection_list.append(cave_ptr); } } cave.connections = cave_connection_list.toOwnedSlice(); } var part1: usize = 0; var part2: usize = 0; const Move = struct { cave: *Cave, index: ?usize = null, }; var stack = List(Move).init(gpa); defer stack.deinit(); try stack.append(Move{ .cave = cave_names.get("start").? }); backtrack: while (stack.items.len != 0) : ({ const move = stack.pop(); move.cave.visits -= 1; }) { while (true) { const move: *Move = &stack.items[stack.items.len - 1]; const cave: *Cave = move.cave; if (move.index) |*index| { index.* += 1; } else { cave.visits += 1; move.index = 0; } if (move.index.? >= cave.connections.len) continue :backtrack; if (std.mem.eql(u8, cave.name, "end")) { // check if any small caves were visited twice const visit_small_twice = blk: { var ret = false; for (caves) |c| { if (c.size == .small and c.visits > 1) { ret = true; break; } } break :blk ret; }; if (!visit_small_twice) part1 += 1; part2 += 1; continue :backtrack; } if (cave.size == Size.small and cave.visits > 2) continue :backtrack; if (cave.size == Size.small and cave.visits > 1) { if (std.mem.eql(u8, cave.name, "start")) continue :backtrack; // check for any other small caves with visits > 1 for (caves) |*c| { if (c.size == .small and c != cave and c.visits > 1) continue :backtrack; } } // go to next cave const next_cave = cave.connections[move.index.?]; try stack.append(Move{ .cave = next_cave }); } } assert(part1 == 4775); assert(part2 == 152480); print("{}\n", .{part1}); print("{}\n", .{part2}); } // 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/day12.zig
const std = @import("std"); const string = []const u8; const print = std.debug.print; const expect = @import("std").testing.expect; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = &gpa.allocator; //-------------------------------------------------------------------------------- test "basic" { print("Basic test\n", .{}); } //-------------------------------------------------------------------------------- // async transfers control to the function // suspend returns control to the frame var foo: i32 = 1; test "suspend with no resume" { var frame = async func(); //1 expect(foo == 2); //4 } fn func() void { foo += 1; //2 suspend; //3 foo += 1; //never reached! } //-------------------------------------------------------------------------------- // async transfers control to the function // suspend retruns control to the frame // resume frame returns control to the func // return returns control to the frame var bar: i32 = 1; test "suspend with resume" { var frame = async func2(); //1 resume frame; //4 expect(bar == 3); //6 } fn func2() void { bar += 1; //2 suspend; //3 bar += 1; //5 } //-------------------------------------------------------------------------------- // note that func3 has no async control / suspend / resume // async transfers control to the function // return returns control to the frame // await waits for the function to return test "async / await" { var frame = async func3(); expect(await frame == 5); } fn func3() u32 { return 5; } //-------------------------------------------------------------------------------- // use nonsuspend to assert no async behaviour // compiler will detect illegal usage fn doTicksDuration(ticker: *u32) i64 { const start = std.time.milliTimestamp(); while (ticker.* > 0) { suspend; ticker.* -= 1; } return std.time.milliTimestamp() - start; } pub fn test_breakout(start: u32) !void { var ticker: u32 = start; const duration = nosuspend doTicksDuration(&ticker); print("duration = {}\n", .{duration}); } test "break out" { try test_breakout(0); // try test_breakout(1); // will throw comptime error because it can suspend } //-------------------------------------------------------------------------------- // @Frame gets a ptr to an async frame fn add(a: i32, b: i32) i64 { return a + b; } test "@Frame" { var frame: @Frame(add) = async add(1, 2); expect(await frame == 3); } //-------------------------------------------------------------------------------- // @frame gets a ptr to self fn double(value: u8) u9 { suspend { resume @frame(); } return value * 2; } test "@frame 1" { var f = async double(1); expect(nosuspend await f == 2); } //-------------------------------------------------------------------------------- // passing the value from @frame to another function to resume us fn callLater(comptime laterFn: fn () void, ms: u64) void { suspend { wakeupLater(@frame(), ms); } laterFn(); } fn wakeupLater(frame: anyframe, ms: u64) void { std.time.sleep(ms * std.time.ns_per_ms); resume frame; } fn alarm() void { std.debug.print("Time's Up!\n", .{}); } test "@frame 2" { nosuspend callLater(alarm, 1000); } //-------------------------------------------------------------------------------- // using ->T to restore the type info otherwise lost by the use of anytype fn zero(comptime x: anytype) x { return 0; } fn awaiter(x: anyframe->f32) f32 { return nosuspend await x; } test "anyframe->T" { var frame = async zero(f32); expect(awaiter(&frame) == 0); }
src/test_async.zig
const std = @import("std"); const warn = std.debug.warn; const Allocator = std.mem.Allocator; const Stream = std.io.OutStream(std.os.WriteError); //showcases conventional method of implementing //interfaces in zig as of 0.5.0 const Animal = struct { const Self = @This(); const SpeakFn = fn(*const Self, *Stream) void; speakFn: SpeakFn, fn speak(self: *const Self, stream: *Stream) void { return self.speakFn(self,stream); } }; const Dog = struct { const Self = @This(); animal: Animal, name: []const u8, allocator: *Allocator, fn init(allocator: *Allocator, name: []const u8) !Self { const animal = Animal { .speakFn = speak, }; const buf = try allocator.alloc(u8,name.len); std.mem.copy(u8,buf,name); return Self { .animal = animal, .name = buf, .allocator = allocator, }; } fn deinit(self: Self) void { self.allocator.free(self.name); } fn speak(animal: *const Animal, stream: *Stream) void { const self = @fieldParentPtr(Self,"animal",animal); stream.print("{} says {}\n",self.name,"Woof!") catch {}; } }; const Cat = struct { const Self = @This(); animal: Animal, name: []const u8, allocator: *Allocator, fn init(allocator: *Allocator, name: []const u8) !Self { const animal = Animal { .speakFn = speak, }; const buf = try allocator.alloc(u8,name.len); std.mem.copy(u8,buf,name); return Self { .animal = animal, .name = buf, .allocator = allocator, }; } fn deinit(self: Self ) void { self.allocator.free(self.name); } fn speak(animal: *const Animal, stream: *Stream) void { const self = @fieldParentPtr(Self,"animal",animal); stream.print("{} says {}\n",self.name,"Meow!") catch {}; } }; pub fn main() !void { const allocator = std.heap.direct_allocator; var stdout = &(try std.io.getStdOut()).outStream().stream; //var stdout_state = (try std.io.getStdOut()).outStream(); //var stdout = &stdout_state.stream; const dog_state = try Dog.init(allocator,"Jeff"); defer dog_state.deinit(); const dog = &dog_state.animal; const cat_state = try Cat.init(allocator,"Will"); defer cat_state.deinit(); const cat = &cat_state.animal; dog.speak(stdout); cat.speak(stdout); }
interface_test.zig
const std = @import("std"); const panic = std.debug.panic; const print = std.debug.print; const fmt = std.fmt; const ascii = std.ascii; const alloc = std.heap.page_allocator; const ArrayList = std.ArrayList; const HashMap = std.AutoHashMap; const PREAMBLE_SIZE: usize = 25; pub fn main() !void { var numbers = ArrayList(i64).init(alloc); var it = std.mem.tokenize(@embedFile("../inputs/day_09"), "\n"); while (it.next()) |line| { const number = try fmt.parseInt(i64, line, 0); try numbers.append(number); } var bad_number: i64 = 0; var weakness: ?i64 = null; for (numbers.items) |current_number, i| { var pairs = HashMap(i64, bool).init(alloc); defer pairs.deinit(); if (i < PREAMBLE_SIZE) { continue; } var slice = numbers.items[i - PREAMBLE_SIZE .. i]; try fill_data(&pairs, slice); if (pairs.get(current_number) == null) { bad_number = current_number; weakness = find_weakness(numbers.items[0..i], bad_number); break; } } print("ANSWER PART 1: {}\n", .{bad_number}); print("ANSWER PART 2: {}\n", .{weakness.?}); } fn fill_data(pairs: *HashMap(i64, bool), data: []const i64) !void { for (data) |a, i| { for (data) |b, j| { if (i == j) continue; try pairs.put(a + b, true); } } } fn find_weakness(data: []const i64, number: i64) ?i64 { var acc: i64 = 0; var begin: ?usize = null; var end: ?usize = null; for (data) |starter, i| { if ((begin != null and end != null) or starter >= number) break; acc = 0; begin = i; for (data[i..]) |current, j| { acc += current; if (acc == number) { end = i + j + 1; break; } } } if (begin != null and end != null) { var min: i64 = std.math.maxInt(i64); var max: i64 = std.math.minInt(i64); for (data[begin.?..end.?]) |n| { min = std.math.min(min, n); max = std.math.max(max, n); } return (max + min); } return null; }
src/09.zig
const std = @import("std"); const math = std.math; const testing = std.testing; pub fn __logh(a: f16) callconv(.C) f16 { // TODO: more efficient implementation return @floatCast(f16, logf(a)); } pub fn logf(x_: f32) callconv(.C) f32 { const ln2_hi: f32 = 6.9313812256e-01; const ln2_lo: f32 = 9.0580006145e-06; const Lg1: f32 = 0xaaaaaa.0p-24; const Lg2: f32 = 0xccce13.0p-25; const Lg3: f32 = 0x91e9ee.0p-25; const Lg4: f32 = 0xf89e26.0p-26; var x = x_; var ix = @bitCast(u32, x); var k: i32 = 0; // x < 2^(-126) if (ix < 0x00800000 or ix >> 31 != 0) { // log(+-0) = -inf if (ix << 1 == 0) { return -math.inf(f32); } // log(-#) = nan if (ix >> 31 != 0) { return math.nan(f32); } // subnormal, scale x k -= 25; x *= 0x1.0p25; ix = @bitCast(u32, x); } else if (ix >= 0x7F800000) { return x; } else if (ix == 0x3F800000) { return 0; } // x into [sqrt(2) / 2, sqrt(2)] ix += 0x3F800000 - 0x3F3504F3; k += @intCast(i32, ix >> 23) - 0x7F; ix = (ix & 0x007FFFFF) + 0x3F3504F3; x = @bitCast(f32, ix); const f = x - 1.0; const s = f / (2.0 + f); const z = s * s; const w = z * z; const t1 = w * (Lg2 + w * Lg4); const t2 = z * (Lg1 + w * Lg3); const R = t2 + t1; const hfsq = 0.5 * f * f; const dk = @intToFloat(f32, k); return s * (hfsq + R) + dk * ln2_lo - hfsq + f + dk * ln2_hi; } pub fn log(x_: f64) callconv(.C) f64 { const ln2_hi: f64 = 6.93147180369123816490e-01; const ln2_lo: f64 = 1.90821492927058770002e-10; const Lg1: f64 = 6.666666666666735130e-01; const Lg2: f64 = 3.999999999940941908e-01; const Lg3: f64 = 2.857142874366239149e-01; const Lg4: f64 = 2.222219843214978396e-01; const Lg5: f64 = 1.818357216161805012e-01; const Lg6: f64 = 1.531383769920937332e-01; const Lg7: f64 = 1.479819860511658591e-01; var x = x_; var ix = @bitCast(u64, x); var hx = @intCast(u32, ix >> 32); var k: i32 = 0; if (hx < 0x00100000 or hx >> 31 != 0) { // log(+-0) = -inf if (ix << 1 == 0) { return -math.inf(f64); } // log(-#) = nan if (hx >> 31 != 0) { return math.nan(f64); } // subnormal, scale x k -= 54; x *= 0x1.0p54; hx = @intCast(u32, @bitCast(u64, ix) >> 32); } else if (hx >= 0x7FF00000) { return x; } else if (hx == 0x3FF00000 and ix << 32 == 0) { return 0; } // x into [sqrt(2) / 2, sqrt(2)] hx += 0x3FF00000 - 0x3FE6A09E; k += @intCast(i32, hx >> 20) - 0x3FF; hx = (hx & 0x000FFFFF) + 0x3FE6A09E; ix = (@as(u64, hx) << 32) | (ix & 0xFFFFFFFF); x = @bitCast(f64, ix); const f = x - 1.0; const hfsq = 0.5 * f * f; const s = f / (2.0 + f); const z = s * s; const w = z * z; const t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); const t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); const R = t2 + t1; const dk = @intToFloat(f64, k); return s * (hfsq + R) + dk * ln2_lo - hfsq + f + dk * ln2_hi; } pub fn __logx(a: f80) callconv(.C) f80 { // TODO: more efficient implementation return @floatCast(f80, logq(a)); } pub fn logq(a: f128) callconv(.C) f128 { // TODO: more correct implementation return log(@floatCast(f64, a)); } pub fn logl(x: c_longdouble) callconv(.C) c_longdouble { switch (@typeInfo(c_longdouble).Float.bits) { 16 => return __logh(x), 32 => return logf(x), 64 => return log(x), 80 => return __logx(x), 128 => return logq(x), else => @compileError("unreachable"), } } test "ln32" { const epsilon = 0.000001; try testing.expect(math.approxEqAbs(f32, logf(0.2), -1.609438, epsilon)); try testing.expect(math.approxEqAbs(f32, logf(0.8923), -0.113953, epsilon)); try testing.expect(math.approxEqAbs(f32, logf(1.5), 0.405465, epsilon)); try testing.expect(math.approxEqAbs(f32, logf(37.45), 3.623007, epsilon)); try testing.expect(math.approxEqAbs(f32, logf(89.123), 4.490017, epsilon)); try testing.expect(math.approxEqAbs(f32, logf(123123.234375), 11.720941, epsilon)); } test "ln64" { const epsilon = 0.000001; try testing.expect(math.approxEqAbs(f64, log(0.2), -1.609438, epsilon)); try testing.expect(math.approxEqAbs(f64, log(0.8923), -0.113953, epsilon)); try testing.expect(math.approxEqAbs(f64, log(1.5), 0.405465, epsilon)); try testing.expect(math.approxEqAbs(f64, log(37.45), 3.623007, epsilon)); try testing.expect(math.approxEqAbs(f64, log(89.123), 4.490017, epsilon)); try testing.expect(math.approxEqAbs(f64, log(123123.234375), 11.720941, epsilon)); } test "ln32.special" { try testing.expect(math.isPositiveInf(logf(math.inf(f32)))); try testing.expect(math.isNegativeInf(logf(0.0))); try testing.expect(math.isNan(logf(-1.0))); try testing.expect(math.isNan(logf(math.nan(f32)))); } test "ln64.special" { try testing.expect(math.isPositiveInf(log(math.inf(f64)))); try testing.expect(math.isNegativeInf(log(0.0))); try testing.expect(math.isNan(log(-1.0))); try testing.expect(math.isNan(log(math.nan(f64)))); }
lib/compiler_rt/log.zig
const std = @import("std"); const builtin = std.builtin; const build = std.build; const ArrayList = std.ArrayList; const fmt = std.fmt; const mem = std.mem; const fs = std.fs; const warn = std.debug.warn; const Mode = builtin.Mode; pub const CompareOutputContext = struct { b: *build.Builder, step: *build.Step, test_index: usize, test_filter: ?[]const u8, modes: []const Mode, const Special = enum { None, Asm, RuntimeSafety, }; const TestCase = struct { name: []const u8, sources: ArrayList(SourceFile), expected_output: []const u8, link_libc: bool, special: Special, cli_args: []const []const u8, const SourceFile = struct { filename: []const u8, source: []const u8, }; pub fn addSourceFile(self: *TestCase, filename: []const u8, source: []const u8) void { self.sources.append(SourceFile{ .filename = filename, .source = source, }) catch unreachable; } pub fn setCommandLineArgs(self: *TestCase, args: []const []const u8) void { self.cli_args = args; } }; pub fn createExtra(self: *CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8, special: Special) TestCase { var tc = TestCase{ .name = name, .sources = ArrayList(TestCase.SourceFile).init(self.b.allocator), .expected_output = expected_output, .link_libc = false, .special = special, .cli_args = &[_][]const u8{}, }; const root_src_name = if (special == Special.Asm) "source.s" else "source.zig"; tc.addSourceFile(root_src_name, source); return tc; } pub fn create(self: *CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) TestCase { return createExtra(self, name, source, expected_output, Special.None); } pub fn addC(self: *CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) void { var tc = self.create(name, source, expected_output); tc.link_libc = true; self.addCase(tc); } pub fn add(self: *CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) void { const tc = self.create(name, source, expected_output); self.addCase(tc); } pub fn addAsm(self: *CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) void { const tc = self.createExtra(name, source, expected_output, Special.Asm); self.addCase(tc); } pub fn addRuntimeSafety(self: *CompareOutputContext, name: []const u8, source: []const u8) void { const tc = self.createExtra(name, source, undefined, Special.RuntimeSafety); self.addCase(tc); } pub fn addCase(self: *CompareOutputContext, case: TestCase) void { const b = self.b; const write_src = b.addWriteFiles(); for (case.sources.span()) |src_file| { write_src.add(src_file.filename, src_file.source); } switch (case.special) { Special.Asm => { const annotated_case_name = fmt.allocPrint(self.b.allocator, "assemble-and-link {}", .{ case.name, }) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } const exe = b.addExecutable("test", null); exe.addAssemblyFileFromWriteFileStep(write_src, case.sources.span()[0].filename); const run = exe.run(); run.addArgs(case.cli_args); run.expectStdErrEqual(""); run.expectStdOutEqual(case.expected_output); self.step.dependOn(&run.step); }, Special.None => { for (self.modes) |mode| { const annotated_case_name = fmt.allocPrint(self.b.allocator, "{} {} ({})", .{ "compare-output", case.name, @tagName(mode), }) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) continue; } const basename = case.sources.span()[0].filename; const exe = b.addExecutableFromWriteFileStep("test", write_src, basename); exe.setBuildMode(mode); if (case.link_libc) { exe.linkSystemLibrary("c"); } const run = exe.run(); run.addArgs(case.cli_args); run.expectStdErrEqual(""); run.expectStdOutEqual(case.expected_output); self.step.dependOn(&run.step); } }, Special.RuntimeSafety => { const annotated_case_name = fmt.allocPrint(self.b.allocator, "safety {}", .{case.name}) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } const basename = case.sources.span()[0].filename; const exe = b.addExecutableFromWriteFileStep("test", write_src, basename); if (case.link_libc) { exe.linkSystemLibrary("c"); } const run = exe.run(); run.addArgs(case.cli_args); run.stderr_action = .ignore; run.stdout_action = .ignore; run.expected_exit_code = 126; self.step.dependOn(&run.step); }, } } };
test/src/compare_output.zig
pub const Oid = enum(u32) { T_bool = 16, T_bytea = 17, T_char = 18, T_name = 19, T_int8 = 20, T_int2 = 21, T_int2vector = 22, T_int4 = 23, T_regproc = 24, T_text = 25, T_oid = 26, T_tid = 27, T_xid = 28, T_cid = 29, T_oidvector = 30, T_pg_ddl_command = 32, T_pg_type = 71, T_pg_attribute = 75, T_pg_proc = 81, T_pg_class = 83, T_json = 114, T_xml = 142, T__xml = 143, T_pg_node_tree = 194, T__json = 199, T_smgr = 210, T_index_am_handler = 325, T_point = 600, T_lseg = 601, T_path = 602, T_box = 603, T_polygon = 604, T_line = 628, T__line = 629, T_cidr = 650, T__cidr = 651, T_float4 = 700, T_float8 = 701, T_abstime = 702, T_reltime = 703, T_tinterval = 704, T_unknown = 705, T_circle = 718, T__circle = 719, T_money = 790, T__money = 791, T_macaddr = 829, T_inet = 869, T__bool = 1000, T__bytea = 1001, T__char = 1002, T__name = 1003, T__int2 = 1005, T__int2vector = 1006, T__int4 = 1007, T__regproc = 1008, T__text = 1009, T__tid = 1010, T__xid = 1011, T__cid = 1012, T__oidvector = 1013, T__bpchar = 1014, T__varchar = 1015, T__int8 = 1016, T__point = 1017, T__lseg = 1018, T__path = 1019, T__box = 1020, T__float4 = 1021, T__float8 = 1022, T__abstime = 1023, T__reltime = 1024, T__tinterval = 1025, T__polygon = 1027, T__oid = 1028, T_aclitem = 1033, T__aclitem = 1034, T__macaddr = 1040, T__inet = 1041, T_bpchar = 1042, T_varchar = 1043, T_date = 1082, T_time = 1083, T_timestamp = 1114, T__timestamp = 1115, T__date = 1182, T__time = 1183, T_timestamptz = 1184, T__timestamptz = 1185, T_interval = 1186, T__interval = 1187, T__numeric = 1231, T_pg_database = 1248, T__cstring = 1263, T_timetz = 1266, T__timetz = 1270, T_bit = 1560, T__bit = 1561, T_varbit = 1562, T__varbit = 1563, T_numeric = 1700, T_refcursor = 1790, T__refcursor = 2201, T_regprocedure = 2202, T_regoper = 2203, T_regoperator = 2204, T_regclass = 2205, T_regtype = 2206, T__regprocedure = 2207, T__regoper = 2208, T__regoperator = 2209, T__regclass = 2210, T__regtype = 2211, T_record = 2249, T_cstring = 2275, T_any = 2276, T_anyarray = 2277, T_void = 2278, T_trigger = 2279, T_language_handler = 2280, T_internal = 2281, T_opaque = 2282, T_anyelement = 2283, T__record = 2287, T_anynonarray = 2776, T_pg_authid = 2842, T_pg_auth_members = 2843, T__txid_snapshot = 2949, T_uuid = 2950, T__uuid = 2951, T_txid_snapshot = 2970, T_fdw_handler = 3115, T_pg_lsn = 3220, T__pg_lsn = 3221, T_tsm_handler = 3310, T_anyenum = 3500, T_tsvector = 3614, T_tsquery = 3615, T_gtsvector = 3642, T__tsvector = 3643, T__gtsvector = 3644, T__tsquery = 3645, T_regconfig = 3734, T__regconfig = 3735, T_regdictionary = 3769, T__regdictionary = 3770, T_jsonb = 3802, T__jsonb = 3807, T_anyrange = 3831, T_event_trigger = 3838, T_int4range = 3904, T__int4range = 3905, T_numrange = 3906, T__numrange = 3907, T_tsrange = 3908, T__tsrange = 3909, T_tstzrange = 3910, T__tstzrange = 3911, T_daterange = 3912, T__daterange = 3913, T_int8range = 3926, T__int8range = 3927, T_pg_shseclabel = 4066, T_regnamespace = 4089, T__regnamespace = 4090, T_regrole = 4096, T__regrole = 4097, pub fn name(self: Oid) []const u8 { return switch (self) { .T_bool => "BOOL", .T_bytea => "BYTEA", .T_char => "CHAR", .T_name => "NAME", .T_int8 => "INT8", .T_int2 => "INT2", .T_int2vector => "INT2VECTOR", .T_int4 => "INT4", .T_regproc => "REGPROC", .T_text => "TEXT", .T_oid => "OID", .T_tid => "TID", .T_xid => "XID", .T_cid => "CID", .T_oidvector => "OIDVECTOR", .T_pg_ddl_command => "PG_DDL_COMMAND", .T_pg_type => "PG_TYPE", .T_pg_attribute => "PG_ATTRIBUTE", .T_pg_proc => "PG_PROC", .T_pg_class => "PG_CLASS", .T_json => "JSON", .T_xml => "XML", .T__xml => "_XML", .T_pg_node_tree => "PG_NODE_TREE", .T__json => "_JSON", .T_smgr => "SMGR", .T_index_am_handler => "INDEX_AM_HANDLER", .T_point => "POINT", .T_lseg => "LSEG", .T_path => "PATH", .T_box => "BOX", .T_polygon => "POLYGON", .T_line => "LINE", .T__line => "_LINE", .T_cidr => "CIDR", .T__cidr => "_CIDR", .T_float4 => "FLOAT4", .T_float8 => "FLOAT8", .T_abstime => "ABSTIME", .T_reltime => "RELTIME", .T_tinterval => "TINTERVAL", .T_unknown => "UNKNOWN", .T_circle => "CIRCLE", .T__circle => "_CIRCLE", .T_money => "MONEY", .T__money => "_MONEY", .T_macaddr => "MACADDR", .T_inet => "INET", .T__bool => "_BOOL", .T__bytea => "_BYTEA", .T__char => "_CHAR", .T__name => "_NAME", .T__int2 => "_INT2", .T__int2vector => "_INT2VECTOR", .T__int4 => "_INT4", .T__regproc => "_REGPROC", .T__text => "_TEXT", .T__tid => "_TID", .T__xid => "_XID", .T__cid => "_CID", .T__oidvector => "_OIDVECTOR", .T__bpchar => "_BPCHAR", .T__varchar => "_VARCHAR", .T__int8 => "_INT8", .T__point => "_POINT", .T__lseg => "_LSEG", .T__path => "_PATH", .T__box => "_BOX", .T__float4 => "_FLOAT4", .T__float8 => "_FLOAT8", .T__abstime => "_ABSTIME", .T__reltime => "_RELTIME", .T__tinterval => "_TINTERVAL", .T__polygon => "_POLYGON", .T__oid => "_OID", .T_aclitem => "ACLITEM", .T__aclitem => "_ACLITEM", .T__macaddr => "_MACADDR", .T__inet => "_INET", .T_bpchar => "BPCHAR", .T_varchar => "VARCHAR", .T_date => "DATE", .T_time => "TIME", .T_timestamp => "TIMESTAMP", .T__timestamp => "_TIMESTAMP", .T__date => "_DATE", .T__time => "_TIME", .T_timestamptz => "TIMESTAMPTZ", .T__timestamptz => "_TIMESTAMPTZ", .T_interval => "INTERVAL", .T__interval => "_INTERVAL", .T__numeric => "_NUMERIC", .T_pg_database => "PG_DATABASE", .T__cstring => "_CSTRING", .T_timetz => "TIMETZ", .T__timetz => "_TIMETZ", .T_bit => "BIT", .T__bit => "_BIT", .T_varbit => "VARBIT", .T__varbit => "_VARBIT", .T_numeric => "NUMERIC", .T_refcursor => "REFCURSOR", .T__refcursor => "_REFCURSOR", .T_regprocedure => "REGPROCEDURE", .T_regoper => "REGOPER", .T_regoperator => "REGOPERATOR", .T_regclass => "REGCLASS", .T_regtype => "REGTYPE", .T__regprocedure => "_REGPROCEDURE", .T__regoper => "_REGOPER", .T__regoperator => "_REGOPERATOR", .T__regclass => "_REGCLASS", .T__regtype => "_REGTYPE", .T_record => "RECORD", .T_cstring => "CSTRING", .T_any => "ANY", .T_anyarray => "ANYARRAY", .T_void => "VOID", .T_trigger => "TRIGGER", .T_language_handler => "LANGUAGE_HANDLER", .T_internal => "INTERNAL", .T_opaque => "OPAQUE", .T_anyelement => "ANYELEMENT", .T__record => "_RECORD", .T_anynonarray => "ANYNONARRAY", .T_pg_authid => "PG_AUTHID", .T_pg_auth_members => "PG_AUTH_MEMBERS", .T__txid_snapshot => "_TXID_SNAPSHOT", .T_uuid => "UUID", .T__uuid => "_UUID", .T_txid_snapshot => "TXID_SNAPSHOT", .T_fdw_handler => "FDW_HANDLER", .T_pg_lsn => "PG_LSN", .T__pg_lsn => "_PG_LSN", .T_tsm_handler => "TSM_HANDLER", .T_anyenum => "ANYENUM", .T_tsvector => "TSVECTOR", .T_tsquery => "TSQUERY", .T_gtsvector => "GTSVECTOR", .T__tsvector => "_TSVECTOR", .T__gtsvector => "_GTSVECTOR", .T__tsquery => "_TSQUERY", .T_regconfig => "REGCONFIG", .T__regconfig => "_REGCONFIG", .T_regdictionary => "REGDICTIONARY", .T__regdictionary => "_REGDICTIONARY", .T_jsonb => "JSONB", .T__jsonb => "_JSONB", .T_anyrange => "ANYRANGE", .T_even.t_trigger => "EVEN.T_TRIGGER", .T_int4range => "INT4RANGE", .T__int4range => "_INT4RANGE", .T_numrange => "NUMRANGE", .T__numrange => "_NUMRANGE", .T_tsrange => "TSRANGE", .T__tsrange => "_TSRANGE", .T_tstzrange => "TSTZRANGE", .T__tstzrange => "_TSTZRANGE", .T_daterange => "DATERANGE", .T__daterange => "_DATERANGE", .T_int8range => "INT8RANGE", .T__int8range => "_INT8RANGE", .T_pg_shseclabel => "PG_SHSECLABEL", .T_regnamespace => "REGNAMESPACE", .T__regnamespace => "_REGNAMESPACE", .T_regrole => "REGROLE", .T__regrole => "_REGROLE", else => unreachable, }; } };
src/db/pq/oid.zig
const std = @import("std"); pub const VirtualMachineError = error{OutOfMemory}; pub const VirtualMachine = struct { allocator: std.mem.Allocator, stack: [stack_size]i32, program: std.ArrayList(u8), sp: usize, // stack pointer pc: usize, // program counter string_pool: std.ArrayList([]const u8), // all the strings in the program globals: std.ArrayList(i32), // all the variables in the program, they are global output: std.ArrayList(u8), // Instead of outputting to stdout, we do it here for better testing. const Self = @This(); const stack_size = 32; // Can be arbitrarily increased/decreased as long as we have enough. const word_size = @sizeOf(i32); pub fn init( allocator: std.mem.Allocator, program: std.ArrayList(u8), string_pool: std.ArrayList([]const u8), globals: std.ArrayList(i32), ) Self { return VirtualMachine{ .allocator = allocator, .stack = [_]i32{std.math.maxInt(i32)} ** stack_size, .program = program, .sp = 0, .pc = 0, .string_pool = string_pool, .globals = globals, .output = std.ArrayList(u8).init(allocator), }; } pub fn interp(self: *Self) VirtualMachineError!void { while (true) : (self.pc += 1) { switch (@intToEnum(Op, self.program.items[self.pc])) { .push => self.push(self.unpackInt()), .store => self.globals.items[@intCast(usize, self.unpackInt())] = self.pop(), .fetch => self.push(self.globals.items[@intCast(usize, self.unpackInt())]), .jmp => self.pc = @intCast(usize, self.unpackInt() - 1), .jz => { if (self.pop() == 0) { // -1 because `while` increases it with every iteration. // This doesn't allow to jump to location 0 because we use `usize` for `pc`, // just arbitrary implementation limitation. self.pc = @intCast(usize, self.unpackInt() - 1); } else { self.pc += word_size; } }, .prts => try self.out("{s}", .{self.string_pool.items[@intCast(usize, self.pop())]}), .prti => try self.out("{d}", .{self.pop()}), .prtc => try self.out("{c}", .{@intCast(u8, self.pop())}), .lt => self.binOp(lt), .le => self.binOp(le), .gt => self.binOp(gt), .ge => self.binOp(ge), .eq => self.binOp(eq), .ne => self.binOp(ne), .add => self.binOp(add), .mul => self.binOp(mul), .sub => self.binOp(sub), .div => self.binOp(div), .mod => self.binOp(mod), .@"and" => self.binOp(@"and"), .@"or" => self.binOp(@"or"), .not => self.push(@boolToInt(self.pop() == 0)), .neg => self.push(-self.pop()), .halt => break, } } } fn push(self: *Self, n: i32) void { self.sp += 1; self.stack[self.sp] = n; } fn pop(self: *Self) i32 { std.debug.assert(self.sp != 0); self.sp -= 1; return self.stack[self.sp + 1]; } fn unpackInt(self: *Self) i32 { const arg_ptr = @ptrCast(*[4]u8, self.program.items[self.pc + 1 .. self.pc + 1 + word_size]); self.pc += word_size; var arg_array = arg_ptr.*; const arg = @ptrCast(*i32, @alignCast(@alignOf(i32), &arg_array)); return arg.*; } pub fn out(self: *Self, comptime format: []const u8, args: anytype) VirtualMachineError!void { try self.output.writer().print(format, args); } fn binOp(self: *Self, func: fn (a: i32, b: i32) i32) void { const a = self.pop(); const b = self.pop(); // Note that arguments are in reversed order because this is how we interact with // push/pop operations of the stack. const result = func(b, a); self.push(result); } fn lt(a: i32, b: i32) i32 { return @boolToInt(a < b); } fn le(a: i32, b: i32) i32 { return @boolToInt(a <= b); } fn gt(a: i32, b: i32) i32 { return @boolToInt(a > b); } fn ge(a: i32, b: i32) i32 { return @boolToInt(a >= b); } fn eq(a: i32, b: i32) i32 { return @boolToInt(a == b); } fn ne(a: i32, b: i32) i32 { return @boolToInt(a != b); } fn add(a: i32, b: i32) i32 { return a + b; } fn sub(a: i32, b: i32) i32 { return a - b; } fn mul(a: i32, b: i32) i32 { return a * b; } fn div(a: i32, b: i32) i32 { return @divTrunc(a, b); } fn mod(a: i32, b: i32) i32 { return @mod(a, b); } fn @"or"(a: i32, b: i32) i32 { return @boolToInt((a != 0) or (b != 0)); } fn @"and"(a: i32, b: i32) i32 { return @boolToInt((a != 0) and (b != 0)); } }; pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); var arg_it = std.process.args(); _ = try arg_it.next(allocator) orelse unreachable; // program name const file_name = arg_it.next(allocator); // We accept both files and standard input. var file_handle = blk: { if (file_name) |file_name_delimited| { const fname: []const u8 = try file_name_delimited; break :blk try std.fs.cwd().openFile(fname, .{}); } else { break :blk std.io.getStdIn(); } }; defer file_handle.close(); const input_content = try file_handle.readToEndAlloc(allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList(i32).init(allocator); const bytecode = try loadBytecode(allocator, input_content, &string_pool, &globals); var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals); try vm.interp(); const result: []const u8 = vm.output.items; _ = try std.io.getStdOut().write(result); } pub const Op = enum(u8) { fetch, store, push, add, sub, mul, div, mod, lt, gt, le, ge, eq, ne, @"and", @"or", neg, not, jmp, jz, prtc, prts, prti, halt, const from_string = std.ComptimeStringMap(Op, .{ .{ "fetch", .fetch }, .{ "store", .store }, .{ "push", .push }, .{ "add", .add }, .{ "sub", .sub }, .{ "mul", .mul }, .{ "div", .div }, .{ "mod", .mod }, .{ "lt", .lt }, .{ "gt", .gt }, .{ "le", .le }, .{ "ge", .ge }, .{ "eq", .eq }, .{ "ne", .ne }, .{ "and", .@"and" }, .{ "or", .@"or" }, .{ "neg", .neg }, .{ "not", .not }, .{ "jmp", .jmp }, .{ "jz", .jz }, .{ "prtc", .prtc }, .{ "prts", .prts }, .{ "prti", .prti }, .{ "halt", .halt }, }); pub fn fromString(str: []const u8) Op { return from_string.get(str).?; } }; // 100 lines of code to load serialized bytecode, eh fn loadBytecode( allocator: std.mem.Allocator, str: []const u8, string_pool: *std.ArrayList([]const u8), globals: *std.ArrayList(i32), ) !std.ArrayList(u8) { var result = std.ArrayList(u8).init(allocator); var line_it = std.mem.split(u8, str, "\n"); while (line_it.next()) |line| { if (std.mem.indexOf(u8, line, "halt")) |_| { var tok_it = std.mem.tokenize(u8, line, " "); const size = try std.fmt.parseInt(usize, tok_it.next().?, 10); try result.resize(size + 1); break; } } line_it.index = 0; const first_line = line_it.next().?; const strings_index = std.mem.indexOf(u8, first_line, " Strings: ").?; const globals_size = try std.fmt.parseInt(usize, first_line["Datasize: ".len..strings_index], 10); const string_pool_size = try std.fmt.parseInt(usize, first_line[strings_index + " Strings: ".len ..], 10); try globals.resize(globals_size); try string_pool.ensureTotalCapacity(string_pool_size); var string_cnt: usize = 0; while (string_cnt < string_pool_size) : (string_cnt += 1) { const line = line_it.next().?; var program_string = try std.ArrayList(u8).initCapacity(allocator, line.len); var escaped = false; // Skip double quotes for (line[1 .. line.len - 1]) |ch| { if (escaped) { escaped = false; switch (ch) { '\\' => try program_string.append('\\'), 'n' => try program_string.append('\n'), else => { std.debug.print("unknown escape sequence: {c}\n", .{ch}); std.os.exit(1); }, } } else { switch (ch) { '\\' => escaped = true, else => try program_string.append(ch), } } } try string_pool.append(program_string.items); } while (line_it.next()) |line| { if (line.len == 0) break; var tok_it = std.mem.tokenize(u8, line, " "); const address = try std.fmt.parseInt(usize, tok_it.next().?, 10); const op = Op.fromString(tok_it.next().?); result.items[address] = @enumToInt(op); switch (op) { .fetch, .store => { const index_bracketed = tok_it.rest(); const index = try std.fmt.parseInt(i32, index_bracketed[1 .. index_bracketed.len - 1], 10); insertInt(&result, address + 1, index); }, .push => { insertInt(&result, address + 1, try std.fmt.parseInt(i32, tok_it.rest(), 10)); }, .jmp, .jz => { _ = tok_it.next(); insertInt(&result, address + 1, try std.fmt.parseInt(i32, tok_it.rest(), 10)); }, else => {}, } } return result; } fn insertInt(array: *std.ArrayList(u8), address: usize, n: i32) void { const word_size = @sizeOf(i32); var i: usize = 0; var n_var = n; var n_bytes = @ptrCast(*[4]u8, &n_var); while (i < word_size) : (i += 1) { array.items[@intCast(usize, address + i)] = n_bytes[@intCast(usize, i)]; } } const testing = std.testing; test "examples" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); { const example_input_path = "examples/codegened0.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/output0.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList(i32).init(allocator); const bytecode = try loadBytecode(allocator, content_input, &string_pool, &globals); var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals); try vm.interp(); const pretty_output: []const u8 = vm.output.items; try testing.expectFmt(content_output, "{s}", .{pretty_output}); } { const example_input_path = "examples/codegened1.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/output1.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList(i32).init(allocator); const bytecode = try loadBytecode(allocator, content_input, &string_pool, &globals); var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals); try vm.interp(); const pretty_output: []const u8 = vm.output.items; try testing.expectFmt(content_output, "{s}", .{pretty_output}); } { const example_input_path = "examples/codegened3.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/output3.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList(i32).init(allocator); const bytecode = try loadBytecode(allocator, content_input, &string_pool, &globals); var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals); try vm.interp(); const pretty_output: []const u8 = vm.output.items; try testing.expectFmt(content_output, "{s}", .{pretty_output}); } { const example_input_path = "examples/codegened4.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/output4.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList(i32).init(allocator); const bytecode = try loadBytecode(allocator, content_input, &string_pool, &globals); var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals); try vm.interp(); const pretty_output: []const u8 = vm.output.items; try testing.expectFmt(content_output, "{s}", .{pretty_output}); } { const example_input_path = "examples/codegened5.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/output5.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList(i32).init(allocator); const bytecode = try loadBytecode(allocator, content_input, &string_pool, &globals); var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals); try vm.interp(); const pretty_output: []const u8 = vm.output.items; try testing.expectFmt(content_output, "{s}", .{pretty_output}); } { const example_input_path = "examples/codegened6.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/output6.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList(i32).init(allocator); const bytecode = try loadBytecode(allocator, content_input, &string_pool, &globals); var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals); try vm.interp(); const pretty_output: []const u8 = vm.output.items; try testing.expectFmt(content_output, "{s}", .{pretty_output}); } { const example_input_path = "examples/codegened7.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/output7.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList(i32).init(allocator); const bytecode = try loadBytecode(allocator, content_input, &string_pool, &globals); var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals); try vm.interp(); const pretty_output: []const u8 = vm.output.items; try testing.expectFmt(content_output, "{s}", .{pretty_output}); } { const example_input_path = "examples/codegened8.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/output8.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList(i32).init(allocator); const bytecode = try loadBytecode(allocator, content_input, &string_pool, &globals); var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals); try vm.interp(); const pretty_output: []const u8 = vm.output.items; try testing.expectFmt(content_output, "{s}", .{pretty_output}); } { const example_input_path = "examples/codegened9.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/output9.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList(i32).init(allocator); const bytecode = try loadBytecode(allocator, content_input, &string_pool, &globals); var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals); try vm.interp(); const pretty_output: []const u8 = vm.output.items; try testing.expectFmt(content_output, "{s}", .{pretty_output}); } { const example_input_path = "examples/codegened10.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/output10.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList(i32).init(allocator); const bytecode = try loadBytecode(allocator, content_input, &string_pool, &globals); var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals); try vm.interp(); const pretty_output: []const u8 = vm.output.items; try testing.expectFmt(content_output, "{s}", .{pretty_output}); } { const example_input_path = "examples/codegened11.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/output11.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList(i32).init(allocator); const bytecode = try loadBytecode(allocator, content_input, &string_pool, &globals); var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals); try vm.interp(); const pretty_output: []const u8 = vm.output.items; try testing.expectFmt(content_output, "{s}", .{pretty_output}); } { const example_input_path = "examples/codegened12.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/output12.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList(i32).init(allocator); const bytecode = try loadBytecode(allocator, content_input, &string_pool, &globals); var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals); try vm.interp(); const pretty_output: []const u8 = vm.output.items; try testing.expectFmt(content_output, "{s}", .{pretty_output}); } { const example_input_path = "examples/codegened13.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/output13.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList(i32).init(allocator); const bytecode = try loadBytecode(allocator, content_input, &string_pool, &globals); var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals); try vm.interp(); const pretty_output: []const u8 = vm.output.items; try testing.expectFmt(content_output, "{s}", .{pretty_output}); } { const example_input_path = "examples/codegened14.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/output14.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList(i32).init(allocator); const bytecode = try loadBytecode(allocator, content_input, &string_pool, &globals); var vm = VirtualMachine.init(allocator, bytecode, string_pool, globals); try vm.interp(); const pretty_output: []const u8 = vm.output.items; try testing.expectFmt(content_output, "{s}", .{pretty_output}); } }
vm.zig
const Self = @This(); const std = @import("std"); const wlr = @import("wlroots"); const wl = @import("wayland").server.wl; const server = &@import("main.zig").server; const util = @import("util.zig"); const Box = @import("Box.zig"); /// The corresponding wlroots object xwayland_surface: *wlr.XwaylandSurface, // Listeners that are always active over the view's lifetime request_configure: wl.Listener(*wlr.XwaylandSurface.event.Configure) = wl.Listener(*wlr.XwaylandSurface.event.Configure).init(handleRequestConfigure), destroy: wl.Listener(*wlr.XwaylandSurface) = wl.Listener(*wlr.XwaylandSurface).init(handleDestroy), map: wl.Listener(*wlr.XwaylandSurface) = wl.Listener(*wlr.XwaylandSurface).init(handleMap), unmap: wl.Listener(*wlr.XwaylandSurface) = wl.Listener(*wlr.XwaylandSurface).init(handleUnmap), commit: wl.Listener(*wlr.Surface) = wl.Listener(*wlr.Surface).init(handleCommit), pub fn init(self: *Self, xwayland_surface: *wlr.XwaylandSurface) void { self.* = .{ .xwayland_surface = xwayland_surface }; // Add listeners that are active over the the entire lifetime xwayland_surface.events.request_configure.add(&self.request_configure); xwayland_surface.events.destroy.add(&self.destroy); xwayland_surface.events.map.add(&self.map); xwayland_surface.events.unmap.add(&self.unmap); } fn handleRequestConfigure( listener: *wl.Listener(*wlr.XwaylandSurface.event.Configure), event: *wlr.XwaylandSurface.event.Configure, ) void { event.surface.configure(event.x, event.y, event.width, event.height); } /// Called when the xwayland surface is destroyed fn handleDestroy(listener: *wl.Listener(*wlr.XwaylandSurface), xwayland_surface: *wlr.XwaylandSurface) void { const self = @fieldParentPtr(Self, "destroy", listener); // Remove listeners that are active for the entire lifetime self.request_configure.link.remove(); self.destroy.link.remove(); self.map.link.remove(); self.unmap.link.remove(); // Deallocate the node const node = @fieldParentPtr(std.TailQueue(Self).Node, "data", self); util.gpa.destroy(node); } /// Called when the xwayland surface is mapped, or ready to display on-screen. fn handleMap(listener: *wl.Listener(*wlr.XwaylandSurface), xwayland_surface: *wlr.XwaylandSurface) void { const self = @fieldParentPtr(Self, "map", listener); // Add self to the list of unmanaged views in the root const node = @fieldParentPtr(std.TailQueue(Self).Node, "data", self); server.root.xwayland_unmanaged_views.prepend(node); xwayland_surface.surface.?.events.commit.add(&self.commit); // TODO: handle keyboard focus // if (wlr_xwayland_or_surface_wants_focus(self.xwayland_surface)) { ... } /// Called when the surface is unmapped and will no longer be displayed. fn handleUnmap(listener: *wl.Listener(*wlr.XwaylandSurface), xwayland_surface: *wlr.XwaylandSurface) void { const self = @fieldParentPtr(Self, "unmap", listener); // Remove self from the list of unmanged views in the root const node = @fieldParentPtr(std.TailQueue(Self).Node, "data", self); server.root.xwayland_unmanaged_views.remove(node); self.commit.link.remove(); } fn handleCommit(listener: *wl.Listener(*wlr.Surface), surface: *wlr.Surface) void { var it = server.root.outputs.first; while (it) |node| : (it = node.next) node.data.damage.addWhole(); }
source/river-0.1.0/river/XwaylandUnmanaged.zig
const std = @import("std"); const colors = @import("../term/colors.zig"); const Color = colors.Color; const ast = @import("./ast.zig"); const Ast = ast.Ast; const Fg = colors.Fg; const eq = std.mem.eql; const meta = std.meta; const mem = std.mem; const enums = std.enums; const fieldNames = meta.fieldNames; const lex = @import("./lexer.zig"); const ops = @import("./token/op.zig"); const bloc = @import("./token/block.zig"); const tt = @import("./token/type.zig"); const kws = @import("./token/kw.zig"); pub const Kind = Token.Kind; pub const Op = ops.Op; pub const Block = bloc.Block; pub const @"Type" = tt.@"Type"; pub const Kw = kws.Kw; pub const TokenError = error{ UnexpectedToken, }; pub const Cursor = struct { line: usize, col: usize, const Self = @This(); pub fn default() Cursor { return Cursor{ .line = 1, .col = 1 }; } pub fn init(l: usize, c: usize) Cursor { return Cursor{ .line = l, .col = c }; } pub fn newLine(self: *Cursor) void { self.line += 1; self.col = 1; } pub fn incrCol(self: *Cursor) void { self.col += 1; } pub fn incrRow(self: *Cursor) Cursor { self.row += 1; } }; pub const Token = struct { pos: Cursor, offset: usize, kind: Token.Kind = .unknown, val: ?Token.Val = null, const Self = @This(); pub fn initKind(k: Token.Kind, v: ?Token.Val) Self { return Self{ .pos = Cursor.default(), .offset = 0, .kind = k, .val = v, }; } // TODO Actually manually define precedence pub fn hasPrecedence(self: Self, other: Self) bool { return @enumToInt(self.kind) > @enumToInt(other.kind); } pub const Kind = union(enum(u8)) { op: Op, type: @"Type", kw: Kw, block: Block, unknown, eof, pub fn op(oper: Op) Token.Kind { return Token.Kind{ .op = oper }; } pub fn kwd(kw: Kw) Token.Kind { return Token.Kind{ .kw = kw }; } pub const isKw = Kw.isKw; pub const isOp = Op.isOp; pub const isBool = @"Type".isBool; pub const isBlock = Block.isBlock; pub fn fromKw(k: Kw) Token.Kind { return Token.Kind{ .kw = k }; } pub fn fromOp(o: Op) Token.Kind { return Token.Kind{ .op = o }; } pub fn fromType(ty: Type) Token.Kind { return Token.Kind{ .type = ty }; } pub fn toStr(self: Token.Kind) []const u8 { return switch (self) { .eof => "eof", .unknown => "unknown", .op => |opt| Op.toStr(opt), .kw => |kwt| Kw.toStr(kwt), .type => |tyt| tyt.toStr(), .block => |blt| blt.toStr(), }; } pub fn fromString(inp: []const u8) ?Token.Kind { inline for (std.meta.fields(Token.Kind)) |field| { if (eq(u8, inp, field.name)) { return @field(Token.Kind, field.name); } } return null; } }; pub const Val = union(enum) { intl: i32, float: f32, byte: u8, str: []const u8, }; pub const Iter = struct { allocator: std.mem.Allocator, items: std.ArrayList(Token), current: usize, const Self = @This(); pub fn init(a: std.mem.Allocator, tok: std.ArrayList(Token)) Token.Iter { return Token.Iter{ .current = 0, .items = tok, .allocator = a }; } pub fn next(self: *Token.Iter) ?Token { if (self.items.popOrNull()) |token| { return token; } else return null; } pub fn fromStr(input: []const u8, a: std.mem.Allocator) !Token.Iter { var ts = std.ArrayList([]const u8).init(a); var tl = std.ArrayList(Token).init(a); const token_ln = std.mem.tokenize(u8, input, "\n"); for (token_ln) |tokln| { for (tokln) |tok| { try ts.append(tok); } } return Iter{ .allocator = a, .items = tl }; } }; }; pub fn tokFile(gpa: std.mem.Allocator, comptime path: ?[]const u8) !void { const test_file = if (path) |p| @embedFile(p) else @embedFile("../../res/test.is"); // var arena = std.heap.ArenaAllocator.init(gpa); // .respOk("Welcome to the Idlang TOKENIZER REPL\n"); var lx = lex.Lexer.init(test_file, gpa); _ = try lx.lex(); const tokens = try lx.tokenListToString(); _ = try std.io.getStdOut().writeAll(tokens); var at = ast.Ast.create(gpa, test_file); std.debug.print("AST DEBUG: {}", .{at}); } const expect = std.testing.expect; const expectStrEq = std.testing.expectEqualStrings; test "Kw toStr" { const kw = Token.Kind{ .kw = Kw.all }; const kwstr = kw.toStr(); try expectStrEq("all", kwstr); } test "Kw isKw" { const kw = "does"; const tok = Kw.isKw(kw); if (tok) |tk| { std.log.warn("{s}", .{tk.toStr()}); try expect(true); } else { try expect(false); } } test "Block isBlock" { const bcmt = "--|"; const tok = Token.Kind.isBlock(bcmt); if (tok) |tk| { std.log.warn("{s}", .{tk.toStr()}); try expect(true); } else { try expect(false); } } test "Op isOp" { const dcmt = "-!"; const tok = Token.Kind.isOp(dcmt); if (tok) |tk| { std.log.warn("{s}", .{tk.toStr()}); try expect(true); } else { try expect(false); } } // test "Op isType" { // const cstr: [_]u8 = "\"literal str\""; // const o1 = isType(cstr); // try expect(o1 == Op.comment); // }
src/lang/token.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const chunks = @import("./chunks.zig"); const values = @import("./value.zig"); const debug = @import("./debug.zig"); const compiler = @import("./compiler.zig"); const Obj = @import("object.zig").Obj; const Value = values.Value; const Chunk = chunks.Chunk; const OpCode = chunks.OpCode; const valuesEq = values.valuesEq; const Table = @import("./table.zig").Table; const debug_trace_execution = false; const debug_gc = true; const stack_max = 256; pub const InterpretError = error{ CompileError, RuntimeError, }; const BinaryOp = enum { sub, div, mul, gt, lt, }; pub const Vm = struct { const Self = @This(); chunk: *Chunk, ip: usize, stack: [stack_max]Value, stack_top: usize, allocator: *Allocator, objects: ?*Obj, strings: Table, globals: Table, pub fn init(allocator: *Allocator) Self { return Self{ .ip = 0, .stack_top = 0, .chunk = undefined, .stack = undefined, .allocator = allocator, .objects = null, .strings = Table.init(allocator), .globals = Table.init(allocator), }; } pub fn interpret(self: *Self, source: []const u8) InterpretError!void { var chunk = Chunk.init(self.allocator); defer chunk.deinit(); compiler.compile(source, &chunk, self) catch return InterpretError.CompileError; self.chunk = &chunk; self.ip = 0; try self.run(); } fn run(self: *Self) InterpretError!void { while (true) { if (comptime debug_trace_execution) { printStack(self.stack[0..self.stack_top]); debug.disassembleInstruction(self.chunk, self.ip); } const instruction = self.readInstruction(); try switch (instruction) { .op_constant => { const constant = self.readConstant(); self.push(constant); }, .op_negate => { if (!self.peek(0).isNumber()) { self.runtimeErr("Operand must be a number", .{}); return InterpretError.RuntimeError; } self.push(Value.fromNumber(-self.pop().asNumber())); }, .op_not => self.push(Value.fromBool(self.pop().isFalsey())), .op_nil => self.push(Value.nil), .op_false => self.push(Value.fromBool(false)), .op_true => self.push(Value.fromBool(true)), .op_add => self.add(), .op_sub => self.binary_op(.sub), .op_mul => self.binary_op(.mul), .op_div => self.binary_op(.div), .op_greater => self.binary_op(.gt), .op_less => self.binary_op(.lt), .op_equal => self.equal(), .op_print => self.printOperation(), .op_define_gloabl => self.defineGlobal(), .op_get_global => self.getGlobal(), .op_set_global => self.setGlobal(), .op_pop => _ = self.pop(), .op_ret => return, }; } } fn resetStack(self: *Self) void { self.stack_top = 0; } fn runtimeErr(self: *Self, comptime fmt: []const u8, args: anytype) void { const err_writer = std.io.getStdErr().writer(); err_writer.print(fmt ++ "\n", args) catch {}; err_writer.print("[line {d}] in script.\n", .{self.chunk.lines.items[self.ip]}) catch {}; self.resetStack(); } inline fn printOperation(self: *Self) void { const stdin_writer = std.io.getStdOut().writer(); stdin_writer.print("{}\n", .{self.pop()}) catch @panic("Panic at printOperation\n"); } inline fn defineGlobal(self: *Self) void { const name = self.readConstant().asObj().asString(); _ = self.globals.set(name, self.peek(0)); _ = self.pop(); } inline fn getGlobal(self: *Self) !void { const name = self.readConstant().asObj().asString(); const value = self.globals.get(name) orelse { self.runtimeErr("Undefined variable {s}.\n", .{name.bytes}); return InterpretError.RuntimeError; }; self.push(value.*); } inline fn setGlobal(self: *Self) !void { const name = self.readConstant().asObj().asString(); if (self.globals.set(name, self.peek(0))) { _ = self.globals.delete(name); self.runtimeErr("Undefined variable '{s}'.", .{name.bytes}); return InterpretError.RuntimeError; } } fn binary_op(self: *Self, comptime op: BinaryOp) InterpretError!void { if (!self.peek(0).isNumber() or !self.peek(1).isNumber()) { self.runtimeErr("Operands must be numbers.", .{}); return InterpretError.RuntimeError; } const b = self.pop().asNumber(); const a = self.pop().asNumber(); const result = switch (op) { .sub => a - b, .mul => a * b, .div => a / b, .gt => a > b, .lt => a < b, }; switch (@TypeOf(result)) { bool => self.push(Value.fromBool(result)), f64 => self.push(Value.fromNumber(result)), else => unreachable, } } inline fn equal(self: *Self) void { const b = self.pop(); const a = self.pop(); self.push(Value.fromBool(a.equals(b))); } inline fn add(self: *Self) !void { if (self.peek(0).isString() and self.peek(1).isString()) { self.concat(); } else if (self.peek(0).isNumber() and self.peek(1).isNumber()) { const b = self.pop().asNumber(); const a = self.pop().asNumber(); self.push(Value.fromNumber(a + b)); } else { self.runtimeErr("Operands must be two numbers or two strings.", .{}); return InterpretError.RuntimeError; } } inline fn concat(self: *Self) void { const b = self.pop().asObj().asString(); const a = self.pop().asObj().asString(); const result = std.mem.concat(self.allocator, u8, &[_][]const u8{ a.bytes, b.bytes }) catch unreachable; const str = Obj.String.take(self, result); self.push(str.obj.toValue()); } inline fn push(self: *Self, value: Value) void { self.stack[self.stack_top] = value; self.stack_top += 1; } inline fn peek(self: *Self, distance: usize) Value { return self.stack[self.stack_top - distance - 1]; } fn pop(self: *Self) Value { self.stack_top -= 1; return self.stack[self.stack_top]; } inline fn readInstruction(self: *Self) OpCode { const instruction = @intToEnum(OpCode, self.chunk.code.items[self.ip]); self.ip += 1; return instruction; } inline fn readConstant(self: *Self) Value { const constant = self.chunk.constants.items[self.chunk.code.items[self.ip]]; self.ip += 1; return constant; } pub fn deinit(self: *Self) void { if (comptime debug_gc) { std.debug.print("Uninitializing VM\n", .{}); } self.resetStack(); self.freeObjects(); self.globals.deinit(); self.strings.deinit(); } fn freeObjects(self: *Self) void { var obj = self.objects; var total_objects: u64 = 0; while (obj) |object| { if (comptime debug_gc) { total_objects += 1; } const next = object.next; object.destroy(self); obj = next; } if (comptime debug_gc) { std.debug.print("Objects freed {d}\n", .{total_objects}); } } }; fn printStack(stack: []Value) void { std.debug.print(" ", .{}); for (stack) |value| { std.debug.print("[{}]", .{value}); } std.debug.print("\n", .{}); }
src/vm.zig
const arch = @import("arch.zig"); const hw = @import("../hw.zig"); const ExceptionContext = packed struct { regs: [30]u64, elr_el1: u64, spsr_el1: u64, lr: u64, far_el1: u64, }; fn handle(ctx: *ExceptionContext, comptime name: []const u8) callconv(.Inline) noreturn { hw.entry_uart.carefully(.{"exception handler running for " ++ name ++ "\r\n"}); dumpRegs(ctx); while (true) {} } fn dumpRegs(ctx: *ExceptionContext) void { hw.entry_uart.carefully(.{ "ctx ptr:", @ptrToInt(ctx), "\r\n" }); hw.entry_uart.carefully(.{ "x0 ", ctx.regs[0], " x1 ", ctx.regs[1], "\r\n" }); hw.entry_uart.carefully(.{ "x2 ", ctx.regs[2], " x3 ", ctx.regs[3], "\r\n" }); hw.entry_uart.carefully(.{ "x4 ", ctx.regs[4], " x5 ", ctx.regs[5], "\r\n" }); hw.entry_uart.carefully(.{ "x6 ", ctx.regs[6], " x7 ", ctx.regs[7], "\r\n" }); hw.entry_uart.carefully(.{ "x8 ", ctx.regs[8], " x9 ", ctx.regs[9], "\r\n" }); hw.entry_uart.carefully(.{ "x10 ", ctx.regs[10], " x11 ", ctx.regs[11], "\r\n" }); hw.entry_uart.carefully(.{ "x12 ", ctx.regs[12], " x13 ", ctx.regs[13], "\r\n" }); hw.entry_uart.carefully(.{ "x14 ", ctx.regs[14], " x15 ", ctx.regs[15], "\r\n" }); hw.entry_uart.carefully(.{ "x16 ", ctx.regs[16], " x17 ", ctx.regs[17], "\r\n" }); hw.entry_uart.carefully(.{ "x18 ", ctx.regs[18], " x19 ", ctx.regs[19], "\r\n" }); hw.entry_uart.carefully(.{ "x20 ", ctx.regs[20], " x21 ", ctx.regs[21], "\r\n" }); hw.entry_uart.carefully(.{ "x22 ", ctx.regs[22], " x23 ", ctx.regs[23], "\r\n" }); hw.entry_uart.carefully(.{ "x24 ", ctx.regs[24], " x25 ", ctx.regs[25], "\r\n" }); hw.entry_uart.carefully(.{ "x26 ", ctx.regs[26], " x27 ", ctx.regs[27], "\r\n" }); hw.entry_uart.carefully(.{ "x28 ", ctx.regs[28], " x29 ", ctx.regs[29], "\r\n" }); hw.entry_uart.carefully(.{ "elr ", ctx.elr_el1, " sps ", ctx.spsr_el1, "\r\n" }); hw.entry_uart.carefully(.{ "lr ", ctx.lr, " far ", ctx.far_el1, "\r\n\r\n" }); } export fn el1_sp0_sync(ctx: *ExceptionContext) void { handle(ctx, "EL1_SP0_SYNC"); } export fn el1_sp0_irq(ctx: *ExceptionContext) void { handle(ctx, "EL1_SP0_IRQ"); } export fn el1_sp0_fiq(ctx: *ExceptionContext) void { handle(ctx, "EL1_SP0_FIQ"); } export fn el1_sp0_error(ctx: *ExceptionContext) void { handle(ctx, "EL1_SP0_ERROR"); } export fn el1_sync(ctx: *ExceptionContext, elr_el1: u64, esr_el1: u64) void { // HACK: dump ELR_EL1/ESR_EL1 before we try to reach through any pointers. hw.entry_uart.hex(elr_el1); hw.entry_uart.hex(esr_el1); handle(ctx, "EL1_SYNC"); } export fn el1_irq(ctx: *ExceptionContext) void { handle(ctx, "TODO: EL1_IRQ"); } export fn el1_fiq(ctx: *ExceptionContext) void { handle(ctx, "EL1_FIQ"); } export fn el1_error(ctx: *ExceptionContext) void { handle(ctx, "EL1_ERROR"); } export fn el0_sync(ctx: *ExceptionContext) void { handle(ctx, "EL0_SYNC"); } export fn el0_irq(ctx: *ExceptionContext) void { handle(ctx, "EL0_IRQ"); } export fn el0_fiq(ctx: *ExceptionContext) void { handle(ctx, "EL0_FIQ"); } export fn el0_error(ctx: *ExceptionContext) void { handle(ctx, "EL0_ERROR"); } export fn el0_32_sync(ctx: *ExceptionContext) void { handle(ctx, "EL0_32_SYNC"); } export fn el0_32_irq(ctx: *ExceptionContext) void { handle(ctx, "EL0_32_IRQ"); } export fn el0_32_fiq(ctx: *ExceptionContext) void { handle(ctx, "EL0_32_FIQ"); } export fn el0_32_error(ctx: *ExceptionContext) void { handle(ctx, "EL0_32_ERROR"); }
dainkrnl/src/arm64/exception.zig
const std = @import("std"); const string = []const u8; const yaml = @import("yaml"); pub fn main() !void { // const source_url = "https://docs.docker.com/engine/api/v1.41.yaml"; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const alloc = gpa.allocator(); // Using local document because upstream has missing chunks // https://github.com/moby/moby/issues/43336 // https://github.com/moby/moby/issues/43337 // https://github.com/moby/moby/issues/43341 // https://github.com/moby/moby/issues/43345 const body_content = @embedFile("./swagger.yaml"); const doc = try yaml.parse(alloc, body_content); const f = try std.fs.cwd().createFile("src/direct.zig", .{}); const w = f.writer(); try w.writeAll("const internal = @import(\"./internal.zig\");\n"); try w.writeAll("const string = []const u8;\n"); try w.writeAll("const Top = @This();\n"); { std.debug.print("definitions:\n", .{}); for (doc.mapping.get("definitions").?.mapping.items) |item| { std.debug.print("|", .{}); try w.writeAll("\npub const "); try w.writeAll(item.key); try w.writeAll(" = "); try printType(alloc, w, item.value.mapping, true); try w.writeAll(";\n"); } std.debug.print("\n", .{}); } { std.debug.print("paths:\n", .{}); for (doc.mapping.get("paths").?.mapping.items) |item| { std.debug.print("|", .{}); try w.writeAll("\npub const "); try printId(w, item.key); try w.writeAll(" = struct {\n"); try printEndpoint(alloc, w, item.value.mapping); try w.writeAll("};\n"); } std.debug.print("\n", .{}); } } const Error = std.fs.File.Writer.Error || std.mem.Allocator.Error; fn printType(alloc: std.mem.Allocator, w: std.fs.File.Writer, m: yaml.Mapping, trailingcomma: bool) Error!void { { const ref = m.get_string("$ref"); if (std.mem.startsWith(u8, ref, "#/definitions/")) { return try w.writeAll(ref["#/definitions/".len..]); } } { const of = m.get("allOf"); if (of != null) { try w.writeAll("internal.AllOf(&.{"); for (of.?.sequence) |item, i| { if (i > 0) try w.writeAll(","); try printType(alloc, w, item.mapping, trailingcomma); } if (trailingcomma) try w.writeAll(","); try w.writeAll("})"); return; } } if (m.get("schema")) |cap| { return printType(alloc, w, cap.mapping, trailingcomma); } const apitype = m.get_string("type"); if (std.mem.eql(u8, apitype, "integer")) return try w.writeAll("i32"); if (std.mem.eql(u8, apitype, "boolean")) return try w.writeAll("bool"); if (std.mem.eql(u8, apitype, "number")) return try w.writeAll("f64"); if (std.mem.eql(u8, apitype, "object")) { try w.writeAll("struct {"); if (m.get("additionalProperties") == null) { if (m.get("properties") != null) { const reqs = try m.get_string_array(alloc, "required"); for (m.get("properties").?.mapping.items) |item, i| { if (i > 0) try w.writeAll(","); try printId(w, item.key); try w.writeAll(": "); if (reqs.len > 0) { if (!contains(reqs, item.key)) try w.writeAll("?"); } try printType(alloc, w, item.value.mapping, trailingcomma); if (reqs.len > 0) { if (!contains(reqs, item.key)) try w.writeAll(" = null"); } } if (trailingcomma) try w.writeAll(","); } } try w.writeAll("}"); return; } if (std.mem.eql(u8, apitype, "array")) { try w.writeAll("[]const "); try printType(alloc, w, m.get("items").?.mapping, trailingcomma); return; } if (std.mem.eql(u8, apitype, "string")) { if (m.get("enum")) |enumcap| { try w.writeAll("enum {"); for (enumcap.sequence) |item, i| { if (i > 0) try w.writeAll(","); try printId(w, item.string); } if (trailingcomma) try w.writeAll(","); try w.writeAll("}"); return; } return try w.writeAll("string"); } @panic(apitype); } fn contains(haystack: []const string, needle: string) bool { for (haystack) |item| { if (std.mem.eql(u8, item, needle)) { return true; } } return false; } fn printId(w: std.fs.File.Writer, id: string) !void { if (id.len == 0) return try w.writeAll("@\"\""); // https://github.com/ziglang/zig/issues/11099 try std.zig.fmtId(id).format("", .{}, w); } fn printEndpoint(alloc: std.mem.Allocator, w: std.fs.File.Writer, m: yaml.Mapping) !void { for (m.items) |item| { try printMethod(alloc, w, item.key, item.value.mapping); } } fn printMethod(alloc: std.mem.Allocator, w: std.fs.File.Writer, method: string, m: yaml.Mapping) !void { try w.writeAll(" pub usingnamespace internal.Fn(\n"); try w.writeAll("."); try w.writeAll(method); try w.writeAll(","); try w.writeAll("internal.name(Top, @This()),"); try printParamStruct(alloc, w, m, "path"); try printParamStruct(alloc, w, m, "query"); try printParamStruct(alloc, w, m, "body"); { try w.writeAll("union(enum) {\n"); for (m.getT("responses", .mapping).?.items) |item| { try w.print(" @\"{s}\": ", .{item.key}); const mm: yaml.Mapping = item.value.mapping; const produces = try m.get_string_array(alloc, "produces"); if (mm.get("type") != null or mm.get("schema") != null) { try printType(alloc, w, mm, false); } else if ((contains(produces, "application/octet-stream") or contains(produces, "text/plain")) and std.mem.eql(u8, item.key, "200")) { try w.writeAll("[]const u8"); } else if (mm.items.len == 1 and mm.get("description") != null) { try w.writeAll("void"); } else if (std.mem.eql(u8, mm.getT("description", .string).?, "no error")) { try w.writeAll("void"); } else { @panic(""); } try w.writeAll(",\n"); } try w.writeAll(" },\n"); } try w.writeAll(");\n"); try w.writeAll("\n"); } fn capitalize(w: std.fs.File.Writer, s: string) !void { try w.writeAll(&.{std.ascii.toUpper(s[0])}); try w.writeAll(s[1..]); } fn hasParamsOf(m: yaml.Mapping, kind: string) bool { for (m.getT("parameters", .sequence).?) |item| { if (std.mem.eql(u8, item.mapping.get_string("in"), kind)) { return true; } } return false; } fn printParamStruct(alloc: std.mem.Allocator, w: std.fs.File.Writer, m: yaml.Mapping, ty: string) !void { if (hasParamsOf(m, ty)) { try w.writeAll("struct {"); var n: usize = 0; for (m.getT("parameters", .sequence).?) |item| { const mm: yaml.Mapping = item.mapping; if (std.mem.eql(u8, mm.get_string("in"), ty)) { defer n += 1; if (n > 0) try w.writeAll(", "); try printId(w, mm.get_string("name")); try w.writeAll(": "); try printType(alloc, w, mm, false); if (mm.get("default")) |cap| { try w.writeAll(" = "); try printDefault(w, cap.string, mm.get_string("type")); } } } try w.writeAll("},\n"); } else { try w.writeAll("void,\n"); } } fn printDefault(w: std.fs.File.Writer, def: string, ty: string) !void { if (std.mem.eql(u8, ty, "boolean")) return try w.writeAll(def); if (std.mem.eql(u8, ty, "string")) return try w.print("\"{}\"", .{std.zig.fmtEscapes(def)}); if (std.mem.eql(u8, ty, "integer")) return try w.writeAll(def); @panic(ty); }
generate.zig
const std = @import("std"); pub fn Callback( comptime ReturnType: type, comptime ArgType: type, comptime inline_capacity: usize, comptime deinitable: bool, ) type { return struct { callFn: fn (usize, ArgType) ReturnType, deinitFn: if (deinitable) fn (usize) void else void, inline_data: [inline_capacity]u8, pub const callback_inline_capacity = inline_capacity; pub const callback_deinitable = deinitable; pub const CallbackReturnType = ReturnType; pub const CallbackArgType = ArgType; pub fn call(self: *const @This(), arg: ArgType) callconv(.Inline) ReturnType { return self.callFn(self.context(), arg); } pub fn deinit(self: *const @This()) callconv(.Inline) void { if (comptime (!deinitable)) @compileError("Cannot deinit() this!"); self.deinitFn(self.context()); } pub fn context(self: *const @This()) callconv(.Inline) usize { return @ptrToInt(&self.inline_data[0]); } }; } fn heapAllocatedCallback( comptime CallbackType: type, thing_to_callback: anytype, allocator: *std.mem.Allocator, ) !CallbackType { const callback_inline_capacity = CallbackType.callback_inline_capacity; const CallbackReturnType = CallbackType.CallbackReturnType; const CallbackArgType = CallbackType.CallbackArgType; // What can we fit in the inline storage? if (callback_inline_capacity < @sizeOf(usize)) { @compileError("Not enough inline capacity to heap allocate, can't fit the heap pointer!"); } const allocator_inline = callback_inline_capacity >= @sizeOf(usize) * 2; const HeapAllocBlock = struct { alloc: if (allocator_inline) void else *std.mem.Allocator, value: @TypeOf(thing_to_callback), }; return inlineAllocatedCallback(CallbackType, try struct { heap_block: *HeapAllocBlock, inline_allocator: if (allocator_inline) *std.mem.Allocator else void, fn init(alloc: *std.mem.Allocator, thing: anytype) !@This() { const heap_block = try alloc.create(HeapAllocBlock); if (comptime (!allocator_inline)) heap_block.alloc = alloc; heap_block.value = thing; return @This(){ .heap_block = heap_block, .inline_allocator = if (comptime (allocator_inline)) alloc else {}, }; } fn allocator(self: *const @This()) callconv(.Inline) *std.mem.Allocator { if (comptime (allocator_inline)) return self.inline_allocator; return self.heap_block.alloc; } fn call(self: *const @This(), arg: CallbackArgType) CallbackReturnType { return @call(.{ .modifier = .always_inline }, self.heap_block.value.call, .{arg}); } fn deinit(self: *const @This()) void { if (@hasDecl(@TypeOf(self.heap_block.value), "deinit")) @call(.{ .modifier = .always_inline }, self.heap_block.value.deinit, .{}); self.allocator().destroy(self.heap_block); } }.init(allocator, thing_to_callback)); } pub fn inlineAllocatedCallback( comptime CallbackType: type, thing_to_callback: anytype, ) CallbackType { if (@sizeOf(@TypeOf(thing_to_callback)) > CallbackType.callback_inline_capacity) { @compileError("Cannot fit this object in the inline capacity!"); } // WARNING: TYPE PUNNING AHEAD var result: CallbackType = undefined; std.mem.copy(u8, result.inline_data[0..], std.mem.asBytes(&thing_to_callback)); if (!@hasDecl(@TypeOf(thing_to_callback), "call")) @compileError("Missing `call` declaration on " ++ @typeName(@TypeOf(thing_to_callback)) ++ "! Are you missing `pub`?"); if (comptime (@hasDecl(@TypeOf(thing_to_callback), "call"))) { const CallType = @TypeOf(@TypeOf(thing_to_callback).call); const ReturnType = CallbackType.CallbackReturnType; const ArgType = CallbackType.CallbackArgType; // zig fmt: off if(CallType != fn(*@TypeOf(thing_to_callback), ArgType) ReturnType and CallType != fn(*const @TypeOf(thing_to_callback), ArgType) ReturnType // zig fmt: on ) { @compileError("Bad call function signature on " ++ @typeName(@TypeOf(thing_to_callback)) ++ "!"); } result.callFn = @intToPtr(fn (usize, ArgType) ReturnType, @ptrToInt(@TypeOf(thing_to_callback).call)); } else { @compileError("Missing call function on " ++ @typeName(@TypeOf(thing_to_callback)) ++ "! Are you missing `pub`?"); } if (comptime (CallbackType.callback_deinitable)) { if (comptime (@hasDecl(@TypeOf(thing_to_callback), "deinit"))) { const DeinitType = @TypeOf(@TypeOf(thing_to_callback).deinit); // zig fmt: off if(DeinitType != fn(*@TypeOf(thing_to_callback)) void and DeinitType != fn(*const @TypeOf(thing_to_callback)) void // zig fmt: on ) { @compileError("Bad deinit function signature on " ++ @typeName(@TypeOf(thing_to_callback)) ++ "!"); } result.deinitFn = @intToPtr(fn (usize) void, @ptrToInt(@TypeOf(thing_to_callback).deinit)); } else { result.deinitFn = struct { fn f(_: usize) void {} }.f; } } return result; } pub fn possiblyHeapAllocatedCallback( comptime CallbackType: type, thing_to_callback: anytype, allocator: *std.mem.Allocator, ) !CallbackType { if (comptime (CallbackType.callback_inline_capacity) < @sizeOf(@TypeOf(thing_to_callback))) { return heapAllocatedCallback(CallbackType, thing_to_callback, allocator); } return inlineAllocatedCallback(CallbackType, thing_to_callback); }
lib/util/callback.zig
const windows = @import("windows.zig"); const IUnknown = windows.IUnknown; const UINT = windows.UINT; const WINAPI = windows.WINAPI; const SIZE_T = windows.SIZE_T; const LPCSTR = windows.LPCSTR; const GUID = windows.GUID; pub const PRIMITIVE_TOPOLOGY = enum(UINT) { UNDEFINED = 0, POINTLIST = 1, LINELIST = 2, LINESTRIP = 3, TRIANGLELIST = 4, TRIANGLESTRIP = 5, LINELIST_ADJ = 10, LINESTRIP_ADJ = 11, TRIANGLELIST_ADJ = 12, TRIANGLESTRIP_ADJ = 13, CONTROL_POINT_PATCHLIST = 33, _2_CONTROL_POINT_PATCHLIST = 34, _3_CONTROL_POINT_PATCHLIST = 35, _4_CONTROL_POINT_PATCHLIST = 36, _5_CONTROL_POINT_PATCHLIST = 37, _6_CONTROL_POINT_PATCHLIST = 38, _7_CONTROL_POINT_PATCHLIST = 39, _8_CONTROL_POINT_PATCHLIST = 40, _9_CONTROL_POINT_PATCHLIST = 41, _10_CONTROL_POINT_PATCHLIST = 42, _11_CONTROL_POINT_PATCHLIST = 43, _12_CONTROL_POINT_PATCHLIST = 44, _13_CONTROL_POINT_PATCHLIST = 45, _14_CONTROL_POINT_PATCHLIST = 46, _15_CONTROL_POINT_PATCHLIST = 47, _16_CONTROL_POINT_PATCHLIST = 48, _17_CONTROL_POINT_PATCHLIST = 49, _18_CONTROL_POINT_PATCHLIST = 50, _19_CONTROL_POINT_PATCHLIST = 51, _20_CONTROL_POINT_PATCHLIST = 52, _21_CONTROL_POINT_PATCHLIST = 53, _22_CONTROL_POINT_PATCHLIST = 54, _23_CONTROL_POINT_PATCHLIST = 55, _24_CONTROL_POINT_PATCHLIST = 56, _25_CONTROL_POINT_PATCHLIST = 57, _26_CONTROL_POINT_PATCHLIST = 58, _27_CONTROL_POINT_PATCHLIST = 59, _28_CONTROL_POINT_PATCHLIST = 60, _29_CONTROL_POINT_PATCHLIST = 61, _30_CONTROL_POINT_PATCHLIST = 62, _31_CONTROL_POINT_PATCHLIST = 63, _32_CONTROL_POINT_PATCHLIST = 64, }; pub const FEATURE_LEVEL = enum(UINT) { FL_1_0_CORE = 0x1000, FL_9_1 = 0x9100, FL_9_2 = 0x9200, FL_9_3 = 0x9300, FL_10_0 = 0xa000, FL_10_1 = 0xa100, FL_11_0 = 0xb000, FL_11_1 = 0xb100, FL_12_0 = 0xc000, FL_12_1 = 0xc100, FL_12_2 = 0xc200, }; pub const DRIVER_TYPE = enum(UINT) { UNKNOWN = 0, HARDWARE = 1, REFERENCE = 2, NULL = 3, SOFTWARE = 4, WARP = 5, }; pub const SHADER_MACRO = extern struct { Name: LPCSTR, Definition: LPCSTR, }; pub const INCLUDE_TYPE = enum(UINT) { INCLUDE_LOCAL = 0, INCLUDE_SYSTEM = 1, }; pub const IID_IBlob = GUID("{8BA5FB08-5195-40e2-AC58-0D989C3A0102}"); pub const IBlob = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), blob: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn GetBufferPointer(self: *T) *anyopaque { return self.v.blob.GetBufferPointer(self); } pub inline fn GetBufferSize(self: *T) SIZE_T { return self.v.blob.GetBufferSize(self); } }; } fn VTable(comptime T: type) type { return extern struct { GetBufferPointer: fn (*T) callconv(WINAPI) *anyopaque, GetBufferSize: fn (*T) callconv(WINAPI) SIZE_T, }; } }; pub const IInclude = extern struct { const Self = @This(); v: *const extern struct { include: VTable(Self), }, usingnamespace Methods(Self); fn Methods(comptime T: type) type { _ = T; return extern struct {}; } fn VTable(comptime T: type) type { return extern struct { Open: fn (*T, INCLUDE_TYPE, LPCSTR, *anyopaque, **anyopaque, *UINT) callconv(WINAPI) void, Close: fn (*T, *anyopaque) callconv(WINAPI) void, }; } };
modules/platform/vendored/zwin32/src/d3dcommon.zig
const std = @import("std"); const Token = @import("lexer.zig").Token; const Slice = @import("util.zig").IndexedSlice; pub const Error = error{ InvalidTokenConversion, InvalidArgs, } || std.mem.Allocator.Error; pub const NodeList = std.ArrayList(Node); pub const RefList = std.ArrayList(Node.Index); const log = std.log.scoped(.ast); pub const Node = struct { tag: Tag, token: Token, children: Slice, pub const Index = u32; pub const Tag = enum { root, block, decl_var, decl_const, decl_var_auto, decl_const_auto, decl_fn, decl_fn_param, decl_struct, decl_union, decl_struct_member, for_stmt, while_stmt, if_stmt, else_stmt, return_stmt, break_stmt, continue_stmt, switch_stmt, switch_prong, binary_expr, unary_negate, unary_bit_negate, unary_cond_negate, unary_deref, unary_ref, binary_add, binary_sub, binary_mul, binary_div, binary_mod, binary_matmul, binary_bit_and, binary_bit_or, binary_bit_xor, binary_bit_lshift, binary_bit_rshift, binary_cond_and, binary_cond_or, binary_cond_eq, binary_cond_neq, binary_cond_lt, binary_cond_leq, binary_cond_gt, binary_cond_geq, member_access, array_access, fn_call, assign_expr, assign_add_expr, assign_sub_expr, assign_mul_expr, assign_div_expr, assign_mod_expr, assign_at_expr, assign_bit_and_expr, assign_bit_or_expr, assign_bit_xor_expr, assign_bit_lshift_expr, assign_bit_rshift_expr, literal_int, literal_float, literal_char, literal_string, literal_hex, literal_oct, literal_bin, identifier, }; }; pub const Ast = struct { nodes: NodeList, refs: RefList, pub fn init(allocator: std.mem.Allocator) Ast { const ast = Ast{ .nodes = std.ArrayList(Node).init(allocator), .refs = std.ArrayList(Node.Index).init(allocator), }; return ast; } pub fn deinit(self: *Ast) void { self.nodes.deinit(); self.refs.deinit(); } pub fn add_literal(self: *Ast, token: Token) !Node.Index { const n_nodes = self.nodes.items.len; try self.nodes.append(Node{ .tag = switch (token.tag) { .literal_int => Node.Tag.literal_int, .literal_float => Node.Tag.literal_float, .literal_char => Node.Tag.literal_char, .literal_string => Node.Tag.literal_string, .literal_hex => Node.Tag.literal_hex, .literal_oct => Node.Tag.literal_oct, .literal_bin => Node.Tag.literal_bin, else => return Error.InvalidTokenConversion, }, .token = token, .children = Slice.EMPTY, }); return @intCast(Node.Index, n_nodes); } pub fn add_identifier(self: *Ast, token: Token) !Node.Index { const n_nodes = self.nodes.items.len; try self.nodes.append(Node{ .tag = .identifier, .token = token, .children = Slice.EMPTY, }); return @intCast(Node.Index, n_nodes); } pub fn add_unary_op(self: *Ast, op: Token, rhs: Node.Index) !Node.Index { const n_nodes = self.nodes.items.len; const n_refs = self.refs.items.len; try self.refs.append(rhs); try self.nodes.append(Node{ .tag = switch (op.tag) { .op_sub => Node.Tag.unary_negate, .op_bit_not => Node.Tag.unary_bit_negate, .op_cond_not => Node.Tag.unary_cond_negate, .op_ampersand => Node.Tag.unary_ref, .op_mul => Node.Tag.unary_deref, else => return Error.InvalidTokenConversion, }, .token = op, .children = Slice.make(@intCast(usize, n_refs), 1), }); return @intCast(Node.Index, n_nodes); } pub fn add_binary_op(self: *Ast, op: Token, lhs: Node.Index, rhs: Node.Index) !Node.Index { const n_nodes = self.nodes.items.len; const n_refs = self.refs.items.len; try self.refs.append(lhs); try self.refs.append(rhs); try self.nodes.append(Node{ .tag = switch (op.tag) { .op_add => Node.Tag.binary_add, .op_sub => Node.Tag.binary_sub, .op_mul => Node.Tag.binary_mul, .op_div => Node.Tag.binary_div, .op_mod => Node.Tag.binary_mod, .op_at => Node.Tag.binary_matmul, .op_ampersand => Node.Tag.binary_bit_and, .op_bit_or => Node.Tag.binary_bit_or, .op_bit_xor => Node.Tag.binary_bit_xor, .op_bit_lshift => Node.Tag.binary_bit_lshift, .op_bit_rshift => Node.Tag.binary_bit_rshift, .op_cond_eq => Node.Tag.binary_cond_eq, .op_cond_neq => Node.Tag.binary_cond_neq, .op_cond_lt => Node.Tag.binary_cond_lt, .op_cond_leq => Node.Tag.binary_cond_leq, .op_cond_gt => Node.Tag.binary_cond_gt, .op_cond_geq => Node.Tag.binary_cond_geq, .kwd_and => Node.Tag.binary_cond_and, .kwd_or => Node.Tag.binary_cond_or, .op_assign => Node.Tag.assign_expr, .op_add_inline => Node.Tag.assign_add_expr, .op_sub_inline => Node.Tag.assign_sub_expr, .op_mul_inline => Node.Tag.assign_mul_expr, .op_div_inline => Node.Tag.assign_div_expr, .op_mod_inline => Node.Tag.assign_mod_expr, .op_at_inline => Node.Tag.assign_at_expr, .op_bit_and_inline => Node.Tag.assign_bit_and_expr, .op_bit_or_inline => Node.Tag.assign_bit_or_expr, .op_bit_xor_inline => Node.Tag.assign_bit_xor_expr, .op_bit_lshift_inline => Node.Tag.assign_bit_lshift_expr, .op_bit_rshift_inline => Node.Tag.assign_bit_rshift_expr, else => return Error.InvalidTokenConversion, }, .token = op, .children = Slice.make(n_refs, 2), }); return @intCast(Node.Index, n_nodes); } pub fn add_statement( self: *Ast, tag: Node.Tag, expr: ?Node.Index, ) !Node.Index { const n_nodes = self.nodes.items.len; const n_refs = self.refs.items.len; switch (tag) { .return_stmt, .break_stmt, .continue_stmt, => {}, else => return Error.InvalidArgs, } if (expr != null and tag != .return_stmt) return Error.InvalidArgs; if (expr != null) try self.refs.append(expr.?); try self.nodes.append(Node{ .tag = tag, .token = undefined, .children = if (expr != null) Slice.make(n_refs, 1) else Slice.EMPTY, }); return @intCast(Node.Index, n_nodes); } pub fn add_func_call( self: *Ast, callee: Node.Index, args: []Node.Index, ) !Node.Index { const n_nodes = self.nodes.items.len; const n_refs = self.refs.items.len; try self.refs.append(callee); for (args) |a| { try self.refs.append(a); } try self.nodes.append(Node{ .tag = .fn_call, .token = undefined, .children = Slice.make(n_refs, args.len + 1), }); return @intCast(Node.Index, n_nodes); } pub fn add_var_decl( self: *Ast, identifier: Token, var_type: ?Node.Index, expr: ?Node.Index, is_const: bool, ) !Node.Index { const n_nodes = self.nodes.items.len; const n_refs = self.refs.items.len; if (is_const and expr == null) { return Error.InvalidArgs; } try self.refs.append(if (var_type != null) var_type.? else 0); try self.refs.append(if (expr != null) expr.? else 0); try self.nodes.append(Node{ .tag = if (is_const) .decl_const else .decl_var, .token = identifier, .children = Slice.make(n_refs, 2), }); return @intCast(Node.Index, n_nodes); } pub fn add_auto_var_decl( self: *Ast, identifier: Token, expr: Node.Index, is_const: bool, ) !Node.Index { const n_nodes = self.nodes.items.len; const n_refs = self.refs.items.len; try self.refs.append(expr); try self.nodes.append(Node{ .tag = if (is_const) .decl_const_auto else .decl_var_auto, .token = identifier, .children = Slice.make(n_refs, 1), }); return @intCast(Node.Index, n_nodes); } pub fn add_struct_member( self: *Ast, identifier: Token, member_type: Node.Index, default_value: ?Node.Index, ) !Node.Index { const n_nodes = self.nodes.items.len; const n_refs = self.refs.items.len; try self.refs.append(member_type); // try self.refs.append(if (default_value != null) default_value.? else 0); if (default_value != null) try self.refs.append(default_value.?); try self.nodes.append(Node{ .tag = .decl_struct_member, .token = identifier, .children = Slice.make(n_refs, 1 + @intCast(usize, @boolToInt(default_value != null))), }); return @intCast(Node.Index, n_nodes); } pub fn add_struct_decl( self: *Ast, identifier: Token, members: []Node.Index, is_union: bool, ) !Node.Index { const n_nodes = self.nodes.items.len; const n_refs = self.refs.items.len; for (members) |m| { try self.refs.append(m); } try self.nodes.append(Node{ .tag = if (is_union) .decl_union else .decl_struct, .token = identifier, .children = Slice.make(n_refs, members.len), }); return @intCast(Node.Index, n_nodes); } pub fn add_member_access( self: *Ast, object: Node.Index, member: Token, ) !Node.Index { const n_nodes = self.nodes.items.len; const n_refs = self.refs.items.len; try self.refs.append(object); try self.refs.append(try self.add_identifier(member)); try self.nodes.append(Node{ .tag = .member_access, .token = member, .children = Slice.make(n_refs, 2), }); return @intCast(Node.Index, n_nodes + 1); // adding an id so add 1 } pub fn add_func_param( self: *Ast, identifier: Token, param_type: Node.Index, ptr_level: usize, ) !Node.Index { const n_nodes = self.nodes.items.len; const n_refs = self.refs.items.len; try self.refs.append(param_type); try self.refs.append(@intCast(Node.Index, ptr_level)); // TODO: hack try self.nodes.append(Node{ .tag = .decl_fn_param, .token = identifier, .children = Slice.make(n_refs, 2), }); return @intCast(Node.Index, n_nodes); } pub fn add_func_decl( self: *Ast, identifier: Token, params: []Node.Index, return_type: ?Node.Index, fn_body: Node.Index, is_extern: bool, is_inline: bool, ) !Node.Index { // TODO(mia): uwu don't do this _ = is_extern; _ = is_inline; const n_nodes = self.nodes.items.len; const n_refs = self.refs.items.len; try self.refs.append(fn_body); // try self.refs.append(if (return_type != null) return_type.? else 0); if (return_type != null) try self.refs.append(return_type.?); for (params) |p| { try self.refs.append(p); } try self.nodes.append(Node{ .tag = .decl_fn, .token = identifier, .children = Slice.make( n_refs, 1 + params.len + @intCast(usize, @boolToInt(return_type != null)), ), }); return @intCast(Node.Index, n_nodes); } pub fn add_while_loop( self: *Ast, condition: Node.Index, update: ?Node.Index, block: Node.Index, ) !Node.Index { const n_nodes = self.nodes.items.len; const n_refs = self.refs.items.len; try self.refs.append(condition); try self.refs.append(block); // try self.refs.append(if (update != null) update.? else 0); if (update != null) try self.refs.append(update.?); try self.nodes.append(Node{ .tag = .while_stmt, .token = undefined, .children = Slice.make(n_refs, 2 + @intCast(usize, @boolToInt(update != null))), }); return @intCast(Node.Index, n_nodes); } pub fn add_if_block( self: *Ast, condition: Node.Index, true_block: Node.Index, false_block: ?Node.Index, ) !Node.Index { const n_nodes = self.nodes.items.len; const n_refs = self.refs.items.len; try self.refs.append(condition); try self.refs.append(true_block); // try self.refs.append(if (false_block != null) false_block.? else 0); if (false_block != null) try self.refs.append(false_block.?); try self.nodes.append(Node{ .tag = .if_stmt, .token = undefined, .children = Slice.make(n_refs, 2 + @intCast(usize, @boolToInt(false_block != null))), }); return @intCast(Node.Index, n_nodes); } pub fn add_switch(self: *Ast, condition: Node.Index, prongs: []Node.Index) !Node.Index { _ = self; _ = condition; _ = prongs; // const n_nodes = self.nodes.items.len; // const n_refs = self.refs.items.len; return 0; } pub fn add_block(self: *Ast, statements: []Node.Index) !Node.Index { const n_nodes = self.nodes.items.len; const n_refs = self.refs.items.len; for (statements) |s| { try self.refs.append(s); } try self.nodes.append(Node{ .tag = .block, .token = undefined, .children = Slice.make(n_refs, statements.len), }); return @intCast(Node.Index, n_nodes); } pub fn add_root(self: *Ast, statements: []Node.Index) !Node.Index { const n_nodes = self.nodes.items.len; const n_refs = self.refs.items.len; for (statements) |stmt| { try self.refs.append(stmt); } try self.nodes.append(Node{ .tag = .root, .token = undefined, .children = Slice.make(n_refs, statements.len), }); return @intCast(Node.Index, n_nodes); } pub fn print(self: *Ast) void { var root = self.nodes.items[self.nodes.items.len - 1]; log.info("printing AST:", .{}); std.debug.print("{}: {}", .{ self.nodes.items.len - 1, root.tag }); self._print_level(1, &root); std.debug.print("\n", .{}); } fn _print_level(self: *Ast, level: usize, node: *Node) void { const children = node.*.children.to_slice(Node.Index, self.refs.items.ptr); for (children) |c| { if (c == self.nodes.items.len) continue; var i: usize = 0; while (i < level) : (i += 1) { std.debug.print(" ", .{}); } std.debug.print("{}: {} -> [ ]\n", .{ c, self.nodes.items[c].tag }); var next_node = self.nodes.items[c]; self._print_level(level + 1, &next_node); } } }; test "init and add" { var allocator = std.heap.GeneralPurposeAllocator(.{}){}; const gpa = allocator.allocator(); var ast = Ast.init(gpa); defer ast.deinit(); // TODO(mia): add }
src/ast.zig
const std = @import("std"); const mem = std.mem; const CurrencySymbol = @This(); allocator: *mem.Allocator, array: []bool, lo: u21 = 36, hi: u21 = 126128, pub fn init(allocator: *mem.Allocator) !CurrencySymbol { var instance = CurrencySymbol{ .allocator = allocator, .array = try allocator.alloc(bool, 126093), }; mem.set(bool, instance.array, false); var index: u21 = 0; instance.array[0] = true; index = 126; while (index <= 129) : (index += 1) { instance.array[index] = true; } instance.array[1387] = true; instance.array[1511] = true; index = 2010; while (index <= 2011) : (index += 1) { instance.array[index] = true; } index = 2510; while (index <= 2511) : (index += 1) { instance.array[index] = true; } instance.array[2519] = true; instance.array[2765] = true; instance.array[3029] = true; instance.array[3611] = true; instance.array[6071] = true; index = 8316; while (index <= 8347) : (index += 1) { instance.array[index] = true; } instance.array[43028] = true; instance.array[64984] = true; instance.array[65093] = true; instance.array[65248] = true; index = 65468; while (index <= 65469) : (index += 1) { instance.array[index] = true; } index = 65473; while (index <= 65474) : (index += 1) { instance.array[index] = true; } index = 73657; while (index <= 73660) : (index += 1) { instance.array[index] = true; } instance.array[123611] = true; instance.array[126092] = true; // Placeholder: 0. Struct name, 1. Code point kind return instance; } pub fn deinit(self: *CurrencySymbol) void { self.allocator.free(self.array); } // isCurrencySymbol checks if cp is of the kind Currency_Symbol. pub fn isCurrencySymbol(self: CurrencySymbol, cp: u21) bool { if (cp < self.lo or cp > self.hi) return false; const index = cp - self.lo; return if (index >= self.array.len) false else self.array[index]; }
src/components/autogen/DerivedGeneralCategory/CurrencySymbol.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const print = std.debug.print; const input = @embedFile("../in08.txt"); const ExecutedArray = std.PackedIntArray(u1, 2048); var line: [2048]usize = undefined; var line_len: usize = 0; fn load() void { line[0] = 0; var ln: u16 = 1; for (input) |c, i| { if (c == '\n') { line[ln] = i + 1; ln += 1; } } line_len = ln - 1; } pub fn main() !void { load(); print("Loaded {} lines.\n", .{line_len}); var i: usize = 0; var prev_acc: isize = undefined; while (i < line_len) { var acc = acc_chg_jmp(i); //if (acc == prev_acc) break; prev_acc = acc; i += 1; } } pub fn acc_chg_jmp(ichange: usize) isize { var executed = ExecutedArray.init(std.mem.zeroes([2048]u1)); var acc: isize = 0; var ic: usize = 0; var nopjmp: usize = 0; print("Changing jmpnop {}: ", .{ichange}); while (executed.get(ic) == 0) { executed.set(ic, 1); //print("Executing line {}: ", .{ic}); var eol: usize = line.len; if (ic < line_len) { eol = line[ic + 1] - 1; } var instr = input[line[ic]..eol]; var num = std.mem.trimLeft(u8, instr[4..], " \n"); var arg = std.fmt.parseInt(i16, num, 10) catch |err| { print("problem parsing {}.", .{num}); @panic("problem parsing number"); }; if (std.mem.startsWith(u8, instr, "jmp")) { nopjmp += 1; if (nopjmp == ichange) { ic += 1; // nop } else { ic = @intCast(usize, @intCast(isize, ic) + arg); } } else if (std.mem.startsWith(u8, instr, "acc")) { acc += arg; ic += 1; } else if (std.mem.startsWith(u8, instr, "nop")) { nopjmp += 1; if (nopjmp == ichange) { ic = @intCast(usize, @intCast(isize, ic) + arg); } else { ic += 1; } } else { print("incomprehensible instruction {}", .{instr}); @panic(":("); } // print("{} ({}) -> {} :", .{ instr, num, ic }); if (ic >= line_len) { print(" No infinite loop! ", .{}); break; } } print("acc is {}.\n", .{acc}); return acc; }
src/day08.zig
const std = @import("std"); const ArrayList = std.ArrayList; const TypeInfo = std.builtin.TypeInfo; const meta = std.meta; const ParseError = error { ParseError } || anyerror; fn parse(comptime Type: type, buf: []const u8) ParseError!Type { const typeInfo = @typeInfo(Type); const TypeId = std.builtin.TypeId; return switch (typeInfo) { .Int => std.fmt.parseInt(Type, buf, 10), .Float => std.fmt.parseFloat(Type, buf), .Enum => |en| { inline for (en.fields) |field| { if (std.mem.eql(u8, field.name, buf)) { return @intToEnum(Type, field.value); } } return ParseError.ParseError; }, .Bool => std.mem.eql(u8, "true", buf), else => { @compileError("parse not supported for " ++ @typeName(Type)); unreachable; }, }; } fn initFromPair(comptime T: type, a: anytype, b: anytype) T { var t = std.mem.zeroInit(T, a); inline for (@typeInfo(@TypeOf(b)).Struct.fields) |field| { @field(t, field.name) = @field(b, field.name); } return t; } fn initSubset(comptime T: type, a: anytype) T { var t = std.mem.zeroInit(T, .{}); inline for (@typeInfo(T).Struct.fields) |field| { if (@hasField(@TypeOf(a), field.name)) { @field(t, field.name) = @field(a, field.name); } } return t; } fn fieldByName(comptime T: type, comptime name: []const u8) TypeInfo.StructField { const index = meta.fieldIndex(T, name) orelse unreachable; return meta.fields(T)[index]; } fn DataFrame(comptime RowLabel: type, comptime ColumnLabel: type) comptime type { if (@typeInfo(RowLabel) != .Struct) { @compileError("Dataframe Row type must be a struct, got " ++ @typeName(RowLabel)); } if (@typeInfo(ColumnLabel) != .Struct) { @compileError("Dataframe Column type must be a struct, got " ++ @typeName(ColumnLabel)); } const rowFields = meta.fields(RowLabel); const columnFields = meta.fields(ColumnLabel); inline for (columnFields) |field| { if (@hasField(RowLabel, field.name)) { @compileError("Dataframe Row & Column types must have disjoint field names; they both have \"" ++ field.name ++ "\""); } } const dataFields = rowFields ++ columnFields; return struct { data: DataArray, const Self = @This(); const RowType = RowLabel; const ColumnType = ColumnLabel; const DataType = @Type(TypeInfo{ .Struct = .{ .layout = .Auto, .fields = dataFields, .decls = &[0]TypeInfo.Declaration{}, .is_tuple = false, } }); const DataArray = ArrayList(DataType); pub fn initEmpty(allocator: *std.mem.Allocator) !Self { var self = Self{ .data = DataArray.init(allocator), }; return self; } pub fn deinit(self: Self) void { self.data.deinit(); } const FileError = error{ParseError} || anyerror; pub fn initFromFile(filename: []const u8, allocator: *std.mem.Allocator) FileError!Self { var self = try Self.initEmpty(allocator); errdefer self.deinit(); var file = try std.fs.cwd().openFile(filename, .{}); defer file.close(); var reader = std.io.bufferedReader(file.reader()).reader(); const max_length: usize = 1024; { const header = (try reader.readUntilDelimiterOrEofAlloc(allocator, '\n', max_length)) orelse return FileError.ParseError; defer allocator.free(header); var headerIter = std.mem.tokenize(header, ","); inline for (columnFields) |field| { const col = headerIter.next(); std.debug.assert(col != null); std.debug.assert(std.mem.eql(u8, col.?, field.name)); } std.debug.assert(headerIter.rest().len == 0); } while (try reader.readUntilDelimiterOrEofAlloc(allocator, '\n', max_length)) |line| { defer allocator.free(line); var lineIter = std.mem.tokenize(line, ","); var entry = std.mem.zeroInit(ColumnLabel, .{}); inline for (columnFields) |field| { const cell = lineIter.next() orelse return FileError.ParseError; const value = try parse(field.field_type, cell); @field(entry, field.name) = value; } var index = std.mem.zeroInit(RowLabel, .{}); try self.append(index, entry); } return self; } pub fn append(self: *Self, index: RowLabel, data: ColumnLabel) !void { var d = initFromPair(DataType, index, data); try self.data.append(d); } pub fn sort(self: *Self, comptime column: [] const u8) void { const sortFn = struct { fn inner(context: void, a: DataType, b: DataType) bool { return @field(a, column) < @field(b, column); } }.inner; std.sort.sort(DataType, self.data.items, {}, sortFn); } fn ReindexType(comptime labels: anytype) comptime type { const labelsInfo = @typeInfo(@TypeOf(labels)); if (labelsInfo != .Struct or !labelsInfo.Struct.is_tuple) { @compileError("Expected `labels` parameter to be a tuple, got " ++ @typeName(@TypeOf(labels))); } const labelFields = labelsInfo.Struct.fields; inline for (labelFields) |field| { const label = @field(labels, field.name); if (!@hasField(DataType, label)) { @compileError("DataFrame does not have label named \"" ++ label ++ "\""); } } comptime var newRowInfo = @typeInfo(RowLabel); comptime var newColumnInfo = @typeInfo(ColumnLabel); newRowInfo.Struct.fields = &[0]TypeInfo.StructField{}; newColumnInfo.Struct.fields = &[0]TypeInfo.StructField{}; // Partition the fields into a new RowType & ColumnType // If the field is in `labels` then it goes in RowType inline for (dataFields) |field| { comptime var inLabels = false; inline for (labelFields) |labelField| { const label = @field(labels, labelField.name); if (std.mem.eql(u8, label, field.name)) { inLabels = true; break; } } if (inLabels) { newRowInfo.Struct.fields = newRowInfo.Struct.fields ++ [1]TypeInfo.StructField{field}; } else { newColumnInfo.Struct.fields = newColumnInfo.Struct.fields ++ [1]TypeInfo.StructField{field}; } } const NewRowType = @Type(newRowInfo); const NewColumnType = @Type(newColumnInfo); return DataFrame(NewRowType, NewColumnType); } pub fn reindex(self: Self, comptime labels: anytype) !ReindexType(labels) { const NewType = ReindexType(labels); var new = try NewType.initEmpty(self.data.allocator); for (self.data.items) |entry| { try new.data.append(std.mem.zeroInit(NewType.DataType, entry)); } return new; } fn PivotType(comptime index: []const u8, comptime columns: []const u8, comptime value: []const u8) comptime type { if (!@hasField(DataType, index)) { @compileError("pivot index \"" ++ index ++ "\" does not exist"); } if (!@hasField(DataType, columns)) { @compileError("pivot column \"" ++ columns ++ "\" does not exist"); } if (!@hasField(DataType, value)) { @compileError("pivot value \"" ++ value ++ "\" does not exist"); } if (std.mem.eql(u8, index, columns) or std.mem.eql(u8, index, value) or std.mem.eql(u8, columns, value)) { @compileError("pivot index, column, and value must all be unique"); } comptime var newRowInfo = @typeInfo(RowLabel); newRowInfo.Struct.fields = &[1]TypeInfo.StructField{ fieldByName(DataType, index) }; const NewRowType = @Type(newRowInfo); const ColumnFieldType = fieldByName(DataType, columns).field_type; if (@typeInfo(ColumnFieldType) != .Enum) { @compileError("column must be an enum: " ++ columns ++ ", " ++ @typeName(NewColumnType)); } const ValueType = fieldByName(DataType, value).field_type; const NewColumnType = std.enums.EnumFieldStruct(ColumnFieldType, ?ValueType, null); return DataFrame(NewRowType, NewColumnType); } pub fn pivot(self: Self, comptime index: []const u8, comptime columns: []const u8, comptime value: []const u8) !PivotType(index, columns, value) { const NewType = PivotType(index, columns, value); const ColumnEnum = fieldByName(DataType, columns).field_type; var new = try NewType.initEmpty(self.data.allocator); for (self.data.items) |entry, idx| { const newRow = idx == 0 or @field(entry, index) != @field(self.data.items[idx-1], index); var d = if (newRow) try new.data.addOne() else &new.data.items[new.data.items.len-1]; if (newRow) { d.* = initSubset(NewType.DataType, entry); } inline for (@typeInfo(NewType.ColumnType).Struct.fields) |field| { if (@field(entry, columns) == std.meta.stringToEnum(ColumnEnum, field.name)) { @field(d.*, field.name) = @field(entry, value); } } } return new; } pub fn format( self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { try writer.print("DataFrame [ ", .{}); inline for (rowFields) |field| { try writer.print("{s}:{} ", .{ field.name, field.field_type }); } try writer.print("] x [ ", .{}); inline for (columnFields) |field| { try writer.print("{s}:{} ", .{ field.name, field.field_type }); } try writer.print("] ({} rows) {{", .{ self.data.items.len }); if (self.data.items.len != 0) { try writer.print("\n", .{}); } for (self.data.items) |row, index| { const r = initSubset(RowType, row); const c = initSubset(ColumnType, row); try writer.print(" {}: {} = {},\n", .{ index, r, c }); } try writer.print("}}", .{}); } }; } test { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const C = enum { foo, bar, baz, }; const Entry = struct { a: usize, b: f64, c: C, d: bool, }; const Label = struct {}; const DF = DataFrame(Label, Entry); var df = try DF.initFromFile("abc.csv", &gpa.allocator); defer df.deinit(); try df.append(.{}, .{ .a = 4, .b = 2.0, .c = .foo, .d = true }); try df.append(.{}, .{ .a = 4, .b = 4.0, .c = .bar, .d = true }); try df.append(.{}, .{ .a = 4, .b = 6.0, .c = .baz, .d = false }); try df.append(.{}, .{ .a = 1, .b = 8.0, .c = .baz, .d = true }); df.sort("a"); std.debug.print("loaded abc.csv:\n{}\n", .{df}); var df2 = try df.reindex(.{"b"}); defer df2.deinit(); std.debug.print("after reindex:\n{}\n", .{df2}); var df3 = try df.pivot("a", "c", "b"); defer df3.deinit(); std.debug.print("after pivot:\n{}\n", .{df3}); }
df.zig
const std = @import("std"); const expect = std.testing.expect; // zig gets polymorphism/generics by using compile time functions that return a type /// DFS Iterator that visits/emits Nodes twice, once on start and when closing/ending /// skip_start_wo_children: skips is_end=false NodeInfo for items without children pub fn DepthFirstIterator( comptime T: type, comptime skip_start_wo_children: bool ) type { return struct { const Self = @This(); // polymorphic type // need struct to be able to signal nodes starting/ending for // postorder traversal pub const NodeInfo = struct { data: *T, is_end: bool, }; start: *T, next_item: ?NodeInfo, pub fn init(start: *T) Self { // TODO fix after this issue gets resolved: // Designated init of optional struct field segfaults in debug mode // https://github.com/ziglang/zig/issues/5573 // .data will always be null in code below even though start can't be // removing the .start field will result in Segfault when creating the NodeInfo struct // see test3.zig // initializing it outside the struct succeeds var next_item = NodeInfo{ .data = start, .is_end = false, }; var dfs = Self{ .start = start, .next_item = undefined, // .next_item = NodeInfo{ // .data = start, // .is_end = false, // }, }; dfs.next_item = next_item; return dfs; } // adapted from: https://github.com/kivikakk/koino/blob/main/src/ast.zig by kivikakk /// NOTE: only a .is_end = false is emitted for the starting node (no is_end=true)! pub fn next(self: *Self) ?NodeInfo { const item = self.next_item orelse return null; if (!item.is_end) { if (item.data.first_child) |child| { if (skip_start_wo_children) { self.next_item = NodeInfo{ .data = child, .is_end = if (child.first_child == null) true else false }; } else { self.next_item = NodeInfo{ .data = child, .is_end = false }; } } else { // end node since it doesn't have children self.next_item = NodeInfo{ .data = item.data, .is_end = true }; } } else { if (item.data == self.start) { // finish when reaching starting node // TODO also emit is_end for start node here? return null; } else if (item.data.next) |sibling| { // current node has been completely traversed -> q sibling // skip_start_sibling_wo_children is comptime known (comptime error if not) // and Zig implicitly inlines if expressions when the condition is // known at compile-time // -> one of these branches will not be part of the runtime function // depending on the bool passed to DepthFirstIterator // cant use comptime { } // since it forces the entire expression (inside {}) to be compile time // (which fails on sibling.first_child etc.) // so we just have to trust that this gets comptime evaluated (also called // inlined in Zig) since skip_start_sibling_wo_children is comptime if (skip_start_wo_children) { // NOTE: checking if sibling is also an end node that doesn't have children // so we don't get one is_end=true and one false version self.next_item = NodeInfo{ .data = sibling, .is_end = if (sibling.first_child == null) true else false, }; } else { self.next_item = NodeInfo{ .data = sibling, .is_end = false }; } } else if (item.data.parent) |parent| { // no siblings and no children (since is_end is false) -> signal // parent node has been traversed completely self.next_item = NodeInfo{ .data = parent, .is_end = true }; } else { unreachable; } } return item; } }; } /// intialize a union with a PayloadType that is known at comptime, but the tag and value only /// being known at runtime pub fn unionInitTagged(comptime U: type, tag: std.meta.Tag(U), comptime PayloadType: type, val: anytype) U { const uT = @typeInfo(U).Union; inline for (uT.fields) |union_field, enum_i| { // field types don't match -> otherwise @unionInit compile error if (union_field.field_type != PayloadType) continue; // check for active tag if (enum_i == @enumToInt(tag)) { // @compileLog("unionfield name ", union_field.name); // @compileLog("enum i ", enum_i, "tag ", @enumToInt(tag)); return @unionInit(U, union_field.name, val); } } // without this return type might be void unreachable; } // src: https://github.com/ziglang/zig/issues/9271 by dbandstra pub fn unionPayloadPtr(comptime T: type, union_ptr: anytype) ?*T { const U = @typeInfo(@TypeOf(union_ptr)).Pointer.child; inline for (@typeInfo(U).Union.fields) |field, i| { if (field.field_type != T) continue; std.debug.print("Ptrint: {d}\n", .{ @enumToInt(union_ptr.*) }); if (@enumToInt(union_ptr.*) == i) return &@field(union_ptr, field.name); } return null; } pub fn unionSetPayload(comptime T: type, union_ptr: anytype, value: T) void { const U = @typeInfo(@TypeOf(union_ptr)).Pointer.child; inline for (@typeInfo(U).Union.fields) |field, i| { if (field.field_type != T) continue; if (@enumToInt(union_ptr.*) == i) { @field(union_ptr, field.name) = value; break; } } else { unreachable; } } pub inline fn intDigits(x: anytype) !u8 { const T = @TypeOf(x); const tT = @typeInfo(T); comptime std.debug.assert(tT == .Int); comptime if (tT.Int.signedness == .unsigned) @compileError("Use uintDigits instead!"); comptime if (tT.Int.bits > 64) @compileError("Only integers up to 64bits are implemented!"); const abs_x = try std.math.absInt(x); comptime var uT = tT; // change type info to an unsigned integer with the same bit count uT.Int.signedness = .unsigned; // use bitCast to cast to unsigned which works due to twos complement // Docs for @bitCast: "Convert i32 to u32 preserving twos complement" // // use @Type(uT) to convert the modified typeInfo back to a type that we can use // @compileLog("Using ", @typeName(@Type(uT)), " for ", @typeName(T) ); // -> *"Using ", *"u29", *" for ", *"i29" return uintDigits(@bitCast(@Type(uT), abs_x)); } pub fn uintDigits(x: anytype) u8 { const T = @TypeOf(x); const tT = @typeInfo(T); comptime std.debug.assert(tT == .Int); comptime std.debug.assert(tT.Int.signedness == .unsigned); comptime if (tT.Int.bits > 64) @compileError("Only integers up to 64bits are implemented!"); if (x < 10) return 1; if (x < 100) return 2; if (x < 1000) return 3; if (x < 10000) return 4; if (x < 100000) return 5; if (x < 1000000) return 6; if (x < 10000000) return 7; if (x < 100000000) return 8; if (x < 1000000000) return 9; if (x < 10000000000) return 10; // 32bit if (x < 100000000000) return 11; if (x < 1000000000000) return 12; if (x < 10000000000000) return 13; if (x < 100000000000000) return 14; if (x < 1000000000000000) return 15; if (x < 10000000000000000) return 16; if (x < 100000000000000000) return 17; if (x < 1000000000000000000) return 18; if (x < 10000000000000000000) return 19; return 20; // 64bit } test "uintDigits" { var x: u13 = 4736; try expect(uintDigits(x) == 4); var y: u32 = 2004234; try expect(uintDigits(y) == 7); var z: u64 = 18446744073709551615; try expect(uintDigits(z) == 20); // TODO test compileError once implemented // https://github.com/ziglang/zig/issues/513 } test "intDigits" { var x: i14 = -4736; try expect((try intDigits(x)) == 4); var y: i32 = 2004234; try expect((try intDigits(y)) == 7); var z: i64 = -9223372036854775807; try expect((try intDigits(z)) == 19); // overflow error var w: i64 = -9223372036854775808; try std.testing.expectError(error.Overflow, intDigits(w)); // TODO test compileError once implemented // https://github.com/ziglang/zig/issues/513 } /// all of the string is_.. functions are ascii only!! pub inline fn is_alpha(char: u8) bool { if ((char >= 'A' and char <= 'Z') or (char >= 'a' and char <= 'z')) { return true; } else { return false; } } pub inline fn is_num(char: u8) bool { if (char >= '0' and char <= '9') { return true; } else { return false; } } pub inline fn is_alphanum(char: u8) bool { if (is_alpha(char) or is_num(char)) { return true; } else { return false; } } pub inline fn is_lowercase(char: u8) bool { if (char >= 'a' and char <= 'z') { return true; } else { return false; } } pub inline fn is_uppercase(char: u8) bool { if (char >= 'A' and char <= 'Z') { return true; } else { return false; } } pub inline fn is_end_of_line(char: u8) bool { if ((char == '\r') or (char == '\n')) { return true; } else { return false; } } pub inline fn is_space_or_tab(char: u8) bool { if ((char == ' ') or (char == '\t')) { return true; } else { return false; } } pub inline fn is_whitespace(char: u8) bool { if (is_space_or_tab(char) or is_end_of_line(char)) { return true; } else { return false; } }
src/utils.zig
const std = @import("std"); const assert = std.debug.assert; const math = std.math; const mem = std.mem; const testing = std.testing; const log = std.log.scoped(.yaml); const Allocator = mem.Allocator; pub const Tokenizer = @import("Tokenizer.zig"); pub const parse = @import("parse.zig"); const Node = parse.Node; const Tree = parse.Tree; const ParseError = parse.ParseError; pub const YamlError = error{UnexpectedNodeType} || ParseError || std.fmt.ParseIntError; pub const ValueType = enum { empty, int, float, string, list, map }; pub const Value = union(ValueType) { empty, int: u64, float: f64, string: []const u8, list: []Value, map: std.StringArrayHashMapUnmanaged(Value), fn deinit(self: *Value, allocator: *Allocator) void { switch (self.*) { .list => |arr| { for (arr) |*value| { value.deinit(allocator); } allocator.free(arr); }, .map => |*m| { for (m.values()) |*value| { value.deinit(allocator); } m.deinit(allocator); }, else => {}, } } fn fromNode(allocator: *Allocator, tree: *const Tree, node: *const Node, type_hint: ?ValueType) YamlError!Value { if (node.cast(Node.Doc)) |doc| { const inner = doc.value orelse { // empty doc return Value{ .empty = .{} }; }; return Value.fromNode(allocator, tree, inner, null); } else if (node.cast(Node.Map)) |map| { var out_map: std.StringArrayHashMapUnmanaged(Value) = .{}; errdefer out_map.deinit(allocator); try out_map.ensureUnusedCapacity(allocator, map.values.items.len); for (map.values.items) |entry| { const key_tok = tree.tokens[entry.key]; const key = tree.source[key_tok.start..key_tok.end]; const value = try Value.fromNode(allocator, tree, entry.value, null); out_map.putAssumeCapacityNoClobber(key, value); } return Value{ .map = out_map }; } else if (node.cast(Node.List)) |list| { var out_list = std.ArrayList(Value).init(allocator); errdefer out_list.deinit(); try out_list.ensureUnusedCapacity(list.values.items.len); if (list.values.items.len > 0) { const hint = if (list.values.items[0].cast(Node.Value)) |value| hint: { const elem = list.values.items[0]; const start = tree.tokens[value.start.?]; const end = tree.tokens[value.end.?]; const raw = tree.source[start.start..end.end]; _ = std.fmt.parseInt(u64, raw, 10) catch { _ = std.fmt.parseFloat(f64, raw) catch { break :hint ValueType.string; }; break :hint ValueType.float; }; break :hint ValueType.int; } else null; for (list.values.items) |elem| { const value = try Value.fromNode(allocator, tree, elem, hint); out_list.appendAssumeCapacity(value); } } return Value{ .list = out_list.toOwnedSlice() }; } else if (node.cast(Node.Value)) |value| { const start = tree.tokens[value.start.?]; const end = tree.tokens[value.end.?]; const raw = tree.source[start.start..end.end]; if (type_hint) |hint| { return switch (hint) { .int => Value{ .int = try std.fmt.parseInt(u64, raw, 10) }, .float => Value{ .float = try std.fmt.parseFloat(f64, raw) }, .string => Value{ .string = raw }, else => unreachable, }; } try_int: { // TODO infer base for int const int = std.fmt.parseInt(u64, raw, 10) catch break :try_int; return Value{ .int = int }; } try_float: { const float = std.fmt.parseFloat(f64, raw) catch break :try_float; return Value{ .float = float }; } return Value{ .string = raw }; } else { log.err("Unexpected node type: {}", .{node.tag}); return error.UnexpectedNodeType; } } }; pub const Yaml = struct { allocator: *Allocator, tree: ?Tree = null, docs: std.ArrayListUnmanaged(Value) = .{}, pub fn deinit(self: *Yaml) void { if (self.tree) |*tree| { tree.deinit(); } for (self.docs.items) |*value| { value.deinit(self.allocator); } self.docs.deinit(self.allocator); } pub fn load(allocator: *Allocator, source: []const u8) !Yaml { var tree = Tree.init(allocator); errdefer tree.deinit(); try tree.parse(source); var docs: std.ArrayListUnmanaged(Value) = .{}; errdefer docs.deinit(allocator); try docs.ensureUnusedCapacity(allocator, tree.docs.items.len); for (tree.docs.items) |node| { const value = try Value.fromNode(allocator, &tree, node, null); docs.appendAssumeCapacity(value); } return Yaml{ .allocator = allocator, .tree = tree, .docs = docs, }; } pub const Error = error{ EmptyYaml, MultiDocUnsupported, StructFieldMissing, ArraySizeMismatch, Overflow, }; pub fn parse(self: *const Yaml, comptime T: type) Error!T { if (self.docs.items.len == 0) return error.EmptyYaml; if (self.docs.items.len > 1) return error.MultiDocUnsupported; switch (@typeInfo(T)) { .Struct => return self.parseStruct(T, self.docs.items[0].map), .Array => return self.parseArray(T, self.docs.items[0].list), .Void => unreachable, else => @compileError("unimplemented for " ++ @typeName(T)), } } fn parseStruct(self: *const Yaml, comptime T: type, map: anytype) Error!T { const struct_info = @typeInfo(T).Struct; var parsed: T = undefined; inline for (struct_info.fields) |field| { const value = map.get(field.name) orelse return error.StructFieldMissing; switch (@typeInfo(field.field_type)) { .Int => { @field(parsed, field.name) = try math.cast(field.field_type, value.int); }, .Float => { @field(parsed, field.name) = math.lossyCast(field.field_type, value.float); }, .Pointer => |ptr_info| { switch (ptr_info.size) { .One => @compileError("unimplemented for pointer to " ++ @typeName(ptr_info.child)), .Slice => { switch (@typeInfo(ptr_info.child)) { .Int => |int_info| { if (int_info.bits == 8) { @field(parsed, field.name) = value.string; } else { @field(parsed, field.name) = try math.cast(field.field_type, value.int); } }, .Float => { @field(parsed, field.name) = math.lossyCast(field.field_type, value.float); }, else => @compileError("unimplemented for " ++ @typeName(ptr_info.child)), } }, else => @compileError("unimplemented for pointer to many " ++ @typeName(ptr_info.child)), } }, .Array => { @field(parsed, field.name) = try self.parseArray(field.field_type, value.list); }, else => @compileError("unimplemented for " ++ @typeName(field.field_type)), } } return parsed; } fn parseArray(self: *const Yaml, comptime T: type, list: []Value) Error!T { const array_info = @typeInfo(T).Array; if (array_info.len != list.len) return error.ArraySizeMismatch; var parsed: T = undefined; switch (@typeInfo(array_info.child)) { .Int => { for (list) |value, i| { parsed[i] = try math.cast(array_info.child, value.int); } }, .Float => { for (list) |value, i| { parsed[i] = math.lossyCast(array_info.child, value.float); } }, .Pointer => |ptr_info| { switch (ptr_info.size) { .One => @compileError("unimplemented for pointer to " ++ @typeName(ptr_info.child)), .Slice => { switch (@typeInfo(ptr_info.child)) { .Int => |int_info| { if (int_info.bits == 8) { for (list) |value, i| { parsed[i] = value.string; } } else { for (list) |value, i| { parsed[i] = try math.cast(field.field_type, value.int); } } }, .Float => { for (list) |value, i| { parsed[i] = math.lossyCast(field.field_type, value.float); } }, else => @compileError("unimplemented for " ++ @typeName(ptr_info.child)), } }, else => @compileError("unimplemented for pointer to many " ++ @typeName(ptr_info.child)), } }, else => @compileError("unimplemented for " ++ @typeName(array_info.child)), } return parsed; } }; test { testing.refAllDecls(@This()); } test "simple list" { const source = \\- a \\- b \\- c ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectEqual(yaml.docs.items.len, 1); const list = yaml.docs.items[0].list; try testing.expectEqual(list.len, 3); try testing.expect(mem.eql(u8, list[0].string, "a")); try testing.expect(mem.eql(u8, list[1].string, "b")); try testing.expect(mem.eql(u8, list[2].string, "c")); } test "simple list typed as array of strings" { const source = \\- a \\- b \\- c ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectEqual(yaml.docs.items.len, 1); const arr = try yaml.parse([3][]const u8); try testing.expectEqual(arr.len, 3); try testing.expect(mem.eql(u8, arr[0], "a")); try testing.expect(mem.eql(u8, arr[1], "b")); try testing.expect(mem.eql(u8, arr[2], "c")); } test "simple list typed as array of ints" { const source = \\- 0 \\- 1 \\- 2 ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectEqual(yaml.docs.items.len, 1); const arr = try yaml.parse([3]u8); try testing.expectEqual(arr.len, 3); try testing.expectEqual(arr[0], 0); try testing.expectEqual(arr[1], 1); try testing.expectEqual(arr[2], 2); } test "simple map untyped" { const source = \\a: 0 ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectEqual(yaml.docs.items.len, 1); const map = yaml.docs.items[0].map; try testing.expect(map.contains("a")); try testing.expectEqual(map.get("a").?.int, 0); } test "simple map typed" { const source = \\a: 0 \\b: hello there \\c: 'wait, what?' ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); const simple = try yaml.parse(struct { a: usize, b: []const u8, c: []const u8 }); try testing.expectEqual(simple.a, 0); try testing.expect(mem.eql(u8, simple.b, "hello there")); try testing.expect(mem.eql(u8, simple.c, "wait, what?")); } test "multidoc typed not supported yet" { const source = \\--- \\a: 0 \\... \\--- \\- 0 \\... ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectError(Yaml.Error.MultiDocUnsupported, yaml.parse(struct { a: usize })); try testing.expectError(Yaml.Error.MultiDocUnsupported, yaml.parse([1]usize)); } test "empty yaml typed not supported" { const source = ""; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectError(Yaml.Error.EmptyYaml, yaml.parse(void)); } test "typed array size mismatch" { const source = \\- 0 \\- 0 ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectError(Yaml.Error.ArraySizeMismatch, yaml.parse([1]usize)); try testing.expectError(Yaml.Error.ArraySizeMismatch, yaml.parse([5]usize)); } test "typed struct missing field" { const source = \\bar: 10 ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectError(Yaml.Error.StructFieldMissing, yaml.parse(struct { foo: usize })); try testing.expectError(Yaml.Error.StructFieldMissing, yaml.parse(struct { foobar: usize })); }
src/main.zig
const LibExeObjStep = @import("std").build.LibExeObjStep; pub const Pkg = struct { name: []const u8, path: []const u8, }; pub const packages = [_]Pkg{ Pkg{ .name = "cmd/commands", .path = "src/cmd/commands.zig" }, Pkg{ .name = "cmd/doc", .path = "src/cmd/doc.zig" }, Pkg{ .name = "cmd/docs/html", .path = "src/cmd/docs/html.zig" }, Pkg{ .name = "cmd/fmt", .path = "src/cmd/fmt.zig" }, Pkg{ .name = "cmd/imports", .path = "src/cmd/imports.zig" }, Pkg{ .name = "cmd/lsp", .path = "src/cmd/lsp.zig" }, Pkg{ .name = "cmd/outline", .path = "src/cmd/outline.zig" }, Pkg{ .name = "cmd/package", .path = "src/cmd/package.zig" }, Pkg{ .name = "cmd/pkg/exports", .path = "src/cmd/pkg/exports.zig" }, Pkg{ .name = "compress/flate/bits", .path = "src/compress/flate/bits.zig" }, Pkg{ .name = "compress/flate/huffman", .path = "src/compress/flate/huffman.zig" }, Pkg{ .name = "flags", .path = "src/flags/flags.zig" }, Pkg{ .name = "hoodie", .path = "src/hoodie.zig" }, Pkg{ .name = "html", .path = "src/html/html.zig" }, Pkg{ .name = "ignore", .path = "src/ignore/ignore.zig" }, Pkg{ .name = "image", .path = "src/image/image.zig" }, Pkg{ .name = "json", .path = "src/json/json.zig" }, Pkg{ .name = "lsp/diff", .path = "src/lsp/diff/diff.zig" }, Pkg{ .name = "lsp/jsonrpc2", .path = "src/lsp/jsonrpc2/jsonrpc2.zig" }, Pkg{ .name = "lsp/protocol", .path = "src/lsp/protocol/protocol.zig" }, Pkg{ .name = "lsp/server", .path = "src/lsp/server/server.zig" }, Pkg{ .name = "lsp/snippet", .path = "src/lsp/snippet/snippet.zig" }, Pkg{ .name = "lsp/span", .path = "src/lsp/span/span.zig" }, Pkg{ .name = "markdown", .path = "src/markdown/markdown.zig" }, Pkg{ .name = "net/url", .path = "src/net/url/url.zig" }, Pkg{ .name = "outline", .path = "src/outline/outline.zig" }, Pkg{ .name = "path/file_info", .path = "src/path/file_info.zig" }, Pkg{ .name = "path/filepath/match", .path = "src/path/filepath/match.zig" }, Pkg{ .name = "path/filepath/path", .path = "src/path/filepath/path.zig" }, Pkg{ .name = "path/match", .path = "src/path/match.zig" }, Pkg{ .name = "pkg/dirhash", .path = "src/pkg/dirhash/dirhash.zig" }, Pkg{ .name = "pkg/exports", .path = "src/pkg/exports/exports.zig" }, Pkg{ .name = "pkg/module", .path = "src/pkg/module.zig" }, Pkg{ .name = "pkg/module_info", .path = "src/pkg/module_info.zig" }, Pkg{ .name = "pkg/semver", .path = "src/pkg/semver/semver.zig" }, Pkg{ .name = "result", .path = "src/result/result.zig" }, Pkg{ .name = "strings", .path = "src/strings/strings.zig" }, Pkg{ .name = "template", .path = "src/template/template.zig" }, Pkg{ .name = "time", .path = "src/time/time.zig" }, Pkg{ .name = "token", .path = "src/token/token.zig" }, Pkg{ .name = "unicode", .path = "src/unicode/index.zig" }, Pkg{ .name = "zig/types", .path = "src/zig/types.zig" }, }; pub fn setupPakcages(steps: []*LibExeObjStep) void { for (steps) |step| { for (packages) |pkg| { step.addPackagePath(pkg.name, pkg.path); } } }
EXPORTS.zig
const zt = @import("deps/ZT/src/zt.zig"); const std = @import("std"); const sling = @import("sling.zig"); const ig = @import("imgui"); const glfw = @import("glfw"); pub var worldMouseDelta: sling.math.Vec2 = .{}; pub var worldMouse: sling.math.Vec2 = .{}; pub var mouse: sling.math.Vec2 = .{}; pub var mouseDelta: sling.math.Vec2 = .{}; pub var mwheel: f32 = 0; var io: [*c]ig.ImGuiIO = undefined; pub var config: struct { /// If true, mouse input is stopped when hovering over an imgui panel, /// and key input is halted when entering text. imguiBlocksInput: bool = true, } = .{}; pub const Key = enum(c_int) { // Mouse lmb = glfw.GLFW_MOUSE_BUTTON_LEFT, rmb = glfw.GLFW_MOUSE_BUTTON_RIGHT, mmb = glfw.GLFW_MOUSE_BUTTON_MIDDLE, // Mods lCtrl = glfw.GLFW_KEY_LEFT_CONTROL, rCtrl = glfw.GLFW_KEY_RIGHT_CONTROL, lAlt = glfw.GLFW_KEY_LEFT_ALT, rAlt = glfw.GLFW_KEY_RIGHT_ALT, lShift = glfw.GLFW_KEY_LEFT_SHIFT, rShift = glfw.GLFW_KEY_RIGHT_SHIFT, // Special capslock = glfw.GLFW_KEY_CAPS_LOCK, tilde = glfw.GLFW_KEY_GRAVE_ACCENT, backslash = glfw.GLFW_KEY_BACKSLASH, forwardslash = glfw.GLFW_KEY_SLASH, backspace = glfw.GLFW_KEY_BACKSPACE, tab = glfw.GLFW_KEY_TAB, escape = glfw.GLFW_KEY_ESCAPE, comma = glfw.GLFW_KEY_COMMA, period = glfw.GLFW_KEY_PERIOD, semicolon = glfw.GLFW_KEY_SEMICOLON, openBracket = glfw.GLFW_KEY_LEFT_BRACKET, closeBracket = glfw.GLFW_KEY_RIGHT_BRACKET, apostraphe = glfw.GLFW_KEY_APOSTROPHE, space = glfw.GLFW_KEY_SPACE, enter = glfw.GLFW_KEY_ENTER, // Arrows arrowUp = glfw.GLFW_KEY_UP, arrowDown = glfw.GLFW_KEY_DOWN, arrowLeft = glfw.GLFW_KEY_LEFT, arrowRight = glfw.GLFW_KEY_RIGHT, // F Keys f1_ = glfw.GLFW_KEY_F1, f2_ = glfw.GLFW_KEY_F2, f3_ = glfw.GLFW_KEY_F3, f4_ = glfw.GLFW_KEY_F4, f5_ = glfw.GLFW_KEY_F5, f6_ = glfw.GLFW_KEY_F6, f7_ = glfw.GLFW_KEY_F7, f8_ = glfw.GLFW_KEY_F8, f9_ = glfw.GLFW_KEY_F9, f10_ = glfw.GLFW_KEY_F10, f11_ = glfw.GLFW_KEY_F11, f12_ = glfw.GLFW_KEY_F12, f13_ = glfw.GLFW_KEY_F13, f14_ = glfw.GLFW_KEY_F14, f15_ = glfw.GLFW_KEY_F15, f16_ = glfw.GLFW_KEY_F16, f17_ = glfw.GLFW_KEY_F17, f18_ = glfw.GLFW_KEY_F18, f19_ = glfw.GLFW_KEY_F19, f20_ = glfw.GLFW_KEY_F20, f21_ = glfw.GLFW_KEY_F21, f22_ = glfw.GLFW_KEY_F22, f23_ = glfw.GLFW_KEY_F23, f24_ = glfw.GLFW_KEY_F24, f25_ = glfw.GLFW_KEY_F25, // Numeric n1 = glfw.GLFW_KEY_1, n2 = glfw.GLFW_KEY_2, n3 = glfw.GLFW_KEY_3, n4 = glfw.GLFW_KEY_4, n5 = glfw.GLFW_KEY_5, n6 = glfw.GLFW_KEY_6, n7 = glfw.GLFW_KEY_7, n8 = glfw.GLFW_KEY_8, n9 = glfw.GLFW_KEY_9, n0 = glfw.GLFW_KEY_0, minus = glfw.GLFW_KEY_MINUS, equals = glfw.GLFW_KEY_EQUAL, // Alpha q = glfw.GLFW_KEY_Q, w = glfw.GLFW_KEY_W, e = glfw.GLFW_KEY_E, r = glfw.GLFW_KEY_R, t = glfw.GLFW_KEY_T, y = glfw.GLFW_KEY_Y, u = glfw.GLFW_KEY_U, i = glfw.GLFW_KEY_I, o = glfw.GLFW_KEY_O, p = glfw.GLFW_KEY_P, a = glfw.GLFW_KEY_A, s = glfw.GLFW_KEY_S, d = glfw.GLFW_KEY_D, f = glfw.GLFW_KEY_F, g = glfw.GLFW_KEY_G, h = glfw.GLFW_KEY_H, j = glfw.GLFW_KEY_J, k = glfw.GLFW_KEY_K, l = glfw.GLFW_KEY_L, z = glfw.GLFW_KEY_Z, x = glfw.GLFW_KEY_X, c = glfw.GLFW_KEY_C, v = glfw.GLFW_KEY_V, b = glfw.GLFW_KEY_B, n = glfw.GLFW_KEY_N, m = glfw.GLFW_KEY_M, inline fn keyCheck(key: Key) bool { if (key.isMouse()) { if (config.imguiBlocksInput and io.*.WantCaptureMouse) { return false; } return io.*.MouseDown[@intCast(usize, @enumToInt(key))]; } else { if (config.imguiBlocksInput and io.*.WantCaptureKeyboard) { return false; } return io.*.KeysDown[@intCast(usize, @enumToInt(key))]; } } inline fn keyDur(key: Key) f32 { if (key.isMouse()) { if (config.imguiBlocksInput and io.*.WantCaptureMouse) { return 0.0; } return io.*.MouseDownDuration[@intCast(usize, @enumToInt(key))]; } else { if (config.imguiBlocksInput and io.*.WantCaptureKeyboard) { return 0.0; } return io.*.KeysDownDuration[@intCast(usize, @enumToInt(key))]; } } inline fn keyPrevDur(key: Key) f32 { if (key.isMouse()) { return io.*.MouseDownDurationPrev[@intCast(usize, @enumToInt(key))]; } else { return io.*.KeysDownDurationPrev[@intCast(usize, @enumToInt(key))]; } } /// True only for the frame it is pressed down. pub fn pressed(key: Key) bool { return keyDur(key) == 0; } /// True only for the frame it is released. pub fn released(key: Key) bool { return keyPrevDur(key) >= 0 and !keyCheck(key); } /// True when down, including when pressed. pub fn down(key: Key) bool { return keyCheck(key); } /// True when up, including when released pub fn up(key: Key) bool { return !down(key); } /// Inspects the key, if its a mouse button returns true. /// Does not inspect the state of the button, just what the button is. pub fn isMouse(key: Key) bool { return @enumToInt(key) >= 0 and @enumToInt(key) <= 2; } /// Inspects the key, if its a character key returns true. /// Does not inspect the state of the key, just what the key is. pub fn isAlpha(key: Key) bool { return @enumToInt(key) >= 65 and @enumToInt(key) <= 90; } /// Inspects the key, if its a character key returns true. /// Does not inspect the state of the key, just what the key is. pub fn isNumeric(key: Key) bool { return @enumToInt(key) >= 48 and @enumToInt(key) <= 57; } }; var prevWorldMouse: sling.math.Vec2 = .{ .x = -1, .y = -1 }; pub fn pump() void { io = ig.igGetIO(); mouse = io.*.MousePos; mouseDelta = io.*.MouseDelta; worldMouse = sling.render.camera.screenToWorld(mouse); if (prevWorldMouse.x == -1.0 and prevWorldMouse.y == -1.0) { prevWorldMouse = worldMouse; } worldMouseDelta = worldMouse.sub(prevWorldMouse); if (config.imguiBlocksInput and io.*.WantCaptureMouse) { mwheel = 0; } else { mwheel = io.*.MouseWheel; } prevWorldMouse = worldMouse; }
src/input.zig
const math = @import("std").math; // => https://youtu.be/LWFzPP8ZbdU?list=FLOZKYzNJILemcDKZwSBSoyg&t=2817 squirrel3 code in C++ // => https://youtu.be/LWFzPP8ZbdU?list=FLOZKYzNJILemcDKZwSBSoyg&t=3167 SquirrelRng API in C++ // => https://github.com/sublee/squirrel3-python/blob/master/squirrel3.py pub fn squirrel3_u32(position: u32, seed: u32) u32 { const noise1 = 0xB5297A4D; const noise2 = 0x68E31DA4; const noise3 = 0x1B56C4E9; const m1 = position *% noise1 +% seed; const m2 = (m1 ^ (m1 >> 8)) +% noise2; const m3 = (m2 ^ (m2 << 8)) *% noise3; const m4 = m3 ^ (m3 >> 8); return m4; } pub fn u32_(position: u32, seed: u32) u32 { return squirrel3_u32(position, seed); } pub fn u32LtBiased(position: u32, seed: u32, limit: u32) u32 { return @intCast(u32, @intCast(u64, u32_(position, seed)) * limit >> 32); } pub fn mixiBiased(position: u32, seed: u32, low: u32, high: u32) u32 { return u32LtBiased(position, seed, high - low + 1) + low; } pub fn f01(position: u32, seed: u32) f64 { return @intToFloat(f64, u32_(position, seed)) / 0xFFFFFFFF; } pub fn mixf(position: u32, seed: u32, low: f64, high: f64) f64 { return f01(position, seed) * (high - low) + low; } pub fn chance(position: u32, seed: u32, probability: f64) bool { return u32_(position, seed) < @floatToInt(u32, probability * 0xFFFFFFFF); } pub const SquirrelU32Noise = struct { const Self = @This(); seed: u32 = 0, pub fn init(seed: u32) Self { return .{ .seed = seed }; } pub fn u32_(self: *const Self, position: u32) u32 { return squirrel3_u32(position, self.seed); } }; pub const SquirrelU32Rng = struct { const Self = @This(); position: u32 = 0, seed: u32 = 0, pub fn init(seed: u32) Self { return .{ .seed = seed }; } pub fn u32_(self: *Self) u32 { const result = squirrel3_u32(self.position, self.seed); self.position += 1; return result; } }; pub fn boxMuller(mu: f64, sigma: f64, uniform1: f64, uniform2: f64) f64 { // TODO: assert uniform1 > epsilon const mag = sigma * math.sqrt(math.ln(uniform1) * -2); const tau: f64 = 6.28318530717958647; const z0 = math.cos(uniform2 * tau) * mag + mu; //const z1 = math.sin(tau * uniform2) * mag + mu; // second random gausian value (two random numbers in, two out) return z0; } pub fn MakeRng(comptime U32Rng: type) type { return struct { const Self = @This(); source: U32Rng, pub fn init(seed: u32) Self { return .{ .source = U32Rng.init(seed) }; } pub fn u32_(self: *Self) u32 { return self.source.u32_(); } pub fn rng(self: *Self) Self { return Self.init(self.u32_()); } pub fn u32LtBiased(self: *Self, limit: u32) u32 { return @intCast(u32, @intCast(u64, self.u32_()) * limit >> 32); } pub fn u32Lt(self: *Self, limit: u32) u32 { const limit64 = @intCast(u64, limit); const t = (((1 << 32) - limit64) * limit64) >> 32; while (true) { const x = self.u32_(); if (x >= t) { return @intCast(u32, (x * limit64) >> 32); } } } pub fn mixi(self: *Self, low: u32, high: u32) u32 { return self.u32Lt(high - low + 1) + low; } pub fn mixiBiased(self: *Self, low: u32, high: u32) u32 { return self.u32LtBiased(high - low + 1) + low; } pub fn f01(self: *Self) f64 { return @intToFloat(f64, self.u32_()) / 0xFFFFFFFF; } pub fn mixf(self: *Self, low: f64, high: f64) f64 { return self.f01() * (high - low) + low; } pub fn quantize01(self: *Self, n: u32) f64 { return @intToFloat(f64, self.u32Lt(n)) / @intToFloat(f64, n); } pub fn chance(self: *Self, probability: f64) bool { return self.u32_() < @floatToInt(u32, probability * 0xFFFFFFFF); } pub fn normal(self: *Self, mu: f64, sigma: f64) f64 { return boxMuller(mu, sigma, self.f01(), self.f01()); } }; } pub const SquirrelRng = MakeRng(SquirrelU32Rng); pub const squirrelRng = SquirrelRng.init; pub fn MakeNoise(comptime U32Noise: type) type { return struct { const Self = @This(); noise: U32Noise, pub fn init(seed: u32) Self { return .{ .noise = U32Noise.init(seed) }; } pub fn u32_(self: *const Self, position: u32) u32 { return self.noise.u32_(position); } pub fn u32LtBiased(self: *const Self, limit: u32, position: u32) u32 { return @intCast(u32, @intCast(u64, self.u32_(position)) * limit >> 32); } pub fn u32Lt(self: *const Self, limit: u32, position: u32) u32 { const limit64 = @intCast(u64, limit); const t = (((1 << 32) - limit64) * limit64) >> 32; var i = 0; while (true) { const x = self.u32_(position +% i); if (x >= t) { return @intCast(u32, (x * limit64) >> 32); } i += 1; } } pub fn mixi(self: *const Self, low: u32, high: u32, position: u32) u32 { return self.u32Lt(high - low + 1, position) + low; } pub fn mixiBiased(self: *const Self, low: u32, high: u32, position: u32) u32 { return self.u32LtBiased(high - low + 1, position) + low; } pub fn f01(self: *const Self, position: u32) f64 { return @intToFloat(f64, self.u32_(position)) / 0xFFFFFFFF; } pub fn mixf(self: *const Self, low: f64, high: f64, position: u32) f64 { return self.f01(position) * (high - low) + low; } pub fn chance(self: *const Self, probability: f64, position: u32) bool { return self.u32_(position) < @floatToInt(u32, probability * 0xFFFFFFFF); } pub fn normal(self: *const Self, mu: f64, sigma: f64, position1: u32, position2: u32) f64 { return boxMuller(mu, sigma, self.f01(position1), self.f01(position2)); } }; } pub const SquirrelNoise = MakeNoise(SquirrelU32Noise); pub const squirrelNoise = SquirrelNoise.init;
lib/squirrel3noise.zig
const std = @import("std"); pub fn flameShotLinux(alloc: *std.mem.Allocator) !bool { const args = [_][]const u8{ "/usr/bin/flameshot", "full", "-p", "/tmp/slide_shots", }; if (std.ChildProcess.init(args[0..], alloc)) |child| { defer child.deinit(); // TODO: this only works in debug builds // release builds return unexpected (literally) errors // one release mode, release-fast I think, returns some panic in thread if (child.spawnAndWait()) |_| { return true; } else |err| { std.log.err("Unable to spawn and wait: {any}", .{err}); switch (err) { error.AccessDenied => { std.log.err("AccessDenied", .{}); }, error.BadPathName => { std.log.err("BadPathName", .{}); }, error.CurrentWorkingDirectoryUnlinked => { std.log.err("CurrentWorkingDirectoryUnlinked", .{}); }, error.FileBusy => { std.log.err("FileBusy", .{}); }, error.FileNotFound => { std.log.err("FileNotFound", .{}); }, error.FileSystem => { std.log.err("FileSystem", .{}); }, error.InvalidExe => { std.log.err("InvalidExe", .{}); }, error.InvalidName => { std.log.err("InvalidName", .{}); }, error.InvalidUserId => { std.log.err("InvalidUserId", .{}); }, error.InvalidUtf8 => { std.log.err("InvalidUtf8", .{}); }, error.IsDir => { std.log.err("IsDir", .{}); }, error.NameTooLong => { std.log.err("NameTooLong", .{}); }, error.NoDevice => { std.log.err("NoDevice", .{}); }, error.NotDir => { std.log.err("NotDir", .{}); }, error.OutOfMemory => { std.log.err("OutOfMemory", .{}); }, error.PermissionDenied => { std.log.err("PermissionDenied", .{}); }, error.ProcessFdQuotaExceeded => { std.log.err("ProcessFdQuotaExceeded", .{}); }, error.ResourceLimitReached => { std.log.err("ResourceLimitReached", .{}); }, error.SymLinkLoop => { std.log.err("SymLinkLoop", .{}); }, error.SystemFdQuotaExceeded => { std.log.err("SystemFdQuotaExceeded", .{}); }, error.SystemResources => { std.log.err("SystemResources", .{}); }, error.Unexpected => { std.log.err("Unexpected", .{}); }, error.WaitAbandoned => { std.log.err("WaitAbandoned", .{}); }, error.WaitTimeOut => { std.log.err("WaitTimeOut", .{}); }, } } } else |err| { std.log.err("Unable to init child process: {any}", .{err}); } return false; }
src/screenshot.zig
const std = @import("std"); const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const mem = std.mem; test "continue in for loop" { const array = [_]i32{ 1, 2, 3, 4, 5, }; var sum: i32 = 0; for (array) |x| { sum += x; if (x < 3) { continue; } break; } if (sum != 6) unreachable; } test "for loop with pointer elem var" { const source = "abcdefg"; var target: [source.len]u8 = undefined; mem.copy(u8, target[0..], source); mangleString(target[0..]); expect(mem.eql(u8, &target, "bcdefgh")); for (source) |*c, i| expect(@TypeOf(c) == *const u8); for (target) |*c, i| expect(@TypeOf(c) == *u8); } fn mangleString(s: []u8) void { for (s) |*c| { c.* += 1; } } test "basic for loop" { const expected_result = [_]u8{ 9, 8, 7, 6, 0, 1, 2, 3 } ** 3; var buffer: [expected_result.len]u8 = undefined; var buf_index: usize = 0; const array = [_]u8{ 9, 8, 7, 6 }; for (array) |item| { buffer[buf_index] = item; buf_index += 1; } for (array) |item, index| { buffer[buf_index] = @intCast(u8, index); buf_index += 1; } const array_ptr = &array; for (array_ptr) |item| { buffer[buf_index] = item; buf_index += 1; } for (array_ptr) |item, index| { buffer[buf_index] = @intCast(u8, index); buf_index += 1; } const unknown_size: []const u8 = &array; for (unknown_size) |item| { buffer[buf_index] = item; buf_index += 1; } for (unknown_size) |item, index| { buffer[buf_index] = @intCast(u8, index); buf_index += 1; } expect(mem.eql(u8, buffer[0..buf_index], &expected_result)); } test "break from outer for loop" { testBreakOuter(); comptime testBreakOuter(); } fn testBreakOuter() void { var array = "aoeu"; var count: usize = 0; outer: for (array) |_| { for (array) |_| { count += 1; break :outer; } } expect(count == 1); } test "continue outer for loop" { testContinueOuter(); comptime testContinueOuter(); } fn testContinueOuter() void { var array = "aoeu"; var counter: usize = 0; outer: for (array) |_| { for (array) |_| { counter += 1; continue :outer; } } expect(counter == array.len); } test "2 break statements and an else" { const S = struct { fn entry(t: bool, f: bool) void { var buf: [10]u8 = undefined; var ok = false; ok = for (buf) |item| { if (f) break false; if (t) break true; } else false; expect(ok); } }; S.entry(true, false); comptime S.entry(true, false); } test "for with null and T peer types and inferred result location type" { const S = struct { fn doTheTest(slice: []const u8) void { if (for (slice) |item| { if (item == 10) { break item; } } else null) |v| { @panic("fail"); } } }; S.doTheTest(&[_]u8{ 1, 2 }); comptime S.doTheTest(&[_]u8{ 1, 2 }); } test "for copies its payload" { const S = struct { fn doTheTest() void { var x = [_]usize{ 1, 2, 3 }; for (x) |value, i| { // Modify the original array x[i] += 99; expectEqual(value, i + 1); } } }; S.doTheTest(); comptime S.doTheTest(); } test "for on slice with allowzero ptr" { const S = struct { fn doTheTest(slice: []const u8) void { var ptr = @ptrCast([*]const allowzero u8, slice.ptr)[0..slice.len]; for (ptr) |x, i| expect(x == i + 1); for (ptr) |*x, i| expect(x.* == i + 1); } }; S.doTheTest(&[_]u8{ 1, 2, 3, 4 }); comptime S.doTheTest(&[_]u8{ 1, 2, 3, 4 }); }
test/stage1/behavior/for.zig
const std = @import("std"); const builtin = @import("builtin"); const mem = std.mem; const expect = std.testing.expect; const Vector = std.meta.Vector; test "@shuffle" { // TODO investigate why this fails when cross-compiling to wasm. if (builtin.os.tag == .wasi) return error.SkipZigTest; const S = struct { fn doTheTest() !void { var v: Vector(4, i32) = [4]i32{ 2147483647, -2, 30, 40 }; var x: Vector(4, i32) = [4]i32{ 1, 2147483647, 3, 4 }; const mask: Vector(4, i32) = [4]i32{ 0, ~@as(i32, 2), 3, ~@as(i32, 3) }; var res = @shuffle(i32, v, x, mask); try expect(mem.eql(i32, &@as([4]i32, res), &[4]i32{ 2147483647, 3, 40, 4 })); // Implicit cast from array (of mask) res = @shuffle(i32, v, x, [4]i32{ 0, ~@as(i32, 2), 3, ~@as(i32, 3) }); try expect(mem.eql(i32, &@as([4]i32, res), &[4]i32{ 2147483647, 3, 40, 4 })); // Undefined const mask2: Vector(4, i32) = [4]i32{ 3, 1, 2, 0 }; res = @shuffle(i32, v, undefined, mask2); try expect(mem.eql(i32, &@as([4]i32, res), &[4]i32{ 40, -2, 30, 2147483647 })); // Upcasting of b var v2: Vector(2, i32) = [2]i32{ 2147483647, undefined }; const mask3: Vector(4, i32) = [4]i32{ ~@as(i32, 0), 2, ~@as(i32, 0), 3 }; res = @shuffle(i32, x, v2, mask3); try expect(mem.eql(i32, &@as([4]i32, res), &[4]i32{ 2147483647, 3, 2147483647, 4 })); // Upcasting of a var v3: Vector(2, i32) = [2]i32{ 2147483647, -2 }; const mask4: Vector(4, i32) = [4]i32{ 0, ~@as(i32, 2), 1, ~@as(i32, 3) }; res = @shuffle(i32, v3, x, mask4); try expect(mem.eql(i32, &@as([4]i32, res), &[4]i32{ 2147483647, 3, -2, 4 })); // bool // Disabled because of #3317 if (@import("builtin").arch != .mipsel and std.Target.current.cpu.arch != .mips) { var x2: Vector(4, bool) = [4]bool{ false, true, false, true }; var v4: Vector(2, bool) = [2]bool{ true, false }; const mask5: Vector(4, i32) = [4]i32{ 0, ~@as(i32, 1), 1, 2 }; var res2 = @shuffle(bool, x2, v4, mask5); try expect(mem.eql(bool, &@as([4]bool, res2), &[4]bool{ false, false, true, false })); } // TODO re-enable when LLVM codegen is fixed // https://github.com/ziglang/zig/issues/3246 if (false) { var x2: Vector(3, bool) = [3]bool{ false, true, false }; var v4: Vector(2, bool) = [2]bool{ true, false }; const mask5: Vector(4, i32) = [4]i32{ 0, ~@as(i32, 1), 1, 2 }; var res2 = @shuffle(bool, x2, v4, mask5); try expect(mem.eql(bool, &@as([4]bool, res2), &[4]bool{ false, false, true, false })); } } }; try S.doTheTest(); comptime try S.doTheTest(); }
test/stage1/behavior/shuffle.zig
const std = @import("std"); const builtin = @import("builtin"); const TestContext = @import("../src/test.zig").TestContext; pub fn addCases(ctx: *TestContext) !void { { const case = ctx.obj("callconv(.Interrupt) on unsupported platform", .{ .cpu_arch = .aarch64, .os_tag = .linux, .abi = .none, }); case.backend = .stage1; case.addError( \\export fn entry() callconv(.Interrupt) void {} , &[_][]const u8{ "tmp.zig:1:28: error: callconv 'Interrupt' is only available on x86, x86_64, AVR, and MSP430, not aarch64", }); } { var case = ctx.obj("callconv(.Signal) on unsupported platform", .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .none, }); case.backend = .stage1; case.addError( \\export fn entry() callconv(.Signal) void {} , &[_][]const u8{ "tmp.zig:1:28: error: callconv 'Signal' is only available on AVR, not x86_64", }); } { const case = ctx.obj("callconv(.Stdcall, .Fastcall, .Thiscall) on unsupported platform", .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .none, }); case.backend = .stage1; case.addError( \\const F1 = fn () callconv(.Stdcall) void; \\const F2 = fn () callconv(.Fastcall) void; \\const F3 = fn () callconv(.Thiscall) void; \\export fn entry1() void { var a: F1 = undefined; _ = a; } \\export fn entry2() void { var a: F2 = undefined; _ = a; } \\export fn entry3() void { var a: F3 = undefined; _ = a; } , &[_][]const u8{ "tmp.zig:1:27: error: callconv 'Stdcall' is only available on x86, not x86_64", "tmp.zig:2:27: error: callconv 'Fastcall' is only available on x86, not x86_64", "tmp.zig:3:27: error: callconv 'Thiscall' is only available on x86, not x86_64", }); } { const case = ctx.obj("callconv(.Stdcall, .Fastcall, .Thiscall) on unsupported platform", .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .none, }); case.backend = .stage1; case.addError( \\export fn entry1() callconv(.Stdcall) void {} \\export fn entry2() callconv(.Fastcall) void {} \\export fn entry3() callconv(.Thiscall) void {} , &[_][]const u8{ "tmp.zig:1:29: error: callconv 'Stdcall' is only available on x86, not x86_64", "tmp.zig:2:29: error: callconv 'Fastcall' is only available on x86, not x86_64", "tmp.zig:3:29: error: callconv 'Thiscall' is only available on x86, not x86_64", }); } { const case = ctx.obj("callconv(.Vectorcall) on unsupported platform", .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .none, }); case.backend = .stage1; case.addError( \\export fn entry() callconv(.Vectorcall) void {} , &[_][]const u8{ "tmp.zig:1:28: error: callconv 'Vectorcall' is only available on x86 and AArch64, not x86_64", }); } { const case = ctx.obj("callconv(.APCS, .AAPCS, .AAPCSVFP) on unsupported platform", .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .none, }); case.backend = .stage1; case.addError( \\export fn entry1() callconv(.APCS) void {} \\export fn entry2() callconv(.AAPCS) void {} \\export fn entry3() callconv(.AAPCSVFP) void {} , &[_][]const u8{ "tmp.zig:1:29: error: callconv 'APCS' is only available on ARM, not x86_64", "tmp.zig:2:29: error: callconv 'AAPCS' is only available on ARM, not x86_64", "tmp.zig:3:29: error: callconv 'AAPCSVFP' is only available on ARM, not x86_64", }); } { const case = ctx.obj("call with new stack on unsupported target", .{ .cpu_arch = .wasm32, .os_tag = .wasi, .abi = .none, }); case.backend = .stage1; case.addError( \\var buf: [10]u8 align(16) = undefined; \\export fn entry() void { \\ @call(.{.stack = &buf}, foo, .{}); \\} \\fn foo() void {} , &[_][]const u8{ "tmp.zig:3:5: error: target arch 'wasm32' does not support calling with a new stack", }); } // Note: One of the error messages here is backwards. It would be nice to fix, but that's not // going to stop me from merging this branch which fixes a bunch of other stuff. ctx.objErrStage1("incompatible sentinels", \\export fn entry1(ptr: [*:255]u8) [*:0]u8 { \\ return ptr; \\} \\export fn entry2(ptr: [*]u8) [*:0]u8 { \\ return ptr; \\} \\export fn entry3() void { \\ var array: [2:0]u8 = [_:255]u8{1, 2}; \\ _ = array; \\} \\export fn entry4() void { \\ var array: [2:0]u8 = [_]u8{1, 2}; \\ _ = array; \\} , &[_][]const u8{ "tmp.zig:2:12: error: expected type '[*:0]u8', found '[*:255]u8'", "tmp.zig:2:12: note: destination pointer requires a terminating '0' sentinel, but source pointer has a terminating '255' sentinel", "tmp.zig:5:12: error: expected type '[*:0]u8', found '[*]u8'", "tmp.zig:5:12: note: destination pointer requires a terminating '0' sentinel", "tmp.zig:8:35: error: expected type '[2:255]u8', found '[2:0]u8'", "tmp.zig:8:35: note: destination array requires a terminating '255' sentinel, but source array has a terminating '0' sentinel", "tmp.zig:12:31: error: expected type '[2:0]u8', found '[2]u8'", "tmp.zig:12:31: note: destination array requires a terminating '0' sentinel", }); { const case = ctx.obj("variable in inline assembly template cannot be found", .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .gnu, }); case.backend = .stage1; case.addError( \\export fn entry() void { \\ var sp = asm volatile ( \\ "mov %[foo], sp" \\ : [bar] "=r" (-> usize) \\ ); \\ _ = sp; \\} , &[_][]const u8{ "tmp.zig:2:14: error: could not find 'foo' in the inputs or outputs", }); } { const case = ctx.obj("bad alignment in @asyncCall", .{ .cpu_arch = .aarch64, .os_tag = .linux, .abi = .none, }); case.backend = .stage1; case.addError( \\export fn entry() void { \\ var ptr: fn () callconv(.Async) void = func; \\ var bytes: [64]u8 = undefined; \\ _ = @asyncCall(&bytes, {}, ptr, .{}); \\} \\fn func() callconv(.Async) void {} , &[_][]const u8{ "tmp.zig:4:21: error: expected type '[]align(8) u8', found '*[64]u8'", }); } if (builtin.os.tag == .linux) { ctx.testErrStage1("implicit dependency on libc", \\extern "c" fn exit(u8) void; \\export fn entry() void { \\ exit(0); \\} , &[_][]const u8{ "tmp.zig:3:5: error: dependency on libc must be explicitly specified in the build command", }); ctx.testErrStage1("libc headers note", \\const c = @cImport(@cInclude("stdio.h")); \\export fn entry() void { \\ _ = c.printf("hello, world!\n"); \\} , &[_][]const u8{ "tmp.zig:1:11: error: C import failed", "tmp.zig:1:11: note: libc headers not available; compilation does not link against libc", }); } { const case = ctx.obj("wrong same named struct", .{}); case.backend = .stage1; case.addSourceFile("a.zig", \\pub const Foo = struct { \\ x: i32, \\}; ); case.addSourceFile("b.zig", \\pub const Foo = struct { \\ z: f64, \\}; ); case.addError( \\const a = @import("a.zig"); \\const b = @import("b.zig"); \\ \\export fn entry() void { \\ var a1: a.Foo = undefined; \\ bar(&a1); \\} \\ \\fn bar(x: *b.Foo) void {_ = x;} , &[_][]const u8{ "tmp.zig:6:10: error: expected type '*b.Foo', found '*a.Foo'", "tmp.zig:6:10: note: pointer type child 'a.Foo' cannot cast into pointer type child 'b.Foo'", "a.zig:1:17: note: a.Foo declared here", "b.zig:1:17: note: b.Foo declared here", }); } { const case = ctx.obj("multiple files with private function error", .{}); case.backend = .stage1; case.addSourceFile("foo.zig", \\fn privateFunction() void { } ); case.addError( \\const foo = @import("foo.zig",); \\ \\export fn callPrivFunction() void { \\ foo.privateFunction(); \\} , &[_][]const u8{ "tmp.zig:4:8: error: 'privateFunction' is private", "foo.zig:1:1: note: declared here", }); } { const case = ctx.obj("multiple files with private member instance function (canonical invocation) error", .{}); case.backend = .stage1; case.addSourceFile("foo.zig", \\pub const Foo = struct { \\ fn privateFunction(self: *Foo) void { _ = self; } \\}; ); case.addError( \\const Foo = @import("foo.zig",).Foo; \\ \\export fn callPrivFunction() void { \\ var foo = Foo{}; \\ Foo.privateFunction(foo); \\} , &[_][]const u8{ "tmp.zig:5:8: error: 'privateFunction' is private", "foo.zig:2:5: note: declared here", }); } { const case = ctx.obj("multiple files with private member instance function error", .{}); case.backend = .stage1; case.addSourceFile("foo.zig", \\pub const Foo = struct { \\ fn privateFunction(self: *Foo) void { _ = self; } \\}; ); case.addError( \\const Foo = @import("foo.zig",).Foo; \\ \\export fn callPrivFunction() void { \\ var foo = Foo{}; \\ foo.privateFunction(); \\} , &[_][]const u8{ "tmp.zig:5:8: error: 'privateFunction' is private", "foo.zig:2:5: note: declared here", }); } { const case = ctx.obj("export collision", .{}); case.backend = .stage1; case.addSourceFile("foo.zig", \\export fn bar() void {} \\pub const baz = 1234; ); case.addError( \\const foo = @import("foo.zig",); \\ \\export fn bar() usize { \\ return foo.baz; \\} , &[_][]const u8{ "foo.zig:1:1: error: exported symbol collision: 'bar'", "tmp.zig:3:1: note: other symbol here", }); } ctx.objErrStage1("non-printable invalid character", "\xff\xfe" ++ "fn foo() bool {\r\n" ++ " return true;\r\n" ++ "}\r\n", &[_][]const u8{ "tmp.zig:1:1: error: expected test, comptime, var decl, or container field, found 'invalid bytes'", "tmp.zig:1:1: note: invalid byte: '\\xff'", }); ctx.objErrStage1("non-printable invalid character with escape alternative", "fn foo() bool {\n" ++ "\treturn true;\n" ++ "}\n", &[_][]const u8{ "tmp.zig:2:1: error: invalid character: '\\t'", }); // TODO test this in stage2, but we won't even try in stage1 //ctx.objErrStage1("inline fn calls itself indirectly", // \\export fn foo() void { // \\ bar(); // \\} // \\fn bar() callconv(.Inline) void { // \\ baz(); // \\ quux(); // \\} // \\fn baz() callconv(.Inline) void { // \\ bar(); // \\ quux(); // \\} // \\extern fn quux() void; //, &[_][]const u8{ // "tmp.zig:4:1: error: unable to inline function", //}); //ctx.objErrStage1("save reference to inline function", // \\export fn foo() void { // \\ quux(@ptrToInt(bar)); // \\} // \\fn bar() callconv(.Inline) void { } // \\extern fn quux(usize) void; //, &[_][]const u8{ // "tmp.zig:4:1: error: unable to inline function", //}); { const case = ctx.obj("align(N) expr function pointers is a compile error", .{ .cpu_arch = .wasm32, .os_tag = .freestanding, .abi = .none, }); case.backend = .stage1; case.addError( \\export fn foo() align(1) void { \\ return; \\} , &[_][]const u8{ "tmp.zig:1:23: error: align(N) expr is not allowed on function prototypes in wasm32/wasm64", }); } }
test/compile_errors.zig
const std = @import("std"); const mem = std.mem; const Allocator = std.mem.Allocator; const Value = @import("value.zig").Value; const Type = @import("type.zig").Type; const assert = std.debug.assert; const BigIntConst = std.math.big.int.Const; const BigIntMutable = std.math.big.int.Mutable; const Target = std.Target; pub const text = @import("ir/text.zig"); /// These are in-memory, analyzed instructions. See `text.Inst` for the representation /// of instructions that correspond to the ZIR text format. /// This struct owns the `Value` and `Type` memory. When the struct is deallocated, /// so are the `Value` and `Type`. The value of a constant must be copied into /// a memory location for the value to survive after a const instruction. pub const Inst = struct { tag: Tag, ty: Type, /// Byte offset into the source. src: usize, pub const Tag = enum { assembly, bitcast, breakpoint, cmp, condbr, constant, isnonnull, isnull, ptrtoint, ret, unreach, }; pub fn cast(base: *Inst, comptime T: type) ?*T { if (base.tag != T.base_tag) return null; return @fieldParentPtr(T, "base", base); } pub fn Args(comptime T: type) type { return std.meta.fieldInfo(T, "args").field_type; } /// Returns `null` if runtime-known. pub fn value(base: *Inst) ?Value { if (base.ty.onePossibleValue()) return Value.initTag(.the_one_possible_value); const inst = base.cast(Constant) orelse return null; return inst.val; } pub const Assembly = struct { pub const base_tag = Tag.assembly; base: Inst, args: struct { asm_source: []const u8, is_volatile: bool, output: ?[]const u8, inputs: []const []const u8, clobbers: []const []const u8, args: []const *Inst, }, }; pub const BitCast = struct { pub const base_tag = Tag.bitcast; base: Inst, args: struct { operand: *Inst, }, }; pub const Breakpoint = struct { pub const base_tag = Tag.breakpoint; base: Inst, args: void, }; pub const Cmp = struct { pub const base_tag = Tag.cmp; base: Inst, args: struct { lhs: *Inst, op: std.math.CompareOperator, rhs: *Inst, }, }; pub const CondBr = struct { pub const base_tag = Tag.condbr; base: Inst, args: struct { condition: *Inst, true_body: Module.Body, false_body: Module.Body, }, }; pub const Constant = struct { pub const base_tag = Tag.constant; base: Inst, val: Value, }; pub const IsNonNull = struct { pub const base_tag = Tag.isnonnull; base: Inst, args: struct { operand: *Inst, }, }; pub const IsNull = struct { pub const base_tag = Tag.isnull; base: Inst, args: struct { operand: *Inst, }, }; pub const PtrToInt = struct { pub const base_tag = Tag.ptrtoint; base: Inst, args: struct { ptr: *Inst, }, }; pub const Ret = struct { pub const base_tag = Tag.ret; base: Inst, args: void, }; pub const Unreach = struct { pub const base_tag = Tag.unreach; base: Inst, args: void, }; }; pub const TypedValue = struct { ty: Type, val: Value, }; pub const Module = struct { exports: []Export, errors: []ErrorMsg, arena: std.heap.ArenaAllocator, fns: []Fn, target: Target, link_mode: std.builtin.LinkMode, output_mode: std.builtin.OutputMode, object_format: std.Target.ObjectFormat, optimize_mode: std.builtin.Mode, pub const Export = struct { name: []const u8, typed_value: TypedValue, src: usize, }; pub const Fn = struct { analysis_status: enum { in_progress, failure, success }, body: Body, fn_type: Type, }; pub const Body = struct { instructions: []*Inst, }; pub fn deinit(self: *Module, allocator: *Allocator) void { allocator.free(self.exports); allocator.free(self.errors); for (self.fns) |f| { allocator.free(f.body.instructions); } allocator.free(self.fns); self.arena.deinit(); self.* = undefined; } }; pub const ErrorMsg = struct { byte_offset: usize, msg: []const u8, }; pub const AnalyzeOptions = struct { target: Target, output_mode: std.builtin.OutputMode, link_mode: std.builtin.LinkMode, object_format: ?std.Target.ObjectFormat = null, optimize_mode: std.builtin.Mode, }; pub fn analyze(allocator: *Allocator, old_module: text.Module, options: AnalyzeOptions) !Module { var ctx = Analyze{ .allocator = allocator, .arena = std.heap.ArenaAllocator.init(allocator), .old_module = &old_module, .errors = std.ArrayList(ErrorMsg).init(allocator), .decl_table = std.AutoHashMap(*text.Inst, Analyze.NewDecl).init(allocator), .exports = std.ArrayList(Module.Export).init(allocator), .fns = std.ArrayList(Module.Fn).init(allocator), .target = options.target, .optimize_mode = options.optimize_mode, .link_mode = options.link_mode, .output_mode = options.output_mode, }; defer ctx.errors.deinit(); defer ctx.decl_table.deinit(); defer ctx.exports.deinit(); defer ctx.fns.deinit(); errdefer ctx.arena.deinit(); ctx.analyzeRoot() catch |err| switch (err) { error.AnalysisFail => { assert(ctx.errors.items.len != 0); }, else => |e| return e, }; return Module{ .exports = ctx.exports.toOwnedSlice(), .errors = ctx.errors.toOwnedSlice(), .fns = ctx.fns.toOwnedSlice(), .arena = ctx.arena, .target = ctx.target, .link_mode = ctx.link_mode, .output_mode = ctx.output_mode, .object_format = options.object_format orelse ctx.target.getObjectFormat(), .optimize_mode = ctx.optimize_mode, }; } const Analyze = struct { allocator: *Allocator, arena: std.heap.ArenaAllocator, old_module: *const text.Module, errors: std.ArrayList(ErrorMsg), decl_table: std.AutoHashMap(*text.Inst, NewDecl), exports: std.ArrayList(Module.Export), fns: std.ArrayList(Module.Fn), target: Target, link_mode: std.builtin.LinkMode, optimize_mode: std.builtin.Mode, output_mode: std.builtin.OutputMode, const NewDecl = struct { /// null means a semantic analysis error happened ptr: ?*Inst, }; const NewInst = struct { /// null means a semantic analysis error happened ptr: ?*Inst, }; const Fn = struct { /// Index into Module fns array fn_index: usize, inner_block: Block, inst_table: std.AutoHashMap(*text.Inst, NewInst), }; const Block = struct { func: *Fn, instructions: std.ArrayList(*Inst), }; const InnerError = error{ OutOfMemory, AnalysisFail }; fn analyzeRoot(self: *Analyze) !void { for (self.old_module.decls) |decl| { if (decl.cast(text.Inst.Export)) |export_inst| { try analyzeExport(self, null, export_inst); } } } fn resolveInst(self: *Analyze, opt_block: ?*Block, old_inst: *text.Inst) InnerError!*Inst { if (opt_block) |block| { if (block.func.inst_table.get(old_inst)) |kv| { return kv.value.ptr orelse return error.AnalysisFail; } } if (self.decl_table.get(old_inst)) |kv| { return kv.value.ptr orelse return error.AnalysisFail; } else { const new_inst = self.analyzeInst(null, old_inst) catch |err| switch (err) { error.AnalysisFail => { try self.decl_table.putNoClobber(old_inst, .{ .ptr = null }); return error.AnalysisFail; }, else => |e| return e, }; try self.decl_table.putNoClobber(old_inst, .{ .ptr = new_inst }); return new_inst; } } fn requireRuntimeBlock(self: *Analyze, block: ?*Block, src: usize) !*Block { return block orelse return self.fail(src, "instruction illegal outside function body", .{}); } fn resolveInstConst(self: *Analyze, block: ?*Block, old_inst: *text.Inst) InnerError!TypedValue { const new_inst = try self.resolveInst(block, old_inst); const val = try self.resolveConstValue(new_inst); return TypedValue{ .ty = new_inst.ty, .val = val, }; } fn resolveConstValue(self: *Analyze, base: *Inst) !Value { return (try self.resolveDefinedValue(base)) orelse return self.fail(base.src, "unable to resolve comptime value", .{}); } fn resolveDefinedValue(self: *Analyze, base: *Inst) !?Value { if (base.value()) |val| { if (val.isUndef()) { return self.fail(base.src, "use of undefined value here causes undefined behavior", .{}); } return val; } return null; } fn resolveConstString(self: *Analyze, block: ?*Block, old_inst: *text.Inst) ![]u8 { const new_inst = try self.resolveInst(block, old_inst); const wanted_type = Type.initTag(.const_slice_u8); const coerced_inst = try self.coerce(block, wanted_type, new_inst); const val = try self.resolveConstValue(coerced_inst); return val.toAllocatedBytes(&self.arena.allocator); } fn resolveType(self: *Analyze, block: ?*Block, old_inst: *text.Inst) !Type { const new_inst = try self.resolveInst(block, old_inst); const wanted_type = Type.initTag(.@"type"); const coerced_inst = try self.coerce(block, wanted_type, new_inst); const val = try self.resolveConstValue(coerced_inst); return val.toType(); } fn analyzeExport(self: *Analyze, block: ?*Block, export_inst: *text.Inst.Export) !void { const symbol_name = try self.resolveConstString(block, export_inst.positionals.symbol_name); const typed_value = try self.resolveInstConst(block, export_inst.positionals.value); switch (typed_value.ty.zigTypeTag()) { .Fn => {}, else => return self.fail( export_inst.positionals.value.src, "unable to export type '{}'", .{typed_value.ty}, ), } try self.exports.append(.{ .name = symbol_name, .typed_value = typed_value, .src = export_inst.base.src, }); } /// TODO should not need the cast on the last parameter at the callsites fn addNewInstArgs( self: *Analyze, block: *Block, src: usize, ty: Type, comptime T: type, args: Inst.Args(T), ) !*Inst { const inst = try self.addNewInst(block, src, ty, T); inst.args = args; return &inst.base; } fn addNewInst(self: *Analyze, block: *Block, src: usize, ty: Type, comptime T: type) !*T { const inst = try self.arena.allocator.create(T); inst.* = .{ .base = .{ .tag = T.base_tag, .ty = ty, .src = src, }, .args = undefined, }; try block.instructions.append(&inst.base); return inst; } fn constInst(self: *Analyze, src: usize, typed_value: TypedValue) !*Inst { const const_inst = try self.arena.allocator.create(Inst.Constant); const_inst.* = .{ .base = .{ .tag = Inst.Constant.base_tag, .ty = typed_value.ty, .src = src, }, .val = typed_value.val, }; return &const_inst.base; } fn constStr(self: *Analyze, src: usize, str: []const u8) !*Inst { const array_payload = try self.arena.allocator.create(Type.Payload.Array_u8_Sentinel0); array_payload.* = .{ .len = str.len }; const ty_payload = try self.arena.allocator.create(Type.Payload.SingleConstPointer); ty_payload.* = .{ .pointee_type = Type.initPayload(&array_payload.base) }; const bytes_payload = try self.arena.allocator.create(Value.Payload.Bytes); bytes_payload.* = .{ .data = str }; return self.constInst(src, .{ .ty = Type.initPayload(&ty_payload.base), .val = Value.initPayload(&bytes_payload.base), }); } fn constType(self: *Analyze, src: usize, ty: Type) !*Inst { return self.constInst(src, .{ .ty = Type.initTag(.type), .val = try ty.toValue(&self.arena.allocator), }); } fn constVoid(self: *Analyze, src: usize) !*Inst { return self.constInst(src, .{ .ty = Type.initTag(.void), .val = Value.initTag(.the_one_possible_value), }); } fn constUndef(self: *Analyze, src: usize, ty: Type) !*Inst { return self.constInst(src, .{ .ty = ty, .val = Value.initTag(.undef), }); } fn constBool(self: *Analyze, src: usize, v: bool) !*Inst { return self.constInst(src, .{ .ty = Type.initTag(.bool), .val = ([2]Value{ Value.initTag(.bool_false), Value.initTag(.bool_true) })[@boolToInt(v)], }); } fn constIntUnsigned(self: *Analyze, src: usize, ty: Type, int: u64) !*Inst { const int_payload = try self.arena.allocator.create(Value.Payload.Int_u64); int_payload.* = .{ .int = int }; return self.constInst(src, .{ .ty = ty, .val = Value.initPayload(&int_payload.base), }); } fn constIntSigned(self: *Analyze, src: usize, ty: Type, int: i64) !*Inst { const int_payload = try self.arena.allocator.create(Value.Payload.Int_i64); int_payload.* = .{ .int = int }; return self.constInst(src, .{ .ty = ty, .val = Value.initPayload(&int_payload.base), }); } fn constIntBig(self: *Analyze, src: usize, ty: Type, big_int: BigIntConst) !*Inst { const val_payload = if (big_int.positive) blk: { if (big_int.to(u64)) |x| { return self.constIntUnsigned(src, ty, x); } else |err| switch (err) { error.NegativeIntoUnsigned => unreachable, error.TargetTooSmall => {}, // handled below } const big_int_payload = try self.arena.allocator.create(Value.Payload.IntBigPositive); big_int_payload.* = .{ .limbs = big_int.limbs }; break :blk &big_int_payload.base; } else blk: { if (big_int.to(i64)) |x| { return self.constIntSigned(src, ty, x); } else |err| switch (err) { error.NegativeIntoUnsigned => unreachable, error.TargetTooSmall => {}, // handled below } const big_int_payload = try self.arena.allocator.create(Value.Payload.IntBigNegative); big_int_payload.* = .{ .limbs = big_int.limbs }; break :blk &big_int_payload.base; }; return self.constInst(src, .{ .ty = ty, .val = Value.initPayload(val_payload), }); } fn analyzeInst(self: *Analyze, block: ?*Block, old_inst: *text.Inst) InnerError!*Inst { switch (old_inst.tag) { .breakpoint => return self.analyzeInstBreakpoint(block, old_inst.cast(text.Inst.Breakpoint).?), .str => { // We can use this reference because Inst.Const's Value is arena-allocated. // The value would get copied to a MemoryCell before the `text.Inst.Str` lifetime ends. const bytes = old_inst.cast(text.Inst.Str).?.positionals.bytes; return self.constStr(old_inst.src, bytes); }, .int => { const big_int = old_inst.cast(text.Inst.Int).?.positionals.int; return self.constIntBig(old_inst.src, Type.initTag(.comptime_int), big_int); }, .ptrtoint => return self.analyzeInstPtrToInt(block, old_inst.cast(text.Inst.PtrToInt).?), .fieldptr => return self.analyzeInstFieldPtr(block, old_inst.cast(text.Inst.FieldPtr).?), .deref => return self.analyzeInstDeref(block, old_inst.cast(text.Inst.Deref).?), .as => return self.analyzeInstAs(block, old_inst.cast(text.Inst.As).?), .@"asm" => return self.analyzeInstAsm(block, old_inst.cast(text.Inst.Asm).?), .@"unreachable" => return self.analyzeInstUnreachable(block, old_inst.cast(text.Inst.Unreachable).?), .@"return" => return self.analyzeInstRet(block, old_inst.cast(text.Inst.Return).?), .@"fn" => return self.analyzeInstFn(block, old_inst.cast(text.Inst.Fn).?), .@"export" => { try self.analyzeExport(block, old_inst.cast(text.Inst.Export).?); return self.constVoid(old_inst.src); }, .primitive => return self.analyzeInstPrimitive(old_inst.cast(text.Inst.Primitive).?), .fntype => return self.analyzeInstFnType(block, old_inst.cast(text.Inst.FnType).?), .intcast => return self.analyzeInstIntCast(block, old_inst.cast(text.Inst.IntCast).?), .bitcast => return self.analyzeInstBitCast(block, old_inst.cast(text.Inst.BitCast).?), .elemptr => return self.analyzeInstElemPtr(block, old_inst.cast(text.Inst.ElemPtr).?), .add => return self.analyzeInstAdd(block, old_inst.cast(text.Inst.Add).?), .cmp => return self.analyzeInstCmp(block, old_inst.cast(text.Inst.Cmp).?), .condbr => return self.analyzeInstCondBr(block, old_inst.cast(text.Inst.CondBr).?), .isnull => return self.analyzeInstIsNull(block, old_inst.cast(text.Inst.IsNull).?), .isnonnull => return self.analyzeInstIsNonNull(block, old_inst.cast(text.Inst.IsNonNull).?), } } fn analyzeInstBreakpoint(self: *Analyze, block: ?*Block, inst: *text.Inst.Breakpoint) InnerError!*Inst { const b = try self.requireRuntimeBlock(block, inst.base.src); return self.addNewInstArgs(b, inst.base.src, Type.initTag(.void), Inst.Breakpoint, Inst.Args(Inst.Breakpoint){}); } fn analyzeInstFn(self: *Analyze, block: ?*Block, fn_inst: *text.Inst.Fn) InnerError!*Inst { const fn_type = try self.resolveType(block, fn_inst.positionals.fn_type); var new_func: Fn = .{ .fn_index = self.fns.items.len, .inner_block = .{ .func = undefined, .instructions = std.ArrayList(*Inst).init(self.allocator), }, .inst_table = std.AutoHashMap(*text.Inst, NewInst).init(self.allocator), }; new_func.inner_block.func = &new_func; defer new_func.inner_block.instructions.deinit(); defer new_func.inst_table.deinit(); // Don't hang on to a reference to this when analyzing body instructions, since the memory // could become invalid. (try self.fns.addOne()).* = .{ .analysis_status = .in_progress, .fn_type = fn_type, .body = undefined, }; try self.analyzeBody(&new_func.inner_block, fn_inst.positionals.body); const f = &self.fns.items[new_func.fn_index]; f.analysis_status = .success; f.body = .{ .instructions = new_func.inner_block.instructions.toOwnedSlice() }; const fn_payload = try self.arena.allocator.create(Value.Payload.Function); fn_payload.* = .{ .index = new_func.fn_index }; return self.constInst(fn_inst.base.src, .{ .ty = fn_type, .val = Value.initPayload(&fn_payload.base), }); } fn analyzeInstFnType(self: *Analyze, block: ?*Block, fntype: *text.Inst.FnType) InnerError!*Inst { const return_type = try self.resolveType(block, fntype.positionals.return_type); if (return_type.zigTypeTag() == .NoReturn and fntype.positionals.param_types.len == 0 and fntype.kw_args.cc == .Naked) { return self.constType(fntype.base.src, Type.initTag(.fn_naked_noreturn_no_args)); } if (return_type.zigTypeTag() == .Void and fntype.positionals.param_types.len == 0 and fntype.kw_args.cc == .C) { return self.constType(fntype.base.src, Type.initTag(.fn_ccc_void_no_args)); } return self.fail(fntype.base.src, "TODO implement fntype instruction more", .{}); } fn analyzeInstPrimitive(self: *Analyze, primitive: *text.Inst.Primitive) InnerError!*Inst { return self.constType(primitive.base.src, primitive.positionals.tag.toType()); } fn analyzeInstAs(self: *Analyze, block: ?*Block, as: *text.Inst.As) InnerError!*Inst { const dest_type = try self.resolveType(block, as.positionals.dest_type); const new_inst = try self.resolveInst(block, as.positionals.value); return self.coerce(block, dest_type, new_inst); } fn analyzeInstPtrToInt(self: *Analyze, block: ?*Block, ptrtoint: *text.Inst.PtrToInt) InnerError!*Inst { const ptr = try self.resolveInst(block, ptrtoint.positionals.ptr); if (ptr.ty.zigTypeTag() != .Pointer) { return self.fail(ptrtoint.positionals.ptr.src, "expected pointer, found '{}'", .{ptr.ty}); } // TODO handle known-pointer-address const b = try self.requireRuntimeBlock(block, ptrtoint.base.src); const ty = Type.initTag(.usize); return self.addNewInstArgs(b, ptrtoint.base.src, ty, Inst.PtrToInt, Inst.Args(Inst.PtrToInt){ .ptr = ptr }); } fn analyzeInstFieldPtr(self: *Analyze, block: ?*Block, fieldptr: *text.Inst.FieldPtr) InnerError!*Inst { const object_ptr = try self.resolveInst(block, fieldptr.positionals.object_ptr); const field_name = try self.resolveConstString(block, fieldptr.positionals.field_name); const elem_ty = switch (object_ptr.ty.zigTypeTag()) { .Pointer => object_ptr.ty.elemType(), else => return self.fail(fieldptr.positionals.object_ptr.src, "expected pointer, found '{}'", .{object_ptr.ty}), }; switch (elem_ty.zigTypeTag()) { .Array => { if (mem.eql(u8, field_name, "len")) { const len_payload = try self.arena.allocator.create(Value.Payload.Int_u64); len_payload.* = .{ .int = elem_ty.arrayLen() }; const ref_payload = try self.arena.allocator.create(Value.Payload.RefVal); ref_payload.* = .{ .val = Value.initPayload(&len_payload.base) }; return self.constInst(fieldptr.base.src, .{ .ty = Type.initTag(.single_const_pointer_to_comptime_int), .val = Value.initPayload(&ref_payload.base), }); } else { return self.fail( fieldptr.positionals.field_name.src, "no member named '{}' in '{}'", .{ field_name, elem_ty }, ); } }, else => return self.fail(fieldptr.base.src, "type '{}' does not support field access", .{elem_ty}), } } fn analyzeInstIntCast(self: *Analyze, block: ?*Block, intcast: *text.Inst.IntCast) InnerError!*Inst { const dest_type = try self.resolveType(block, intcast.positionals.dest_type); const new_inst = try self.resolveInst(block, intcast.positionals.value); const dest_is_comptime_int = switch (dest_type.zigTypeTag()) { .ComptimeInt => true, .Int => false, else => return self.fail( intcast.positionals.dest_type.src, "expected integer type, found '{}'", .{ dest_type, }, ), }; switch (new_inst.ty.zigTypeTag()) { .ComptimeInt, .Int => {}, else => return self.fail( intcast.positionals.value.src, "expected integer type, found '{}'", .{new_inst.ty}, ), } if (dest_is_comptime_int or new_inst.value() != null) { return self.coerce(block, dest_type, new_inst); } return self.fail(intcast.base.src, "TODO implement analyze widen or shorten int", .{}); } fn analyzeInstBitCast(self: *Analyze, block: ?*Block, inst: *text.Inst.BitCast) InnerError!*Inst { const dest_type = try self.resolveType(block, inst.positionals.dest_type); const operand = try self.resolveInst(block, inst.positionals.operand); return self.bitcast(block, dest_type, operand); } fn analyzeInstElemPtr(self: *Analyze, block: ?*Block, inst: *text.Inst.ElemPtr) InnerError!*Inst { const array_ptr = try self.resolveInst(block, inst.positionals.array_ptr); const uncasted_index = try self.resolveInst(block, inst.positionals.index); const elem_index = try self.coerce(block, Type.initTag(.usize), uncasted_index); if (array_ptr.ty.isSinglePointer() and array_ptr.ty.elemType().zigTypeTag() == .Array) { if (array_ptr.value()) |array_ptr_val| { if (elem_index.value()) |index_val| { // Both array pointer and index are compile-time known. const index_u64 = index_val.toUnsignedInt(); // @intCast here because it would have been impossible to construct a value that // required a larger index. const elem_val = try array_ptr_val.elemValueAt(&self.arena.allocator, @intCast(usize, index_u64)); const ref_payload = try self.arena.allocator.create(Value.Payload.RefVal); ref_payload.* = .{ .val = elem_val }; const type_payload = try self.arena.allocator.create(Type.Payload.SingleConstPointer); type_payload.* = .{ .pointee_type = array_ptr.ty.elemType().elemType() }; return self.constInst(inst.base.src, .{ .ty = Type.initPayload(&type_payload.base), .val = Value.initPayload(&ref_payload.base), }); } } } return self.fail(inst.base.src, "TODO implement more analyze elemptr", .{}); } fn analyzeInstAdd(self: *Analyze, block: ?*Block, inst: *text.Inst.Add) InnerError!*Inst { const lhs = try self.resolveInst(block, inst.positionals.lhs); const rhs = try self.resolveInst(block, inst.positionals.rhs); if (lhs.ty.zigTypeTag() == .Int and rhs.ty.zigTypeTag() == .Int) { if (lhs.value()) |lhs_val| { if (rhs.value()) |rhs_val| { // TODO is this a performance issue? maybe we should try the operation without // resorting to BigInt first. var lhs_space: Value.BigIntSpace = undefined; var rhs_space: Value.BigIntSpace = undefined; const lhs_bigint = lhs_val.toBigInt(&lhs_space); const rhs_bigint = rhs_val.toBigInt(&rhs_space); const limbs = try self.arena.allocator.alloc( std.math.big.Limb, std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1, ); var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined }; result_bigint.add(lhs_bigint, rhs_bigint); const result_limbs = result_bigint.limbs[0..result_bigint.len]; if (!lhs.ty.eql(rhs.ty)) { return self.fail(inst.base.src, "TODO implement peer type resolution", .{}); } const val_payload = if (result_bigint.positive) blk: { const val_payload = try self.arena.allocator.create(Value.Payload.IntBigPositive); val_payload.* = .{ .limbs = result_limbs }; break :blk &val_payload.base; } else blk: { const val_payload = try self.arena.allocator.create(Value.Payload.IntBigNegative); val_payload.* = .{ .limbs = result_limbs }; break :blk &val_payload.base; }; return self.constInst(inst.base.src, .{ .ty = lhs.ty, .val = Value.initPayload(val_payload), }); } } } return self.fail(inst.base.src, "TODO implement more analyze add", .{}); } fn analyzeInstDeref(self: *Analyze, block: ?*Block, deref: *text.Inst.Deref) InnerError!*Inst { const ptr = try self.resolveInst(block, deref.positionals.ptr); const elem_ty = switch (ptr.ty.zigTypeTag()) { .Pointer => ptr.ty.elemType(), else => return self.fail(deref.positionals.ptr.src, "expected pointer, found '{}'", .{ptr.ty}), }; if (ptr.value()) |val| { return self.constInst(deref.base.src, .{ .ty = elem_ty, .val = val.pointerDeref(), }); } return self.fail(deref.base.src, "TODO implement runtime deref", .{}); } fn analyzeInstAsm(self: *Analyze, block: ?*Block, assembly: *text.Inst.Asm) InnerError!*Inst { const return_type = try self.resolveType(block, assembly.positionals.return_type); const asm_source = try self.resolveConstString(block, assembly.positionals.asm_source); const output = if (assembly.kw_args.output) |o| try self.resolveConstString(block, o) else null; const inputs = try self.arena.allocator.alloc([]const u8, assembly.kw_args.inputs.len); const clobbers = try self.arena.allocator.alloc([]const u8, assembly.kw_args.clobbers.len); const args = try self.arena.allocator.alloc(*Inst, assembly.kw_args.args.len); for (inputs) |*elem, i| { elem.* = try self.resolveConstString(block, assembly.kw_args.inputs[i]); } for (clobbers) |*elem, i| { elem.* = try self.resolveConstString(block, assembly.kw_args.clobbers[i]); } for (args) |*elem, i| { const arg = try self.resolveInst(block, assembly.kw_args.args[i]); elem.* = try self.coerce(block, Type.initTag(.usize), arg); } const b = try self.requireRuntimeBlock(block, assembly.base.src); return self.addNewInstArgs(b, assembly.base.src, return_type, Inst.Assembly, Inst.Args(Inst.Assembly){ .asm_source = asm_source, .is_volatile = assembly.kw_args.@"volatile", .output = output, .inputs = inputs, .clobbers = clobbers, .args = args, }); } fn analyzeInstCmp(self: *Analyze, block: ?*Block, inst: *text.Inst.Cmp) InnerError!*Inst { const lhs = try self.resolveInst(block, inst.positionals.lhs); const rhs = try self.resolveInst(block, inst.positionals.rhs); const op = inst.positionals.op; const is_equality_cmp = switch (op) { .eq, .neq => true, else => false, }; const lhs_ty_tag = lhs.ty.zigTypeTag(); const rhs_ty_tag = rhs.ty.zigTypeTag(); if (is_equality_cmp and lhs_ty_tag == .Null and rhs_ty_tag == .Null) { // null == null, null != null return self.constBool(inst.base.src, op == .eq); } else if (is_equality_cmp and ((lhs_ty_tag == .Null and rhs_ty_tag == .Optional) or rhs_ty_tag == .Null and lhs_ty_tag == .Optional)) { // comparing null with optionals const opt_operand = if (lhs_ty_tag == .Optional) lhs else rhs; if (opt_operand.value()) |opt_val| { const is_null = opt_val.isNull(); return self.constBool(inst.base.src, if (op == .eq) is_null else !is_null); } const b = try self.requireRuntimeBlock(block, inst.base.src); switch (op) { .eq => return self.addNewInstArgs( b, inst.base.src, Type.initTag(.bool), Inst.IsNull, Inst.Args(Inst.IsNull){ .operand = opt_operand }, ), .neq => return self.addNewInstArgs( b, inst.base.src, Type.initTag(.bool), Inst.IsNonNull, Inst.Args(Inst.IsNonNull){ .operand = opt_operand }, ), else => unreachable, } } else if (is_equality_cmp and ((lhs_ty_tag == .Null and rhs.ty.isCPtr()) or (rhs_ty_tag == .Null and lhs.ty.isCPtr()))) { return self.fail(inst.base.src, "TODO implement C pointer cmp", .{}); } else if (lhs_ty_tag == .Null or rhs_ty_tag == .Null) { const non_null_type = if (lhs_ty_tag == .Null) rhs.ty else lhs.ty; return self.fail(inst.base.src, "comparison of '{}' with null", .{non_null_type}); } else if (is_equality_cmp and ((lhs_ty_tag == .EnumLiteral and rhs_ty_tag == .Union) or (rhs_ty_tag == .EnumLiteral and lhs_ty_tag == .Union))) { return self.fail(inst.base.src, "TODO implement equality comparison between a union's tag value and an enum literal", .{}); } else if (lhs_ty_tag == .ErrorSet and rhs_ty_tag == .ErrorSet) { if (!is_equality_cmp) { return self.fail(inst.base.src, "{} operator not allowed for errors", .{@tagName(op)}); } return self.fail(inst.base.src, "TODO implement equality comparison between errors", .{}); } else if (lhs.ty.isNumeric() and rhs.ty.isNumeric()) { // This operation allows any combination of integer and float types, regardless of the // signed-ness, comptime-ness, and bit-width. So peer type resolution is incorrect for // numeric types. return self.cmpNumeric(block, inst.base.src, lhs, rhs, op); } return self.fail(inst.base.src, "TODO implement more cmp analysis", .{}); } fn analyzeInstIsNull(self: *Analyze, block: ?*Block, inst: *text.Inst.IsNull) InnerError!*Inst { const operand = try self.resolveInst(block, inst.positionals.operand); return self.analyzeIsNull(block, inst.base.src, operand, true); } fn analyzeInstIsNonNull(self: *Analyze, block: ?*Block, inst: *text.Inst.IsNonNull) InnerError!*Inst { const operand = try self.resolveInst(block, inst.positionals.operand); return self.analyzeIsNull(block, inst.base.src, operand, false); } fn analyzeInstCondBr(self: *Analyze, block: ?*Block, inst: *text.Inst.CondBr) InnerError!*Inst { const uncasted_cond = try self.resolveInst(block, inst.positionals.condition); const cond = try self.coerce(block, Type.initTag(.bool), uncasted_cond); if (try self.resolveDefinedValue(cond)) |cond_val| { const body = if (cond_val.toBool()) &inst.positionals.true_body else &inst.positionals.false_body; try self.analyzeBody(block, body.*); return self.constVoid(inst.base.src); } const parent_block = try self.requireRuntimeBlock(block, inst.base.src); var true_block: Block = .{ .func = parent_block.func, .instructions = std.ArrayList(*Inst).init(self.allocator), }; defer true_block.instructions.deinit(); try self.analyzeBody(&true_block, inst.positionals.true_body); var false_block: Block = .{ .func = parent_block.func, .instructions = std.ArrayList(*Inst).init(self.allocator), }; defer false_block.instructions.deinit(); try self.analyzeBody(&false_block, inst.positionals.false_body); // Copy the instruction pointers to the arena memory const true_instructions = try self.arena.allocator.alloc(*Inst, true_block.instructions.items.len); const false_instructions = try self.arena.allocator.alloc(*Inst, false_block.instructions.items.len); mem.copy(*Inst, true_instructions, true_block.instructions.items); mem.copy(*Inst, false_instructions, false_block.instructions.items); return self.addNewInstArgs(parent_block, inst.base.src, Type.initTag(.void), Inst.CondBr, Inst.Args(Inst.CondBr){ .condition = cond, .true_body = .{ .instructions = true_instructions }, .false_body = .{ .instructions = false_instructions }, }); } fn wantSafety(self: *Analyze, block: ?*Block) bool { return switch (self.optimize_mode) { .Debug => true, .ReleaseSafe => true, .ReleaseFast => false, .ReleaseSmall => false, }; } fn analyzeInstUnreachable(self: *Analyze, block: ?*Block, unreach: *text.Inst.Unreachable) InnerError!*Inst { const b = try self.requireRuntimeBlock(block, unreach.base.src); if (self.wantSafety(block)) { // TODO Once we have a panic function to call, call it here instead of this. _ = try self.addNewInstArgs(b, unreach.base.src, Type.initTag(.void), Inst.Breakpoint, {}); } return self.addNewInstArgs(b, unreach.base.src, Type.initTag(.noreturn), Inst.Unreach, {}); } fn analyzeInstRet(self: *Analyze, block: ?*Block, inst: *text.Inst.Return) InnerError!*Inst { const b = try self.requireRuntimeBlock(block, inst.base.src); return self.addNewInstArgs(b, inst.base.src, Type.initTag(.noreturn), Inst.Ret, {}); } fn analyzeBody(self: *Analyze, block: ?*Block, body: text.Module.Body) !void { for (body.instructions) |src_inst| { const new_inst = self.analyzeInst(block, src_inst) catch |err| { if (block) |b| { self.fns.items[b.func.fn_index].analysis_status = .failure; try b.func.inst_table.putNoClobber(src_inst, .{ .ptr = null }); } return err; }; if (block) |b| try b.func.inst_table.putNoClobber(src_inst, .{ .ptr = new_inst }); } } fn analyzeIsNull( self: *Analyze, block: ?*Block, src: usize, operand: *Inst, invert_logic: bool, ) InnerError!*Inst { return self.fail(src, "TODO implement analysis of isnull and isnotnull", .{}); } /// Asserts that lhs and rhs types are both numeric. fn cmpNumeric( self: *Analyze, block: ?*Block, src: usize, lhs: *Inst, rhs: *Inst, op: std.math.CompareOperator, ) !*Inst { assert(lhs.ty.isNumeric()); assert(rhs.ty.isNumeric()); const lhs_ty_tag = lhs.ty.zigTypeTag(); const rhs_ty_tag = rhs.ty.zigTypeTag(); if (lhs_ty_tag == .Vector and rhs_ty_tag == .Vector) { if (lhs.ty.arrayLen() != rhs.ty.arrayLen()) { return self.fail(src, "vector length mismatch: {} and {}", .{ lhs.ty.arrayLen(), rhs.ty.arrayLen(), }); } return self.fail(src, "TODO implement support for vectors in cmpNumeric", .{}); } else if (lhs_ty_tag == .Vector or rhs_ty_tag == .Vector) { return self.fail(src, "mixed scalar and vector operands to comparison operator: '{}' and '{}'", .{ lhs.ty, rhs.ty, }); } if (lhs.value()) |lhs_val| { if (rhs.value()) |rhs_val| { return self.constBool(src, Value.compare(lhs_val, op, rhs_val)); } } // TODO handle comparisons against lazy zero values // Some values can be compared against zero without being runtime known or without forcing // a full resolution of their value, for example `@sizeOf(@Frame(function))` is known to // always be nonzero, and we benefit from not forcing the full evaluation and stack frame layout // of this function if we don't need to. // It must be a runtime comparison. const b = try self.requireRuntimeBlock(block, src); // For floats, emit a float comparison instruction. const lhs_is_float = switch (lhs_ty_tag) { .Float, .ComptimeFloat => true, else => false, }; const rhs_is_float = switch (rhs_ty_tag) { .Float, .ComptimeFloat => true, else => false, }; if (lhs_is_float and rhs_is_float) { // Implicit cast the smaller one to the larger one. const dest_type = x: { if (lhs_ty_tag == .ComptimeFloat) { break :x rhs.ty; } else if (rhs_ty_tag == .ComptimeFloat) { break :x lhs.ty; } if (lhs.ty.floatBits(self.target) >= rhs.ty.floatBits(self.target)) { break :x lhs.ty; } else { break :x rhs.ty; } }; const casted_lhs = try self.coerce(block, dest_type, lhs); const casted_rhs = try self.coerce(block, dest_type, rhs); return self.addNewInstArgs(b, src, dest_type, Inst.Cmp, Inst.Args(Inst.Cmp){ .lhs = casted_lhs, .rhs = casted_rhs, .op = op, }); } // For mixed unsigned integer sizes, implicit cast both operands to the larger integer. // For mixed signed and unsigned integers, implicit cast both operands to a signed // integer with + 1 bit. // For mixed floats and integers, extract the integer part from the float, cast that to // a signed integer with mantissa bits + 1, and if there was any non-integral part of the float, // add/subtract 1. const lhs_is_signed = if (lhs.value()) |lhs_val| lhs_val.compareWithZero(.lt) else (lhs.ty.isFloat() or lhs.ty.isSignedInt()); const rhs_is_signed = if (rhs.value()) |rhs_val| rhs_val.compareWithZero(.lt) else (rhs.ty.isFloat() or rhs.ty.isSignedInt()); const dest_int_is_signed = lhs_is_signed or rhs_is_signed; var dest_float_type: ?Type = null; var lhs_bits: usize = undefined; if (lhs.value()) |lhs_val| { if (lhs_val.isUndef()) return self.constUndef(src, Type.initTag(.bool)); const is_unsigned = if (lhs_is_float) x: { var bigint_space: Value.BigIntSpace = undefined; var bigint = try lhs_val.toBigInt(&bigint_space).toManaged(self.allocator); defer bigint.deinit(); const zcmp = lhs_val.orderAgainstZero(); if (lhs_val.floatHasFraction()) { switch (op) { .eq => return self.constBool(src, false), .neq => return self.constBool(src, true), else => {}, } if (zcmp == .lt) { try bigint.addScalar(bigint.toConst(), -1); } else { try bigint.addScalar(bigint.toConst(), 1); } } lhs_bits = bigint.toConst().bitCountTwosComp(); break :x (zcmp != .lt); } else x: { lhs_bits = lhs_val.intBitCountTwosComp(); break :x (lhs_val.orderAgainstZero() != .lt); }; lhs_bits += @boolToInt(is_unsigned and dest_int_is_signed); } else if (lhs_is_float) { dest_float_type = lhs.ty; } else { const int_info = lhs.ty.intInfo(self.target); lhs_bits = int_info.bits + @boolToInt(!int_info.signed and dest_int_is_signed); } var rhs_bits: usize = undefined; if (rhs.value()) |rhs_val| { if (rhs_val.isUndef()) return self.constUndef(src, Type.initTag(.bool)); const is_unsigned = if (rhs_is_float) x: { var bigint_space: Value.BigIntSpace = undefined; var bigint = try rhs_val.toBigInt(&bigint_space).toManaged(self.allocator); defer bigint.deinit(); const zcmp = rhs_val.orderAgainstZero(); if (rhs_val.floatHasFraction()) { switch (op) { .eq => return self.constBool(src, false), .neq => return self.constBool(src, true), else => {}, } if (zcmp == .lt) { try bigint.addScalar(bigint.toConst(), -1); } else { try bigint.addScalar(bigint.toConst(), 1); } } rhs_bits = bigint.toConst().bitCountTwosComp(); break :x (zcmp != .lt); } else x: { rhs_bits = rhs_val.intBitCountTwosComp(); break :x (rhs_val.orderAgainstZero() != .lt); }; rhs_bits += @boolToInt(is_unsigned and dest_int_is_signed); } else if (rhs_is_float) { dest_float_type = rhs.ty; } else { const int_info = rhs.ty.intInfo(self.target); rhs_bits = int_info.bits + @boolToInt(!int_info.signed and dest_int_is_signed); } const dest_type = if (dest_float_type) |ft| ft else blk: { const max_bits = std.math.max(lhs_bits, rhs_bits); const casted_bits = std.math.cast(u16, max_bits) catch |err| switch (err) { error.Overflow => return self.fail(src, "{} exceeds maximum integer bit count", .{max_bits}), }; break :blk try self.makeIntType(dest_int_is_signed, casted_bits); }; const casted_lhs = try self.coerce(block, dest_type, lhs); const casted_rhs = try self.coerce(block, dest_type, lhs); return self.addNewInstArgs(b, src, dest_type, Inst.Cmp, Inst.Args(Inst.Cmp){ .lhs = casted_lhs, .rhs = casted_rhs, .op = op, }); } fn makeIntType(self: *Analyze, signed: bool, bits: u16) !Type { if (signed) { const int_payload = try self.arena.allocator.create(Type.Payload.IntSigned); int_payload.* = .{ .bits = bits }; return Type.initPayload(&int_payload.base); } else { const int_payload = try self.arena.allocator.create(Type.Payload.IntUnsigned); int_payload.* = .{ .bits = bits }; return Type.initPayload(&int_payload.base); } } fn coerce(self: *Analyze, block: ?*Block, dest_type: Type, inst: *Inst) !*Inst { // If the types are the same, we can return the operand. if (dest_type.eql(inst.ty)) return inst; const in_memory_result = coerceInMemoryAllowed(dest_type, inst.ty); if (in_memory_result == .ok) { return self.bitcast(block, dest_type, inst); } // *[N]T to []T if (inst.ty.isSinglePointer() and dest_type.isSlice() and (!inst.ty.pointerIsConst() or dest_type.pointerIsConst())) { const array_type = inst.ty.elemType(); const dst_elem_type = dest_type.elemType(); if (array_type.zigTypeTag() == .Array and coerceInMemoryAllowed(dst_elem_type, array_type.elemType()) == .ok) { return self.coerceArrayPtrToSlice(dest_type, inst); } } // comptime_int to fixed-width integer if (inst.ty.zigTypeTag() == .ComptimeInt and dest_type.zigTypeTag() == .Int) { // The representation is already correct; we only need to make sure it fits in the destination type. const val = inst.value().?; // comptime_int always has comptime known value if (!val.intFitsInType(dest_type, self.target)) { return self.fail(inst.src, "type {} cannot represent integer value {}", .{ inst.ty, val }); } return self.constInst(inst.src, .{ .ty = dest_type, .val = val }); } // integer widening if (inst.ty.zigTypeTag() == .Int and dest_type.zigTypeTag() == .Int) { const src_info = inst.ty.intInfo(self.target); const dst_info = dest_type.intInfo(self.target); if (src_info.signed == dst_info.signed and dst_info.bits >= src_info.bits) { if (inst.value()) |val| { return self.constInst(inst.src, .{ .ty = dest_type, .val = val }); } else { return self.fail(inst.src, "TODO implement runtime integer widening", .{}); } } else { return self.fail(inst.src, "TODO implement more int widening {} to {}", .{ inst.ty, dest_type }); } } return self.fail(inst.src, "TODO implement type coercion from {} to {}", .{ inst.ty, dest_type }); } fn bitcast(self: *Analyze, block: ?*Block, dest_type: Type, inst: *Inst) !*Inst { if (inst.value()) |val| { // Keep the comptime Value representation; take the new type. return self.constInst(inst.src, .{ .ty = dest_type, .val = val }); } // TODO validate the type size and other compile errors const b = try self.requireRuntimeBlock(block, inst.src); return self.addNewInstArgs(b, inst.src, dest_type, Inst.BitCast, Inst.Args(Inst.BitCast){ .operand = inst }); } fn coerceArrayPtrToSlice(self: *Analyze, dest_type: Type, inst: *Inst) !*Inst { if (inst.value()) |val| { // The comptime Value representation is compatible with both types. return self.constInst(inst.src, .{ .ty = dest_type, .val = val }); } return self.fail(inst.src, "TODO implement coerceArrayPtrToSlice runtime instruction", .{}); } fn fail(self: *Analyze, src: usize, comptime format: []const u8, args: var) InnerError { @setCold(true); const msg = try std.fmt.allocPrint(&self.arena.allocator, format, args); (try self.errors.addOne()).* = .{ .byte_offset = src, .msg = msg, }; return error.AnalysisFail; } const InMemoryCoercionResult = enum { ok, no_match, }; fn coerceInMemoryAllowed(dest_type: Type, src_type: Type) InMemoryCoercionResult { if (dest_type.eql(src_type)) return .ok; // TODO: implement more of this function return .no_match; } }; pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = if (std.builtin.link_libc) std.heap.c_allocator else &arena.allocator; const args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); const src_path = args[1]; const debug_error_trace = true; const source = try std.fs.cwd().readFileAllocOptions(allocator, src_path, std.math.maxInt(u32), 1, 0); defer allocator.free(source); var zir_module = try text.parse(allocator, source); defer zir_module.deinit(allocator); if (zir_module.errors.len != 0) { for (zir_module.errors) |err_msg| { const loc = std.zig.findLineColumn(source, err_msg.byte_offset); std.debug.warn("{}:{}:{}: error: {}\n", .{ src_path, loc.line + 1, loc.column + 1, err_msg.msg }); } if (debug_error_trace) return error.ParseFailure; std.process.exit(1); } const native_info = try std.zig.system.NativeTargetInfo.detect(allocator, .{}); var analyzed_module = try analyze(allocator, zir_module, .{ .target = native_info.target, .output_mode = .Obj, .link_mode = .Static, .optimize_mode = .Debug, }); defer analyzed_module.deinit(allocator); if (analyzed_module.errors.len != 0) { for (analyzed_module.errors) |err_msg| { const loc = std.zig.findLineColumn(source, err_msg.byte_offset); std.debug.warn("{}:{}:{}: error: {}\n", .{ src_path, loc.line + 1, loc.column + 1, err_msg.msg }); } if (debug_error_trace) return error.AnalysisFail; std.process.exit(1); } const output_zir = true; if (output_zir) { var new_zir_module = try text.emit_zir(allocator, analyzed_module); defer new_zir_module.deinit(allocator); var bos = std.io.bufferedOutStream(std.io.getStdOut().outStream()); try new_zir_module.writeToStream(allocator, bos.outStream()); try bos.flush(); } const link = @import("link.zig"); var result = try link.updateFilePath(allocator, analyzed_module, std.fs.cwd(), "zir.o"); defer result.deinit(allocator); if (result.errors.len != 0) { for (result.errors) |err_msg| { const loc = std.zig.findLineColumn(source, err_msg.byte_offset); std.debug.warn("{}:{}:{}: error: {}\n", .{ src_path, loc.line + 1, loc.column + 1, err_msg.msg }); } if (debug_error_trace) return error.LinkFailure; std.process.exit(1); } } // Performance optimization ideas: // * when analyzing use a field in the Inst instead of HashMap to track corresponding instructions
src-self-hosted/ir.zig
const std = @import("std.zig"); const builtin = @import("builtin"); const testing = std.testing; const SpinLock = std.SpinLock; const assert = std.debug.assert; const c = std.c; const os = std.os; const time = std.time; const linux = os.linux; const windows = os.windows; /// A resource object which supports blocking until signaled. /// Once finished, the `deinit()` method should be called for correctness. pub const ResetEvent = struct { os_event: OsEvent, pub const OsEvent = if (builtin.single_threaded) DebugEvent else if (builtin.link_libc and builtin.os != .windows and builtin.os != .linux) PosixEvent else AtomicEvent; pub fn init() ResetEvent { return ResetEvent{ .os_event = OsEvent.init() }; } pub fn deinit(self: *ResetEvent) void { self.os_event.deinit(); } /// Returns whether or not the event is currenetly set pub fn isSet(self: *ResetEvent) bool { return self.os_event.isSet(); } /// Sets the event if not already set and /// wakes up all the threads waiting on the event. pub fn set(self: *ResetEvent) void { return self.os_event.set(); } /// Resets the event to its original, unset state. pub fn reset(self: *ResetEvent) void { return self.os_event.reset(); } /// Wait for the event to be set by blocking the current thread. pub fn wait(self: *ResetEvent) void { return self.os_event.wait(null) catch unreachable; } /// Wait for the event to be set by blocking the current thread. /// A timeout in nanoseconds can be provided as a hint for how /// long the thread should block on the unset event before throwind error.TimedOut. pub fn timedWait(self: *ResetEvent, timeout_ns: u64) !void { return self.os_event.wait(timeout_ns); } }; const DebugEvent = struct { is_set: bool, fn init() DebugEvent { return DebugEvent{ .is_set = false }; } fn deinit(self: *DebugEvent) void { self.* = undefined; } fn isSet(self: *DebugEvent) bool { return self.is_set; } fn reset(self: *DebugEvent) void { self.is_set = false; } fn set(self: *DebugEvent) void { self.is_set = true; } fn wait(self: *DebugEvent, timeout: ?u64) !void { if (self.is_set) return; if (timeout != null) return error.TimedOut; @panic("deadlock detected"); } }; const PosixEvent = struct { is_set: bool, cond: c.pthread_cond_t, mutex: c.pthread_mutex_t, fn init() PosixEvent { return PosixEvent{ .is_set = false, .cond = c.PTHREAD_COND_INITIALIZER, .mutex = c.PTHREAD_MUTEX_INITIALIZER, }; } fn deinit(self: *PosixEvent) void { // on dragonfly, *destroy() functions can return EINVAL // for statically initialized pthread structures const err = if (builtin.os == .dragonfly) os.EINVAL else 0; const retm = c.pthread_mutex_destroy(&self.mutex); assert(retm == 0 or retm == err); const retc = c.pthread_cond_destroy(&self.cond); assert(retc == 0 or retc == err); } fn isSet(self: *PosixEvent) bool { assert(c.pthread_mutex_lock(&self.mutex) == 0); defer assert(c.pthread_mutex_unlock(&self.mutex) == 0); return self.is_set; } fn reset(self: *PosixEvent) void { assert(c.pthread_mutex_lock(&self.mutex) == 0); defer assert(c.pthread_mutex_unlock(&self.mutex) == 0); self.is_set = false; } fn set(self: *PosixEvent) void { assert(c.pthread_mutex_lock(&self.mutex) == 0); defer assert(c.pthread_mutex_unlock(&self.mutex) == 0); if (!self.is_set) { self.is_set = true; assert(c.pthread_cond_broadcast(&self.cond) == 0); } } fn wait(self: *PosixEvent, timeout: ?u64) !void { assert(c.pthread_mutex_lock(&self.mutex) == 0); defer assert(c.pthread_mutex_unlock(&self.mutex) == 0); // quick guard before possibly calling time syscalls below if (self.is_set) return; var ts: os.timespec = undefined; if (timeout) |timeout_ns| { var timeout_abs = timeout_ns; if (comptime std.Target.current.isDarwin()) { var tv: os.darwin.timeval = undefined; assert(os.darwin.gettimeofday(&tv, null) == 0); timeout_abs += @intCast(u64, tv.tv_sec) * time.second; timeout_abs += @intCast(u64, tv.tv_usec) * time.microsecond; } else { os.clock_gettime(os.CLOCK_REALTIME, &ts) catch unreachable; timeout_abs += @intCast(u64, ts.tv_sec) * time.second; timeout_abs += @intCast(u64, ts.tv_nsec); } ts.tv_sec = @intCast(@TypeOf(ts.tv_sec), @divFloor(timeout_abs, time.second)); ts.tv_nsec = @intCast(@TypeOf(ts.tv_nsec), @mod(timeout_abs, time.second)); } while (!self.is_set) { const rc = switch (timeout == null) { true => c.pthread_cond_wait(&self.cond, &self.mutex), else => c.pthread_cond_timedwait(&self.cond, &self.mutex, &ts), }; switch (rc) { 0 => {}, os.ETIMEDOUT => return error.TimedOut, os.EINVAL => unreachable, os.EPERM => unreachable, else => unreachable, } } } }; const AtomicEvent = struct { waiters: u32, const WAKE = 1 << 0; const WAIT = 1 << 1; fn init() AtomicEvent { return AtomicEvent{ .waiters = 0 }; } fn deinit(self: *AtomicEvent) void { self.* = undefined; } fn isSet(self: *const AtomicEvent) bool { return @atomicLoad(u32, &self.waiters, .Acquire) == WAKE; } fn reset(self: *AtomicEvent) void { @atomicStore(u32, &self.waiters, 0, .Monotonic); } fn set(self: *AtomicEvent) void { const waiters = @atomicRmw(u32, &self.waiters, .Xchg, WAKE, .Release); if (waiters >= WAIT) { return Futex.wake(&self.waiters, waiters >> 1); } } fn wait(self: *AtomicEvent, timeout: ?u64) !void { var waiters = @atomicLoad(u32, &self.waiters, .Acquire); while (waiters != WAKE) { waiters = @cmpxchgWeak(u32, &self.waiters, waiters, waiters + WAIT, .Acquire, .Acquire) orelse return Futex.wait(&self.waiters, timeout); } } pub const Futex = switch (builtin.os) { .windows => WindowsFutex, .linux => LinuxFutex, else => SpinFutex, }; const SpinFutex = struct { fn wake(waiters: *u32, wake_count: u32) void {} fn wait(waiters: *u32, timeout: ?u64) !void { // TODO: handle platforms where a monotonic timer isnt available var timer: time.Timer = undefined; if (timeout != null) timer = time.Timer.start() catch unreachable; while (@atomicLoad(u32, waiters, .Acquire) != WAKE) { SpinLock.yield(); if (timeout) |timeout_ns| { if (timer.read() >= timeout_ns) return error.TimedOut; } } } }; const LinuxFutex = struct { fn wake(waiters: *u32, wake_count: u32) void { const waiting = std.math.maxInt(i32); // wake_count const ptr = @ptrCast(*const i32, waiters); const rc = linux.futex_wake(ptr, linux.FUTEX_WAKE | linux.FUTEX_PRIVATE_FLAG, waiting); assert(linux.getErrno(rc) == 0); } fn wait(waiters: *u32, timeout: ?u64) !void { var ts: linux.timespec = undefined; var ts_ptr: ?*linux.timespec = null; if (timeout) |timeout_ns| { ts_ptr = &ts; ts.tv_sec = @intCast(isize, timeout_ns / time.ns_per_s); ts.tv_nsec = @intCast(isize, timeout_ns % time.ns_per_s); } while (true) { const waiting = @atomicLoad(u32, waiters, .Acquire); if (waiting == WAKE) return; const expected = @intCast(i32, waiting); const ptr = @ptrCast(*const i32, waiters); const rc = linux.futex_wait(ptr, linux.FUTEX_WAIT | linux.FUTEX_PRIVATE_FLAG, expected, ts_ptr); switch (linux.getErrno(rc)) { 0 => continue, os.ETIMEDOUT => return error.TimedOut, os.EINTR => continue, os.EAGAIN => return, else => unreachable, } } } }; const WindowsFutex = struct { pub fn wake(waiters: *u32, wake_count: u32) void { const handle = getEventHandle() orelse return SpinFutex.wake(waiters, wake_count); const key = @ptrCast(*const c_void, waiters); var waiting = wake_count; while (waiting != 0) : (waiting -= 1) { const rc = windows.ntdll.NtReleaseKeyedEvent(handle, key, windows.FALSE, null); assert(rc == 0); } } pub fn wait(waiters: *u32, timeout: ?u64) !void { const handle = getEventHandle() orelse return SpinFutex.wait(waiters, timeout); const key = @ptrCast(*const c_void, waiters); // NT uses timeouts in units of 100ns with negative value being relative var timeout_ptr: ?*windows.LARGE_INTEGER = null; var timeout_value: windows.LARGE_INTEGER = undefined; if (timeout) |timeout_ns| { timeout_ptr = &timeout_value; timeout_value = -@intCast(windows.LARGE_INTEGER, timeout_ns / 100); } // NtWaitForKeyedEvent doesnt have spurious wake-ups var rc = windows.ntdll.NtWaitForKeyedEvent(handle, key, windows.FALSE, timeout_ptr); switch (rc) { windows.WAIT_TIMEOUT => { // update the wait count to signal that we're not waiting anymore. // if the .set() thread already observed that we are, perform a // matching NtWaitForKeyedEvent so that the .set() thread doesn't // deadlock trying to run NtReleaseKeyedEvent above. var waiting = @atomicLoad(u32, waiters, .Monotonic); while (true) { if (waiting == WAKE) { rc = windows.ntdll.NtWaitForKeyedEvent(handle, key, windows.FALSE, null); assert(rc == windows.WAIT_OBJECT_0); break; } else { waiting = @cmpxchgWeak(u32, waiters, waiting, waiting - WAIT, .Acquire, .Monotonic) orelse break; continue; } } return error.TimedOut; }, windows.WAIT_OBJECT_0 => {}, else => unreachable, } } var event_handle: usize = EMPTY; const EMPTY = ~@as(usize, 0); const LOADING = EMPTY - 1; pub fn getEventHandle() ?windows.HANDLE { var handle = @atomicLoad(usize, &event_handle, .Monotonic); while (true) { switch (handle) { EMPTY => handle = @cmpxchgWeak(usize, &event_handle, EMPTY, LOADING, .Acquire, .Monotonic) orelse { const handle_ptr = @ptrCast(*windows.HANDLE, &handle); const access_mask = windows.GENERIC_READ | windows.GENERIC_WRITE; if (windows.ntdll.NtCreateKeyedEvent(handle_ptr, access_mask, null, 0) != 0) handle = 0; @atomicStore(usize, &event_handle, handle, .Monotonic); return @intToPtr(?windows.HANDLE, handle); }, LOADING => { SpinLock.yield(); handle = @atomicLoad(usize, &event_handle, .Monotonic); }, else => { return @intToPtr(?windows.HANDLE, handle); }, } } } }; }; test "std.ResetEvent" { var event = ResetEvent.init(); defer event.deinit(); // test event setting testing.expect(event.isSet() == false); event.set(); testing.expect(event.isSet() == true); // test event resetting event.reset(); testing.expect(event.isSet() == false); // test event waiting (non-blocking) event.set(); event.wait(); try event.timedWait(1); // test cross-thread signaling if (builtin.single_threaded) return; const Context = struct { const Self = @This(); value: u128, in: ResetEvent, out: ResetEvent, fn init() Self { return Self{ .value = 0, .in = ResetEvent.init(), .out = ResetEvent.init(), }; } fn deinit(self: *Self) void { self.in.deinit(); self.out.deinit(); self.* = undefined; } fn sender(self: *Self) void { // update value and signal input testing.expect(self.value == 0); self.value = 1; self.in.set(); // wait for receiver to update value and signal output self.out.wait(); testing.expect(self.value == 2); // update value and signal final input self.value = 3; self.in.set(); } fn receiver(self: *Self) void { // wait for sender to update value and signal input self.in.wait(); assert(self.value == 1); // update value and signal output self.in.reset(); self.value = 2; self.out.set(); // wait for sender to update value and signal final input self.in.wait(); assert(self.value == 3); } }; var context = Context.init(); defer context.deinit(); const receiver = try std.Thread.spawn(&context, Context.receiver); defer receiver.wait(); context.sender(); }
lib/std/reset_event.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; // const data = @embedFile("../data/day03-tst.txt"); const data = @embedFile("../data/day03.txt"); pub fn main() !void { try part1(); try part2(); } fn part1() !void { const bins = try util.parseBinaries(data); const bit_length = bins.items[0].unmanaged.bit_length; var counts = List(usize).init(gpa); try counts.resize(bit_length); for (counts.items) |_, i| { counts.items[i] = 0; } for (bins.items) |bin| { var i: usize = 0; while (i < bit_length) : (i += 1) { if (bin.isSet(i)) { counts.items[i] += 1; } } } var gamma_rate = try BitSet.initEmpty(bit_length, gpa); var epsilon_rate = try BitSet.initEmpty(bit_length, gpa); var half: f32 = @intToFloat(f32, bins.items.len) * 0.5; for (counts.items) |count, i| { if (@intToFloat(f32, count) < half) { epsilon_rate.set(i); } else { gamma_rate.set(i); } } print("{}\n", .{util.binToDecimal(&gamma_rate) * util.binToDecimal(&epsilon_rate)}); } fn part2() !void { var oxy_rating = try util.parseBinaries(data); var co2_rating = try util.parseBinaries(data); var index: usize = 0; while (oxy_rating.items.len != 1) : (index += 1) { const amnt = oxy_rating.items.len; const ones = bitCount(&oxy_rating, index); const zero = amnt - ones; var to_be_removed: bool = ones < zero; var rm_index: usize = 0; while (rm_index < oxy_rating.items.len) { if (oxy_rating.items[rm_index].isSet(index) == to_be_removed) { _ = oxy_rating.orderedRemove(rm_index); } else { rm_index += 1; } } } index = 0; while (co2_rating.items.len != 1) : (index += 1) { const amnt = co2_rating.items.len; const ones = bitCount(&co2_rating, index); const zero = amnt - ones; var to_be_removed: bool = ones >= zero; var rm_index: usize = 0; while (rm_index < co2_rating.items.len) { if (co2_rating.items[rm_index].isSet(index) == to_be_removed) { _ = co2_rating.orderedRemove(rm_index); } else { rm_index += 1; } } } print("{}\n", .{util.binToDecimal(&oxy_rating.items[0]) * util.binToDecimal(&co2_rating.items[0])}); } fn bitCount(bitset: *List(BitSet), index: usize) usize { var count: usize = 0; for (bitset.items) |bits| { if (bits.isSet(index)) { count += 1; } } return count; } const print = std.debug.print;
src/day03.zig
const std = @import("std"); const print = std.debug.print; pub fn main() anyerror!void { const input = "iwrupvqb"; var running = true; const t0 = try std.Thread.spawn(.{}, find_md5, .{ true, input, &running, 0, 4 }); const t1 = try std.Thread.spawn(.{}, find_md5, .{ true, input, &running, 1, 4 }); const t2 = try std.Thread.spawn(.{}, find_md5, .{ true, input, &running, 2, 4 }); const t3 = try std.Thread.spawn(.{}, find_md5, .{ true, input, &running, 3, 4 }); t0.join(); t1.join(); t2.join(); t3.join(); running = true; const t4 = try std.Thread.spawn(.{}, find_md5, .{ false, input, &running, 0, 4 }); const t5 = try std.Thread.spawn(.{}, find_md5, .{ false, input, &running, 1, 4 }); const t6 = try std.Thread.spawn(.{}, find_md5, .{ false, input, &running, 2, 4 }); const t7 = try std.Thread.spawn(.{}, find_md5, .{ false, input, &running, 3, 4 }); t4.join(); t5.join(); t6.join(); t7.join(); } fn find_md5(find_5: bool, input: []const u8, running: *bool, start: usize, step: usize) void { var i: usize = start; const Md5 = std.crypto.hash.Md5; var hash_buf: [16]u8 = undefined; var allocator_buffer: [100]u8 = undefined; var allocator = &std.heap.FixedBufferAllocator.init(&allocator_buffer).allocator; while (running.*) { var s = std.fmt.allocPrint(allocator, "{d}", .{i}) catch @panic("Unhandled"); defer allocator.free(s); var h = Md5.init(.{}); h.update(input); h.update(s); h.final(&hash_buf); var hash_hex = std.fmt.allocPrint(allocator, "{s}", .{std.fmt.fmtSliceHexUpper(&hash_buf)}) catch @panic("Unhandled"); defer allocator.free(hash_hex); if (find_5) { if (std.mem.eql(u8, hash_hex[0..5], "00000")) { print("Number {d} produces hash {s}\n", .{ i, std.fmt.fmtSliceHexUpper(&hash_buf) }); running.* = false; return; } } else { if (std.mem.eql(u8, hash_hex[0..6], "000000")) { print("Number {d} produces hash {s}\n", .{ i, std.fmt.fmtSliceHexUpper(&hash_buf) }); running.* = false; return; } } i += step; } }
src/day04.zig
const std = @import("std"); const math = std.math; const assert = std.debug.assert; const zwin32 = @import("zwin32"); const w = zwin32.base; const d3d12 = zwin32.d3d12; const hrPanic = zwin32.hrPanic; const hrPanicOnFail = zwin32.hrPanicOnFail; const zd3d12 = @import("zd3d12"); const common = @import("common"); const c = common.c; const vm = common.vectormath; const GuiRenderer = common.GuiRenderer; pub export const D3D12SDKVersion: u32 = 4; pub export const D3D12SDKPath: [*:0]const u8 = ".\\d3d12\\"; const content_dir = @import("build_options").content_dir; const Vertex = struct { position: vm.Vec3, normal: vm.Vec3, texcoords0: vm.Vec2, }; comptime { assert(@sizeOf([2]Vertex) == 64); assert(@alignOf([2]Vertex) == 4); } fn loadMesh( filename: []const u8, indices: *std.ArrayList(u32), positions: *std.ArrayList(vm.Vec3), normals: ?*std.ArrayList(vm.Vec3), texcoords0: ?*std.ArrayList(vm.Vec2), ) void { const data = blk: { var data: *c.cgltf_data = undefined; const options = std.mem.zeroes(c.cgltf_options); // Parse. { const result = c.cgltf_parse_file(&options, filename.ptr, @ptrCast([*c][*c]c.cgltf_data, &data)); assert(result == c.cgltf_result_success); } // Load. { const result = c.cgltf_load_buffers(&options, data, filename.ptr); assert(result == c.cgltf_result_success); } break :blk data; }; defer c.cgltf_free(data); const num_vertices: u32 = @intCast(u32, data.meshes[0].primitives[0].attributes[0].data.*.count); const num_indices: u32 = @intCast(u32, data.meshes[0].primitives[0].indices.*.count); indices.resize(num_indices) catch unreachable; positions.resize(num_vertices) catch unreachable; // Indices. { const accessor = data.meshes[0].primitives[0].indices; assert(accessor.*.buffer_view != null); assert(accessor.*.stride == accessor.*.buffer_view.*.stride or accessor.*.buffer_view.*.stride == 0); assert((accessor.*.stride * accessor.*.count) == accessor.*.buffer_view.*.size); assert(accessor.*.buffer_view.*.buffer.*.data != null); const data_addr = @alignCast(4, @ptrCast([*]const u8, accessor.*.buffer_view.*.buffer.*.data) + accessor.*.offset + accessor.*.buffer_view.*.offset); if (accessor.*.stride == 1) { assert(accessor.*.component_type == c.cgltf_component_type_r_8u); const src = @ptrCast([*]const u8, data_addr); var i: u32 = 0; while (i < num_indices) : (i += 1) { indices.items[i] = src[i]; } } else if (accessor.*.stride == 2) { assert(accessor.*.component_type == c.cgltf_component_type_r_16u); const src = @ptrCast([*]const u16, data_addr); var i: u32 = 0; while (i < num_indices) : (i += 1) { indices.items[i] = src[i]; } } else if (accessor.*.stride == 4) { assert(accessor.*.component_type == c.cgltf_component_type_r_32u); const src = @ptrCast([*]const u32, data_addr); var i: u32 = 0; while (i < num_indices) : (i += 1) { indices.items[i] = src[i]; } } else { unreachable; } } // Attributes. { const num_attribs: u32 = @intCast(u32, data.meshes[0].primitives[0].attributes_count); var attrib_index: u32 = 0; while (attrib_index < num_attribs) : (attrib_index += 1) { const attrib = &data.*.meshes[0].primitives[0].attributes[attrib_index]; const accessor = attrib.*.data; assert(accessor.*.buffer_view != null); assert(accessor.*.stride == accessor.*.buffer_view.*.stride or accessor.*.buffer_view.*.stride == 0); assert((accessor.*.stride * accessor.*.count) == accessor.*.buffer_view.*.size); assert(accessor.*.buffer_view.*.buffer.*.data != null); const data_addr = @ptrCast([*]const u8, accessor.*.buffer_view.*.buffer.*.data) + accessor.*.offset + accessor.*.buffer_view.*.offset; if (attrib.*.type == c.cgltf_attribute_type_position) { assert(accessor.*.type == c.cgltf_type_vec3); assert(accessor.*.component_type == c.cgltf_component_type_r_32f); @memcpy(@ptrCast([*]u8, positions.items.ptr), data_addr, accessor.*.count * accessor.*.stride); } else if (attrib.*.type == c.cgltf_attribute_type_normal and normals != null) { assert(accessor.*.type == c.cgltf_type_vec3); assert(accessor.*.component_type == c.cgltf_component_type_r_32f); normals.?.resize(num_vertices) catch unreachable; @memcpy(@ptrCast([*]u8, normals.?.items.ptr), data_addr, accessor.*.count * accessor.*.stride); } else if (attrib.*.type == c.cgltf_attribute_type_texcoord and texcoords0 != null) { assert(accessor.*.type == c.cgltf_type_vec2); assert(accessor.*.component_type == c.cgltf_component_type_r_32f); texcoords0.?.resize(num_vertices) catch unreachable; @memcpy(@ptrCast([*]u8, texcoords0.?.items.ptr), data_addr, accessor.*.count * accessor.*.stride); } } } } const DemoState = struct { const window_name = "zig-gamedev: simple3d"; const window_width = 1920; const window_height = 1080; grfx: zd3d12.GraphicsContext, gui: GuiRenderer, frame_stats: common.FrameStats, pipeline: zd3d12.PipelineHandle, vertex_buffer: zd3d12.ResourceHandle, index_buffer: zd3d12.ResourceHandle, entity_buffer: zd3d12.ResourceHandle, base_color_texture: zd3d12.ResourceHandle, depth_texture: zd3d12.ResourceHandle, entity_buffer_srv: d3d12.CPU_DESCRIPTOR_HANDLE, base_color_texture_srv: d3d12.CPU_DESCRIPTOR_HANDLE, depth_texture_srv: d3d12.CPU_DESCRIPTOR_HANDLE, num_mesh_vertices: u32, num_mesh_indices: u32, fn init(gpa_allocator: std.mem.Allocator) DemoState { const window = common.initWindow(gpa_allocator, window_name, window_width, window_height) catch unreachable; var grfx = zd3d12.GraphicsContext.init(gpa_allocator, window); var arena_allocator_state = std.heap.ArenaAllocator.init(gpa_allocator); defer arena_allocator_state.deinit(); const arena_allocator = arena_allocator_state.allocator(); const pipeline = blk: { const input_layout_desc = [_]d3d12.INPUT_ELEMENT_DESC{ d3d12.INPUT_ELEMENT_DESC.init("POSITION", 0, .R32G32B32_FLOAT, 0, 0, .PER_VERTEX_DATA, 0), d3d12.INPUT_ELEMENT_DESC.init("_Normal", 0, .R32G32B32_FLOAT, 0, 12, .PER_VERTEX_DATA, 0), d3d12.INPUT_ELEMENT_DESC.init("_Texcoords", 0, .R32G32_FLOAT, 0, 24, .PER_VERTEX_DATA, 0), }; var pso_desc = d3d12.GRAPHICS_PIPELINE_STATE_DESC.initDefault(); pso_desc.DSVFormat = .D32_FLOAT; pso_desc.InputLayout = .{ .pInputElementDescs = &input_layout_desc, .NumElements = input_layout_desc.len, }; pso_desc.RTVFormats[0] = .R8G8B8A8_UNORM; pso_desc.NumRenderTargets = 1; pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf; pso_desc.PrimitiveTopologyType = .TRIANGLE; break :blk grfx.createGraphicsShaderPipeline( arena_allocator, &pso_desc, content_dir ++ "shaders/simple3d.vs.cso", content_dir ++ "shaders/simple3d.ps.cso", ); }; const entity_buffer = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(1 * @sizeOf(vm.Mat4)), d3d12.RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, null, ) catch |err| hrPanic(err); const entity_buffer_srv = grfx.allocateCpuDescriptors(.CBV_SRV_UAV, 1); grfx.device.CreateShaderResourceView( grfx.lookupResource(entity_buffer).?, &d3d12.SHADER_RESOURCE_VIEW_DESC.initStructuredBuffer(0, 1, @sizeOf(vm.Mat4)), entity_buffer_srv, ); var mipgen = zd3d12.MipmapGenerator.init(arena_allocator, &grfx, .R8G8B8A8_UNORM, content_dir); grfx.beginFrame(); var gui = GuiRenderer.init(arena_allocator, &grfx, 1, content_dir); const base_color_texture = grfx.createAndUploadTex2dFromFile( content_dir ++ "SciFiHelmet/SciFiHelmet_BaseColor.png", .{}, // Create complete mipmap chain (up to 1x1). ) catch |err| hrPanic(err); mipgen.generateMipmaps(&grfx, base_color_texture); const base_color_texture_srv = grfx.allocateCpuDescriptors(.CBV_SRV_UAV, 1); grfx.device.CreateShaderResourceView( grfx.lookupResource(base_color_texture).?, null, base_color_texture_srv, ); const depth_texture = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &blk: { var desc = d3d12.RESOURCE_DESC.initTex2d(.D32_FLOAT, grfx.viewport_width, grfx.viewport_height, 1); desc.Flags = d3d12.RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | d3d12.RESOURCE_FLAG_DENY_SHADER_RESOURCE; break :blk desc; }, d3d12.RESOURCE_STATE_DEPTH_WRITE, &d3d12.CLEAR_VALUE.initDepthStencil(.D32_FLOAT, 1.0, 0), ) catch |err| hrPanic(err); const depth_texture_srv = grfx.allocateCpuDescriptors(.DSV, 1); grfx.device.CreateDepthStencilView(grfx.lookupResource(depth_texture).?, null, depth_texture_srv); const buffers = blk: { var indices = std.ArrayList(u32).init(arena_allocator); defer indices.deinit(); var positions = std.ArrayList(vm.Vec3).init(arena_allocator); defer positions.deinit(); var normals = std.ArrayList(vm.Vec3).init(arena_allocator); defer normals.deinit(); var texcoords0 = std.ArrayList(vm.Vec2).init(arena_allocator); defer texcoords0.deinit(); loadMesh(content_dir ++ "SciFiHelmet/SciFiHelmet.gltf", &indices, &positions, &normals, &texcoords0); const num_vertices = @intCast(u32, positions.items.len); const num_indices = @intCast(u32, indices.items.len); const vertex_buffer = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(num_vertices * @sizeOf(Vertex)), d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err); const index_buffer = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(num_indices * @sizeOf(u32)), d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err); const upload_verts = grfx.allocateUploadBufferRegion(Vertex, num_vertices); for (positions.items) |_, i| { upload_verts.cpu_slice[i] = .{ .position = positions.items[i], .normal = normals.items[i], .texcoords0 = texcoords0.items[i], }; } grfx.cmdlist.CopyBufferRegion( grfx.lookupResource(vertex_buffer).?, 0, upload_verts.buffer, upload_verts.buffer_offset, upload_verts.cpu_slice.len * @sizeOf(@TypeOf(upload_verts.cpu_slice[0])), ); const upload_indices = grfx.allocateUploadBufferRegion(u32, num_indices); for (indices.items) |index, i| { upload_indices.cpu_slice[i] = index; } grfx.cmdlist.CopyBufferRegion( grfx.lookupResource(index_buffer).?, 0, upload_indices.buffer, upload_indices.buffer_offset, upload_indices.cpu_slice.len * @sizeOf(@TypeOf(upload_indices.cpu_slice[0])), ); break :blk .{ .num_vertices = num_vertices, .num_indices = num_indices, .vertex = vertex_buffer, .index = index_buffer, }; }; grfx.addTransitionBarrier(buffers.vertex, d3d12.RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); grfx.addTransitionBarrier(buffers.index, d3d12.RESOURCE_STATE_INDEX_BUFFER); grfx.addTransitionBarrier(base_color_texture, d3d12.RESOURCE_STATE_PIXEL_SHADER_RESOURCE); grfx.flushResourceBarriers(); grfx.endFrame(); grfx.finishGpuCommands(); mipgen.deinit(&grfx); return .{ .grfx = grfx, .gui = gui, .frame_stats = common.FrameStats.init(), .pipeline = pipeline, .vertex_buffer = buffers.vertex, .index_buffer = buffers.index, .entity_buffer = entity_buffer, .base_color_texture = base_color_texture, .depth_texture = depth_texture, .entity_buffer_srv = entity_buffer_srv, .base_color_texture_srv = base_color_texture_srv, .depth_texture_srv = depth_texture_srv, .num_mesh_vertices = buffers.num_vertices, .num_mesh_indices = buffers.num_indices, }; } fn deinit(demo: *DemoState, gpa_allocator: std.mem.Allocator) void { demo.grfx.finishGpuCommands(); demo.gui.deinit(&demo.grfx); demo.grfx.deinit(gpa_allocator); common.deinitWindow(gpa_allocator); demo.* = undefined; } fn update(demo: *DemoState) void { demo.frame_stats.update(demo.grfx.window, window_name); common.newImGuiFrame(demo.frame_stats.delta_time); c.igShowDemoWindow(null); } fn draw(demo: *DemoState) void { var grfx = &demo.grfx; grfx.beginFrame(); grfx.addTransitionBarrier(demo.entity_buffer, d3d12.RESOURCE_STATE_COPY_DEST); grfx.flushResourceBarriers(); { const object_to_camera = vm.Mat4.initRotationY(@floatCast(f32, 0.5 * demo.frame_stats.time)).mul( vm.Mat4.initLookAtLh( vm.Vec3.init(2.2, 2.2, -2.2), vm.Vec3.init(0.0, 0.0, 0.0), vm.Vec3.init(0.0, 1.0, 0.0), ), ); const upload_entity = grfx.allocateUploadBufferRegion(vm.Mat4, 1); upload_entity.cpu_slice[0] = object_to_camera.mul( vm.Mat4.initPerspectiveFovLh( math.pi / 3.0, @intToFloat(f32, grfx.viewport_width) / @intToFloat(f32, grfx.viewport_height), 0.1, 100.0, ), ).transpose(); grfx.cmdlist.CopyBufferRegion( grfx.lookupResource(demo.entity_buffer).?, 0, upload_entity.buffer, upload_entity.buffer_offset, upload_entity.cpu_slice.len * @sizeOf(vm.Mat4), ); } const back_buffer = grfx.getBackBuffer(); grfx.addTransitionBarrier(demo.entity_buffer, d3d12.RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); grfx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_RENDER_TARGET); grfx.flushResourceBarriers(); grfx.cmdlist.OMSetRenderTargets( 1, &[_]d3d12.CPU_DESCRIPTOR_HANDLE{back_buffer.descriptor_handle}, w.TRUE, &demo.depth_texture_srv, ); grfx.cmdlist.ClearRenderTargetView( back_buffer.descriptor_handle, &[4]f32{ 0.2, 0.4, 0.8, 1.0 }, 0, null, ); grfx.cmdlist.ClearDepthStencilView(demo.depth_texture_srv, d3d12.CLEAR_FLAG_DEPTH, 1.0, 0, 0, null); grfx.setCurrentPipeline(demo.pipeline); grfx.cmdlist.IASetPrimitiveTopology(.TRIANGLELIST); grfx.cmdlist.IASetVertexBuffers(0, 1, &[_]d3d12.VERTEX_BUFFER_VIEW{.{ .BufferLocation = grfx.lookupResource(demo.vertex_buffer).?.GetGPUVirtualAddress(), .SizeInBytes = demo.num_mesh_vertices * @sizeOf(Vertex), .StrideInBytes = @sizeOf(Vertex), }}); grfx.cmdlist.IASetIndexBuffer(&.{ .BufferLocation = grfx.lookupResource(demo.index_buffer).?.GetGPUVirtualAddress(), .SizeInBytes = demo.num_mesh_indices * @sizeOf(u32), .Format = .R32_UINT, }); grfx.cmdlist.SetGraphicsRootDescriptorTable(2, grfx.copyDescriptorsToGpuHeap(1, demo.base_color_texture_srv)); grfx.cmdlist.SetGraphicsRootDescriptorTable(1, grfx.copyDescriptorsToGpuHeap(1, demo.entity_buffer_srv)); grfx.cmdlist.SetGraphicsRoot32BitConstant(0, 0, 0); grfx.cmdlist.DrawIndexedInstanced(demo.num_mesh_indices, 1, 0, 0, 0); demo.gui.draw(grfx); grfx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_PRESENT); grfx.flushResourceBarriers(); grfx.endFrame(); } }; pub fn main() !void { common.init(); defer common.deinit(); var gpa_allocator_state = std.heap.GeneralPurposeAllocator(.{}){}; defer { const leaked = gpa_allocator_state.deinit(); std.debug.assert(leaked == false); } const gpa_allocator = gpa_allocator_state.allocator(); var demo = DemoState.init(gpa_allocator); defer demo.deinit(gpa_allocator); while (true) { var message = std.mem.zeroes(w.user32.MSG); const has_message = w.user32.peekMessageA(&message, null, 0, 0, w.user32.PM_REMOVE) catch unreachable; if (has_message) { _ = w.user32.translateMessage(&message); _ = w.user32.dispatchMessageA(&message); if (message.message == w.user32.WM_QUIT) { break; } } else { demo.update(); demo.draw(); } } }
samples/simple3d/src/simple3d.zig
const nvg = @import("nanovg"); pub fn iconNew() void { nvg.beginPath(); nvg.moveTo(2.5, 0.5); nvg.lineTo(2.5, 15.5); nvg.lineTo(13.5, 15.5); nvg.lineTo(13.5, 3.5); nvg.lineTo(10.5, 0.5); nvg.closePath(); nvg.fillColor(nvg.rgb(255, 255, 255)); nvg.fill(); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); nvg.beginPath(); nvg.moveTo(8.5, 0.5); nvg.lineTo(8.5, 5.5); nvg.lineTo(13.5, 5.5); nvg.stroke(); } pub fn iconOpen() void { nvg.beginPath(); nvg.moveTo(1.5, 1.5); nvg.lineTo(0.5, 2.5); nvg.lineTo(0.5, 14.5); nvg.lineTo(12.5, 14.5); nvg.lineTo(13.5, 13.5); nvg.lineTo(15.5, 8.5); nvg.lineTo(15.5, 7.5); nvg.lineTo(13.5, 7.5); nvg.lineTo(13.5, 2.5); nvg.lineTo(6.5, 2.5); nvg.lineTo(5.5, 1.5); nvg.closePath(); nvg.fillColor(nvg.rgb(245, 218, 97)); nvg.fill(); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); nvg.beginPath(); nvg.moveTo(13.5, 7.5); nvg.lineTo(4.5, 7.5); nvg.lineTo(2.5, 12.5); nvg.stroke(); } pub fn iconSave() void { nvg.beginPath(); nvg.moveTo(0.5, 0.5); nvg.lineTo(0.5, 14.5); nvg.lineTo(1.5, 15.5); nvg.lineTo(15.5, 15.5); nvg.lineTo(15.5, 0.5); nvg.closePath(); nvg.fillColor(nvg.rgb(40, 140, 200)); nvg.fill(); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); nvg.beginPath(); nvg.moveTo(3, 10); nvg.lineTo(3, 15); nvg.lineTo(13, 15); nvg.lineTo(13, 10); nvg.fillColor(nvg.rgb(171, 171, 171)); nvg.fill(); nvg.beginPath(); nvg.moveTo(4, 11); nvg.lineTo(4, 14); nvg.lineTo(6, 14); nvg.lineTo(6, 11); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); nvg.beginPath(); nvg.moveTo(3, 1); nvg.lineTo(3, 8); nvg.lineTo(13, 8); nvg.lineTo(13, 1); nvg.fillColor(nvg.rgb(255, 255, 255)); nvg.fill(); nvg.beginPath(); nvg.moveTo(3, 1); nvg.lineTo(3, 2); nvg.lineTo(13, 2); nvg.lineTo(13, 1); nvg.fillColor(nvg.rgb(250, 10, 0)); nvg.fill(); nvg.beginPath(); nvg.moveTo(4, 3); nvg.lineTo(4, 5); nvg.lineTo(12, 5); nvg.lineTo(12, 3); nvg.moveTo(4, 6); nvg.lineTo(4, 7); nvg.lineTo(12, 7); nvg.lineTo(12, 6); nvg.fillColor(nvg.rgb(224, 224, 224)); nvg.fill(); } pub fn iconUndoEnabled() void { iconUndo(true); } pub fn iconUndoDisabled() void { iconUndo(false); } fn iconUndo(enabled: bool) void { nvg.beginPath(); nvg.arc(8, 8, 6, -0.75 * nvg.Pi, 0.75 * nvg.Pi, .cw); nvg.lineCap(.round); nvg.strokeColor(if (enabled) nvg.rgb(80, 80, 80) else nvg.rgb(170, 170, 170)); nvg.strokeWidth(4); nvg.stroke(); nvg.beginPath(); nvg.moveTo(0.5, 7.5); nvg.lineTo(0.5, 0.5); nvg.lineTo(1.5, 0.5); nvg.lineTo(7.5, 6.5); nvg.lineTo(7.5, 7.5); nvg.closePath(); nvg.fillColor(if (enabled) nvg.rgb(255, 255, 255) else nvg.rgb(170, 170, 170)); nvg.fill(); nvg.strokeWidth(1); nvg.strokeColor(if (enabled) nvg.rgb(80, 80, 80) else nvg.rgb(170, 170, 170)); nvg.stroke(); nvg.beginPath(); nvg.arc(8, 8, 6, -0.75 * nvg.Pi, 0.75 * nvg.Pi, .cw); nvg.strokeColor(if (enabled) nvg.rgb(255, 255, 255) else nvg.rgb(170, 170, 170)); nvg.strokeWidth(2); nvg.stroke(); // reset nvg.lineCap(.butt); nvg.strokeWidth(1); } pub fn iconRedoEnabled() void { iconRedo(true); } pub fn iconRedoDisabled() void { iconRedo(false); } fn iconRedo(enabled: bool) void { nvg.beginPath(); nvg.arc(8, 8, 6, -0.25 * nvg.Pi, 0.25 * nvg.Pi, .ccw); nvg.lineCap(.round); nvg.strokeColor(if (enabled) nvg.rgb(80, 80, 80) else nvg.rgb(170, 170, 170)); nvg.strokeWidth(4); nvg.stroke(); nvg.beginPath(); nvg.moveTo(15.5, 7.5); nvg.lineTo(15.5, 0.5); nvg.lineTo(14.5, 0.5); nvg.lineTo(8.5, 6.5); nvg.lineTo(8.5, 7.5); nvg.closePath(); nvg.fillColor(if (enabled) nvg.rgb(255, 255, 255) else nvg.rgb(170, 170, 170)); nvg.fill(); nvg.strokeWidth(1); nvg.strokeColor(if (enabled) nvg.rgb(80, 80, 80) else nvg.rgb(170, 170, 170)); nvg.stroke(); nvg.beginPath(); nvg.arc(8, 8, 6, -0.25 * nvg.Pi, 0.25 * nvg.Pi, .ccw); nvg.strokeColor(if (enabled) nvg.rgb(255, 255, 255) else nvg.rgb(170, 170, 170)); nvg.strokeWidth(2); nvg.stroke(); // reset nvg.lineCap(.butt); nvg.strokeWidth(1); } pub fn iconCut() void { nvg.beginPath(); nvg.ellipse(4, 13, 2, 2); nvg.ellipse(12, 13, 2, 2); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.strokeWidth(2); nvg.stroke(); nvg.beginPath(); nvg.moveTo(10, 10); nvg.lineTo(4.5, 0.5); nvg.lineTo(3.5, 0.5); nvg.lineTo(3.5, 3.5); nvg.lineTo(3.5, 3.5); nvg.lineTo(7, 10); nvg.fillColor(nvg.rgb(255, 255, 255)); nvg.fill(); nvg.strokeWidth(1); nvg.stroke(); nvg.beginPath(); nvg.moveTo(6, 10); nvg.lineTo(11.5, 0.5); nvg.lineTo(12.5, 0.5); nvg.lineTo(12.5, 3.5); nvg.lineTo(12.5, 3.5); nvg.lineTo(9, 10); nvg.fill(); nvg.stroke(); nvg.beginPath(); nvg.moveTo(6, 9); nvg.lineTo(4.5, 10.5); nvg.lineTo(7, 13); nvg.lineTo(7, 11.5); nvg.lineTo(7.5, 11); nvg.lineTo(8.5, 11); nvg.lineTo(9, 11.5); nvg.lineTo(9, 13); nvg.lineTo(11.5, 10.5); nvg.lineTo(10, 9); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); } pub fn iconCopy() void { for ([_]u0{ 0, 0 }) |_| { nvg.beginPath(); nvg.moveTo(2.5, 0.5); nvg.lineTo(2.5, 10.5); nvg.lineTo(10.5, 10.5); nvg.lineTo(10.5, 2.5); nvg.lineTo(8.5, 0.5); nvg.closePath(); nvg.fillColor(nvg.rgb(255, 255, 255)); nvg.fill(); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); nvg.beginPath(); nvg.moveTo(7.5, 0.5); nvg.lineTo(7.5, 3.5); nvg.lineTo(10.5, 3.5); nvg.stroke(); nvg.translate(3, 5); } } pub fn iconPasteEnabled() void { iconPaste(true); } pub fn iconPasteDisabled() void { iconPaste(false); } pub fn iconPaste(enabled: bool) void { const stroke_color = if (enabled) nvg.rgb(66, 66, 66) else nvg.rgb(170, 170, 170); nvg.beginPath(); nvg.roundedRect(1.5, 1.5, 13, 14, 1.5); nvg.fillColor(if (enabled) nvg.rgb(215, 162, 71) else stroke_color); nvg.fill(); nvg.strokeColor(stroke_color); nvg.stroke(); nvg.beginPath(); nvg.rect(3.5, 3.5, 9, 10); nvg.fillColor(if (enabled) nvg.rgb(255, 255, 255) else nvg.rgb(224, 224, 224)); // TODO: use gui constant or alpha nvg.fill(); nvg.stroke(); nvg.beginPath(); nvg.moveTo(6.5, 0.5); nvg.lineTo(6.5, 1.5); nvg.lineTo(5.5, 2.5); nvg.lineTo(5.5, 4.5); nvg.lineTo(10.5, 4.5); nvg.lineTo(10.5, 2.5); nvg.lineTo(9.5, 1.5); nvg.lineTo(9.5, 0.5); nvg.closePath(); nvg.fillColor(nvg.rgb(170, 170, 170)); nvg.fill(); nvg.stroke(); nvg.beginPath(); nvg.rect(5, 6, 6, 1); nvg.rect(5, 8, 4, 1); nvg.rect(5, 10, 5, 1); nvg.fillColor(stroke_color); nvg.fill(); } pub fn iconToolCrop() void { nvg.fillColor(nvg.rgb(170, 170, 170)); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.beginPath(); nvg.moveTo(2.5, 0.5); nvg.lineTo(2.5, 13.5); nvg.lineTo(15.5, 13.5); nvg.lineTo(15.5, 10.5); nvg.lineTo(5.5, 10.5); nvg.lineTo(5.5, 0.5); nvg.closePath(); nvg.fill(); nvg.stroke(); nvg.beginPath(); nvg.moveTo(0.5, 5.5); nvg.lineTo(10.5, 5.5); nvg.lineTo(10.5, 15.5); nvg.lineTo(13.5, 15.5); nvg.lineTo(13.5, 2.5); nvg.lineTo(0.5, 2.5); nvg.closePath(); nvg.fill(); nvg.stroke(); } pub fn iconToolSelect() void { nvg.beginPath(); nvg.moveTo(1.5, 4); nvg.lineTo(1.5, 1.5); nvg.lineTo(4, 1.5); nvg.moveTo(6, 1.5); nvg.lineTo(10, 1.5); nvg.moveTo(12, 1.5); nvg.lineTo(14.5, 1.5); nvg.lineTo(14.5, 4); nvg.moveTo(14.5, 6); nvg.lineTo(14.5, 10); nvg.moveTo(14.5, 12); nvg.lineTo(14.5, 14.5); nvg.lineTo(12, 14.5); nvg.moveTo(10, 14.5); nvg.lineTo(6, 14.5); nvg.moveTo(4, 14.5); nvg.lineTo(1.5, 14.5); nvg.lineTo(1.5, 12); nvg.moveTo(1.5, 10); nvg.lineTo(1.5, 6); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); } pub fn iconToolLine() void { nvg.beginPath(); nvg.moveTo(13, 1); nvg.lineTo(5, 5); nvg.lineTo(10, 10); nvg.lineTo(2, 14); nvg.lineCap(.Round); defer nvg.lineCap(.Butt); nvg.strokeWidth(2); defer nvg.strokeWidth(1); nvg.strokeColor(nvg.rgb(0, 0, 0)); nvg.stroke(); } pub fn iconToolPen() void { nvg.beginPath(); nvg.moveTo(5.5, 14.5); nvg.lineTo(5.5, 12.5); nvg.lineTo(15.5, 2.5); nvg.lineTo(15.5, 4.5); nvg.closePath(); nvg.fillColor(nvg.rgb(68, 137, 26)); nvg.fill(); nvg.beginPath(); nvg.moveTo(5.5, 12.5); nvg.lineTo(3.5, 10.5); nvg.lineTo(13.5, 0.5); nvg.lineTo(15.5, 2.5); nvg.closePath(); nvg.fillColor(nvg.rgb(163, 206, 39)); nvg.fill(); nvg.beginPath(); nvg.moveTo(3.5, 10.5); nvg.lineTo(1.5, 10.5); nvg.lineTo(11.5, 0.5); nvg.lineTo(13.5, 0.5); nvg.closePath(); nvg.fillColor(nvg.rgb(213, 228, 102)); nvg.fill(); nvg.lineJoin(.round); defer nvg.lineJoin(.miter); nvg.beginPath(); nvg.moveTo(0.5, 15.5); nvg.lineTo(1.5, 10.5); nvg.lineTo(11.5, 0.5); nvg.lineTo(13.5, 0.5); nvg.lineTo(15.5, 2.5); nvg.lineTo(15.5, 4.5); nvg.lineTo(5.5, 14.5); nvg.closePath(); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); nvg.beginPath(); nvg.moveTo(0.5, 15.5); nvg.lineTo(1.5, 10.5); nvg.lineTo(3.5, 10.5); nvg.lineTo(5.5, 12.5); nvg.lineTo(5.5, 14.5); nvg.closePath(); nvg.fillColor(nvg.rgb(217, 190, 138)); nvg.fill(); nvg.stroke(); nvg.beginPath(); nvg.moveTo(0.5, 15.5); nvg.lineTo(1, 13.5); nvg.lineTo(2.5, 15); nvg.closePath(); nvg.stroke(); } pub fn iconToolBucket() void { nvg.beginPath(); nvg.moveTo(9.5, 2.5); nvg.lineTo(3.5, 8.5); nvg.lineTo(8.5, 13.5); nvg.bezierTo(9.5, 14.5, 11.5, 14.5, 12.5, 13.5); nvg.lineTo(14.5, 11.5); nvg.bezierTo(15.5, 10.5, 15.5, 8.5, 14.5, 7.5); nvg.closePath(); nvg.fillColor(nvg.rgb(171, 171, 171)); nvg.fill(); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); nvg.beginPath(); nvg.moveTo(4.5, 9.5); nvg.lineTo(10.5, 3.5); nvg.stroke(); nvg.beginPath(); nvg.roundedRect(8.5, 0.5, 2, 9, 1); nvg.fill(); nvg.stroke(); nvg.beginPath(); nvg.ellipse(9.5, 8.5, 1, 1); nvg.stroke(); nvg.beginPath(); nvg.moveTo(3.5, 10.5); nvg.lineTo(3.5, 8.5); nvg.lineTo(6.5, 5.5); nvg.lineTo(5, 5.5); nvg.bezierTo(2, 5.5, 0.5, 7, 0.5, 10.5); nvg.bezierTo(0.5, 12, 1, 12.5, 2, 12.5); nvg.bezierTo(3, 12.5, 3.5, 12, 3.5, 10.5); nvg.fillColor(nvg.rgb(210, 80, 60)); nvg.fill(); nvg.stroke(); } pub fn iconMirrorHorizontally() void { nvg.beginPath(); var y: f32 = 0; while (y < 16) : (y += 2) { nvg.moveTo(7.5, y + 0); nvg.lineTo(7.5, y + 1); } nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); nvg.beginPath(); nvg.rect(0.5, 5.5, 5, 5); nvg.strokeColor(nvg.rgb(170, 170, 170)); nvg.stroke(); nvg.beginPath(); nvg.rect(9.5, 5.5, 5, 5); nvg.fillColor(nvg.rgb(247, 226, 107)); nvg.fill(); nvg.strokeColor(nvg.rgb(164, 100, 34)); nvg.stroke(); } pub fn iconMirrorVertically() void { nvg.beginPath(); var x: f32 = 0; while (x < 16) : (x += 2) { nvg.moveTo(x + 0, 7.5); nvg.lineTo(x + 1, 7.5); } nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); nvg.beginPath(); nvg.rect(5.5, 0.5, 5, 5); nvg.strokeColor(nvg.rgb(170, 170, 170)); nvg.stroke(); nvg.beginPath(); nvg.rect(5.5, 9.5, 5, 5); nvg.fillColor(nvg.rgb(247, 226, 107)); nvg.fill(); nvg.strokeColor(nvg.rgb(164, 100, 34)); nvg.stroke(); } pub fn iconRotateCw() void { nvg.beginPath(); nvg.rect(1.5, 8.5, 14, 6); nvg.strokeColor(nvg.rgb(170, 170, 170)); nvg.stroke(); nvg.beginPath(); nvg.rect(9.5, 0.5, 6, 14); nvg.fillColor(nvg.rgb(247, 226, 107)); nvg.fill(); nvg.strokeColor(nvg.rgb(164, 100, 34)); nvg.stroke(); nvg.beginPath(); nvg.moveTo(3.5, 7); nvg.quadTo(3.5, 4.5, 6, 4.5); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); nvg.beginPath(); nvg.moveTo(6, 7.5); nvg.lineTo(9, 4.5); nvg.lineTo(6, 1.5); nvg.closePath(); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); } pub fn iconRotateCcw() void { nvg.beginPath(); nvg.rect(0.5, 8.5, 14, 6); nvg.strokeColor(nvg.rgb(170, 170, 170)); nvg.stroke(); nvg.beginPath(); nvg.rect(0.5, 0.5, 6, 14); nvg.fillColor(nvg.rgb(247, 226, 107)); nvg.fill(); nvg.strokeColor(nvg.rgb(164, 100, 34)); nvg.stroke(); nvg.beginPath(); nvg.moveTo(12.5, 7); nvg.quadTo(12.5, 4.5, 10, 4.5); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); nvg.beginPath(); nvg.moveTo(10, 7.5); nvg.lineTo(7, 4.5); nvg.lineTo(10, 1.5); nvg.closePath(); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); } pub fn iconGrid() void { nvg.beginPath(); nvg.moveTo(0, 0.5); nvg.lineTo(16, 0.5); nvg.moveTo(0, 5.5); nvg.lineTo(16, 5.5); nvg.moveTo(0, 10.5); nvg.lineTo(16, 10.5); nvg.moveTo(0, 15.5); nvg.lineTo(16, 15.5); nvg.moveTo(0.5, 0); nvg.lineTo(0.5, 16); nvg.moveTo(5.5, 0); nvg.lineTo(5.5, 16); nvg.moveTo(10.5, 0); nvg.lineTo(10.5, 16); nvg.moveTo(15.5, 0); nvg.lineTo(15.5, 16); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); } pub fn iconSnap() void { nvg.beginPath(); nvg.moveTo(1.5, 0.5); nvg.lineTo(1.5, 12.5); nvg.lineTo(2.5, 14.5); nvg.lineTo(4.5, 15.5); nvg.lineTo(11.5, 15.5); nvg.lineTo(13.5, 14.5); nvg.lineTo(14.5, 12.5); nvg.lineTo(14.5, 0.5); nvg.lineTo(10.5, 0.5); nvg.lineTo(10.5, 10.5); nvg.lineTo(9.5, 11.5); nvg.lineTo(6.5, 11.5); nvg.lineTo(5.5, 10.5); nvg.lineTo(5.5, 0.5); nvg.closePath(); nvg.fillColor(nvg.rgb(250, 8, 0)); nvg.fill(); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); nvg.beginPath(); nvg.moveTo(2, 1); nvg.lineTo(2, 4); nvg.lineTo(5, 4); nvg.lineTo(5, 1); nvg.moveTo(11, 1); nvg.lineTo(11, 4); nvg.lineTo(14, 4); nvg.lineTo(14, 1); nvg.fillColor(nvg.rgb(255, 255, 255)); nvg.fill(); } pub fn iconPlus() void { nvg.beginPath(); nvg.moveTo(10.5, 8.5); nvg.lineTo(10.5, 10.5); nvg.lineTo(8.5, 10.5); nvg.lineTo(8.5, 13.5); nvg.lineTo(10.5, 13.5); nvg.lineTo(10.5, 15.5); nvg.lineTo(13.5, 15.5); nvg.lineTo(13.5, 13.5); nvg.lineTo(15.5, 13.5); nvg.lineTo(15.5, 10.5); nvg.lineTo(13.5, 10.5); nvg.lineTo(13.5, 8.5); nvg.closePath(); nvg.fillColor(nvg.rgb(60, 175, 45)); nvg.fill(); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); } pub fn iconMinus() void { nvg.beginPath(); nvg.moveTo(8.5, 10.5); nvg.lineTo(8.5, 13.5); nvg.lineTo(15.5, 13.5); nvg.lineTo(15.5, 10.5); nvg.closePath(); nvg.fillColor(nvg.rgb(250, 10, 0)); nvg.fill(); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); } pub fn iconDelete() void { nvg.beginPath(); nvg.moveTo(7, 0.5); nvg.lineTo(6.5, 1); nvg.lineTo(6.5, 2.5); nvg.lineTo(3, 2.5); nvg.lineTo(2.5, 3); nvg.lineTo(2.5, 5.5); nvg.lineTo(3.5, 5.5); nvg.lineTo(3.5, 15); nvg.lineTo(4, 15.5); nvg.lineTo(12, 15.5); nvg.lineTo(12.5, 15); nvg.lineTo(12.5, 5.5); nvg.lineTo(13.5, 5.5); nvg.lineTo(13.5, 3); nvg.lineTo(13, 2.5); nvg.lineTo(9.5, 2.5); nvg.lineTo(9.5, 1); nvg.lineTo(9, 0.5); nvg.closePath(); nvg.fillColor(nvg.rgb(170, 170, 170)); nvg.fill(); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); nvg.beginPath(); nvg.moveTo(6.5, 2.5); nvg.lineTo(9.5, 2.5); nvg.moveTo(3.5, 5.5); nvg.lineTo(12.5, 5.5); nvg.moveTo(6.5, 7); nvg.lineTo(6.5, 14); nvg.moveTo(9.5, 7); nvg.lineTo(9.5, 14); nvg.stroke(); } pub fn iconMoveUp() void { nvg.beginPath(); nvg.moveTo(8, 1); nvg.lineTo(1.5, 7.5); nvg.lineTo(1.5, 9.5); nvg.lineTo(4.5, 9.5); nvg.lineTo(4.5, 14.5); nvg.lineTo(11.5, 14.5); nvg.lineTo(11.5, 9.5); nvg.lineTo(14.5, 9.5); nvg.lineTo(14.5, 7.5); nvg.closePath(); nvg.fillColor(nvg.rgb(255, 255, 255)); nvg.fill(); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); } pub fn iconMoveDown() void { nvg.beginPath(); nvg.moveTo(8, 15); nvg.lineTo(14.5, 8.5); nvg.lineTo(14.5, 6.5); nvg.lineTo(11.5, 6.5); nvg.lineTo(11.5, 1.5); nvg.lineTo(4.5, 1.5); nvg.lineTo(4.5, 6.5); nvg.lineTo(1.5, 6.5); nvg.lineTo(1.5, 8.5); nvg.closePath(); nvg.fillColor(nvg.rgb(255, 255, 255)); nvg.fill(); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); } pub fn iconCapButt() void { nvg.beginPath(); nvg.rect(7, 0, 8, 15); nvg.rect(5, 5, 5, 5); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); nvg.beginPath(); nvg.rect(7, 7, 8, 1); nvg.rect(6, 6, 3, 3); nvg.fillColor(nvg.rgb(255, 255, 255)); nvg.fill(); } pub fn iconCapRound() void { nvg.beginPath(); nvg.rect(7.5, 0, 7.5, 15); nvg.circle(7.5, 7.5, 7.5); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); nvg.beginPath(); nvg.rect(7, 7, 8, 1); nvg.rect(6, 6, 3, 3); nvg.fillColor(nvg.rgb(255, 255, 255)); nvg.fill(); } pub fn iconCapSquare() void { nvg.beginPath(); nvg.rect(0, 0, 15, 15); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); nvg.beginPath(); nvg.rect(7, 7, 8, 1); nvg.rect(6, 6, 3, 3); nvg.fillColor(nvg.rgb(255, 255, 255)); nvg.fill(); } pub fn iconJoinRound() void { nvg.beginPath(); nvg.moveTo(15, 15); nvg.lineTo(15, 0); nvg.arcTo(0, 0, 0, 7.5, 7.5); nvg.lineTo(0, 15); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); nvg.beginPath(); nvg.rect(7, 7, 8, 1); nvg.rect(7, 7, 1, 8); nvg.rect(6, 6, 3, 3); nvg.fillColor(nvg.rgb(255, 255, 255)); nvg.fill(); } pub fn iconJoinBevel() void { nvg.beginPath(); nvg.moveTo(15, 15); nvg.lineTo(15, 0); nvg.lineTo(7.5, 0); nvg.lineTo(0, 7.5); nvg.lineTo(0, 15); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); nvg.beginPath(); nvg.rect(7, 7, 8, 1); nvg.rect(7, 7, 1, 8); nvg.rect(6, 6, 3, 3); nvg.fillColor(nvg.rgb(255, 255, 255)); nvg.fill(); } pub fn iconJoinSquare() void { nvg.beginPath(); nvg.rect(0, 0, 15, 15); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); nvg.beginPath(); nvg.rect(7, 7, 8, 1); nvg.rect(7, 7, 1, 8); nvg.rect(6, 6, 3, 3); nvg.fillColor(nvg.rgb(255, 255, 255)); nvg.fill(); } pub fn iconCross() void { nvg.beginPath(); nvg.moveTo(4, 4); nvg.lineTo(11, 11); nvg.moveTo(4, 11); nvg.lineTo(11, 4); nvg.lineCap(.Round); defer nvg.lineCap(.Butt); nvg.strokeWidth(2); defer nvg.strokeWidth(1); nvg.strokeColor(nvg.rgb(66, 66, 66)); nvg.stroke(); } pub fn iconTimelineBegin() void { nvg.beginPath(); nvg.moveTo(11, 2); nvg.lineTo(11, 11); nvg.lineTo(2, 6.5); nvg.closePath(); nvg.rect(2, 2, 1, 9); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); } pub fn iconTimelineLeft() void { nvg.beginPath(); nvg.moveTo(6, 2); nvg.lineTo(6, 11); nvg.lineTo(1.5, 6.5); nvg.closePath(); nvg.rect(7, 2, 2, 9); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); } pub fn iconTimelinePlay() void { nvg.beginPath(); nvg.moveTo(2, 2); nvg.lineTo(2, 11); nvg.lineTo(11, 6.5); nvg.closePath(); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); } pub fn iconTimelinePause() void { nvg.beginPath(); nvg.rect(4, 2, 2, 9); nvg.rect(7, 2, 2, 9); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); } pub fn iconTimelineRight() void { nvg.beginPath(); nvg.moveTo(7, 2); nvg.lineTo(7, 11); nvg.lineTo(11.5, 6.5); nvg.closePath(); nvg.rect(4, 2, 2, 9); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); } pub fn iconTimelineEnd() void { nvg.beginPath(); nvg.moveTo(2, 2); nvg.lineTo(2, 11); nvg.lineTo(11, 6.5); nvg.closePath(); nvg.rect(10, 2, 1, 9); nvg.fillColor(nvg.rgb(66, 66, 66)); nvg.fill(); } pub fn iconOnionSkinning() void { nvg.beginPath(); nvg.rect(1.5, 1.5, 9, 9); nvg.fillColor(nvg.rgb(203, 219, 252)); nvg.fill(); nvg.strokeColor(nvg.rgb(95, 205, 228)); nvg.stroke(); nvg.beginPath(); nvg.rect(5.5, 5.5, 9, 9); nvg.fillColor(nvg.rgb(99, 155, 255)); nvg.fill(); nvg.strokeColor(nvg.rgb(48, 96, 130)); nvg.stroke(); } pub fn cursorArrow() void { nvg.beginPath(); nvg.moveTo(-0.5, -0.5); nvg.lineTo(-0.5, 12.5); nvg.lineTo(3.5, 8.5); nvg.lineTo(8.5, 8.5); nvg.closePath(); nvg.fillColor(nvg.rgb(0, 0, 0)); nvg.fill(); nvg.strokeColor(nvg.rgb(255, 255, 255)); nvg.stroke(); } pub fn cursorArrowInverted() void { nvg.beginPath(); nvg.moveTo(-0.5, -0.5); nvg.lineTo(-0.5, 12.5); nvg.lineTo(3.5, 8.5); nvg.lineTo(8.5, 8.5); nvg.closePath(); nvg.fillColor(nvg.rgb(255, 255, 255)); nvg.fill(); nvg.strokeColor(nvg.rgb(0, 0, 0)); nvg.stroke(); } pub fn cursorCrosshair() void { nvg.beginPath(); nvg.moveTo(-5.5, 0.5); nvg.lineTo(-2.5, 0.5); nvg.moveTo(3.5, 0.5); nvg.lineTo(6.5, 0.5); nvg.moveTo(0.5, -5.5); nvg.lineTo(0.5, -2.5); nvg.moveTo(0.5, 3.5); nvg.lineTo(0.5, 6.5); nvg.lineCap(.square); defer nvg.lineCap(.butt); nvg.strokeColor(nvg.rgbf(1, 1, 1)); nvg.strokeWidth(2); nvg.stroke(); nvg.strokeWidth(1); nvg.strokeColor(nvg.rgb(0, 0, 0)); nvg.stroke(); nvg.beginPath(); nvg.rect(-0.5, -0.5, 2, 2); nvg.fillColor(nvg.rgbf(1, 1, 1)); nvg.fill(); nvg.beginPath(); nvg.rect(0, 0, 1, 1); nvg.fillColor(nvg.rgb(0, 0, 0)); nvg.fill(); } pub fn cursorPen() void { nvg.fillColor(nvg.rgbf(1, 1, 1)); nvg.strokeColor(nvg.rgb(0, 0, 0)); nvg.save(); nvg.scale(1, -1); nvg.translate(0, -16); nvg.lineJoin(.round); defer nvg.restore(); nvg.beginPath(); nvg.moveTo(0.5, 15.5); nvg.lineTo(1.5, 10.5); nvg.lineTo(11.5, 0.5); nvg.lineTo(13.5, 0.5); nvg.lineTo(15.5, 2.5); nvg.lineTo(15.5, 4.5); nvg.lineTo(5.5, 14.5); nvg.closePath(); nvg.fill(); nvg.stroke(); nvg.beginPath(); nvg.moveTo(0.5, 15.5); nvg.lineTo(1.5, 10.5); nvg.lineTo(3.5, 10.5); nvg.lineTo(5.5, 12.5); nvg.lineTo(5.5, 14.5); nvg.closePath(); nvg.fill(); nvg.stroke(); nvg.beginPath(); nvg.moveTo(0.5, 15.5); nvg.lineTo(1, 13.5); nvg.lineTo(2.5, 15); nvg.closePath(); nvg.stroke(); } pub fn cursorBucket() void { cursorCrosshair(); nvg.fillColor(nvg.rgbf(1, 1, 1)); nvg.strokeColor(nvg.rgb(0, 0, 0)); nvg.save(); defer nvg.restore(); nvg.translate(3, -15); nvg.beginPath(); nvg.moveTo(9.5, 2.5); nvg.lineTo(3.5, 8.5); nvg.lineTo(8.5, 13.5); nvg.bezierTo(9.5, 14.5, 11.5, 14.5, 12.5, 13.5); nvg.lineTo(14.5, 11.5); nvg.bezierTo(15.5, 10.5, 15.5, 8.5, 14.5, 7.5); nvg.closePath(); nvg.fill(); nvg.stroke(); nvg.beginPath(); nvg.moveTo(4.5, 9.5); nvg.lineTo(10.5, 3.5); nvg.stroke(); nvg.beginPath(); nvg.roundedRect(8.5, 0.5, 2, 9, 1); nvg.fill(); nvg.stroke(); nvg.beginPath(); nvg.ellipse(9.5, 8.5, 1, 1); nvg.stroke(); nvg.beginPath(); nvg.moveTo(3.5, 10.5); nvg.lineTo(3.5, 8.5); nvg.lineTo(6.5, 5.5); nvg.lineTo(5, 5.5); nvg.bezierTo(2, 5.5, 0.5, 7, 0.5, 10.5); nvg.bezierTo(0.5, 12, 1, 12.5, 2, 12.5); nvg.bezierTo(3, 12.5, 3.5, 12, 3.5, 10.5); nvg.fill(); nvg.stroke(); } pub fn cursorPipette() void { nvg.save(); defer nvg.restore(); nvg.translate(0, -15); nvg.lineJoin(.round); nvg.fillColor(nvg.rgbf(1, 1, 1)); nvg.strokeColor(nvg.rgb(0, 0, 0)); nvg.beginPath(); nvg.moveTo(10.5, 3.5); nvg.lineTo(1.5, 12.5); nvg.lineTo(1.5, 13.5); nvg.lineTo(0.5, 14.5); nvg.lineTo(0.5, 15.5); nvg.lineTo(1.5, 15.5); nvg.lineTo(2.5, 14.5); nvg.lineTo(3.5, 14.5); nvg.lineTo(12.5, 5.5); nvg.fill(); nvg.stroke(); nvg.beginPath(); nvg.moveTo(11.5, 6.5); nvg.lineTo(13.5, 6.5); nvg.lineTo(13.5, 4.5); nvg.lineTo(14.5, 3.5); nvg.lineTo(15.5, 3.5); nvg.lineTo(15.5, 1.5); nvg.lineTo(14.5, 0.5); nvg.lineTo(12.5, 0.5); nvg.lineTo(12.5, 1.5); nvg.lineTo(11.5, 2.5); nvg.lineTo(9.5, 2.5); nvg.lineTo(9.5, 4.5); nvg.lineTo(10.5, 4.5); nvg.lineTo(11.5, 5.5); nvg.closePath(); nvg.fill(); nvg.stroke(); } pub fn cursorMove() void { nvg.beginPath(); nvg.moveTo(-0.5, -0.5); nvg.lineTo(-0.5, -3.5); nvg.lineTo(-1.5, -3.5); nvg.lineTo(-1.5, -4); nvg.lineTo(0, -6.5); nvg.lineTo(1, -6.5); nvg.lineTo(2.5, -4); nvg.lineTo(2.5, -3.5); nvg.lineTo(1.5, -3.5); nvg.lineTo(1.5, -0.5); nvg.lineTo(4.5, -0.5); nvg.lineTo(4.5, -1.5); nvg.lineTo(5, -1.5); nvg.lineTo(7.5, 0); nvg.lineTo(7.5, 1); nvg.lineTo(5, 2.5); nvg.lineTo(4.5, 2.5); nvg.lineTo(4.5, 1.5); nvg.lineTo(1.5, 1.5); nvg.lineTo(1.5, 4.5); nvg.lineTo(2.5, 4.5); nvg.lineTo(2.5, 5); nvg.lineTo(1, 7.5); nvg.lineTo(0, 7.5); nvg.lineTo(-1.5, 5); nvg.lineTo(-1.5, 4.5); nvg.lineTo(-0.5, 4.5); nvg.lineTo(-0.5, 1.5); nvg.lineTo(-3.5, 1.5); nvg.lineTo(-3.5, 2.5); nvg.lineTo(-4, 2.5); nvg.lineTo(-6.5, 1); nvg.lineTo(-6.5, 0); nvg.lineTo(-4, -1.5); nvg.lineTo(-3.5, -1.5); nvg.lineTo(-3.5, -0.5); nvg.closePath(); nvg.fillColor(nvg.rgbf(1, 1, 1)); nvg.fill(); nvg.strokeColor(nvg.rgb(0, 0, 0)); nvg.stroke(); }
src/icons.zig
const std = @import("std"); const tools = @import("tools"); const with_trace = false; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } const assert = std.debug.assert; const Vec2 = tools.Vec2; const BBox = tools.BBox; pub const main = tools.defaultMain("2021/day17.txt", run); fn saturate(x: i32) i32 { return @minimum(1, @maximum(-1, x)); } fn hitsTarget(target: BBox, v_: Vec2) bool { assert(v_[0] >= 0); var p = Vec2{ 0, 0 }; var v = v_; while (p[0] <= target.max[0] and p[1] >= target.min[1]) { if (target.includes(p)) return true; p += v; const accel = Vec2{ @maximum(-1, -v[0]), -1 }; v += accel; } return false; } fn computeApex(v: Vec2) i32 { const y = v[1]; if (y <= 0) return 0; return @divFloor(y * (y + 1), 2); } pub fn run(input: []const u8, gpa: std.mem.Allocator) tools.RunError![2][]const u8 { //var arena_alloc = std.heap.ArenaAllocator.init(gpa); //defer arena_alloc.deinit(); //const arena = arena_alloc.allocator(); const target = blk: { if (tools.match_pattern("target area: x={}..{}, y={}..{}", std.mem.trim(u8, input, "\n\r \t"))) |val| { break :blk BBox{ .min = Vec2{ @intCast(i32, val[0].imm), @intCast(i32, val[2].imm) }, .max = Vec2{ @intCast(i32, val[1].imm), @intCast(i32, val[3].imm) }, }; } else { return error.UnsupportedInput; } }; // les deux axes sont indépendants // x le plus rapide qui touche en un coup: xmax // x le plus lent qui touche: (x0*(x0+1))/2=xmin -> x= (sqrt(1+8*xmin)-1)/2 // y le plus direct qui touche en un coup: ymin // y le plus long..mmm. quand on reppasse par zero, c'est symétrique de la vitesse de lancement. et donc meme raisonnement, a partir de là, en un coup ymin const ans = ans: { const fastest_x = target.max[0]; const slowest_x = (std.math.sqrt(1 + 8 * @intCast(u32, target.min[0])) - 1) / 2; trace("valid initial xvels={}..{}\n", .{ slowest_x, fastest_x }); trace(" yvels={}..{}\n", .{ target.min[1], -target.min[1] }); var v = Vec2{ slowest_x, 0 }; var best_apex: i32 = 0; var hit_count: i32 = 0; while (v[0] <= fastest_x) : (v[0] += 1) { v[1] = target.min[1]; while (v[1] <= -target.min[1]) : (v[1] += 1) { const hits = @boolToInt(hitsTarget(target, v)); hit_count += hits; best_apex = @maximum(best_apex, hits * computeApex(v)); } } break :ans [2]i32{ best_apex, hit_count }; }; return [_][]const u8{ try std.fmt.allocPrint(gpa, "{}", .{ans[0]}), try std.fmt.allocPrint(gpa, "{}", .{ans[1]}), }; } test { const res = try run("target area: x=20..30, y=-10..-5", std.testing.allocator); defer std.testing.allocator.free(res[0]); defer std.testing.allocator.free(res[1]); try std.testing.expectEqualStrings("45", res[0]); try std.testing.expectEqualStrings("112", res[1]); const res2 = try run("target area: x=352..377, y=-49..-30", std.testing.allocator); defer std.testing.allocator.free(res2[0]); defer std.testing.allocator.free(res2[1]); try std.testing.expectEqualStrings("66", res2[0]); try std.testing.expectEqualStrings("820", res2[1]); }
2021/day17.zig
pub const PROP_ID_SECURE_MIN = @as(u32, 26608); pub const PROP_ID_SECURE_MAX = @as(u32, 26623); pub const MAPI_DIM = @as(u32, 1); pub const MAPI_P1 = @as(u32, 268435456); pub const MAPI_SUBMITTED = @as(u32, 2147483648); pub const MAPI_SHORTTERM = @as(u32, 128); pub const MAPI_NOTRECIP = @as(u32, 64); pub const MAPI_THISSESSION = @as(u32, 32); pub const MAPI_NOW = @as(u32, 16); pub const MAPI_NOTRESERVED = @as(u32, 8); pub const MAPI_COMPOUND = @as(u32, 128); pub const MV_FLAG = @as(u32, 4096); pub const PROP_ID_NULL = @as(u32, 0); pub const PROP_ID_INVALID = @as(u32, 65535); pub const MV_INSTANCE = @as(u32, 8192); pub const TABLE_CHANGED = @as(u32, 1); pub const TABLE_ERROR = @as(u32, 2); pub const TABLE_ROW_ADDED = @as(u32, 3); pub const TABLE_ROW_DELETED = @as(u32, 4); pub const TABLE_ROW_MODIFIED = @as(u32, 5); pub const TABLE_SORT_DONE = @as(u32, 6); pub const TABLE_RESTRICT_DONE = @as(u32, 7); pub const TABLE_SETCOL_DONE = @as(u32, 8); pub const TABLE_RELOAD = @as(u32, 9); pub const MAPI_ERROR_VERSION = @as(i32, 0); pub const MAPI_USE_DEFAULT = @as(u32, 64); pub const MNID_ID = @as(u32, 0); pub const MNID_STRING = @as(u32, 1); pub const WAB_LOCAL_CONTAINERS = @as(u32, 1048576); pub const WAB_PROFILE_CONTENTS = @as(u32, 2097152); pub const WAB_IGNORE_PROFILES = @as(u32, 8388608); pub const MAPI_ONE_OFF_NO_RICH_INFO = @as(u32, 1); pub const UI_SERVICE = @as(u32, 2); pub const SERVICE_UI_ALWAYS = @as(u32, 2); pub const SERVICE_UI_ALLOWED = @as(u32, 16); pub const UI_CURRENT_PROVIDER_FIRST = @as(u32, 4); pub const WABOBJECT_LDAPURL_RETURN_MAILUSER = @as(u32, 1); pub const WABOBJECT_ME_NEW = @as(u32, 1); pub const WABOBJECT_ME_NOCREATE = @as(u32, 2); pub const WAB_VCARD_FILE = @as(u32, 0); pub const WAB_VCARD_STREAM = @as(u32, 1); pub const WAB_USE_OE_SENDMAIL = @as(u32, 1); pub const WAB_ENABLE_PROFILES = @as(u32, 4194304); pub const WAB_DISPLAY_LDAPURL = @as(u32, 1); pub const WAB_CONTEXT_ADRLIST = @as(u32, 2); pub const WAB_DISPLAY_ISNTDS = @as(u32, 4); pub const E_IMAPI_REQUEST_CANCELLED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600702)); pub const E_IMAPI_RECORDER_REQUIRED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600701)); pub const S_IMAPI_SPEEDADJUSTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 11141124)); pub const S_IMAPI_ROTATIONADJUSTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 11141125)); pub const S_IMAPI_BOTHADJUSTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 11141126)); pub const E_IMAPI_BURN_VERIFICATION_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600697)); pub const S_IMAPI_COMMAND_HAS_SENSE_DATA = @import("../zig.zig").typedConst(HRESULT, @as(i32, 11141632)); pub const E_IMAPI_RECORDER_NO_SUCH_MODE_PAGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600191)); pub const E_IMAPI_RECORDER_MEDIA_NO_MEDIA = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600190)); pub const E_IMAPI_RECORDER_MEDIA_INCOMPATIBLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600189)); pub const E_IMAPI_RECORDER_MEDIA_UPSIDE_DOWN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600188)); pub const E_IMAPI_RECORDER_MEDIA_BECOMING_READY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600187)); pub const E_IMAPI_RECORDER_MEDIA_FORMAT_IN_PROGRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600186)); pub const E_IMAPI_RECORDER_MEDIA_BUSY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600185)); pub const E_IMAPI_RECORDER_INVALID_MODE_PARAMETERS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600184)); pub const E_IMAPI_RECORDER_MEDIA_WRITE_PROTECTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600183)); pub const E_IMAPI_RECORDER_NO_SUCH_FEATURE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600182)); pub const E_IMAPI_RECORDER_FEATURE_IS_NOT_CURRENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600181)); pub const E_IMAPI_RECORDER_GET_CONFIGURATION_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600180)); pub const E_IMAPI_RECORDER_COMMAND_TIMEOUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600179)); pub const E_IMAPI_RECORDER_DVD_STRUCTURE_NOT_PRESENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600178)); pub const E_IMAPI_RECORDER_MEDIA_SPEED_MISMATCH = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600177)); pub const E_IMAPI_RECORDER_LOCKED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600176)); pub const E_IMAPI_RECORDER_CLIENT_NAME_IS_NOT_VALID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600175)); pub const E_IMAPI_RECORDER_MEDIA_NOT_FORMATTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062600174)); pub const E_IMAPI_RECORDER_INVALID_RESPONSE_FROM_DEVICE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599937)); pub const E_IMAPI_LOSS_OF_STREAMING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599936)); pub const E_IMAPI_UNEXPECTED_RESPONSE_FROM_DEVICE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599935)); pub const S_IMAPI_WRITE_NOT_IN_PROGRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, 11141890)); pub const E_IMAPI_DF2DATA_WRITE_IN_PROGRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599680)); pub const E_IMAPI_DF2DATA_WRITE_NOT_IN_PROGRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599679)); pub const E_IMAPI_DF2DATA_INVALID_MEDIA_STATE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599678)); pub const E_IMAPI_DF2DATA_STREAM_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599677)); pub const E_IMAPI_DF2DATA_STREAM_TOO_LARGE_FOR_CURRENT_MEDIA = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599676)); pub const E_IMAPI_DF2DATA_MEDIA_NOT_BLANK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599675)); pub const E_IMAPI_DF2DATA_MEDIA_IS_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599674)); pub const E_IMAPI_DF2DATA_RECORDER_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599673)); pub const E_IMAPI_DF2DATA_CLIENT_NAME_IS_NOT_VALID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599672)); pub const E_IMAPI_DF2TAO_WRITE_IN_PROGRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599424)); pub const E_IMAPI_DF2TAO_WRITE_NOT_IN_PROGRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599423)); pub const E_IMAPI_DF2TAO_MEDIA_IS_NOT_PREPARED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599422)); pub const E_IMAPI_DF2TAO_MEDIA_IS_PREPARED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599421)); pub const E_IMAPI_DF2TAO_PROPERTY_FOR_BLANK_MEDIA_ONLY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599420)); pub const E_IMAPI_DF2TAO_TABLE_OF_CONTENTS_EMPTY_DISC = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599419)); pub const E_IMAPI_DF2TAO_MEDIA_IS_NOT_BLANK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599418)); pub const E_IMAPI_DF2TAO_MEDIA_IS_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599417)); pub const E_IMAPI_DF2TAO_TRACK_LIMIT_REACHED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599416)); pub const E_IMAPI_DF2TAO_NOT_ENOUGH_SPACE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599415)); pub const E_IMAPI_DF2TAO_NO_RECORDER_SPECIFIED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599414)); pub const E_IMAPI_DF2TAO_INVALID_ISRC = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599413)); pub const E_IMAPI_DF2TAO_INVALID_MCN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599412)); pub const E_IMAPI_DF2TAO_STREAM_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599411)); pub const E_IMAPI_DF2TAO_RECORDER_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599410)); pub const E_IMAPI_DF2TAO_CLIENT_NAME_IS_NOT_VALID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599409)); pub const E_IMAPI_DF2RAW_WRITE_IN_PROGRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599168)); pub const E_IMAPI_DF2RAW_WRITE_NOT_IN_PROGRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599167)); pub const E_IMAPI_DF2RAW_MEDIA_IS_NOT_PREPARED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599166)); pub const E_IMAPI_DF2RAW_MEDIA_IS_PREPARED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599165)); pub const E_IMAPI_DF2RAW_CLIENT_NAME_IS_NOT_VALID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599164)); pub const E_IMAPI_DF2RAW_MEDIA_IS_NOT_BLANK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599162)); pub const E_IMAPI_DF2RAW_MEDIA_IS_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599161)); pub const E_IMAPI_DF2RAW_NOT_ENOUGH_SPACE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599159)); pub const E_IMAPI_DF2RAW_NO_RECORDER_SPECIFIED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599158)); pub const E_IMAPI_DF2RAW_STREAM_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599155)); pub const E_IMAPI_DF2RAW_DATA_BLOCK_TYPE_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599154)); pub const E_IMAPI_DF2RAW_STREAM_LEADIN_TOO_SHORT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599153)); pub const E_IMAPI_DF2RAW_RECORDER_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062599152)); pub const E_IMAPI_ERASE_RECORDER_IN_USE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136340224)); pub const E_IMAPI_ERASE_ONLY_ONE_RECORDER_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136340223)); pub const E_IMAPI_ERASE_DISC_INFORMATION_TOO_SMALL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136340222)); pub const E_IMAPI_ERASE_MODE_PAGE_2A_TOO_SMALL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136340221)); pub const E_IMAPI_ERASE_MEDIA_IS_NOT_ERASABLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136340220)); pub const E_IMAPI_ERASE_DRIVE_FAILED_ERASE_COMMAND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136340219)); pub const E_IMAPI_ERASE_TOOK_LONGER_THAN_ONE_HOUR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136340218)); pub const E_IMAPI_ERASE_UNEXPECTED_DRIVE_RESPONSE_DURING_ERASE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136340217)); pub const E_IMAPI_ERASE_DRIVE_FAILED_SPINUP_COMMAND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136340216)); pub const E_IMAPI_ERASE_MEDIA_IS_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062598391)); pub const E_IMAPI_ERASE_RECORDER_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062598390)); pub const E_IMAPI_ERASE_CLIENT_NAME_IS_NOT_VALID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062598389)); pub const E_IMAPI_RAW_IMAGE_IS_READ_ONLY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136339968)); pub const E_IMAPI_RAW_IMAGE_TOO_MANY_TRACKS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136339967)); pub const E_IMAPI_RAW_IMAGE_SECTOR_TYPE_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136339966)); pub const E_IMAPI_RAW_IMAGE_NO_TRACKS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136339965)); pub const E_IMAPI_RAW_IMAGE_TRACKS_ALREADY_ADDED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136339964)); pub const E_IMAPI_RAW_IMAGE_INSUFFICIENT_SPACE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136339963)); pub const E_IMAPI_RAW_IMAGE_TOO_MANY_TRACK_INDEXES = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136339962)); pub const E_IMAPI_RAW_IMAGE_TRACK_INDEX_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136339961)); pub const S_IMAPI_RAW_IMAGE_TRACK_INDEX_ALREADY_EXISTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, 11143688)); pub const E_IMAPI_RAW_IMAGE_TRACK_INDEX_OFFSET_ZERO_CANNOT_BE_CLEARED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136339959)); pub const E_IMAPI_RAW_IMAGE_TRACK_INDEX_TOO_CLOSE_TO_OTHER_INDEX = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2136339958)); pub const FACILITY_IMAPI2 = @as(u32, 170); pub const IMAPI_E_FSI_INTERNAL_ERROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555392)); pub const IMAPI_E_INVALID_PARAM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555391)); pub const IMAPI_E_READONLY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555390)); pub const IMAPI_E_NO_OUTPUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555389)); pub const IMAPI_E_INVALID_VOLUME_NAME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555388)); pub const IMAPI_E_INVALID_DATE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555387)); pub const IMAPI_E_FILE_SYSTEM_NOT_EMPTY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555386)); pub const IMAPI_E_NOT_FILE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555384)); pub const IMAPI_E_NOT_DIR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555383)); pub const IMAPI_E_DIR_NOT_EMPTY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555382)); pub const IMAPI_E_NOT_IN_FILE_SYSTEM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555381)); pub const IMAPI_E_INVALID_PATH = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555376)); pub const IMAPI_E_RESTRICTED_NAME_VIOLATION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555375)); pub const IMAPI_E_DUP_NAME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555374)); pub const IMAPI_E_NO_UNIQUE_NAME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555373)); pub const IMAPI_E_ITEM_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555368)); pub const IMAPI_E_FILE_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555367)); pub const IMAPI_E_DIR_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555366)); pub const IMAPI_E_IMAGE_SIZE_LIMIT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555360)); pub const IMAPI_E_IMAGE_TOO_BIG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555359)); pub const IMAPI_E_DATA_STREAM_INCONSISTENCY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555352)); pub const IMAPI_E_DATA_STREAM_READ_FAILURE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555351)); pub const IMAPI_E_DATA_STREAM_CREATE_FAILURE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555350)); pub const IMAPI_E_DIRECTORY_READ_FAILURE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555349)); pub const IMAPI_E_TOO_MANY_DIRS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555344)); pub const IMAPI_E_ISO9660_LEVELS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555343)); pub const IMAPI_E_DATA_TOO_BIG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555342)); pub const IMAPI_E_INCOMPATIBLE_PREVIOUS_SESSION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555341)); pub const IMAPI_E_STASHFILE_OPEN_FAILURE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555336)); pub const IMAPI_E_STASHFILE_SEEK_FAILURE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555335)); pub const IMAPI_E_STASHFILE_WRITE_FAILURE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555334)); pub const IMAPI_E_STASHFILE_READ_FAILURE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555333)); pub const IMAPI_E_INVALID_WORKING_DIRECTORY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555328)); pub const IMAPI_E_WORKING_DIRECTORY_SPACE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555327)); pub const IMAPI_E_STASHFILE_MOVE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555326)); pub const IMAPI_E_BOOT_IMAGE_DATA = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555320)); pub const IMAPI_E_BOOT_OBJECT_CONFLICT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555319)); pub const IMAPI_E_BOOT_EMULATION_IMAGE_SIZE_MISMATCH = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555318)); pub const IMAPI_E_EMPTY_DISC = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555312)); pub const IMAPI_E_NO_SUPPORTED_FILE_SYSTEM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555311)); pub const IMAPI_E_FILE_SYSTEM_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555310)); pub const IMAPI_E_FILE_SYSTEM_READ_CONSISTENCY_ERROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555309)); pub const IMAPI_E_FILE_SYSTEM_FEATURE_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555308)); pub const IMAPI_E_IMPORT_TYPE_COLLISION_FILE_EXISTS_AS_DIRECTORY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555307)); pub const IMAPI_E_IMPORT_SEEK_FAILURE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555306)); pub const IMAPI_E_IMPORT_READ_FAILURE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555305)); pub const IMAPI_E_DISC_MISMATCH = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555304)); pub const IMAPI_E_IMPORT_MEDIA_NOT_ALLOWED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555303)); pub const IMAPI_E_UDF_NOT_WRITE_COMPATIBLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555302)); pub const IMAPI_E_INCOMPATIBLE_MULTISESSION_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555301)); pub const IMAPI_E_NO_COMPATIBLE_MULTISESSION_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555300)); pub const IMAPI_E_MULTISESSION_NOT_SET = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555299)); pub const IMAPI_E_IMPORT_TYPE_COLLISION_DIRECTORY_EXISTS_AS_FILE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555298)); pub const IMAPI_S_IMAGE_FEATURE_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 11186527)); pub const IMAPI_E_PROPERTY_NOT_ACCESSIBLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555296)); pub const IMAPI_E_UDF_REVISION_CHANGE_NOT_ALLOWED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555295)); pub const IMAPI_E_BAD_MULTISESSION_PARAMETER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555294)); pub const IMAPI_E_FILE_SYSTEM_CHANGE_NOT_ALLOWED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555293)); pub const IMAPI_E_IMAGEMANAGER_IMAGE_NOT_ALIGNED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555136)); pub const IMAPI_E_IMAGEMANAGER_NO_VALID_VD_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555135)); pub const IMAPI_E_IMAGEMANAGER_NO_IMAGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555134)); pub const IMAPI_E_IMAGEMANAGER_IMAGE_TOO_BIG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1062555133)); pub const MAPI_E_CALL_FAILED = @as(i32, -2147467259); pub const MAPI_E_NOT_ENOUGH_MEMORY = @as(i32, -2147024882); pub const MAPI_E_INVALID_PARAMETER = @as(i32, -2147024809); pub const MAPI_E_INTERFACE_NOT_SUPPORTED = @as(i32, -2147467262); pub const MAPI_E_NO_ACCESS = @as(i32, -2147024891); pub const TAD_ALL_ROWS = @as(u32, 1); pub const PRILOWEST = @as(i32, -32768); pub const PRIHIGHEST = @as(u32, 32767); pub const PRIUSER = @as(u32, 0); //-------------------------------------------------------------------------------- // Section: Types (129) //-------------------------------------------------------------------------------- pub const ENTRYID = extern struct { abFlags: [4]u8, ab: [1]u8, }; pub const MAPIUID = extern struct { ab: [16]u8, }; pub const SPropTagArray = extern struct { cValues: u32, aulPropTag: [1]u32, }; pub const SBinary = extern struct { cb: u32, lpb: ?*u8, }; pub const SShortArray = extern struct { cValues: u32, lpi: ?*i16, }; pub const SGuidArray = extern struct { cValues: u32, lpguid: ?*Guid, }; pub const SRealArray = extern struct { cValues: u32, lpflt: ?*f32, }; pub const SLongArray = extern struct { cValues: u32, lpl: ?*i32, }; pub const SLargeIntegerArray = extern struct { cValues: u32, lpli: ?*LARGE_INTEGER, }; pub const SDateTimeArray = extern struct { cValues: u32, lpft: ?*FILETIME, }; pub const SAppTimeArray = extern struct { cValues: u32, lpat: ?*f64, }; pub const SCurrencyArray = extern struct { cValues: u32, lpcur: ?*CY, }; pub const SBinaryArray = extern struct { cValues: u32, lpbin: ?*SBinary, }; pub const SDoubleArray = extern struct { cValues: u32, lpdbl: ?*f64, }; pub const SWStringArray = extern struct { cValues: u32, lppszW: ?*?PWSTR, }; pub const SLPSTRArray = extern struct { cValues: u32, lppszA: ?*?PSTR, }; pub const _PV = extern union { i: i16, l: i32, ul: u32, flt: f32, dbl: f64, b: u16, cur: CY, at: f64, ft: FILETIME, lpszA: ?PSTR, bin: SBinary, lpszW: ?PWSTR, lpguid: ?*Guid, li: LARGE_INTEGER, MVi: SShortArray, MVl: SLongArray, MVflt: SRealArray, MVdbl: SDoubleArray, MVcur: SCurrencyArray, MVat: SAppTimeArray, MVft: SDateTimeArray, MVbin: SBinaryArray, MVszA: SLPSTRArray, MVszW: SWStringArray, MVguid: SGuidArray, MVli: SLargeIntegerArray, err: i32, x: i32, }; pub const SPropValue = extern struct { ulPropTag: u32, dwAlignPad: u32, Value: _PV, }; pub const SPropProblem = extern struct { ulIndex: u32, ulPropTag: u32, scode: i32, }; pub const SPropProblemArray = extern struct { cProblem: u32, aProblem: [1]SPropProblem, }; pub const FLATENTRY = extern struct { cb: u32, abEntry: [1]u8, }; pub const FLATENTRYLIST = extern struct { cEntries: u32, cbEntries: u32, abEntries: [1]u8, }; pub const MTSID = extern struct { cb: u32, ab: [1]u8, }; pub const FLATMTSIDLIST = extern struct { cMTSIDs: u32, cbMTSIDs: u32, abMTSIDs: [1]u8, }; pub const ADRENTRY = extern struct { ulReserved1: u32, cValues: u32, rgPropVals: ?*SPropValue, }; pub const ADRLIST = extern struct { cEntries: u32, aEntries: [1]ADRENTRY, }; pub const SRow = extern struct { ulAdrEntryPad: u32, cValues: u32, lpProps: ?*SPropValue, }; pub const SRowSet = extern struct { cRows: u32, aRow: [1]SRow, }; pub const LPALLOCATEBUFFER = fn( cbSize: u32, lppBuffer: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub const LPALLOCATEMORE = fn( cbSize: u32, lpObject: ?*anyopaque, lppBuffer: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub const LPFREEBUFFER = fn( lpBuffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const MAPIERROR = extern struct { ulVersion: u32, lpszError: ?*i8, lpszComponent: ?*i8, ulLowLevelError: u32, ulContext: u32, }; pub const ERROR_NOTIFICATION = extern struct { cbEntryID: u32, lpEntryID: ?*ENTRYID, scode: i32, ulFlags: u32, lpMAPIError: ?*MAPIERROR, }; pub const NEWMAIL_NOTIFICATION = extern struct { cbEntryID: u32, lpEntryID: ?*ENTRYID, cbParentID: u32, lpParentID: ?*ENTRYID, ulFlags: u32, lpszMessageClass: ?*i8, ulMessageFlags: u32, }; pub const OBJECT_NOTIFICATION = extern struct { cbEntryID: u32, lpEntryID: ?*ENTRYID, ulObjType: u32, cbParentID: u32, lpParentID: ?*ENTRYID, cbOldID: u32, lpOldID: ?*ENTRYID, cbOldParentID: u32, lpOldParentID: ?*ENTRYID, lpPropTagArray: ?*SPropTagArray, }; pub const TABLE_NOTIFICATION = extern struct { ulTableEvent: u32, hResult: HRESULT, propIndex: SPropValue, propPrior: SPropValue, row: SRow, ulPad: u32, }; pub const EXTENDED_NOTIFICATION = extern struct { ulEvent: u32, cb: u32, pbEventParameters: ?*u8, }; pub const STATUS_OBJECT_NOTIFICATION = extern struct { cbEntryID: u32, lpEntryID: ?*ENTRYID, cValues: u32, lpPropVals: ?*SPropValue, }; pub const NOTIFICATION = extern struct { ulEventType: u32, ulAlignPad: u32, info: extern union { err: ERROR_NOTIFICATION, newmail: NEWMAIL_NOTIFICATION, obj: OBJECT_NOTIFICATION, tab: TABLE_NOTIFICATION, ext: EXTENDED_NOTIFICATION, statobj: STATUS_OBJECT_NOTIFICATION, }, }; pub const IMAPIAdviseSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnNotify: fn( self: *const IMAPIAdviseSink, cNotif: u32, lpNotifications: ?*NOTIFICATION, ) callconv(@import("std").os.windows.WINAPI) u32, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIAdviseSink_OnNotify(self: *const T, cNotif: u32, lpNotifications: ?*NOTIFICATION) callconv(.Inline) u32 { return @ptrCast(*const IMAPIAdviseSink.VTable, self.vtable).OnNotify(@ptrCast(*const IMAPIAdviseSink, self), cNotif, lpNotifications); } };} pub usingnamespace MethodMixin(@This()); }; pub const LPNOTIFCALLBACK = fn( lpvContext: ?*anyopaque, cNotification: u32, lpNotifications: ?*NOTIFICATION, ) callconv(@import("std").os.windows.WINAPI) i32; pub const IMAPIProgress = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Progress: fn( self: *const IMAPIProgress, ulValue: u32, ulCount: u32, ulTotal: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFlags: fn( self: *const IMAPIProgress, lpulFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMax: fn( self: *const IMAPIProgress, lpulMax: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMin: fn( self: *const IMAPIProgress, lpulMin: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLimits: fn( self: *const IMAPIProgress, lpulMin: ?*u32, lpulMax: ?*u32, lpulFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProgress_Progress(self: *const T, ulValue: u32, ulCount: u32, ulTotal: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProgress.VTable, self.vtable).Progress(@ptrCast(*const IMAPIProgress, self), ulValue, ulCount, ulTotal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProgress_GetFlags(self: *const T, lpulFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProgress.VTable, self.vtable).GetFlags(@ptrCast(*const IMAPIProgress, self), lpulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProgress_GetMax(self: *const T, lpulMax: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProgress.VTable, self.vtable).GetMax(@ptrCast(*const IMAPIProgress, self), lpulMax); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProgress_GetMin(self: *const T, lpulMin: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProgress.VTable, self.vtable).GetMin(@ptrCast(*const IMAPIProgress, self), lpulMin); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProgress_SetLimits(self: *const T, lpulMin: ?*u32, lpulMax: ?*u32, lpulFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProgress.VTable, self.vtable).SetLimits(@ptrCast(*const IMAPIProgress, self), lpulMin, lpulMax, lpulFlags); } };} pub usingnamespace MethodMixin(@This()); }; pub const MAPINAMEID = extern struct { lpguid: ?*Guid, ulKind: u32, Kind: extern union { lID: i32, lpwstrName: ?PWSTR, }, }; pub const IMAPIProp = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLastError: fn( self: *const IMAPIProp, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveChanges: fn( self: *const IMAPIProp, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProps: fn( self: *const IMAPIProp, lpPropTagArray: ?*SPropTagArray, ulFlags: u32, lpcValues: ?*u32, lppPropArray: ?*?*SPropValue, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPropList: fn( self: *const IMAPIProp, ulFlags: u32, lppPropTagArray: ?*?*SPropTagArray, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenProperty: fn( self: *const IMAPIProp, ulPropTag: u32, lpiid: ?*Guid, ulInterfaceOptions: u32, ulFlags: u32, lppUnk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProps: fn( self: *const IMAPIProp, cValues: u32, lpPropArray: ?*SPropValue, lppProblems: ?*?*SPropProblemArray, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteProps: fn( self: *const IMAPIProp, lpPropTagArray: ?*SPropTagArray, lppProblems: ?*?*SPropProblemArray, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyTo: fn( self: *const IMAPIProp, ciidExclude: u32, rgiidExclude: ?*Guid, lpExcludeProps: ?*SPropTagArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, lpInterface: ?*Guid, lpDestObj: ?*anyopaque, ulFlags: u32, lppProblems: ?*?*SPropProblemArray, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyProps: fn( self: *const IMAPIProp, lpIncludeProps: ?*SPropTagArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, lpInterface: ?*Guid, lpDestObj: ?*anyopaque, ulFlags: u32, lppProblems: ?*?*SPropProblemArray, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNamesFromIDs: fn( self: *const IMAPIProp, lppPropTags: ?*?*SPropTagArray, lpPropSetGuid: ?*Guid, ulFlags: u32, lpcPropNames: ?*u32, lpppPropNames: ?*?*?*MAPINAMEID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIDsFromNames: fn( self: *const IMAPIProp, cPropNames: u32, lppPropNames: ?*?*MAPINAMEID, ulFlags: u32, lppPropTags: ?*?*SPropTagArray, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_GetLastError(self: *const T, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).GetLastError(@ptrCast(*const IMAPIProp, self), hResult, ulFlags, lppMAPIError); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_SaveChanges(self: *const T, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).SaveChanges(@ptrCast(*const IMAPIProp, self), ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_GetProps(self: *const T, lpPropTagArray: ?*SPropTagArray, ulFlags: u32, lpcValues: ?*u32, lppPropArray: ?*?*SPropValue) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).GetProps(@ptrCast(*const IMAPIProp, self), lpPropTagArray, ulFlags, lpcValues, lppPropArray); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_GetPropList(self: *const T, ulFlags: u32, lppPropTagArray: ?*?*SPropTagArray) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).GetPropList(@ptrCast(*const IMAPIProp, self), ulFlags, lppPropTagArray); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_OpenProperty(self: *const T, ulPropTag: u32, lpiid: ?*Guid, ulInterfaceOptions: u32, ulFlags: u32, lppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).OpenProperty(@ptrCast(*const IMAPIProp, self), ulPropTag, lpiid, ulInterfaceOptions, ulFlags, lppUnk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_SetProps(self: *const T, cValues: u32, lpPropArray: ?*SPropValue, lppProblems: ?*?*SPropProblemArray) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).SetProps(@ptrCast(*const IMAPIProp, self), cValues, lpPropArray, lppProblems); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_DeleteProps(self: *const T, lpPropTagArray: ?*SPropTagArray, lppProblems: ?*?*SPropProblemArray) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).DeleteProps(@ptrCast(*const IMAPIProp, self), lpPropTagArray, lppProblems); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_CopyTo(self: *const T, ciidExclude: u32, rgiidExclude: ?*Guid, lpExcludeProps: ?*SPropTagArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, lpInterface: ?*Guid, lpDestObj: ?*anyopaque, ulFlags: u32, lppProblems: ?*?*SPropProblemArray) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).CopyTo(@ptrCast(*const IMAPIProp, self), ciidExclude, rgiidExclude, lpExcludeProps, ulUIParam, lpProgress, lpInterface, lpDestObj, ulFlags, lppProblems); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_CopyProps(self: *const T, lpIncludeProps: ?*SPropTagArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, lpInterface: ?*Guid, lpDestObj: ?*anyopaque, ulFlags: u32, lppProblems: ?*?*SPropProblemArray) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).CopyProps(@ptrCast(*const IMAPIProp, self), lpIncludeProps, ulUIParam, lpProgress, lpInterface, lpDestObj, ulFlags, lppProblems); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_GetNamesFromIDs(self: *const T, lppPropTags: ?*?*SPropTagArray, lpPropSetGuid: ?*Guid, ulFlags: u32, lpcPropNames: ?*u32, lpppPropNames: ?*?*?*MAPINAMEID) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).GetNamesFromIDs(@ptrCast(*const IMAPIProp, self), lppPropTags, lpPropSetGuid, ulFlags, lpcPropNames, lpppPropNames); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIProp_GetIDsFromNames(self: *const T, cPropNames: u32, lppPropNames: ?*?*MAPINAMEID, ulFlags: u32, lppPropTags: ?*?*SPropTagArray) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIProp.VTable, self.vtable).GetIDsFromNames(@ptrCast(*const IMAPIProp, self), cPropNames, lppPropNames, ulFlags, lppPropTags); } };} pub usingnamespace MethodMixin(@This()); }; pub const SSortOrder = extern struct { ulPropTag: u32, ulOrder: u32, }; pub const SSortOrderSet = extern struct { cSorts: u32, cCategories: u32, cExpanded: u32, aSort: [1]SSortOrder, }; pub const SAndRestriction = extern struct { cRes: u32, lpRes: ?*SRestriction, }; pub const SOrRestriction = extern struct { cRes: u32, lpRes: ?*SRestriction, }; pub const SNotRestriction = extern struct { ulReserved: u32, lpRes: ?*SRestriction, }; pub const SContentRestriction = extern struct { ulFuzzyLevel: u32, ulPropTag: u32, lpProp: ?*SPropValue, }; pub const SBitMaskRestriction = extern struct { relBMR: u32, ulPropTag: u32, ulMask: u32, }; pub const SPropertyRestriction = extern struct { relop: u32, ulPropTag: u32, lpProp: ?*SPropValue, }; pub const SComparePropsRestriction = extern struct { relop: u32, ulPropTag1: u32, ulPropTag2: u32, }; pub const SSizeRestriction = extern struct { relop: u32, ulPropTag: u32, cb: u32, }; pub const SExistRestriction = extern struct { ulReserved1: u32, ulPropTag: u32, ulReserved2: u32, }; pub const SSubRestriction = extern struct { ulSubObject: u32, lpRes: ?*SRestriction, }; pub const SCommentRestriction = extern struct { cValues: u32, lpRes: ?*SRestriction, lpProp: ?*SPropValue, }; pub const SRestriction = extern struct { rt: u32, res: extern union { resCompareProps: SComparePropsRestriction, resAnd: SAndRestriction, resOr: SOrRestriction, resNot: SNotRestriction, resContent: SContentRestriction, resProperty: SPropertyRestriction, resBitMask: SBitMaskRestriction, resSize: SSizeRestriction, resExist: SExistRestriction, resSub: SSubRestriction, resComment: SCommentRestriction, }, }; // TODO: this type is limited to platform 'windows5.0' pub const IMAPITable = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLastError: fn( self: *const IMAPITable, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Advise: fn( self: *const IMAPITable, ulEventMask: u32, lpAdviseSink: ?*IMAPIAdviseSink, lpulConnection: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unadvise: fn( self: *const IMAPITable, ulConnection: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatus: fn( self: *const IMAPITable, lpulTableStatus: ?*u32, lpulTableType: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColumns: fn( self: *const IMAPITable, lpPropTagArray: ?*SPropTagArray, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryColumns: fn( self: *const IMAPITable, ulFlags: u32, lpPropTagArray: ?*?*SPropTagArray, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRowCount: fn( self: *const IMAPITable, ulFlags: u32, lpulCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SeekRow: fn( self: *const IMAPITable, bkOrigin: u32, lRowCount: i32, lplRowsSought: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SeekRowApprox: fn( self: *const IMAPITable, ulNumerator: u32, ulDenominator: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryPosition: fn( self: *const IMAPITable, lpulRow: ?*u32, lpulNumerator: ?*u32, lpulDenominator: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FindRow: fn( self: *const IMAPITable, lpRestriction: ?*SRestriction, bkOrigin: u32, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Restrict: fn( self: *const IMAPITable, lpRestriction: ?*SRestriction, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateBookmark: fn( self: *const IMAPITable, lpbkPosition: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FreeBookmark: fn( self: *const IMAPITable, bkPosition: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SortTable: fn( self: *const IMAPITable, lpSortCriteria: ?*SSortOrderSet, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QuerySortOrder: fn( self: *const IMAPITable, lppSortCriteria: ?*?*SSortOrderSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryRows: fn( self: *const IMAPITable, lRowCount: i32, ulFlags: u32, lppRows: ?*?*SRowSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Abort: fn( self: *const IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ExpandRow: fn( self: *const IMAPITable, cbInstanceKey: u32, pbInstanceKey: ?*u8, ulRowCount: u32, ulFlags: u32, lppRows: ?*?*SRowSet, lpulMoreRows: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CollapseRow: fn( self: *const IMAPITable, cbInstanceKey: u32, pbInstanceKey: ?*u8, ulFlags: u32, lpulRowCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WaitForCompletion: fn( self: *const IMAPITable, ulFlags: u32, ulTimeout: u32, lpulTableStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCollapseState: fn( self: *const IMAPITable, ulFlags: u32, cbInstanceKey: u32, lpbInstanceKey: ?*u8, lpcbCollapseState: ?*u32, lppbCollapseState: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCollapseState: fn( self: *const IMAPITable, ulFlags: u32, cbCollapseState: u32, pbCollapseState: ?*u8, lpbkLocation: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_GetLastError(self: *const T, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).GetLastError(@ptrCast(*const IMAPITable, self), hResult, ulFlags, lppMAPIError); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_Advise(self: *const T, ulEventMask: u32, lpAdviseSink: ?*IMAPIAdviseSink, lpulConnection: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).Advise(@ptrCast(*const IMAPITable, self), ulEventMask, lpAdviseSink, lpulConnection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_Unadvise(self: *const T, ulConnection: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).Unadvise(@ptrCast(*const IMAPITable, self), ulConnection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_GetStatus(self: *const T, lpulTableStatus: ?*u32, lpulTableType: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).GetStatus(@ptrCast(*const IMAPITable, self), lpulTableStatus, lpulTableType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_SetColumns(self: *const T, lpPropTagArray: ?*SPropTagArray, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).SetColumns(@ptrCast(*const IMAPITable, self), lpPropTagArray, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_QueryColumns(self: *const T, ulFlags: u32, lpPropTagArray: ?*?*SPropTagArray) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).QueryColumns(@ptrCast(*const IMAPITable, self), ulFlags, lpPropTagArray); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_GetRowCount(self: *const T, ulFlags: u32, lpulCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).GetRowCount(@ptrCast(*const IMAPITable, self), ulFlags, lpulCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_SeekRow(self: *const T, bkOrigin: u32, lRowCount: i32, lplRowsSought: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).SeekRow(@ptrCast(*const IMAPITable, self), bkOrigin, lRowCount, lplRowsSought); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_SeekRowApprox(self: *const T, ulNumerator: u32, ulDenominator: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).SeekRowApprox(@ptrCast(*const IMAPITable, self), ulNumerator, ulDenominator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_QueryPosition(self: *const T, lpulRow: ?*u32, lpulNumerator: ?*u32, lpulDenominator: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).QueryPosition(@ptrCast(*const IMAPITable, self), lpulRow, lpulNumerator, lpulDenominator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_FindRow(self: *const T, lpRestriction: ?*SRestriction, bkOrigin: u32, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).FindRow(@ptrCast(*const IMAPITable, self), lpRestriction, bkOrigin, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_Restrict(self: *const T, lpRestriction: ?*SRestriction, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).Restrict(@ptrCast(*const IMAPITable, self), lpRestriction, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_CreateBookmark(self: *const T, lpbkPosition: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).CreateBookmark(@ptrCast(*const IMAPITable, self), lpbkPosition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_FreeBookmark(self: *const T, bkPosition: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).FreeBookmark(@ptrCast(*const IMAPITable, self), bkPosition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_SortTable(self: *const T, lpSortCriteria: ?*SSortOrderSet, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).SortTable(@ptrCast(*const IMAPITable, self), lpSortCriteria, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_QuerySortOrder(self: *const T, lppSortCriteria: ?*?*SSortOrderSet) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).QuerySortOrder(@ptrCast(*const IMAPITable, self), lppSortCriteria); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_QueryRows(self: *const T, lRowCount: i32, ulFlags: u32, lppRows: ?*?*SRowSet) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).QueryRows(@ptrCast(*const IMAPITable, self), lRowCount, ulFlags, lppRows); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_Abort(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).Abort(@ptrCast(*const IMAPITable, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_ExpandRow(self: *const T, cbInstanceKey: u32, pbInstanceKey: ?*u8, ulRowCount: u32, ulFlags: u32, lppRows: ?*?*SRowSet, lpulMoreRows: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).ExpandRow(@ptrCast(*const IMAPITable, self), cbInstanceKey, pbInstanceKey, ulRowCount, ulFlags, lppRows, lpulMoreRows); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_CollapseRow(self: *const T, cbInstanceKey: u32, pbInstanceKey: ?*u8, ulFlags: u32, lpulRowCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).CollapseRow(@ptrCast(*const IMAPITable, self), cbInstanceKey, pbInstanceKey, ulFlags, lpulRowCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_WaitForCompletion(self: *const T, ulFlags: u32, ulTimeout: u32, lpulTableStatus: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).WaitForCompletion(@ptrCast(*const IMAPITable, self), ulFlags, ulTimeout, lpulTableStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_GetCollapseState(self: *const T, ulFlags: u32, cbInstanceKey: u32, lpbInstanceKey: ?*u8, lpcbCollapseState: ?*u32, lppbCollapseState: ?*?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).GetCollapseState(@ptrCast(*const IMAPITable, self), ulFlags, cbInstanceKey, lpbInstanceKey, lpcbCollapseState, lppbCollapseState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPITable_SetCollapseState(self: *const T, ulFlags: u32, cbCollapseState: u32, pbCollapseState: ?*u8, lpbkLocation: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPITable.VTable, self.vtable).SetCollapseState(@ptrCast(*const IMAPITable, self), ulFlags, cbCollapseState, pbCollapseState, lpbkLocation); } };} pub usingnamespace MethodMixin(@This()); }; pub const IProfSect = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; pub const IMAPIStatus = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, ValidateState: fn( self: *const IMAPIStatus, ulUIParam: usize, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SettingsDialog: fn( self: *const IMAPIStatus, ulUIParam: usize, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ChangePassword: fn( self: *const IMAPIStatus, lpOldPass: ?*i8, lpNewPass: ?*i8, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FlushQueues: fn( self: *const IMAPIStatus, ulUIParam: usize, cbTargetTransport: u32, lpTargetTransport: ?[*]ENTRYID, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIStatus_ValidateState(self: *const T, ulUIParam: usize, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIStatus.VTable, self.vtable).ValidateState(@ptrCast(*const IMAPIStatus, self), ulUIParam, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIStatus_SettingsDialog(self: *const T, ulUIParam: usize, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIStatus.VTable, self.vtable).SettingsDialog(@ptrCast(*const IMAPIStatus, self), ulUIParam, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIStatus_ChangePassword(self: *const T, lpOldPass: ?*i8, lpNewPass: ?*i8, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIStatus.VTable, self.vtable).ChangePassword(@ptrCast(*const IMAPIStatus, self), lpOldPass, lpNewPass, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIStatus_FlushQueues(self: *const T, ulUIParam: usize, cbTargetTransport: u32, lpTargetTransport: ?[*]ENTRYID, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIStatus.VTable, self.vtable).FlushQueues(@ptrCast(*const IMAPIStatus, self), ulUIParam, cbTargetTransport, lpTargetTransport, ulFlags); } };} pub usingnamespace MethodMixin(@This()); }; pub const IMAPIContainer = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, GetContentsTable: fn( self: *const IMAPIContainer, ulFlags: u32, lppTable: ?*?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetHierarchyTable: fn( self: *const IMAPIContainer, ulFlags: u32, lppTable: ?*?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenEntry: fn( self: *const IMAPIContainer, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, ulFlags: u32, lpulObjType: ?*u32, lppUnk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSearchCriteria: fn( self: *const IMAPIContainer, lpRestriction: ?*SRestriction, lpContainerList: ?*SBinaryArray, ulSearchFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSearchCriteria: fn( self: *const IMAPIContainer, ulFlags: u32, lppRestriction: ?*?*SRestriction, lppContainerList: ?*?*SBinaryArray, lpulSearchState: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIContainer_GetContentsTable(self: *const T, ulFlags: u32, lppTable: ?*?*IMAPITable) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIContainer.VTable, self.vtable).GetContentsTable(@ptrCast(*const IMAPIContainer, self), ulFlags, lppTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIContainer_GetHierarchyTable(self: *const T, ulFlags: u32, lppTable: ?*?*IMAPITable) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIContainer.VTable, self.vtable).GetHierarchyTable(@ptrCast(*const IMAPIContainer, self), ulFlags, lppTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIContainer_OpenEntry(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, ulFlags: u32, lpulObjType: ?*u32, lppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIContainer.VTable, self.vtable).OpenEntry(@ptrCast(*const IMAPIContainer, self), cbEntryID, lpEntryID, lpInterface, ulFlags, lpulObjType, lppUnk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIContainer_SetSearchCriteria(self: *const T, lpRestriction: ?*SRestriction, lpContainerList: ?*SBinaryArray, ulSearchFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIContainer.VTable, self.vtable).SetSearchCriteria(@ptrCast(*const IMAPIContainer, self), lpRestriction, lpContainerList, ulSearchFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIContainer_GetSearchCriteria(self: *const T, ulFlags: u32, lppRestriction: ?*?*SRestriction, lppContainerList: ?*?*SBinaryArray, lpulSearchState: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIContainer.VTable, self.vtable).GetSearchCriteria(@ptrCast(*const IMAPIContainer, self), ulFlags, lppRestriction, lppContainerList, lpulSearchState); } };} pub usingnamespace MethodMixin(@This()); }; pub const _flaglist = extern struct { cFlags: u32, ulFlag: [1]u32, }; // TODO: this type is limited to platform 'windows5.0' pub const IABContainer = extern struct { pub const VTable = extern struct { base: IMAPIContainer.VTable, CreateEntry: fn( self: *const IABContainer, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, ulCreateFlags: u32, lppMAPIPropEntry: ?*?*IMAPIProp, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyEntries: fn( self: *const IABContainer, lpEntries: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteEntries: fn( self: *const IABContainer, lpEntries: ?*SBinaryArray, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResolveNames: fn( self: *const IABContainer, lpPropTagArray: ?*SPropTagArray, ulFlags: u32, lpAdrList: ?*ADRLIST, lpFlagList: ?*_flaglist, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIContainer.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IABContainer_CreateEntry(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulCreateFlags: u32, lppMAPIPropEntry: ?*?*IMAPIProp) callconv(.Inline) HRESULT { return @ptrCast(*const IABContainer.VTable, self.vtable).CreateEntry(@ptrCast(*const IABContainer, self), cbEntryID, lpEntryID, ulCreateFlags, lppMAPIPropEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IABContainer_CopyEntries(self: *const T, lpEntries: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IABContainer.VTable, self.vtable).CopyEntries(@ptrCast(*const IABContainer, self), lpEntries, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IABContainer_DeleteEntries(self: *const T, lpEntries: ?*SBinaryArray, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IABContainer.VTable, self.vtable).DeleteEntries(@ptrCast(*const IABContainer, self), lpEntries, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IABContainer_ResolveNames(self: *const T, lpPropTagArray: ?*SPropTagArray, ulFlags: u32, lpAdrList: ?*ADRLIST, lpFlagList: ?*_flaglist) callconv(.Inline) HRESULT { return @ptrCast(*const IABContainer.VTable, self.vtable).ResolveNames(@ptrCast(*const IABContainer, self), lpPropTagArray, ulFlags, lpAdrList, lpFlagList); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' pub const IMailUser = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' pub const IDistList = extern struct { pub const VTable = extern struct { base: IMAPIContainer.VTable, CreateEntry: fn( self: *const IDistList, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, ulCreateFlags: u32, lppMAPIPropEntry: ?*?*IMAPIProp, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyEntries: fn( self: *const IDistList, lpEntries: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteEntries: fn( self: *const IDistList, lpEntries: ?*SBinaryArray, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResolveNames: fn( self: *const IDistList, lpPropTagArray: ?*SPropTagArray, ulFlags: u32, lpAdrList: ?*ADRLIST, lpFlagList: ?*_flaglist, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIContainer.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDistList_CreateEntry(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulCreateFlags: u32, lppMAPIPropEntry: ?*?*IMAPIProp) callconv(.Inline) HRESULT { return @ptrCast(*const IDistList.VTable, self.vtable).CreateEntry(@ptrCast(*const IDistList, self), cbEntryID, lpEntryID, ulCreateFlags, lppMAPIPropEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDistList_CopyEntries(self: *const T, lpEntries: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDistList.VTable, self.vtable).CopyEntries(@ptrCast(*const IDistList, self), lpEntries, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDistList_DeleteEntries(self: *const T, lpEntries: ?*SBinaryArray, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDistList.VTable, self.vtable).DeleteEntries(@ptrCast(*const IDistList, self), lpEntries, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDistList_ResolveNames(self: *const T, lpPropTagArray: ?*SPropTagArray, ulFlags: u32, lpAdrList: ?*ADRLIST, lpFlagList: ?*_flaglist) callconv(.Inline) HRESULT { return @ptrCast(*const IDistList.VTable, self.vtable).ResolveNames(@ptrCast(*const IDistList, self), lpPropTagArray, ulFlags, lpAdrList, lpFlagList); } };} pub usingnamespace MethodMixin(@This()); }; pub const IMAPIFolder = extern struct { pub const VTable = extern struct { base: IMAPIContainer.VTable, CreateMessage: fn( self: *const IMAPIFolder, lpInterface: ?*Guid, ulFlags: u32, lppMessage: ?*?*IMessage, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyMessages: fn( self: *const IMAPIFolder, lpMsgList: ?*SBinaryArray, lpInterface: ?*Guid, lpDestFolder: ?*anyopaque, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteMessages: fn( self: *const IMAPIFolder, lpMsgList: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateFolder: fn( self: *const IMAPIFolder, ulFolderType: u32, lpszFolderName: ?*i8, lpszFolderComment: ?*i8, lpInterface: ?*Guid, ulFlags: u32, lppFolder: ?*?*IMAPIFolder, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyFolder: fn( self: *const IMAPIFolder, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, lpDestFolder: ?*anyopaque, lpszNewFolderName: ?*i8, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteFolder: fn( self: *const IMAPIFolder, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetReadFlags: fn( self: *const IMAPIFolder, lpMsgList: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMessageStatus: fn( self: *const IMAPIFolder, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, ulFlags: u32, lpulMessageStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMessageStatus: fn( self: *const IMAPIFolder, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, ulNewStatus: u32, ulNewStatusMask: u32, lpulOldStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveContentsSort: fn( self: *const IMAPIFolder, lpSortCriteria: ?*SSortOrderSet, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EmptyFolder: fn( self: *const IMAPIFolder, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIContainer.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_CreateMessage(self: *const T, lpInterface: ?*Guid, ulFlags: u32, lppMessage: ?*?*IMessage) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).CreateMessage(@ptrCast(*const IMAPIFolder, self), lpInterface, ulFlags, lppMessage); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_CopyMessages(self: *const T, lpMsgList: ?*SBinaryArray, lpInterface: ?*Guid, lpDestFolder: ?*anyopaque, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).CopyMessages(@ptrCast(*const IMAPIFolder, self), lpMsgList, lpInterface, lpDestFolder, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_DeleteMessages(self: *const T, lpMsgList: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).DeleteMessages(@ptrCast(*const IMAPIFolder, self), lpMsgList, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_CreateFolder(self: *const T, ulFolderType: u32, lpszFolderName: ?*i8, lpszFolderComment: ?*i8, lpInterface: ?*Guid, ulFlags: u32, lppFolder: ?*?*IMAPIFolder) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).CreateFolder(@ptrCast(*const IMAPIFolder, self), ulFolderType, lpszFolderName, lpszFolderComment, lpInterface, ulFlags, lppFolder); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_CopyFolder(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, lpDestFolder: ?*anyopaque, lpszNewFolderName: ?*i8, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).CopyFolder(@ptrCast(*const IMAPIFolder, self), cbEntryID, lpEntryID, lpInterface, lpDestFolder, lpszNewFolderName, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_DeleteFolder(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).DeleteFolder(@ptrCast(*const IMAPIFolder, self), cbEntryID, lpEntryID, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_SetReadFlags(self: *const T, lpMsgList: ?*SBinaryArray, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).SetReadFlags(@ptrCast(*const IMAPIFolder, self), lpMsgList, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_GetMessageStatus(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulFlags: u32, lpulMessageStatus: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).GetMessageStatus(@ptrCast(*const IMAPIFolder, self), cbEntryID, lpEntryID, ulFlags, lpulMessageStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_SetMessageStatus(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulNewStatus: u32, ulNewStatusMask: u32, lpulOldStatus: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).SetMessageStatus(@ptrCast(*const IMAPIFolder, self), cbEntryID, lpEntryID, ulNewStatus, ulNewStatusMask, lpulOldStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_SaveContentsSort(self: *const T, lpSortCriteria: ?*SSortOrderSet, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).SaveContentsSort(@ptrCast(*const IMAPIFolder, self), lpSortCriteria, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIFolder_EmptyFolder(self: *const T, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIFolder.VTable, self.vtable).EmptyFolder(@ptrCast(*const IMAPIFolder, self), ulUIParam, lpProgress, ulFlags); } };} pub usingnamespace MethodMixin(@This()); }; pub const IMsgStore = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, Advise: fn( self: *const IMsgStore, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, ulEventMask: u32, lpAdviseSink: ?*IMAPIAdviseSink, lpulConnection: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unadvise: fn( self: *const IMsgStore, ulConnection: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CompareEntryIDs: fn( self: *const IMsgStore, cbEntryID1: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID1: ?*ENTRYID, cbEntryID2: u32, // TODO: what to do with BytesParamIndex 2? lpEntryID2: ?*ENTRYID, ulFlags: u32, lpulResult: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenEntry: fn( self: *const IMsgStore, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, ulFlags: u32, lpulObjType: ?*u32, ppUnk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetReceiveFolder: fn( self: *const IMsgStore, lpszMessageClass: ?*i8, ulFlags: u32, cbEntryID: u32, // TODO: what to do with BytesParamIndex 2? lpEntryID: ?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReceiveFolder: fn( self: *const IMsgStore, lpszMessageClass: ?*i8, ulFlags: u32, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID, lppszExplicitClass: ?*?*i8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReceiveFolderTable: fn( self: *const IMsgStore, ulFlags: u32, lppTable: ?*?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StoreLogoff: fn( self: *const IMsgStore, lpulFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AbortSubmit: fn( self: *const IMsgStore, cbEntryID: u32, // TODO: what to do with BytesParamIndex 0? lpEntryID: ?*ENTRYID, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOutgoingQueue: fn( self: *const IMsgStore, ulFlags: u32, lppTable: ?*?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLockState: fn( self: *const IMsgStore, lpMessage: ?*IMessage, ulLockState: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FinishedMsg: fn( self: *const IMsgStore, ulFlags: u32, cbEntryID: u32, // TODO: what to do with BytesParamIndex 1? lpEntryID: ?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifyNewMail: fn( self: *const IMsgStore, lpNotification: ?*NOTIFICATION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_Advise(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulEventMask: u32, lpAdviseSink: ?*IMAPIAdviseSink, lpulConnection: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).Advise(@ptrCast(*const IMsgStore, self), cbEntryID, lpEntryID, ulEventMask, lpAdviseSink, lpulConnection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_Unadvise(self: *const T, ulConnection: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).Unadvise(@ptrCast(*const IMsgStore, self), ulConnection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_CompareEntryIDs(self: *const T, cbEntryID1: u32, lpEntryID1: ?*ENTRYID, cbEntryID2: u32, lpEntryID2: ?*ENTRYID, ulFlags: u32, lpulResult: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).CompareEntryIDs(@ptrCast(*const IMsgStore, self), cbEntryID1, lpEntryID1, cbEntryID2, lpEntryID2, ulFlags, lpulResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_OpenEntry(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, ulFlags: u32, lpulObjType: ?*u32, ppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).OpenEntry(@ptrCast(*const IMsgStore, self), cbEntryID, lpEntryID, lpInterface, ulFlags, lpulObjType, ppUnk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_SetReceiveFolder(self: *const T, lpszMessageClass: ?*i8, ulFlags: u32, cbEntryID: u32, lpEntryID: ?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).SetReceiveFolder(@ptrCast(*const IMsgStore, self), lpszMessageClass, ulFlags, cbEntryID, lpEntryID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_GetReceiveFolder(self: *const T, lpszMessageClass: ?*i8, ulFlags: u32, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID, lppszExplicitClass: ?*?*i8) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).GetReceiveFolder(@ptrCast(*const IMsgStore, self), lpszMessageClass, ulFlags, lpcbEntryID, lppEntryID, lppszExplicitClass); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_GetReceiveFolderTable(self: *const T, ulFlags: u32, lppTable: ?*?*IMAPITable) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).GetReceiveFolderTable(@ptrCast(*const IMsgStore, self), ulFlags, lppTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_StoreLogoff(self: *const T, lpulFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).StoreLogoff(@ptrCast(*const IMsgStore, self), lpulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_AbortSubmit(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).AbortSubmit(@ptrCast(*const IMsgStore, self), cbEntryID, lpEntryID, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_GetOutgoingQueue(self: *const T, ulFlags: u32, lppTable: ?*?*IMAPITable) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).GetOutgoingQueue(@ptrCast(*const IMsgStore, self), ulFlags, lppTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_SetLockState(self: *const T, lpMessage: ?*IMessage, ulLockState: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).SetLockState(@ptrCast(*const IMsgStore, self), lpMessage, ulLockState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_FinishedMsg(self: *const T, ulFlags: u32, cbEntryID: u32, lpEntryID: ?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).FinishedMsg(@ptrCast(*const IMsgStore, self), ulFlags, cbEntryID, lpEntryID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMsgStore_NotifyNewMail(self: *const T, lpNotification: ?*NOTIFICATION) callconv(.Inline) HRESULT { return @ptrCast(*const IMsgStore.VTable, self.vtable).NotifyNewMail(@ptrCast(*const IMsgStore, self), lpNotification); } };} pub usingnamespace MethodMixin(@This()); }; pub const IMessage = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, GetAttachmentTable: fn( self: *const IMessage, ulFlags: u32, lppTable: ?*?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenAttach: fn( self: *const IMessage, ulAttachmentNum: u32, lpInterface: ?*Guid, ulFlags: u32, lppAttach: ?*?*IAttach, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateAttach: fn( self: *const IMessage, lpInterface: ?*Guid, ulFlags: u32, lpulAttachmentNum: ?*u32, lppAttach: ?*?*IAttach, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAttach: fn( self: *const IMessage, ulAttachmentNum: u32, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRecipientTable: fn( self: *const IMessage, ulFlags: u32, lppTable: ?*?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ModifyRecipients: fn( self: *const IMessage, ulFlags: u32, lpMods: ?*ADRLIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SubmitMessage: fn( self: *const IMessage, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetReadFlag: fn( self: *const IMessage, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_GetAttachmentTable(self: *const T, ulFlags: u32, lppTable: ?*?*IMAPITable) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).GetAttachmentTable(@ptrCast(*const IMessage, self), ulFlags, lppTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_OpenAttach(self: *const T, ulAttachmentNum: u32, lpInterface: ?*Guid, ulFlags: u32, lppAttach: ?*?*IAttach) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).OpenAttach(@ptrCast(*const IMessage, self), ulAttachmentNum, lpInterface, ulFlags, lppAttach); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_CreateAttach(self: *const T, lpInterface: ?*Guid, ulFlags: u32, lpulAttachmentNum: ?*u32, lppAttach: ?*?*IAttach) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).CreateAttach(@ptrCast(*const IMessage, self), lpInterface, ulFlags, lpulAttachmentNum, lppAttach); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_DeleteAttach(self: *const T, ulAttachmentNum: u32, ulUIParam: usize, lpProgress: ?*IMAPIProgress, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).DeleteAttach(@ptrCast(*const IMessage, self), ulAttachmentNum, ulUIParam, lpProgress, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_GetRecipientTable(self: *const T, ulFlags: u32, lppTable: ?*?*IMAPITable) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).GetRecipientTable(@ptrCast(*const IMessage, self), ulFlags, lppTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_ModifyRecipients(self: *const T, ulFlags: u32, lpMods: ?*ADRLIST) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).ModifyRecipients(@ptrCast(*const IMessage, self), ulFlags, lpMods); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_SubmitMessage(self: *const T, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).SubmitMessage(@ptrCast(*const IMessage, self), ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessage_SetReadFlag(self: *const T, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMessage.VTable, self.vtable).SetReadFlag(@ptrCast(*const IMessage, self), ulFlags); } };} pub usingnamespace MethodMixin(@This()); }; pub const IAttach = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; pub const LPFNABSDI = fn( ulUIParam: usize, lpvmsg: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const LPFNDISMISS = fn( ulUIParam: usize, lpvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const LPFNBUTTON = fn( ulUIParam: usize, lpvContext: ?*anyopaque, cbEntryID: u32, lpSelection: ?*ENTRYID, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub const ADRPARM = extern struct { cbABContEntryID: u32, lpABContEntryID: ?*ENTRYID, ulFlags: u32, lpReserved: ?*anyopaque, ulHelpContext: u32, lpszHelpFileName: ?*i8, lpfnABSDI: ?LPFNABSDI, lpfnDismiss: ?LPFNDISMISS, lpvDismissContext: ?*anyopaque, lpszCaption: ?*i8, lpszNewEntryTitle: ?*i8, lpszDestWellsTitle: ?*i8, cDestFields: u32, nDestFieldFocus: u32, lppszDestTitles: ?*?*i8, lpulDestComps: ?*u32, lpContRestriction: ?*SRestriction, lpHierRestriction: ?*SRestriction, }; pub const IMAPIControl = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLastError: fn( self: *const IMAPIControl, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Activate: fn( self: *const IMAPIControl, ulFlags: u32, ulUIParam: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetState: fn( self: *const IMAPIControl, ulFlags: u32, lpulState: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIControl_GetLastError(self: *const T, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIControl.VTable, self.vtable).GetLastError(@ptrCast(*const IMAPIControl, self), hResult, ulFlags, lppMAPIError); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIControl_Activate(self: *const T, ulFlags: u32, ulUIParam: usize) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIControl.VTable, self.vtable).Activate(@ptrCast(*const IMAPIControl, self), ulFlags, ulUIParam); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMAPIControl_GetState(self: *const T, ulFlags: u32, lpulState: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IMAPIControl.VTable, self.vtable).GetState(@ptrCast(*const IMAPIControl, self), ulFlags, lpulState); } };} pub usingnamespace MethodMixin(@This()); }; pub const DTBLLABEL = extern struct { ulbLpszLabelName: u32, ulFlags: u32, }; pub const DTBLEDIT = extern struct { ulbLpszCharsAllowed: u32, ulFlags: u32, ulNumCharsAllowed: u32, ulPropTag: u32, }; pub const DTBLLBX = extern struct { ulFlags: u32, ulPRSetProperty: u32, ulPRTableName: u32, }; pub const DTBLCOMBOBOX = extern struct { ulbLpszCharsAllowed: u32, ulFlags: u32, ulNumCharsAllowed: u32, ulPRPropertyName: u32, ulPRTableName: u32, }; pub const DTBLDDLBX = extern struct { ulFlags: u32, ulPRDisplayProperty: u32, ulPRSetProperty: u32, ulPRTableName: u32, }; pub const DTBLCHECKBOX = extern struct { ulbLpszLabel: u32, ulFlags: u32, ulPRPropertyName: u32, }; pub const DTBLGROUPBOX = extern struct { ulbLpszLabel: u32, ulFlags: u32, }; pub const DTBLBUTTON = extern struct { ulbLpszLabel: u32, ulFlags: u32, ulPRControl: u32, }; pub const DTBLPAGE = extern struct { ulbLpszLabel: u32, ulFlags: u32, ulbLpszComponent: u32, ulContext: u32, }; pub const DTBLRADIOBUTTON = extern struct { ulbLpszLabel: u32, ulFlags: u32, ulcButtons: u32, ulPropTag: u32, lReturnValue: i32, }; pub const DTBLMVLISTBOX = extern struct { ulFlags: u32, ulMVPropTag: u32, }; pub const DTBLMVDDLBX = extern struct { ulFlags: u32, ulMVPropTag: u32, }; pub const IProviderAdmin = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLastError: fn( self: *const IProviderAdmin, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProviderTable: fn( self: *const IProviderAdmin, ulFlags: u32, lppTable: ?*?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateProvider: fn( self: *const IProviderAdmin, lpszProvider: ?*i8, cValues: u32, lpProps: [*]SPropValue, ulUIParam: usize, ulFlags: u32, lpUID: ?*MAPIUID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteProvider: fn( self: *const IProviderAdmin, lpUID: ?*MAPIUID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenProfileSection: fn( self: *const IProviderAdmin, lpUID: ?*MAPIUID, lpInterface: ?*Guid, ulFlags: u32, lppProfSect: ?*?*IProfSect, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderAdmin_GetLastError(self: *const T, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderAdmin.VTable, self.vtable).GetLastError(@ptrCast(*const IProviderAdmin, self), hResult, ulFlags, lppMAPIError); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderAdmin_GetProviderTable(self: *const T, ulFlags: u32, lppTable: ?*?*IMAPITable) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderAdmin.VTable, self.vtable).GetProviderTable(@ptrCast(*const IProviderAdmin, self), ulFlags, lppTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderAdmin_CreateProvider(self: *const T, lpszProvider: ?*i8, cValues: u32, lpProps: [*]SPropValue, ulUIParam: usize, ulFlags: u32, lpUID: ?*MAPIUID) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderAdmin.VTable, self.vtable).CreateProvider(@ptrCast(*const IProviderAdmin, self), lpszProvider, cValues, lpProps, ulUIParam, ulFlags, lpUID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderAdmin_DeleteProvider(self: *const T, lpUID: ?*MAPIUID) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderAdmin.VTable, self.vtable).DeleteProvider(@ptrCast(*const IProviderAdmin, self), lpUID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderAdmin_OpenProfileSection(self: *const T, lpUID: ?*MAPIUID, lpInterface: ?*Guid, ulFlags: u32, lppProfSect: ?*?*IProfSect) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderAdmin.VTable, self.vtable).OpenProfileSection(@ptrCast(*const IProviderAdmin, self), lpUID, lpInterface, ulFlags, lppProfSect); } };} pub usingnamespace MethodMixin(@This()); }; pub const Gender = enum(i32) { Unspecified = 0, Female = 1, Male = 2, }; pub const genderUnspecified = Gender.Unspecified; pub const genderFemale = Gender.Female; pub const genderMale = Gender.Male; pub const CALLERRELEASE = fn( ulCallerData: u32, lpTblData: ?*ITableData, lpVue: ?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) void; pub const ITableData = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, HrGetView: fn( self: *const ITableData, lpSSortOrderSet: ?*SSortOrderSet, lpfCallerRelease: ?*?CALLERRELEASE, ulCallerData: u32, lppMAPITable: ?*?*IMAPITable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HrModifyRow: fn( self: *const ITableData, param0: ?*SRow, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HrDeleteRow: fn( self: *const ITableData, lpSPropValue: ?*SPropValue, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HrQueryRow: fn( self: *const ITableData, lpsPropValue: ?*SPropValue, lppSRow: ?*?*SRow, lpuliRow: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HrEnumRow: fn( self: *const ITableData, ulRowNumber: u32, lppSRow: ?*?*SRow, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HrNotify: fn( self: *const ITableData, ulFlags: u32, cValues: u32, lpSPropValue: ?*SPropValue, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HrInsertRow: fn( self: *const ITableData, uliRow: u32, lpSRow: ?*SRow, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HrModifyRows: fn( self: *const ITableData, ulFlags: u32, lpSRowSet: ?*SRowSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HrDeleteRows: fn( self: *const ITableData, ulFlags: u32, lprowsetToDelete: ?*SRowSet, cRowsDeleted: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITableData_HrGetView(self: *const T, lpSSortOrderSet: ?*SSortOrderSet, lpfCallerRelease: ?*?CALLERRELEASE, ulCallerData: u32, lppMAPITable: ?*?*IMAPITable) callconv(.Inline) HRESULT { return @ptrCast(*const ITableData.VTable, self.vtable).HrGetView(@ptrCast(*const ITableData, self), lpSSortOrderSet, lpfCallerRelease, ulCallerData, lppMAPITable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITableData_HrModifyRow(self: *const T, param0: ?*SRow) callconv(.Inline) HRESULT { return @ptrCast(*const ITableData.VTable, self.vtable).HrModifyRow(@ptrCast(*const ITableData, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITableData_HrDeleteRow(self: *const T, lpSPropValue: ?*SPropValue) callconv(.Inline) HRESULT { return @ptrCast(*const ITableData.VTable, self.vtable).HrDeleteRow(@ptrCast(*const ITableData, self), lpSPropValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITableData_HrQueryRow(self: *const T, lpsPropValue: ?*SPropValue, lppSRow: ?*?*SRow, lpuliRow: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITableData.VTable, self.vtable).HrQueryRow(@ptrCast(*const ITableData, self), lpsPropValue, lppSRow, lpuliRow); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITableData_HrEnumRow(self: *const T, ulRowNumber: u32, lppSRow: ?*?*SRow) callconv(.Inline) HRESULT { return @ptrCast(*const ITableData.VTable, self.vtable).HrEnumRow(@ptrCast(*const ITableData, self), ulRowNumber, lppSRow); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITableData_HrNotify(self: *const T, ulFlags: u32, cValues: u32, lpSPropValue: ?*SPropValue) callconv(.Inline) HRESULT { return @ptrCast(*const ITableData.VTable, self.vtable).HrNotify(@ptrCast(*const ITableData, self), ulFlags, cValues, lpSPropValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITableData_HrInsertRow(self: *const T, uliRow: u32, lpSRow: ?*SRow) callconv(.Inline) HRESULT { return @ptrCast(*const ITableData.VTable, self.vtable).HrInsertRow(@ptrCast(*const ITableData, self), uliRow, lpSRow); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITableData_HrModifyRows(self: *const T, ulFlags: u32, lpSRowSet: ?*SRowSet) callconv(.Inline) HRESULT { return @ptrCast(*const ITableData.VTable, self.vtable).HrModifyRows(@ptrCast(*const ITableData, self), ulFlags, lpSRowSet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITableData_HrDeleteRows(self: *const T, ulFlags: u32, lprowsetToDelete: ?*SRowSet, cRowsDeleted: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITableData.VTable, self.vtable).HrDeleteRows(@ptrCast(*const ITableData, self), ulFlags, lprowsetToDelete, cRowsDeleted); } };} pub usingnamespace MethodMixin(@This()); }; pub const IPropData = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, HrSetObjAccess: fn( self: *const IPropData, ulAccess: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HrSetPropAccess: fn( self: *const IPropData, lpPropTagArray: ?*SPropTagArray, rgulAccess: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HrGetPropAccess: fn( self: *const IPropData, lppPropTagArray: ?*?*SPropTagArray, lprgulAccess: ?*?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HrAddObjProps: fn( self: *const IPropData, lppPropTagArray: ?*SPropTagArray, lprgulAccess: ?*?*SPropProblemArray, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropData_HrSetObjAccess(self: *const T, ulAccess: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPropData.VTable, self.vtable).HrSetObjAccess(@ptrCast(*const IPropData, self), ulAccess); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropData_HrSetPropAccess(self: *const T, lpPropTagArray: ?*SPropTagArray, rgulAccess: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPropData.VTable, self.vtable).HrSetPropAccess(@ptrCast(*const IPropData, self), lpPropTagArray, rgulAccess); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropData_HrGetPropAccess(self: *const T, lppPropTagArray: ?*?*SPropTagArray, lprgulAccess: ?*?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPropData.VTable, self.vtable).HrGetPropAccess(@ptrCast(*const IPropData, self), lppPropTagArray, lprgulAccess); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropData_HrAddObjProps(self: *const T, lppPropTagArray: ?*SPropTagArray, lprgulAccess: ?*?*SPropProblemArray) callconv(.Inline) HRESULT { return @ptrCast(*const IPropData.VTable, self.vtable).HrAddObjProps(@ptrCast(*const IPropData, self), lppPropTagArray, lprgulAccess); } };} pub usingnamespace MethodMixin(@This()); }; pub const FNIDLE = fn( param0: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFNIDLE = fn( ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const LPOPENSTREAMONFILE = fn( lpAllocateBuffer: ?LPALLOCATEBUFFER, lpFreeBuffer: ?LPFREEBUFFER, ulFlags: u32, lpszFileName: ?*i8, lpszPrefix: ?*i8, lppStream: ?*?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const DTCTL = extern struct { ulCtlType: u32, ulCtlFlags: u32, lpbNotif: ?*u8, cbNotif: u32, lpszFilter: ?*i8, ulItemID: u32, ctl: extern union { lpv: ?*anyopaque, lplabel: ?*DTBLLABEL, lpedit: ?*DTBLEDIT, lplbx: ?*DTBLLBX, lpcombobox: ?*DTBLCOMBOBOX, lpddlbx: ?*DTBLDDLBX, lpcheckbox: ?*DTBLCHECKBOX, lpgroupbox: ?*DTBLGROUPBOX, lpbutton: ?*DTBLBUTTON, lpradiobutton: ?*DTBLRADIOBUTTON, lpmvlbx: ?*DTBLMVLISTBOX, lpmvddlbx: ?*DTBLMVDDLBX, lppage: ?*DTBLPAGE, }, }; pub const DTPAGE = extern struct { cctl: u32, lpszResourceName: ?*i8, Anonymous: extern union { lpszComponent: ?*i8, ulItemID: u32, }, lpctl: ?*DTCTL, }; pub const LPDISPATCHNOTIFICATIONS = fn( ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const LPCREATECONVERSATIONINDEX = fn( cbParent: u32, lpbParent: ?*u8, lpcbConvIndex: ?*u32, lppbConvIndex: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub const IAddrBook = extern struct { pub const VTable = extern struct { base: IMAPIProp.VTable, OpenEntry: fn( self: *const IAddrBook, cbEntryID: u32, lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, ulFlags: u32, lpulObjType: ?*u32, lppUnk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CompareEntryIDs: fn( self: *const IAddrBook, cbEntryID1: u32, lpEntryID1: ?*ENTRYID, cbEntryID2: u32, lpEntryID2: ?*ENTRYID, ulFlags: u32, lpulResult: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Advise: fn( self: *const IAddrBook, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulEventMask: u32, lpAdviseSink: ?*IMAPIAdviseSink, lpulConnection: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unadvise: fn( self: *const IAddrBook, ulConnection: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateOneOff: fn( self: *const IAddrBook, lpszName: ?*i8, lpszAdrType: ?*i8, lpszAddress: ?*i8, ulFlags: u32, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NewEntry: fn( self: *const IAddrBook, ulUIParam: u32, ulFlags: u32, cbEIDContainer: u32, lpEIDContainer: ?*ENTRYID, cbEIDNewEntryTpl: u32, lpEIDNewEntryTpl: ?*ENTRYID, lpcbEIDNewEntry: ?*u32, lppEIDNewEntry: ?*?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResolveName: fn( self: *const IAddrBook, ulUIParam: usize, ulFlags: u32, lpszNewEntryTitle: ?*i8, lpAdrList: ?*ADRLIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Address: fn( self: *const IAddrBook, lpulUIParam: ?*u32, lpAdrParms: ?*ADRPARM, lppAdrList: ?*?*ADRLIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Details: fn( self: *const IAddrBook, lpulUIParam: ?*usize, lpfnDismiss: ?LPFNDISMISS, lpvDismissContext: ?*anyopaque, cbEntryID: u32, lpEntryID: ?*ENTRYID, lpfButtonCallback: ?LPFNBUTTON, lpvButtonContext: ?*anyopaque, lpszButtonText: ?*i8, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RecipOptions: fn( self: *const IAddrBook, ulUIParam: u32, ulFlags: u32, lpRecip: ?*ADRENTRY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryDefaultRecipOpt: fn( self: *const IAddrBook, lpszAdrType: ?*i8, ulFlags: u32, lpcValues: ?*u32, lppOptions: ?*?*SPropValue, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPAB: fn( self: *const IAddrBook, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPAB: fn( self: *const IAddrBook, cbEntryID: u32, lpEntryID: ?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDefaultDir: fn( self: *const IAddrBook, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDefaultDir: fn( self: *const IAddrBook, cbEntryID: u32, lpEntryID: ?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSearchPath: fn( self: *const IAddrBook, ulFlags: u32, lppSearchPath: ?*?*SRowSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSearchPath: fn( self: *const IAddrBook, ulFlags: u32, lpSearchPath: ?*SRowSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PrepareRecips: fn( self: *const IAddrBook, ulFlags: u32, lpPropTagArray: ?*SPropTagArray, lpRecipList: ?*ADRLIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IMAPIProp.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_OpenEntry(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, lpInterface: ?*Guid, ulFlags: u32, lpulObjType: ?*u32, lppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).OpenEntry(@ptrCast(*const IAddrBook, self), cbEntryID, lpEntryID, lpInterface, ulFlags, lpulObjType, lppUnk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_CompareEntryIDs(self: *const T, cbEntryID1: u32, lpEntryID1: ?*ENTRYID, cbEntryID2: u32, lpEntryID2: ?*ENTRYID, ulFlags: u32, lpulResult: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).CompareEntryIDs(@ptrCast(*const IAddrBook, self), cbEntryID1, lpEntryID1, cbEntryID2, lpEntryID2, ulFlags, lpulResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_Advise(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID, ulEventMask: u32, lpAdviseSink: ?*IMAPIAdviseSink, lpulConnection: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).Advise(@ptrCast(*const IAddrBook, self), cbEntryID, lpEntryID, ulEventMask, lpAdviseSink, lpulConnection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_Unadvise(self: *const T, ulConnection: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).Unadvise(@ptrCast(*const IAddrBook, self), ulConnection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_CreateOneOff(self: *const T, lpszName: ?*i8, lpszAdrType: ?*i8, lpszAddress: ?*i8, ulFlags: u32, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).CreateOneOff(@ptrCast(*const IAddrBook, self), lpszName, lpszAdrType, lpszAddress, ulFlags, lpcbEntryID, lppEntryID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_NewEntry(self: *const T, ulUIParam: u32, ulFlags: u32, cbEIDContainer: u32, lpEIDContainer: ?*ENTRYID, cbEIDNewEntryTpl: u32, lpEIDNewEntryTpl: ?*ENTRYID, lpcbEIDNewEntry: ?*u32, lppEIDNewEntry: ?*?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).NewEntry(@ptrCast(*const IAddrBook, self), ulUIParam, ulFlags, cbEIDContainer, lpEIDContainer, cbEIDNewEntryTpl, lpEIDNewEntryTpl, lpcbEIDNewEntry, lppEIDNewEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_ResolveName(self: *const T, ulUIParam: usize, ulFlags: u32, lpszNewEntryTitle: ?*i8, lpAdrList: ?*ADRLIST) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).ResolveName(@ptrCast(*const IAddrBook, self), ulUIParam, ulFlags, lpszNewEntryTitle, lpAdrList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_Address(self: *const T, lpulUIParam: ?*u32, lpAdrParms: ?*ADRPARM, lppAdrList: ?*?*ADRLIST) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).Address(@ptrCast(*const IAddrBook, self), lpulUIParam, lpAdrParms, lppAdrList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_Details(self: *const T, lpulUIParam: ?*usize, lpfnDismiss: ?LPFNDISMISS, lpvDismissContext: ?*anyopaque, cbEntryID: u32, lpEntryID: ?*ENTRYID, lpfButtonCallback: ?LPFNBUTTON, lpvButtonContext: ?*anyopaque, lpszButtonText: ?*i8, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).Details(@ptrCast(*const IAddrBook, self), lpulUIParam, lpfnDismiss, lpvDismissContext, cbEntryID, lpEntryID, lpfButtonCallback, lpvButtonContext, lpszButtonText, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_RecipOptions(self: *const T, ulUIParam: u32, ulFlags: u32, lpRecip: ?*ADRENTRY) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).RecipOptions(@ptrCast(*const IAddrBook, self), ulUIParam, ulFlags, lpRecip); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_QueryDefaultRecipOpt(self: *const T, lpszAdrType: ?*i8, ulFlags: u32, lpcValues: ?*u32, lppOptions: ?*?*SPropValue) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).QueryDefaultRecipOpt(@ptrCast(*const IAddrBook, self), lpszAdrType, ulFlags, lpcValues, lppOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_GetPAB(self: *const T, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).GetPAB(@ptrCast(*const IAddrBook, self), lpcbEntryID, lppEntryID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_SetPAB(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).SetPAB(@ptrCast(*const IAddrBook, self), cbEntryID, lpEntryID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_GetDefaultDir(self: *const T, lpcbEntryID: ?*u32, lppEntryID: ?*?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).GetDefaultDir(@ptrCast(*const IAddrBook, self), lpcbEntryID, lppEntryID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_SetDefaultDir(self: *const T, cbEntryID: u32, lpEntryID: ?*ENTRYID) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).SetDefaultDir(@ptrCast(*const IAddrBook, self), cbEntryID, lpEntryID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_GetSearchPath(self: *const T, ulFlags: u32, lppSearchPath: ?*?*SRowSet) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).GetSearchPath(@ptrCast(*const IAddrBook, self), ulFlags, lppSearchPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_SetSearchPath(self: *const T, ulFlags: u32, lpSearchPath: ?*SRowSet) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).SetSearchPath(@ptrCast(*const IAddrBook, self), ulFlags, lpSearchPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAddrBook_PrepareRecips(self: *const T, ulFlags: u32, lpPropTagArray: ?*SPropTagArray, lpRecipList: ?*ADRLIST) callconv(.Inline) HRESULT { return @ptrCast(*const IAddrBook.VTable, self.vtable).PrepareRecips(@ptrCast(*const IAddrBook, self), ulFlags, lpPropTagArray, lpRecipList); } };} pub usingnamespace MethodMixin(@This()); }; pub const _WABACTIONITEM = extern struct { placeholder: usize, // TODO: why is this type empty? }; // TODO: this type is limited to platform 'windows5.0' pub const IWABObject = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLastError: fn( self: *const IWABObject, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocateBuffer: fn( self: *const IWABObject, cbSize: u32, lppBuffer: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocateMore: fn( self: *const IWABObject, cbSize: u32, lpObject: ?*anyopaque, lppBuffer: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FreeBuffer: fn( self: *const IWABObject, lpBuffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Backup: fn( self: *const IWABObject, lpFileName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Import: fn( self: *const IWABObject, lpWIP: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Find: fn( self: *const IWABObject, lpIAB: ?*IAddrBook, hWnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, VCardDisplay: fn( self: *const IWABObject, lpIAB: ?*IAddrBook, hWnd: ?HWND, lpszFileName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LDAPUrl: fn( self: *const IWABObject, lpIAB: ?*IAddrBook, hWnd: ?HWND, ulFlags: u32, lpszURL: ?PSTR, lppMailUser: ?*?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT, VCardCreate: fn( self: *const IWABObject, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lpMailUser: ?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT, VCardRetrieve: fn( self: *const IWABObject, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lppMailUser: ?*?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMe: fn( self: *const IWABObject, lpIAB: ?*IAddrBook, ulFlags: u32, lpdwAction: ?*u32, lpsbEID: ?*SBinary, hwnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMe: fn( self: *const IWABObject, lpIAB: ?*IAddrBook, ulFlags: u32, sbEID: SBinary, hwnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_GetLastError(self: *const T, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).GetLastError(@ptrCast(*const IWABObject, self), hResult, ulFlags, lppMAPIError); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_AllocateBuffer(self: *const T, cbSize: u32, lppBuffer: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).AllocateBuffer(@ptrCast(*const IWABObject, self), cbSize, lppBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_AllocateMore(self: *const T, cbSize: u32, lpObject: ?*anyopaque, lppBuffer: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).AllocateMore(@ptrCast(*const IWABObject, self), cbSize, lpObject, lppBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_FreeBuffer(self: *const T, lpBuffer: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).FreeBuffer(@ptrCast(*const IWABObject, self), lpBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_Backup(self: *const T, lpFileName: ?PSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).Backup(@ptrCast(*const IWABObject, self), lpFileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_Import(self: *const T, lpWIP: ?PSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).Import(@ptrCast(*const IWABObject, self), lpWIP); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_Find(self: *const T, lpIAB: ?*IAddrBook, hWnd: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).Find(@ptrCast(*const IWABObject, self), lpIAB, hWnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_VCardDisplay(self: *const T, lpIAB: ?*IAddrBook, hWnd: ?HWND, lpszFileName: ?PSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).VCardDisplay(@ptrCast(*const IWABObject, self), lpIAB, hWnd, lpszFileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_LDAPUrl(self: *const T, lpIAB: ?*IAddrBook, hWnd: ?HWND, ulFlags: u32, lpszURL: ?PSTR, lppMailUser: ?*?*IMailUser) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).LDAPUrl(@ptrCast(*const IWABObject, self), lpIAB, hWnd, ulFlags, lpszURL, lppMailUser); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_VCardCreate(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lpMailUser: ?*IMailUser) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).VCardCreate(@ptrCast(*const IWABObject, self), lpIAB, ulFlags, lpszVCard, lpMailUser); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_VCardRetrieve(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lppMailUser: ?*?*IMailUser) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).VCardRetrieve(@ptrCast(*const IWABObject, self), lpIAB, ulFlags, lpszVCard, lppMailUser); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_GetMe(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, lpdwAction: ?*u32, lpsbEID: ?*SBinary, hwnd: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).GetMe(@ptrCast(*const IWABObject, self), lpIAB, ulFlags, lpdwAction, lpsbEID, hwnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABObject_SetMe(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, sbEID: SBinary, hwnd: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IWABObject.VTable, self.vtable).SetMe(@ptrCast(*const IWABObject, self), lpIAB, ulFlags, sbEID, hwnd); } };} pub usingnamespace MethodMixin(@This()); }; pub const IWABOBJECT_QueryInterface_METHOD = fn( riid: ?*const Guid, ppvObj: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_AddRef_METHOD = fn( ) callconv(@import("std").os.windows.WINAPI) u32; pub const IWABOBJECT_Release_METHOD = fn( ) callconv(@import("std").os.windows.WINAPI) u32; pub const IWABOBJECT_GetLastError_METHOD = fn( hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_AllocateBuffer_METHOD = fn( cbSize: u32, lppBuffer: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_AllocateMore_METHOD = fn( cbSize: u32, lpObject: ?*anyopaque, lppBuffer: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_FreeBuffer_METHOD = fn( lpBuffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_Backup_METHOD = fn( lpFileName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_Import_METHOD = fn( lpWIP: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_Find_METHOD = fn( lpIAB: ?*IAddrBook, hWnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_VCardDisplay_METHOD = fn( lpIAB: ?*IAddrBook, hWnd: ?HWND, lpszFileName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_LDAPUrl_METHOD = fn( lpIAB: ?*IAddrBook, hWnd: ?HWND, ulFlags: u32, lpszURL: ?PSTR, lppMailUser: ?*?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_VCardCreate_METHOD = fn( lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lpMailUser: ?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_VCardRetrieve_METHOD = fn( lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lppMailUser: ?*?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_GetMe_METHOD = fn( lpIAB: ?*IAddrBook, ulFlags: u32, lpdwAction: ?*u32, lpsbEID: ?*SBinary, hwnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_SetMe_METHOD = fn( lpIAB: ?*IAddrBook, ulFlags: u32, sbEID: SBinary, hwnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const IWABOBJECT_ = extern struct { pub const VTable = extern struct { QueryInterface: fn( self: *const IWABOBJECT_, riid: ?*const Guid, ppvObj: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddRef: fn( self: *const IWABOBJECT_, ) callconv(@import("std").os.windows.WINAPI) u32, Release: fn( self: *const IWABOBJECT_, ) callconv(@import("std").os.windows.WINAPI) u32, GetLastError: fn( self: *const IWABOBJECT_, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocateBuffer: fn( self: *const IWABOBJECT_, cbSize: u32, lppBuffer: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocateMore: fn( self: *const IWABOBJECT_, cbSize: u32, lpObject: ?*anyopaque, lppBuffer: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FreeBuffer: fn( self: *const IWABOBJECT_, lpBuffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Backup: fn( self: *const IWABOBJECT_, lpFileName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Import: fn( self: *const IWABOBJECT_, lpWIP: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Find: fn( self: *const IWABOBJECT_, lpIAB: ?*IAddrBook, hWnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, VCardDisplay: fn( self: *const IWABOBJECT_, lpIAB: ?*IAddrBook, hWnd: ?HWND, lpszFileName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LDAPUrl: fn( self: *const IWABOBJECT_, lpIAB: ?*IAddrBook, hWnd: ?HWND, ulFlags: u32, lpszURL: ?PSTR, lppMailUser: ?*?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT, VCardCreate: fn( self: *const IWABOBJECT_, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lpMailUser: ?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT, VCardRetrieve: fn( self: *const IWABOBJECT_, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lppMailUser: ?*?*IMailUser, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMe: fn( self: *const IWABOBJECT_, lpIAB: ?*IAddrBook, ulFlags: u32, lpdwAction: ?*u32, lpsbEID: ?*SBinary, hwnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMe: fn( self: *const IWABOBJECT_, lpIAB: ?*IAddrBook, ulFlags: u32, sbEID: SBinary, hwnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__QueryInterface(self: *const T, riid: ?*const Guid, ppvObj: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).QueryInterface(@ptrCast(*const IWABOBJECT_, self), riid, ppvObj); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__AddRef(self: *const T) callconv(.Inline) u32 { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).AddRef(@ptrCast(*const IWABOBJECT_, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__Release(self: *const T) callconv(.Inline) u32 { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).Release(@ptrCast(*const IWABOBJECT_, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__GetLastError(self: *const T, hResult: HRESULT, ulFlags: u32, lppMAPIError: ?*?*MAPIERROR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).GetLastError(@ptrCast(*const IWABOBJECT_, self), hResult, ulFlags, lppMAPIError); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__AllocateBuffer(self: *const T, cbSize: u32, lppBuffer: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).AllocateBuffer(@ptrCast(*const IWABOBJECT_, self), cbSize, lppBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__AllocateMore(self: *const T, cbSize: u32, lpObject: ?*anyopaque, lppBuffer: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).AllocateMore(@ptrCast(*const IWABOBJECT_, self), cbSize, lpObject, lppBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__FreeBuffer(self: *const T, lpBuffer: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).FreeBuffer(@ptrCast(*const IWABOBJECT_, self), lpBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__Backup(self: *const T, lpFileName: ?PSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).Backup(@ptrCast(*const IWABOBJECT_, self), lpFileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__Import(self: *const T, lpWIP: ?PSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).Import(@ptrCast(*const IWABOBJECT_, self), lpWIP); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__Find(self: *const T, lpIAB: ?*IAddrBook, hWnd: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).Find(@ptrCast(*const IWABOBJECT_, self), lpIAB, hWnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__VCardDisplay(self: *const T, lpIAB: ?*IAddrBook, hWnd: ?HWND, lpszFileName: ?PSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).VCardDisplay(@ptrCast(*const IWABOBJECT_, self), lpIAB, hWnd, lpszFileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__LDAPUrl(self: *const T, lpIAB: ?*IAddrBook, hWnd: ?HWND, ulFlags: u32, lpszURL: ?PSTR, lppMailUser: ?*?*IMailUser) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).LDAPUrl(@ptrCast(*const IWABOBJECT_, self), lpIAB, hWnd, ulFlags, lpszURL, lppMailUser); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__VCardCreate(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lpMailUser: ?*IMailUser) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).VCardCreate(@ptrCast(*const IWABOBJECT_, self), lpIAB, ulFlags, lpszVCard, lpMailUser); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__VCardRetrieve(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, lpszVCard: ?PSTR, lppMailUser: ?*?*IMailUser) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).VCardRetrieve(@ptrCast(*const IWABOBJECT_, self), lpIAB, ulFlags, lpszVCard, lppMailUser); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__GetMe(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, lpdwAction: ?*u32, lpsbEID: ?*SBinary, hwnd: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).GetMe(@ptrCast(*const IWABOBJECT_, self), lpIAB, ulFlags, lpdwAction, lpsbEID, hwnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABOBJECT__SetMe(self: *const T, lpIAB: ?*IAddrBook, ulFlags: u32, sbEID: SBinary, hwnd: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IWABOBJECT_.VTable, self.vtable).SetMe(@ptrCast(*const IWABOBJECT_, self), lpIAB, ulFlags, sbEID, hwnd); } };} pub usingnamespace MethodMixin(@This()); }; pub const WAB_PARAM = extern struct { cbSize: u32, hwnd: ?HWND, szFileName: ?PSTR, ulFlags: u32, guidPSExt: Guid, }; pub const LPWABOPEN = fn( lppAdrBook: ?*?*IAddrBook, lppWABObject: ?*?*IWABObject, lpWP: ?*WAB_PARAM, Reserved2: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const LPWABOPENEX = fn( lppAdrBook: ?*?*IAddrBook, lppWABObject: ?*?*IWABObject, lpWP: ?*WAB_PARAM, Reserved: u32, fnAllocateBuffer: ?LPALLOCATEBUFFER, fnAllocateMore: ?LPALLOCATEMORE, fnFreeBuffer: ?LPFREEBUFFER, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const WABIMPORTPARAM = extern struct { cbSize: u32, lpAdrBook: ?*IAddrBook, hWnd: ?HWND, ulFlags: u32, lpszFileName: ?PSTR, }; pub const WABEXTDISPLAY = extern struct { cbSize: u32, lpWABObject: ?*IWABObject, lpAdrBook: ?*IAddrBook, lpPropObj: ?*IMAPIProp, fReadOnly: BOOL, fDataChanged: BOOL, ulFlags: u32, lpv: ?*anyopaque, lpsz: ?*i8, }; // TODO: this type is limited to platform 'windows5.0' const IID_IWABExtInit_Value = @import("../zig.zig").Guid.initString("ea22ebf0-87a4-11d1-9acf-00a0c91f9c8b"); pub const IID_IWABExtInit = &IID_IWABExtInit_Value; pub const IWABExtInit = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IWABExtInit, lpWABExtDisplay: ?*WABEXTDISPLAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWABExtInit_Initialize(self: *const T, lpWABExtDisplay: ?*WABEXTDISPLAY) callconv(.Inline) HRESULT { return @ptrCast(*const IWABExtInit.VTable, self.vtable).Initialize(@ptrCast(*const IWABExtInit, self), lpWABExtDisplay); } };} pub usingnamespace MethodMixin(@This()); }; pub const LPWABALLOCATEBUFFER = fn( lpWABObject: ?*IWABObject, cbSize: u32, lppBuffer: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub const LPWABALLOCATEMORE = fn( lpWABObject: ?*IWABObject, cbSize: u32, lpObject: ?*anyopaque, lppBuffer: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub const LPWABFREEBUFFER = fn( lpWABObject: ?*IWABObject, lpBuffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const NOTIFKEY = extern struct { cb: u32, ab: [1]u8, }; //-------------------------------------------------------------------------------- // Section: Functions (57) //-------------------------------------------------------------------------------- pub extern "rtm" fn CreateTable( lpInterface: ?*Guid, lpAllocateBuffer: ?LPALLOCATEBUFFER, lpAllocateMore: ?LPALLOCATEMORE, lpFreeBuffer: ?LPFREEBUFFER, lpvReserved: ?*anyopaque, ulTableType: u32, ulPropTagIndexColumn: u32, lpSPropTagArrayColumns: ?*SPropTagArray, lppTableData: ?*?*ITableData, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn CreateIProp( lpInterface: ?*Guid, lpAllocateBuffer: ?LPALLOCATEBUFFER, lpAllocateMore: ?LPALLOCATEMORE, lpFreeBuffer: ?LPFREEBUFFER, lpvReserved: ?*anyopaque, lppPropData: ?*?*IPropData, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn MAPIInitIdle( lpvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn MAPIDeinitIdle( ) callconv(@import("std").os.windows.WINAPI) void; pub extern "MAPI32" fn FtgRegisterIdleRoutine( lpfnIdle: ?PFNIDLE, lpvIdleParam: ?*anyopaque, priIdle: i16, csecIdle: u32, iroIdle: u16, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "MAPI32" fn DeregisterIdleRoutine( ftg: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "MAPI32" fn EnableIdleRoutine( ftg: ?*anyopaque, fEnable: BOOL, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "MAPI32" fn ChangeIdleRoutine( ftg: ?*anyopaque, lpfnIdle: ?PFNIDLE, lpvIdleParam: ?*anyopaque, priIdle: i16, csecIdle: u32, iroIdle: u16, ircIdle: u16, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "MAPI32" fn MAPIGetDefaultMalloc( ) callconv(@import("std").os.windows.WINAPI) ?*IMalloc; pub extern "MAPI32" fn OpenStreamOnFile( lpAllocateBuffer: ?LPALLOCATEBUFFER, lpFreeBuffer: ?LPFREEBUFFER, ulFlags: u32, lpszFileName: ?*i8, lpszPrefix: ?*i8, lppStream: ?*?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "MAPI32" fn PropCopyMore( lpSPropValueDest: ?*SPropValue, lpSPropValueSrc: ?*SPropValue, lpfAllocMore: ?LPALLOCATEMORE, lpvObject: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn UlPropSize( lpSPropValue: ?*SPropValue, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "MAPI32" fn FEqualNames( lpName1: ?*MAPINAMEID, lpName2: ?*MAPINAMEID, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "MAPI32" fn FPropContainsProp( lpSPropValueDst: ?*SPropValue, lpSPropValueSrc: ?*SPropValue, ulFuzzyLevel: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "MAPI32" fn FPropCompareProp( lpSPropValue1: ?*SPropValue, ulRelOp: u32, lpSPropValue2: ?*SPropValue, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "MAPI32" fn LPropCompareProp( lpSPropValueA: ?*SPropValue, lpSPropValueB: ?*SPropValue, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn HrAddColumns( lptbl: ?*IMAPITable, lpproptagColumnsNew: ?*SPropTagArray, lpAllocateBuffer: ?LPALLOCATEBUFFER, lpFreeBuffer: ?LPFREEBUFFER, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "MAPI32" fn HrAddColumnsEx( lptbl: ?*IMAPITable, lpproptagColumnsNew: ?*SPropTagArray, lpAllocateBuffer: ?LPALLOCATEBUFFER, lpFreeBuffer: ?LPFREEBUFFER, lpfnFilterColumns: isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "MAPI32" fn HrAllocAdviseSink( lpfnCallback: ?LPNOTIFCALLBACK, lpvContext: ?*anyopaque, lppAdviseSink: ?*?*IMAPIAdviseSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "MAPI32" fn HrThisThreadAdviseSink( lpAdviseSink: ?*IMAPIAdviseSink, lppAdviseSink: ?*?*IMAPIAdviseSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "MAPI32" fn HrDispatchNotifications( ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "MAPI32" fn BuildDisplayTable( lpAllocateBuffer: ?LPALLOCATEBUFFER, lpAllocateMore: ?LPALLOCATEMORE, lpFreeBuffer: ?LPFREEBUFFER, lpMalloc: ?*IMalloc, hInstance: ?HINSTANCE, cPages: u32, lpPage: ?*DTPAGE, ulFlags: u32, lppTable: ?*?*IMAPITable, lppTblData: ?*?*ITableData, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "MAPI32" fn ScCountNotifications( cNotifications: i32, lpNotifications: ?*NOTIFICATION, lpcb: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn ScCopyNotifications( cNotification: i32, lpNotifications: ?*NOTIFICATION, lpvDst: ?*anyopaque, lpcb: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn ScRelocNotifications( cNotification: i32, lpNotifications: ?*NOTIFICATION, lpvBaseOld: ?*anyopaque, lpvBaseNew: ?*anyopaque, lpcb: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn ScCountProps( cValues: i32, lpPropArray: ?*SPropValue, lpcb: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn LpValFindProp( ulPropTag: u32, cValues: u32, lpPropArray: ?*SPropValue, ) callconv(@import("std").os.windows.WINAPI) ?*SPropValue; pub extern "MAPI32" fn ScCopyProps( cValues: i32, lpPropArray: ?*SPropValue, lpvDst: ?*anyopaque, lpcb: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn ScRelocProps( cValues: i32, lpPropArray: ?*SPropValue, lpvBaseOld: ?*anyopaque, lpvBaseNew: ?*anyopaque, lpcb: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn ScDupPropset( cValues: i32, lpPropArray: ?*SPropValue, lpAllocateBuffer: ?LPALLOCATEBUFFER, lppPropArray: ?*?*SPropValue, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn UlAddRef( lpunk: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "MAPI32" fn UlRelease( lpunk: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "MAPI32" fn HrGetOneProp( lpMapiProp: ?*IMAPIProp, ulPropTag: u32, lppProp: ?*?*SPropValue, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "MAPI32" fn HrSetOneProp( lpMapiProp: ?*IMAPIProp, lpProp: ?*SPropValue, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "MAPI32" fn FPropExists( lpMapiProp: ?*IMAPIProp, ulPropTag: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "MAPI32" fn PpropFindProp( lpPropArray: ?*SPropValue, cValues: u32, ulPropTag: u32, ) callconv(@import("std").os.windows.WINAPI) ?*SPropValue; pub extern "MAPI32" fn FreePadrlist( lpAdrlist: ?*ADRLIST, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "MAPI32" fn FreeProws( lpRows: ?*SRowSet, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "MAPI32" fn HrQueryAllRows( lpTable: ?*IMAPITable, lpPropTags: ?*SPropTagArray, lpRestriction: ?*SRestriction, lpSortOrderSet: ?*SSortOrderSet, crowsMax: i32, lppRows: ?*?*SRowSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "MAPI32" fn SzFindCh( lpsz: ?*i8, ch: u16, ) callconv(@import("std").os.windows.WINAPI) ?*i8; pub extern "MAPI32" fn SzFindLastCh( lpsz: ?*i8, ch: u16, ) callconv(@import("std").os.windows.WINAPI) ?*i8; pub extern "MAPI32" fn SzFindSz( lpsz: ?*i8, lpszKey: ?*i8, ) callconv(@import("std").os.windows.WINAPI) ?*i8; pub extern "MAPI32" fn UFromSz( lpsz: ?*i8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "MAPI32" fn ScUNCFromLocalPath( lpszLocal: ?PSTR, lpszUNC: [*:0]u8, cchUNC: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn ScLocalPathFromUNC( lpszUNC: ?PSTR, lpszLocal: [*:0]u8, cchLocal: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn FtAddFt( ftAddend1: FILETIME, ftAddend2: FILETIME, ) callconv(@import("std").os.windows.WINAPI) FILETIME; pub extern "MAPI32" fn FtMulDwDw( ftMultiplicand: u32, ftMultiplier: u32, ) callconv(@import("std").os.windows.WINAPI) FILETIME; pub extern "MAPI32" fn FtMulDw( ftMultiplier: u32, ftMultiplicand: FILETIME, ) callconv(@import("std").os.windows.WINAPI) FILETIME; pub extern "MAPI32" fn FtSubFt( ftMinuend: FILETIME, ftSubtrahend: FILETIME, ) callconv(@import("std").os.windows.WINAPI) FILETIME; pub extern "MAPI32" fn FtNegFt( ft: FILETIME, ) callconv(@import("std").os.windows.WINAPI) FILETIME; pub extern "MAPI32" fn ScCreateConversationIndex( cbParent: u32, lpbParent: ?*u8, lpcbConvIndex: ?*u32, lppbConvIndex: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn WrapStoreEntryID( ulFlags: u32, lpszDLLName: ?*i8, cbOrigEntry: u32, // TODO: what to do with BytesParamIndex 2? lpOrigEntry: ?*ENTRYID, lpcbWrappedEntry: ?*u32, // TODO: what to do with BytesParamIndex 4? lppWrappedEntry: ?*?*ENTRYID, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "MAPI32" fn RTFSync( lpMessage: ?*IMessage, ulFlags: u32, lpfMessageUpdated: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "MAPI32" fn WrapCompressedRTFStream( lpCompressedRTFStream: ?*IStream, ulFlags: u32, lpUncompressedRTFStream: ?*?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "MAPI32" fn HrIStorageFromStream( lpUnkIn: ?*IUnknown, lpInterface: ?*Guid, ulFlags: u32, lppStorageOut: ?*?*IStorage, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "MAPI32" fn ScInitMapiUtil( ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "MAPI32" fn DeinitMapiUtil( ) callconv(@import("std").os.windows.WINAPI) void; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (14) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const CY = @import("../system/com.zig").CY; const FILETIME = @import("../foundation.zig").FILETIME; const HINSTANCE = @import("../foundation.zig").HINSTANCE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IMalloc = @import("../system/com.zig").IMalloc; const IStorage = @import("../system/com/structured_storage.zig").IStorage; const IStream = @import("../system/com.zig").IStream; const IUnknown = @import("../system/com.zig").IUnknown; const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "LPALLOCATEBUFFER")) { _ = LPALLOCATEBUFFER; } if (@hasDecl(@This(), "LPALLOCATEMORE")) { _ = LPALLOCATEMORE; } if (@hasDecl(@This(), "LPFREEBUFFER")) { _ = LPFREEBUFFER; } if (@hasDecl(@This(), "LPNOTIFCALLBACK")) { _ = LPNOTIFCALLBACK; } if (@hasDecl(@This(), "LPFNABSDI")) { _ = LPFNABSDI; } if (@hasDecl(@This(), "LPFNDISMISS")) { _ = LPFNDISMISS; } if (@hasDecl(@This(), "LPFNBUTTON")) { _ = LPFNBUTTON; } if (@hasDecl(@This(), "CALLERRELEASE")) { _ = CALLERRELEASE; } if (@hasDecl(@This(), "FNIDLE")) { _ = FNIDLE; } if (@hasDecl(@This(), "PFNIDLE")) { _ = PFNIDLE; } if (@hasDecl(@This(), "LPOPENSTREAMONFILE")) { _ = LPOPENSTREAMONFILE; } if (@hasDecl(@This(), "LPDISPATCHNOTIFICATIONS")) { _ = LPDISPATCHNOTIFICATIONS; } if (@hasDecl(@This(), "LPCREATECONVERSATIONINDEX")) { _ = LPCREATECONVERSATIONINDEX; } if (@hasDecl(@This(), "IWABOBJECT_QueryInterface_METHOD")) { _ = IWABOBJECT_QueryInterface_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_AddRef_METHOD")) { _ = IWABOBJECT_AddRef_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_Release_METHOD")) { _ = IWABOBJECT_Release_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_GetLastError_METHOD")) { _ = IWABOBJECT_GetLastError_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_AllocateBuffer_METHOD")) { _ = IWABOBJECT_AllocateBuffer_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_AllocateMore_METHOD")) { _ = IWABOBJECT_AllocateMore_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_FreeBuffer_METHOD")) { _ = IWABOBJECT_FreeBuffer_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_Backup_METHOD")) { _ = IWABOBJECT_Backup_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_Import_METHOD")) { _ = IWABOBJECT_Import_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_Find_METHOD")) { _ = IWABOBJECT_Find_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_VCardDisplay_METHOD")) { _ = IWABOBJECT_VCardDisplay_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_LDAPUrl_METHOD")) { _ = IWABOBJECT_LDAPUrl_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_VCardCreate_METHOD")) { _ = IWABOBJECT_VCardCreate_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_VCardRetrieve_METHOD")) { _ = IWABOBJECT_VCardRetrieve_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_GetMe_METHOD")) { _ = IWABOBJECT_GetMe_METHOD; } if (@hasDecl(@This(), "IWABOBJECT_SetMe_METHOD")) { _ = IWABOBJECT_SetMe_METHOD; } if (@hasDecl(@This(), "LPWABOPEN")) { _ = LPWABOPEN; } if (@hasDecl(@This(), "LPWABOPENEX")) { _ = LPWABOPENEX; } if (@hasDecl(@This(), "LPWABALLOCATEBUFFER")) { _ = LPWABALLOCATEBUFFER; } if (@hasDecl(@This(), "LPWABALLOCATEMORE")) { _ = LPWABALLOCATEMORE; } if (@hasDecl(@This(), "LPWABFREEBUFFER")) { _ = LPWABFREEBUFFER; } @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/address_book.zig
const std = @import("std"); const print = std.debug.print; const assert = std.debug.assert; const gnss = @import("gnss.zig"); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const c = @cImport({ @cInclude("libexif/exif-data.h"); }); pub extern "c" fn free(?*c_void) void; const bounded_array = @import("bounded_array.zig"); const MAX_SIZE: usize = 1024; pub const APP0_HEADER = [_]u8{ 0xFF, 0xE0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00 }; pub const MARK_APP1 = [_]u8{ 0xFF, 0xE1 }; pub const image_offset: usize = 20; // offset of image in JPEG buffer fn exif_create_tag(arg_exif: [*c]c.ExifData, arg_ifd: c.ExifIfd, arg_tag: c.ExifTag) callconv(.C) [*c]c.ExifEntry { var exif = arg_exif; var ifd = @intCast(usize, @enumToInt(arg_ifd)); var tag = arg_tag; var entry = c.exif_content_get_entry(exif.*.ifd[ifd], tag); if (entry == null) { // Tag does not exist, so we have to create one entry = c.exif_entry_new(); if (entry == null) { std.log.err("EXIF | failed to allocate exif memory", .{}); return null; } // tag must be set before calling exif_content_add_entry entry.*.tag = tag; // Attach the ExifEntry to an IFD c.exif_content_add_entry(exif.*.ifd[ifd], entry); // Allocate memory for the entry and fill with default data c.exif_entry_initialize(entry, tag); // Ownership of the ExifEntry has now been passed to the IFD. c.exif_entry_unref(entry); } return entry; } fn exif_rational(numerator: c.ExifLong, denominator: c.ExifLong) c.ExifRational { return c.ExifRational{ .numerator = numerator, .denominator = denominator }; } fn exif_set_latitude_or_longitude(entry: [*c]c.ExifEntry, byte_order: c.ExifByteOrder, value: f64) void { const arcfrac = 1000000; const degrees = @floatToInt(c.ExifLong, @fabs(value)); const remainder = 60.0 * (@fabs(value) - @intToFloat(f64, degrees)); const minutes = @floatToInt(c.ExifLong, remainder); const seconds = @floatToInt(c.ExifLong, 60.0 * (remainder - @intToFloat(f64, minutes)) * arcfrac); c.exif_set_rational(entry.*.data, byte_order, exif_rational(degrees, 1)); c.exif_set_rational(entry.*.data + 1 * @sizeOf(c.ExifRational), byte_order, exif_rational(minutes, 1)); c.exif_set_rational(entry.*.data + 2 * @sizeOf(c.ExifRational), byte_order, exif_rational(seconds, arcfrac)); } fn exif_set_string(entry: [*c]c.ExifEntry, s: []const u8) void { if (entry.*.data != null) { free(@ptrCast(*c_void, entry.*.data)); } entry.*.size = s.len; entry.*.components = s.len; var cstr = std.cstr.addNullByte(&gpa.allocator, s) catch |err| { std.log.err("EXIF | failed to terminate exif string : {any}", .{err}); return; }; entry.*.data = @ptrCast([*c]u8, cstr); if (entry.*.data == null) { std.log.err("EXIF | failed to copy exif string", .{}); } entry.*.format = c.ExifFormat.EXIF_FORMAT_ASCII; } pub const Exif = struct { image_x: usize = 0, image_y: usize = 0, gnss_nav_pvt: ?gnss.NAV_PVT = null, byte_order: c.ExifByteOrder = c.ExifByteOrder.EXIF_BYTE_ORDER_MOTOROLA, pub fn set_gnss(self: *Exif, nav_pvt: gnss.NAV_PVT) void { self.gnss_nav_pvt = nav_pvt; } pub fn bytes(self: *Exif) ?bounded_array.BoundedArray(u8, MAX_SIZE) { var exif: [*c]c.ExifData = c.exif_data_new(); var entry: [*c]c.ExifEntry = undefined; var exif_data: []u8 = undefined; var exif_len: usize = 0; const ifd_exif = c.ExifIfd.EXIF_IFD_EXIF; const ifd_gps = c.ExifIfd.EXIF_IFD_GPS; // Create the mandatory EXIF fields with default data c.exif_data_fix(exif); c.exif_data_set_byte_order(exif, self.byte_order); if (self.image_x != 0) { entry = exif_create_tag(exif, c.ExifIfd.EXIF_IFD_EXIF, c.ExifTag.EXIF_TAG_PIXEL_X_DIMENSION); c.exif_set_long(entry.*.data, self.byte_order, self.image_x); } if (self.image_y != 0) { entry = exif_create_tag(exif, c.ExifIfd.EXIF_IFD_EXIF, c.ExifTag.EXIF_TAG_PIXEL_Y_DIMENSION); c.exif_set_long(entry.*.data, self.byte_order, self.image_y); } // entry = exif_create_tag(exif, ifd, c.ExifTag.EXIF_TAG_MAKE); // exif_set_string(entry, ""); entry = exif_create_tag(exif, ifd_exif, c.ExifTag.EXIF_TAG_MODEL); exif_set_string(entry, "Open Dashcam"); // entry = exif_create_tag(exif, ifd, c.ExifTag.EXIF_TAG_SOFTWARE); // exif_set_string(entry, ""); entry = exif_create_tag(exif, ifd_exif, c.ExifTag.EXIF_TAG_COLOR_SPACE); c.exif_set_short(entry.*.data, self.byte_order, 1); entry = exif_create_tag(exif, ifd_exif, c.ExifTag.EXIF_TAG_COMPRESSION); c.exif_set_short(entry.*.data, self.byte_order, 6); // Embed GNSS data if it has been set if (self.gnss_nav_pvt) |nav_pvt| { // EXIF_TAG_GPS_LATITUDE_REF and EXIF_TAG_INTEROPERABILITY_INDEX both have the value : 0x0001 entry = exif_create_tag(exif, ifd_gps, @ptrCast(c.ExifTag, c.ExifTag.EXIF_TAG_INTEROPERABILITY_INDEX)); if (nav_pvt.latitude > 0) { exif_set_string(entry, "N"); } else { exif_set_string(entry, "S"); } // EXIF_TAG_GPS_LATITUDE and EXIF_TAG_INTEROPERABILITY_VERSION both have the value : 0x0002 entry = exif_create_tag(exif, ifd_gps, @ptrCast(c.ExifTag, c.ExifTag.EXIF_TAG_INTEROPERABILITY_VERSION)); exif_set_latitude_or_longitude(entry, self.byte_order, nav_pvt.latitude); entry = exif_create_tag(exif, ifd_gps, @ptrCast(c.ExifTag, c.ExifTag.EXIF_TAG_GPS_LONGITUDE_REF)); if (nav_pvt.longitude > 0) { exif_set_string(entry, "E"); } else { exif_set_string(entry, "W"); } entry = exif_create_tag(exif, ifd_gps, @ptrCast(c.ExifTag, c.ExifTag.EXIF_TAG_GPS_LONGITUDE)); exif_set_latitude_or_longitude(entry, self.byte_order, nav_pvt.longitude); entry = exif_create_tag(exif, ifd_gps, @ptrCast(c.ExifTag, c.ExifTag.EXIF_TAG_GPS_ALTITUDE_REF)); if (nav_pvt.height > 0) { c.exif_set_short(entry.*.data, self.byte_order, 0); } else { c.exif_set_short(entry.*.data, self.byte_order, 1); } entry = exif_create_tag(exif, ifd_gps, @ptrCast(c.ExifTag, c.ExifTag.EXIF_TAG_GPS_ALTITUDE)); c.exif_set_rational(entry.*.data, self.byte_order, exif_rational(@floatToInt(c.ExifLong, @fabs(nav_pvt.height) * 1000), 1000)); entry = exif_create_tag(exif, ifd_gps, @ptrCast(c.ExifTag, c.ExifTag.EXIF_TAG_GPS_SATELLITES)); var satellite_count: [2]u8 = undefined; _ = std.fmt.bufPrint(&satellite_count, "{d}", .{nav_pvt.satellite_count}) catch unreachable; exif_set_string(entry, satellite_count[0..]); var datestamp: [10]u8 = undefined; _ = std.fmt.bufPrint(&datestamp, "{d:0>4}:{d:0>2}:{d:0>2}", .{ nav_pvt.time.year, nav_pvt.time.month, nav_pvt.time.day }) catch unreachable; entry = exif_create_tag(exif, ifd_gps, @ptrCast(c.ExifTag, c.ExifTag.EXIF_TAG_GPS_DATE_STAMP)); exif_set_string(entry, datestamp[0..]); // Care taken here to round nanoseconds correctly, so that 27.499656311 rounds to 27.50 (scaled with rational denominator of course) const second_scale: u8 = 100; const second_fraction = @floatToInt(i32, @round(@intToFloat(f64, nav_pvt.time.nanosecond) * @intToFloat(f64, second_scale) * 1e-9)); const second_value = @as(i32, nav_pvt.time.second) * second_scale + second_fraction; entry = exif_create_tag(exif, ifd_gps, @ptrCast(c.ExifTag, c.ExifTag.EXIF_TAG_GPS_TIME_STAMP)); c.exif_set_rational(entry.*.data, self.byte_order, exif_rational(nav_pvt.time.hour, 1)); c.exif_set_rational(entry.*.data + 1 * @sizeOf(c.ExifRational), self.byte_order, exif_rational(nav_pvt.time.minute, 1)); c.exif_set_rational(entry.*.data + 2 * @sizeOf(c.ExifRational), self.byte_order, exif_rational(@intCast(u32, second_value), second_scale)); entry = exif_create_tag(exif, ifd_gps, @ptrCast(c.ExifTag, c.ExifTag.EXIF_TAG_GPS_SPEED_REF)); exif_set_string(entry, "K"); // GNSS module provide speed in m/s, this converts it to km / hour (the reference noted above) const speed_scale: u8 = 100; entry = exif_create_tag(exif, ifd_gps, @ptrCast(c.ExifTag, c.ExifTag.EXIF_TAG_GPS_SPEED)); c.exif_set_rational(entry.*.data, self.byte_order, exif_rational(@floatToInt(u32, @round(nav_pvt.speed * 3.6 * @intToFloat(f32, speed_scale))), speed_scale)); const track_scale: u8 = 100; entry = exif_create_tag(exif, ifd_gps, @ptrCast(c.ExifTag, c.ExifTag.EXIF_TAG_GPS_TRACK)); c.exif_set_rational(entry.*.data, self.byte_order, exif_rational(@floatToInt(u32, @round(nav_pvt.heading * @intToFloat(f32, track_scale))), track_scale)); } // Get a pointer to the EXIF data block we just created c.exif_data_save_data(exif, @ptrCast([*][*c]u8, &exif_data), &exif_len); // std.log.info("EXIF | exif_data {any}", .{exif_data[0..exif_len]}); var output = bounded_array.BoundedArray(u8, MAX_SIZE).fromSlice(exif_data[0..exif_len]) catch |err| { std.log.err("EXIF | could not created BoundedArray : {}", .{err}); return null; }; std.c.free(@ptrCast(*c_void, exif_data)); std.c.free(@ptrCast(*c_void, exif)); return output; } }; pub fn init() Exif { return Exif{}; }
src/exif.zig
const __extenddftf2 = @import("extendXfYf2.zig").__extenddftf2; const __extendhfsf2 = @import("extendXfYf2.zig").__extendhfsf2; const __extendsftf2 = @import("extendXfYf2.zig").__extendsftf2; const assert = @import("std").debug.assert; fn test__extenddftf2(a: f64, expectedHi: u64, expectedLo: u64) void { const x = __extenddftf2(a); const rep = @bitCast(u128, x); const hi = @intCast(u64, rep >> 64); const lo = @truncate(u64, rep); if (hi == expectedHi and lo == expectedLo) return; // test other possible NaN representation(signal NaN) if (expectedHi == 0x7fff800000000000 and expectedLo == 0x0) { if ((hi & 0x7fff000000000000) == 0x7fff000000000000 and ((hi & 0xffffffffffff) > 0 or lo > 0)) { return; } } @panic("__extenddftf2 test failure"); } fn test__extendhfsf2(a: u16, expected: u32) void { const x = __extendhfsf2(a); const rep = @bitCast(u32, x); if (rep == expected) { if (rep & 0x7fffffff > 0x7f800000) { return; // NaN is always unequal. } if (x == @bitCast(f32, expected)) { return; } } @panic("__extendhfsf2 test failure"); } fn test__extendsftf2(a: f32, expectedHi: u64, expectedLo: u64) void { const x = __extendsftf2(a); const rep = @bitCast(u128, x); const hi = @intCast(u64, rep >> 64); const lo = @truncate(u64, rep); if (hi == expectedHi and lo == expectedLo) return; // test other possible NaN representation(signal NaN) if (expectedHi == 0x7fff800000000000 and expectedLo == 0x0) { if ((hi & 0x7fff000000000000) == 0x7fff000000000000 and ((hi & 0xffffffffffff) > 0 or lo > 0)) { return; } } @panic("__extendsftf2 test failure"); } test "extenddftf2" { // qNaN test__extenddftf2(makeQNaN64(), 0x7fff800000000000, 0x0); // NaN test__extenddftf2(makeNaN64(0x7100000000000), 0x7fff710000000000, 0x0); // inf test__extenddftf2(makeInf64(), 0x7fff000000000000, 0x0); // zero test__extenddftf2(0.0, 0x0, 0x0); test__extenddftf2(0x1.23456789abcdefp+5, 0x400423456789abcd, 0xf000000000000000); test__extenddftf2(0x1.edcba987654321fp-9, 0x3ff6edcba9876543, 0x2000000000000000); test__extenddftf2(0x1.23456789abcdefp+45, 0x402c23456789abcd, 0xf000000000000000); test__extenddftf2(0x1.edcba987654321fp-45, 0x3fd2edcba9876543, 0x2000000000000000); } test "extendhfsf2" { test__extendhfsf2(0x7e00, 0x7fc00000); // qNaN test__extendhfsf2(0x7f00, 0x7fe00000); // sNaN test__extendhfsf2(0x7c01, 0x7f802000); // sNaN test__extendhfsf2(0, 0); // 0 test__extendhfsf2(0x8000, 0x80000000); // -0 test__extendhfsf2(0x7c00, 0x7f800000); // inf test__extendhfsf2(0xfc00, 0xff800000); // -inf test__extendhfsf2(0x0001, 0x33800000); // denormal (min), 2**-24 test__extendhfsf2(0x8001, 0xb3800000); // denormal (min), -2**-24 test__extendhfsf2(0x03ff, 0x387fc000); // denormal (max), 2**-14 - 2**-24 test__extendhfsf2(0x83ff, 0xb87fc000); // denormal (max), -2**-14 + 2**-24 test__extendhfsf2(0x0400, 0x38800000); // normal (min), 2**-14 test__extendhfsf2(0x8400, 0xb8800000); // normal (min), -2**-14 test__extendhfsf2(0x7bff, 0x477fe000); // normal (max), 65504 test__extendhfsf2(0xfbff, 0xc77fe000); // normal (max), -65504 test__extendhfsf2(0x3c01, 0x3f802000); // normal, 1 + 2**-10 test__extendhfsf2(0xbc01, 0xbf802000); // normal, -1 - 2**-10 test__extendhfsf2(0x3555, 0x3eaaa000); // normal, approx. 1/3 test__extendhfsf2(0xb555, 0xbeaaa000); // normal, approx. -1/3 } test "extendsftf2" { // qNaN test__extendsftf2(makeQNaN32(), 0x7fff800000000000, 0x0); // NaN test__extendsftf2(makeNaN32(0x410000), 0x7fff820000000000, 0x0); // inf test__extendsftf2(makeInf32(), 0x7fff000000000000, 0x0); // zero test__extendsftf2(0.0, 0x0, 0x0); test__extendsftf2(0x1.23456p+5, 0x4004234560000000, 0x0); test__extendsftf2(0x1.edcbap-9, 0x3ff6edcba0000000, 0x0); test__extendsftf2(0x1.23456p+45, 0x402c234560000000, 0x0); test__extendsftf2(0x1.edcbap-45, 0x3fd2edcba0000000, 0x0); } fn makeQNaN64() f64 { return @bitCast(f64, u64(0x7ff8000000000000)); } fn makeInf64() f64 { return @bitCast(f64, u64(0x7ff0000000000000)); } fn makeNaN64(rand: u64) f64 { return @bitCast(f64, 0x7ff0000000000000 | (rand & 0xfffffffffffff)); } fn makeQNaN32() f32 { return @bitCast(f32, u32(0x7fc00000)); } fn makeNaN32(rand: u32) f32 { return @bitCast(f32, 0x7f800000 | (rand & 0x7fffff)); } fn makeInf32() f32 { return @bitCast(f32, u32(0x7f800000)); }
std/special/compiler_rt/extendXfYf2_test.zig
const Gdt = @import("global_descriptor_table.zig").GlobalDescriptorTable; const Port = @import("port.zig").X86Port; // temporary. const Video = @import("video_buffer.zig"); // //////////////////////////////////////////////////////////////////// // TYPES /// type of interrupt id. pub const int_t = u8; /// type of the extended stack pointer. pub const esp_t = u32; // gate type, privilege, and exists flags. const gate_type_t = u5; const gate_priv_t = u2; const gate_exists_t = u1; /// handles interrupts. is passed the byte corresponding /// to the interrupt id and stack pointer. export fn handle_interrupt(int: int_t, esp: esp_t) esp_t { Video.print("INTERRUPT"); return esp; } // ///////////////////////////////////////////////////////////////////// // Gate Descriptor functions // these are bindings that happen externally, and we need to be able // to address these to populate the IDT. extern fn ignore_irq() void; extern fn handle_irq0x00() void; extern fn handle_irq0x01() void; const gate_func_t = *const fn() callconv(.C) void; // ///////////////////////////////////////////////////////////////////// // Gate DESCRIPTOR structure and array const GateDescriptor = packed struct { addr_lo: u16, // address, low bytes gdt_css: Gdt.off_t, // code segment selector _reserved: u8 = 0, gate_type: gate_type_t, gate_priv: gate_type_t, exists: gate_exists_t, addr_hi: u16, // address, high bytes }; export var gates: [256]GateDescriptor = undefined; const IDT_INTERRUPT_GATE = 0xE; const IRQ_BASE = 0x20; // programmable interrupt controller ports. const PIC_PRIMARY_CMD = 0x20; const PIC_PRIMARY_DATA = 0x21; const PIC_SECONDARY_CMD = 0xA0; const PIC_SECONDARY_DATA = 0xA1; const PIC_CMD_SET_OFFSET = 0x11; const PIC_PRIMARY_INT_OFFSET = 0x20; const PIC_SECONDARY_INT_OFFSET = 0x28; const PIC_SET_PRIMARY = 0x04; const PIC_SET_SECONDARY = 0x02; // ///////////////////////////////////////////////////////////////////// // IDT structure pub const InterruptDescriptorTable = packed struct { size: u16, addr: u32, pub fn init(gdt: *const Gdt) void { var cs_offset = gdt.cs_offset(); var idx: int_t = 0; // set up all gates with preliminary trapping functions. while (idx < 255) { init_gate(idx, cs_offset, &ignore_irq, 0, IDT_INTERRUPT_GATE); idx = idx + 1; } // manually set 255 init_gate(255, cs_offset, &ignore_irq, 0, IDT_INTERRUPT_GATE); init_gate(0x00 + IRQ_BASE, cs_offset, &handle_irq0x00, 0, IDT_INTERRUPT_GATE); init_gate(0x01 + IRQ_BASE, cs_offset, &handle_irq0x01, 0, IDT_INTERRUPT_GATE); // program the PICs. Port.write_slow(u8, PIC_PRIMARY_CMD, PIC_CMD_SET_OFFSET); Port.write_slow(u8, PIC_PRIMARY_DATA, PIC_PRIMARY_INT_OFFSET); Port.write_slow(u8, PIC_SECONDARY_CMD, PIC_CMD_SET_OFFSET); Port.write_slow(u8, PIC_SECONDARY_DATA, PIC_SECONDARY_INT_OFFSET); Port.write_slow(u8, PIC_PRIMARY_DATA, PIC_SET_PRIMARY); Port.write_slow(u8, PIC_SECONDARY_DATA, PIC_SET_SECONDARY); // flush commands Port.write_slow(u8, PIC_PRIMARY_DATA, 0x01); Port.write_slow(u8, PIC_SECONDARY_DATA, 0x01); Port.write_slow(u8, PIC_PRIMARY_DATA, 0x00); Port.write_slow(u8, PIC_SECONDARY_DATA, 0x00); var idt = InterruptDescriptorTable{ .size = 256 * @sizeOf(GateDescriptor) - 1, .addr = @intCast(u32, @ptrToInt(&gates[0])), }; load_idt(&idt); } pub fn activate() void { // TODO: understand why setting sti fails? asm volatile("sti"); } fn init_gate( entry: int_t, cs_offset: Gdt.off_t, gate_func: gate_func_t, gate_priv: gate_priv_t, gate_type: gate_type_t) void { var gate_addr = @intCast(u32, @ptrToInt(gate_func)); gates[entry].addr_lo = @intCast(u16, gate_addr & 0x0000_FFFF); gates[entry].addr_hi = @intCast(u16, gate_addr >> 16); gates[entry].gdt_css = cs_offset; gates[entry].gate_type = gate_type; gates[entry].gate_priv = gate_priv; gates[entry].exists = 1; } fn load_idt(idt_ptr: *const InterruptDescriptorTable) void { asm volatile("lidt (%%eax)" : : [idt_ptr] "{eax}" (idt_ptr)); } };
kernel/interrupts.zig
const std = @import("std"); const testing = std.testing; const log = std.log.scoped(.tzif); pub const TimeZone = struct { allocator: *std.mem.Allocator, version: Version, transitionTimes: []i64, transitionTypes: []u8, localTimeTypes: []LocalTimeType, designations: []u8, leapSeconds: []LeapSecond, transitionIsStd: []bool, transitionIsUT: []bool, string: []u8, posixTZ: ?PosixTZ, pub fn deinit(this: @This()) void { this.allocator.free(this.transitionTimes); this.allocator.free(this.transitionTypes); this.allocator.free(this.localTimeTypes); this.allocator.free(this.designations); this.allocator.free(this.leapSeconds); this.allocator.free(this.transitionIsStd); this.allocator.free(this.transitionIsUT); this.allocator.free(this.string); } fn findTransitionTime(this: @This(), utc: i64) ?usize { var left: usize = 0; var right: usize = this.transitionTimes.len; while (left < right) { // Avoid overflowing in the midpoint calculation const mid = left + (right - left) / 2; // Compare the key with the midpoint element if (this.transitionTimes[mid] == utc) { if (mid + 1 < this.transitionTimes.len) { return mid; } else { return null; } } else if (this.transitionTimes[mid] > utc) { right = mid; } else if (this.transitionTimes[mid] < utc) { left = mid + 1; } } if (right == this.transitionTimes.len) { return null; } else if (right > 0) { return right - 1; } else { return 0; } } pub const ConversionResult = struct { timestamp: i64, offset: i32, dst: bool, designation: []const u8, }; pub fn localTimeFromUTC(this: @This(), utc: i64) ?ConversionResult { if (this.findTransitionTime(utc)) |idx| { const transition_type = this.transitionTypes[idx]; const local_time_type = this.localTimeTypes[transition_type]; var designation = this.designations[local_time_type.idx .. this.designations.len - 1]; for (designation) |c, i| { if (c == 0) { designation = designation[0..i]; break; } } return ConversionResult{ .timestamp = utc + local_time_type.utoff, .offset = local_time_type.utoff, .dst = local_time_type.dst, .designation = designation, }; } else if (this.posixTZ) |posixTZ| { // Base offset on the TZ string const offset_res = posixTZ.offset(utc); return ConversionResult{ .timestamp = utc - offset_res.offset, .offset = offset_res.offset, .dst = offset_res.dst, .designation = offset_res.designation, }; } else { return null; } } }; pub const Version = enum(u8) { V1 = 0, V2 = '2', V3 = '3', pub fn timeSize(this: @This()) u32 { return switch (this) { .V1 => 4, .V2, .V3 => 8, }; } pub fn leapSize(this: @This()) u32 { return this.timeSize() + 4; } pub fn string(this: @This()) []const u8 { return switch (this) { .V1 => "1", .V2 => "2", .V3 => "3", }; } }; pub const LocalTimeType = struct { utoff: i32, /// Indicates whether this local time is Daylight Saving Time dst: bool, idx: u8, }; pub const LeapSecond = struct { occur: i64, corr: i32, }; /// This is based on Posix definition of the TZ environment variable pub const PosixTZ = struct { std: []const u8, std_offset: i32, dst: ?[]const u8 = null, /// This field is ignored when dst is null dst_offset: i32 = 0, dst_range: ?struct { start: Rule, end: Rule, } = null, pub const Rule = union(enum) { JulianDay: struct { /// 1 <= day <= 365. Leap days are not counted and are impossible to refer to /// 0 <= day <= 365. Leap days are counted, and can be referred to. oneBased: bool, day: u16, time: i32, }, MonthWeekDay: struct { /// 1 <= m <= 12 m: u8, /// 1 <= n <= 5 n: u8, /// 0 <= n <= 6 d: u8, time: i32, }, pub fn toSecs(this: @This(), year: i32) i64 { var is_leap: bool = undefined; var t = year_to_secs(year, &is_leap); switch (this) { .JulianDay => |j| { var x: i64 = j.day; if (j.oneBased and (x < 60 or !is_leap)) x -= 1; t += std.time.s_per_day * x; t += j.time; }, .MonthWeekDay => |mwd| { t += month_to_secs(mwd.m - 1, is_leap); const wday = @divFloor(@mod((t + 4 * std.time.s_per_day), (7 * std.time.s_per_day)), std.time.s_per_day); var days = mwd.d - wday; if (days < 0) days += 7; var n = mwd.n; if (mwd.n == 5 and days + 28 >= days_in_month(mwd.m, is_leap)) n = 4; t += std.time.s_per_day * (days + 7 * (n - 1)); t += mwd.time; }, } return t; } }; pub const OffsetResult = struct { offset: i32, designation: []const u8, dst: bool, }; pub fn offset(this: @This(), utc: i64) OffsetResult { if (this.dst == null) { std.debug.assert(this.dst_range == null); return .{ .offset = this.std_offset, .designation = this.std, .dst = false }; } if (this.dst_range) |range| { const utc_year = secs_to_year(utc); const start_dst = range.start.toSecs(utc_year); const end_dst = range.end.toSecs(utc_year); if (start_dst < end_dst) { if (utc >= start_dst and utc < end_dst) { return .{ .offset = this.dst_offset, .designation = this.dst.?, .dst = true }; } else { return .{ .offset = this.std_offset, .designation = this.std, .dst = false }; } } else { if (utc >= end_dst and utc < start_dst) { return .{ .offset = this.dst_offset, .designation = this.dst.?, .dst = true }; } else { return .{ .offset = this.std_offset, .designation = this.std, .dst = false }; } } } else { return .{ .offset = this.std_offset, .designation = this.std, .dst = false }; } } }; fn days_in_month(m: u8, is_leap: bool) i32 { if (m == 2) { return 28 + @as(i32, @boolToInt(is_leap)); } else { return 30 + ((@as(i32, 0xad5) >> @intCast(u5, m - 1)) & 1); } } fn month_to_secs(m: u8, is_leap: bool) i32 { const d = std.time.s_per_day; const secs_though_month = [12]i32{ 0 * d, 31 * d, 59 * d, 90 * d, 120 * d, 151 * d, 181 * d, 212 * d, 243 * d, 273 * d, 304 * d, 334 * d, }; var t = secs_though_month[m]; if (is_leap and m >= 2) t += d; return t; } fn secs_to_year(secs: i64) i32 { // Copied from MUSL // TODO: make more efficient? var _is_leap: bool = undefined; var y = @intCast(i32, @divFloor(secs, 31556952) + 70); while (year_to_secs(y, &_is_leap) > secs) y -= 1; while (year_to_secs(y + 1, &_is_leap) < secs) y += 1; return y; } fn year_to_secs(year: i32, is_leap: *bool) i64 { if (year - 2 <= 136) { const y = year; var leaps = (y - 68) >> 2; if (((y - 68) & 3) != 0) { leaps -= 1; is_leap.* = true; } else is_leap.* = false; return 31536000 * (y - 70) + std.time.s_per_day * leaps; } is_leap.* = false; var centuries: i64 = undefined; var leaps: i64 = undefined; var cycles = @divFloor((year - 100), 400); var rem = @mod((year - 100), 400); if (rem < 0) { cycles -= 1; rem += 400; } if (rem != 0) { is_leap.* = true; centuries = 0; leaps = 0; } else { if (rem >= 200) { if (rem >= 300) { centuries = 3; rem -= 300; } else { centuries = 2; rem -= 200; } } else { if (rem >= 100) { centuries = 1; rem -= 100; } else { centuries = 0; } } if (rem != 0) { is_leap.* = false; leaps = 0; } else { leaps = @divFloor(rem, 4); rem = @mod(rem, 4); is_leap.* = rem != 0; } } leaps += 97 * cycles + 24 * centuries - @boolToInt(is_leap.*); return (year - 100) * 31536000 + leaps * std.time.s_per_day + 946684800 + std.time.s_per_day; } const TIME_TYPE_SIZE = 6; pub const TZifHeader = struct { version: Version, isutcnt: u32, isstdcnt: u32, leapcnt: u32, timecnt: u32, typecnt: u32, charcnt: u32, pub fn dataSize(this: @This(), dataBlockVersion: Version) u32 { return this.timecnt * dataBlockVersion.timeSize() + this.timecnt + this.typecnt * TIME_TYPE_SIZE + this.charcnt + this.leapcnt * dataBlockVersion.leapSize() + this.isstdcnt + this.isutcnt; } }; pub fn parseHeader(reader: anytype, seekableStream: anytype) !TZifHeader { var magic_buf: [4]u8 = undefined; try reader.readNoEof(&magic_buf); if (!std.mem.eql(u8, "TZif", &magic_buf)) { log.warn("File is missing magic string 'TZif'", .{}); return error.InvalidFormat; } // Check verison const version = reader.readEnum(Version, .Little) catch |err| switch (err) { error.InvalidValue => return error.UnsupportedVersion, else => |e| return e, }; if (version == .V1) { return error.UnsupportedVersion; } // Seek past reserved bytes try seekableStream.seekBy(15); return TZifHeader{ .version = version, .isutcnt = try reader.readInt(u32, .Big), .isstdcnt = try reader.readInt(u32, .Big), .leapcnt = try reader.readInt(u32, .Big), .timecnt = try reader.readInt(u32, .Big), .typecnt = try reader.readInt(u32, .Big), .charcnt = try reader.readInt(u32, .Big), }; } fn hhmmss_offset_to_s(_string: []const u8, idx: *usize) !i32 { var string = _string; var sign: i2 = 1; if (string[0] == '+') { sign = 1; string = string[1..]; idx.* += 1; } else if (string[0] == '-') { sign = -1; string = string[1..]; idx.* += 1; } for (string) |c, i| { if (!(std.ascii.isDigit(c) or c == ':')) { string = string[0..i]; break; } idx.* += 1; } var result: i32 = 0; var segment_iter = std.mem.split(u8, string, ":"); const hour_string = segment_iter.next() orelse return error.EmptyString; const hours = try std.fmt.parseInt(u32, hour_string, 10); if (hours > 167) { log.warn("too many hours! {}", .{hours}); return error.InvalidFormat; } result += std.time.s_per_hour * @intCast(i32, hours); if (segment_iter.next()) |minute_string| { const minutes = try std.fmt.parseInt(u32, minute_string, 10); if (minutes > 59) return error.InvalidFormat; result += std.time.s_per_min * @intCast(i32, minutes); } if (segment_iter.next()) |second_string| { const seconds = try std.fmt.parseInt(u8, second_string, 10); if (seconds > 59) return error.InvalidFormat; result += seconds; } return result * sign; } fn parsePosixTZ_rule(_string: []const u8) !PosixTZ.Rule { var string = _string; if (string.len < 2) return error.InvalidFormat; const time: i32 = if (std.mem.indexOf(u8, string, "/")) |start_of_time| parse_time: { var _i: usize = 0; // This is ugly, should stick with one unit or the other for hhmmss offsets const time = try hhmmss_offset_to_s(string[start_of_time + 1 ..], &_i); string = string[0..start_of_time]; break :parse_time time; } else 2 * std.time.s_per_hour; if (string[0] == 'J') { const julian_day1 = try std.fmt.parseInt(u16, string[1..], 10); if (julian_day1 < 1 or julian_day1 > 365) return error.InvalidFormat; return PosixTZ.Rule{ .JulianDay = .{ .oneBased = true, .day = julian_day1, .time = time } }; } else if (std.ascii.isDigit(string[0])) { const julian_day0 = try std.fmt.parseInt(u16, string[0..], 10); if (julian_day0 > 365) return error.InvalidFormat; return PosixTZ.Rule{ .JulianDay = .{ .oneBased = false, .day = julian_day0, .time = time } }; } else if (string[0] == 'M') { var split_iter = std.mem.split(u8, string[1..], "."); const m_str = split_iter.next() orelse return error.InvalidFormat; const n_str = split_iter.next() orelse return error.InvalidFormat; const d_str = split_iter.next() orelse return error.InvalidFormat; const m = try std.fmt.parseInt(u8, m_str, 10); const n = try std.fmt.parseInt(u8, n_str, 10); const d = try std.fmt.parseInt(u8, d_str, 10); if (m < 1 or m > 12) return error.InvalidFormat; if (n < 1 or n > 5) return error.InvalidFormat; if (d > 6) return error.InvalidFormat; return PosixTZ.Rule{ .MonthWeekDay = .{ .m = m, .n = n, .d = d, .time = time } }; } else { return error.InvalidFormat; } } fn parsePosixTZ_designation(string: []const u8, idx: *usize) ![]const u8 { var quoted = string[idx.*] == '<'; if (quoted) idx.* += 1; var start = idx.*; while (idx.* < string.len) : (idx.* += 1) { if ((quoted and string[idx.*] == '>') or (!quoted and !std.ascii.isAlpha(string[idx.*]))) { const designation = string[start..idx.*]; if (quoted) idx.* += 1; return designation; } } return error.InvalidFormat; } pub fn parsePosixTZ(string: []const u8) !PosixTZ { var result = PosixTZ{ .std = undefined, .std_offset = undefined }; var idx: usize = 0; result.std = try parsePosixTZ_designation(string, &idx); result.std_offset = try hhmmss_offset_to_s(string[idx..], &idx); if (idx >= string.len) { return result; } if (string[idx] != ',') { result.dst = try parsePosixTZ_designation(string, &idx); if (idx < string.len and string[idx] != ',') { result.dst_offset = try hhmmss_offset_to_s(string[idx..], &idx); } else { result.dst_offset = result.std_offset + std.time.s_per_hour; } if (idx >= string.len) { return result; } } std.debug.assert(string[idx] == ','); idx += 1; if (std.mem.indexOf(u8, string[idx..], ",")) |_end_of_start_rule| { const end_of_start_rule = idx + _end_of_start_rule; result.dst_range = .{ .start = try parsePosixTZ_rule(string[idx..end_of_start_rule]), .end = try parsePosixTZ_rule(string[end_of_start_rule + 1 ..]), }; } else { return error.InvalidFormat; } return result; } pub fn parse(allocator: *std.mem.Allocator, reader: anytype, seekableStream: anytype) !TimeZone { const v1_header = try parseHeader(reader, seekableStream); try seekableStream.seekBy(v1_header.dataSize(.V1)); const v2_header = try parseHeader(reader, seekableStream); // Parse transition times var transition_times = try allocator.alloc(i64, v2_header.timecnt); errdefer allocator.free(transition_times); { var prev: i64 = -(2 << 59); // Earliest time supported, this is earlier than the big bang var i: usize = 0; while (i < transition_times.len) : (i += 1) { transition_times[i] = try reader.readInt(i64, .Big); if (transition_times[i] <= prev) { return error.InvalidFormat; } prev = transition_times[i]; } } // Parse transition types var transition_types = try allocator.alloc(u8, v2_header.timecnt); errdefer allocator.free(transition_types); try reader.readNoEof(transition_types); for (transition_types) |transition_type| { if (transition_type >= v2_header.typecnt) { return error.InvalidFormat; // a transition type index is out of bounds } } // Parse local time type records var local_time_types = try allocator.alloc(LocalTimeType, v2_header.typecnt); errdefer allocator.free(local_time_types); { var i: usize = 0; while (i < local_time_types.len) : (i += 1) { local_time_types[i].utoff = try reader.readInt(i32, .Big); local_time_types[i].dst = switch (try reader.readByte()) { 0 => false, 1 => true, else => return error.InvalidFormat, }; local_time_types[i].idx = try reader.readByte(); if (local_time_types[i].idx >= v2_header.charcnt) { return error.InvalidFormat; } } } // Read designations var time_zone_designations = try allocator.alloc(u8, v2_header.charcnt); errdefer allocator.free(time_zone_designations); try reader.readNoEof(time_zone_designations); // Parse leap seconds records var leap_seconds = try allocator.alloc(LeapSecond, v2_header.leapcnt); errdefer allocator.free(leap_seconds); { var i: usize = 0; while (i < leap_seconds.len) : (i += 1) { leap_seconds[i].occur = try reader.readInt(i64, .Big); if (i == 0 and leap_seconds[i].occur < 0) { return error.InvalidFormat; } else if (i != 0 and leap_seconds[i].occur - leap_seconds[i - 1].occur < 2419199) { return error.InvalidFormat; // There must be at least 28 days worth of seconds between leap seconds } leap_seconds[i].corr = try reader.readInt(i32, .Big); if (i == 0 and (leap_seconds[0].corr != 1 and leap_seconds[0].corr != -1)) { log.warn("First leap second correction is not 1 or -1: {}", .{leap_seconds[0]}); return error.InvalidFormat; } else if (i != 0) { const diff = leap_seconds[i].corr - leap_seconds[i - 1].corr; if (diff != 1 and diff != -1) { log.warn("Too large of a difference between leap seconds: {}", .{diff}); return error.InvalidFormat; } } } } // Parse standard/wall indicators var transition_is_std = try allocator.alloc(bool, v2_header.isstdcnt); errdefer allocator.free(transition_is_std); { var i: usize = 0; while (i < transition_is_std.len) : (i += 1) { transition_is_std[i] = switch (try reader.readByte()) { 1 => true, 0 => false, else => return error.InvalidFormat, }; } } // Parse UT/local indicators var transition_is_ut = try allocator.alloc(bool, v2_header.isutcnt); errdefer allocator.free(transition_is_ut); { var i: usize = 0; while (i < transition_is_ut.len) : (i += 1) { transition_is_ut[i] = switch (try reader.readByte()) { 1 => true, 0 => false, else => return error.InvalidFormat, }; } } // Parse TZ string from footer if ((try reader.readByte()) != '\n') return error.InvalidFormat; const tz_string = try reader.readUntilDelimiterAlloc(allocator, '\n', 60); errdefer allocator.free(tz_string); const posixTZ: ?PosixTZ = if (tz_string.len > 0) try parsePosixTZ(tz_string) else null; return TimeZone{ .allocator = allocator, .version = v2_header.version, .transitionTimes = transition_times, .transitionTypes = transition_types, .localTimeTypes = local_time_types, .designations = time_zone_designations, .leapSeconds = leap_seconds, .transitionIsStd = transition_is_std, .transitionIsUT = transition_is_ut, .string = tz_string, .posixTZ = posixTZ, }; } pub fn parseFile(allocator: *std.mem.Allocator, path: []const u8) !TimeZone { const cwd = std.fs.cwd(); const file = try cwd.openFile(path, .{}); defer file.close(); return parse(allocator, file.reader(), file.seekableStream()); } test "parse invalid bytes" { var fbs = std.io.fixedBufferStream("dflkasjreklnlkvnalkfek"); try testing.expectError(error.InvalidFormat, parse(std.testing.allocator, fbs.reader(), fbs.seekableStream())); } test "parse UTC zoneinfo" { var fbs = std.io.fixedBufferStream(@embedFile("zoneinfo/UTC")); const res = try parse(std.testing.allocator, fbs.reader(), fbs.seekableStream()); defer res.deinit(); try testing.expectEqual(Version.V2, res.version); try testing.expectEqualSlices(i64, &[_]i64{}, res.transitionTimes); try testing.expectEqualSlices(u8, &[_]u8{}, res.transitionTypes); try testing.expectEqualSlices(LocalTimeType, &[_]LocalTimeType{.{ .utoff = 0, .dst = false, .idx = 0 }}, res.localTimeTypes); try testing.expectEqualSlices(u8, "UTC\x00", res.designations); } test "parse Pacific/Honolulu zoneinfo and calculate local times" { const transition_times = [7]i64{ -2334101314, -1157283000, -1155436200, -880198200, -769395600, -765376200, -712150200 }; const transition_types = [7]u8{ 1, 2, 1, 3, 4, 1, 5 }; const local_time_types = [6]LocalTimeType{ .{ .utoff = -37886, .dst = false, .idx = 0 }, .{ .utoff = -37800, .dst = false, .idx = 4 }, .{ .utoff = -34200, .dst = true, .idx = 8 }, .{ .utoff = -34200, .dst = true, .idx = 12 }, .{ .utoff = -34200, .dst = true, .idx = 16 }, .{ .utoff = -36000, .dst = false, .idx = 4 }, }; const designations = "LMT\x00HST\x00HDT\x00HWT\x00HPT\x00"; const is_std = &[6]bool{ false, false, false, false, true, false }; const is_ut = &[6]bool{ false, false, false, false, true, false }; const string = "HST10"; var fbs = std.io.fixedBufferStream(@embedFile("zoneinfo/Pacific/Honolulu")); const res = try parse(std.testing.allocator, fbs.reader(), fbs.seekableStream()); defer res.deinit(); try testing.expectEqual(Version.V2, res.version); try testing.expectEqualSlices(i64, &transition_times, res.transitionTimes); try testing.expectEqualSlices(u8, &transition_types, res.transitionTypes); try testing.expectEqualSlices(LocalTimeType, &local_time_types, res.localTimeTypes); try testing.expectEqualSlices(u8, designations, res.designations); try testing.expectEqualSlices(bool, is_std, res.transitionIsStd); try testing.expectEqualSlices(bool, is_ut, res.transitionIsUT); try testing.expectEqualSlices(u8, string, res.string); { const conversion = res.localTimeFromUTC(-1156939200).?; try testing.expectEqual(@as(i64, -1156973400), conversion.timestamp); try testing.expectEqual(true, conversion.dst); try testing.expectEqualSlices(u8, "HDT", conversion.designation); } { const conversion = res.localTimeFromUTC(1546300800).?; try testing.expectEqual(@as(i64, 1546300800) - 10 * std.time.s_per_hour, conversion.timestamp); try testing.expectEqual(false, conversion.dst); try testing.expectEqualSlices(u8, "HST", conversion.designation); } } test "posix TZ string" { const result = try parsePosixTZ("MST7MDT,M3.2.0,M11.1.0"); try testing.expectEqualSlices(u8, "MST", result.std); try testing.expectEqual(@as(i32, 25200), result.std_offset); try testing.expectEqualSlices(u8, "MDT", result.dst.?); try testing.expectEqual(@as(i32, 28800), result.dst_offset); try testing.expectEqual(PosixTZ.Rule{ .MonthWeekDay = .{ .m = 3, .n = 2, .d = 0, .time = 2 * std.time.s_per_hour } }, result.dst_range.?.start); try testing.expectEqual(PosixTZ.Rule{ .MonthWeekDay = .{ .m = 11, .n = 1, .d = 0, .time = 2 * std.time.s_per_hour } }, result.dst_range.?.end); try testing.expectEqual(@as(i32, 25200), result.offset(1612734960).offset); try testing.expectEqual(@as(i32, 25200), result.offset(1615712399 - 7 * std.time.s_per_hour).offset); try testing.expectEqual(@as(i32, 28800), result.offset(1615712400 - 7 * std.time.s_per_hour).offset); try testing.expectEqual(@as(i32, 28800), result.offset(1620453601).offset); try testing.expectEqual(@as(i32, 28800), result.offset(1636275599 - 7 * std.time.s_per_hour).offset); try testing.expectEqual(@as(i32, 25200), result.offset(1636275600 - 7 * std.time.s_per_hour).offset); }
tzif.zig
const std = @import("std"); const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const cpu = @import("cpu.zig"); const execution = @import("execution.zig"); const keyboard = @import("keyboard.zig"); test "CLS" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.screen[0][0] = 0b11001100; state.screen[cpu.ScreenHeight - 1][cpu.ScreenLineSizeInBytes - 1] = 0b10101010; execution.execute_instruction(&state, 0x00E0); try expectEqual(state.screen[0][0], 0x00); try expectEqual(state.screen[cpu.ScreenHeight - 1][cpu.ScreenLineSizeInBytes - 1], 0x00); } test "JP" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); execution.execute_instruction(&state, 0x1240); try expectEqual(state.pc, 0x0240); execution.execute_instruction(&state, 0x1FFE); try expectEqual(state.pc, 0x0FFE); } test "CALL/RET" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); execution.execute_instruction(&state, 0x2F00); try expectEqual(state.sp, 1); try expectEqual(state.pc, 0x0F00); execution.execute_instruction(&state, 0x2A00); try expectEqual(state.sp, 2); try expectEqual(state.pc, 0x0A00); execution.execute_instruction(&state, 0x00EE); try expectEqual(state.sp, 1); try expectEqual(state.pc, 0x0F02); execution.execute_instruction(&state, 0x00EE); try expectEqual(state.sp, 0); try expectEqual(state.pc, cpu.MinProgramAddress + 2); } test "SE" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); execution.execute_instruction(&state, 0x3000); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 0); try expectEqual(state.pc, cpu.MinProgramAddress + 4); } test "SNE" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); execution.execute_instruction(&state, 0x40FF); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 0); try expectEqual(state.pc, cpu.MinProgramAddress + 4); } test "SE2" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); execution.execute_instruction(&state, 0x5120); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 0); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V1)], 0); try expectEqual(state.pc, cpu.MinProgramAddress + 4); } test "LD" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); execution.execute_instruction(&state, 0x06042); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 0x42); execution.execute_instruction(&state, 0x06A33); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VA)], 0x33); } test "ADD" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V2)], 0x00); execution.execute_instruction(&state, 0x7203); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V2)], 0x03); execution.execute_instruction(&state, 0x7204); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V2)], 0x07); } test "LD2" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.V3)] = 32; execution.execute_instruction(&state, 0x8030); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 32); } test "OR" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.VC)] = 0xF0; state.vRegisters[@enumToInt(cpu.Register.VD)] = 0x0F; execution.execute_instruction(&state, 0x8CD1); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VC)], 0xFF); } test "AND" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.VC)] = 0xF0; state.vRegisters[@enumToInt(cpu.Register.VD)] = 0x0F; execution.execute_instruction(&state, 0x8CD2); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VC)], 0x00); state.vRegisters[@enumToInt(cpu.Register.VC)] = 0xF0; state.vRegisters[@enumToInt(cpu.Register.VD)] = 0xFF; execution.execute_instruction(&state, 0x8CD2); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VC)], 0xF0); } test "XOR" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.VC)] = 0x10; state.vRegisters[@enumToInt(cpu.Register.VD)] = 0x1F; execution.execute_instruction(&state, 0x8CD3); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VC)], 0x0F); } test "ADD" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.V0)] = 8; state.vRegisters[@enumToInt(cpu.Register.V1)] = 8; execution.execute_instruction(&state, 0x8014); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 16); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VF)], 0); state.vRegisters[@enumToInt(cpu.Register.V0)] = 128; state.vRegisters[@enumToInt(cpu.Register.V1)] = 130; execution.execute_instruction(&state, 0x8014); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 2); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VF)], 1); } test "SUB" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.V0)] = 8; state.vRegisters[@enumToInt(cpu.Register.V1)] = 7; execution.execute_instruction(&state, 0x8015); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 1); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VF)], 1); state.vRegisters[@enumToInt(cpu.Register.V0)] = 8; state.vRegisters[@enumToInt(cpu.Register.V1)] = 9; execution.execute_instruction(&state, 0x8015); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 255); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VF)], 0); } test "SHR" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.V0)] = 8; execution.execute_instruction(&state, 0x8016); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 4); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VF)], 0); execution.execute_instruction(&state, 0x8026); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 2); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VF)], 0); execution.execute_instruction(&state, 0x8026); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 1); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VF)], 0); execution.execute_instruction(&state, 0x8026); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 0); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VF)], 1); } test "SUBN" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.V0)] = 7; state.vRegisters[@enumToInt(cpu.Register.V1)] = 8; execution.execute_instruction(&state, 0x8017); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 1); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VF)], 1); state.vRegisters[@enumToInt(cpu.Register.V0)] = 2; state.vRegisters[@enumToInt(cpu.Register.V1)] = 1; execution.execute_instruction(&state, 0x8017); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 255); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VF)], 0); } test "SHL" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.V0)] = 64; execution.execute_instruction(&state, 0x801E); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 128); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VF)], 0); execution.execute_instruction(&state, 0x801E); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 0); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.VF)], 1); } test "SNE2" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.V9)] = 64; state.vRegisters[@enumToInt(cpu.Register.VA)] = 64; execution.execute_instruction(&state, 0x99A0); try expectEqual(state.pc, cpu.MinProgramAddress + 2); state.vRegisters[@enumToInt(cpu.Register.VA)] = 0; execution.execute_instruction(&state, 0x99A0); try expectEqual(state.pc, cpu.MinProgramAddress + 6); } test "LDI" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); execution.execute_instruction(&state, 0xA242); try expectEqual(state.i, 0x0242); } test "JP2" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.V0)] = 0x02; execution.execute_instruction(&state, 0xB240); try expectEqual(state.pc, 0x0242); } test "RND" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); execution.execute_instruction(&state, 0xC10F); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V1)] & 0xF0, 0); execution.execute_instruction(&state, 0xC1F0); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V1)] & 0x0F, 0); } test "DRW" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); // TODO // execution.execute_instruction(&state, 0x00E0); // Clear screen // state.vRegisters[@enumToInt(cpu.Register.V0)] = 0x0F; // Set digit to print // state.vRegisters[@enumToInt(cpu.Register.V1)] = 0x00; // Set digit to print // execution.execute_instruction(&state, 0xF029); // Load digit sprite address // execution.execute_instruction(&state, 0xD115); // Draw sprite // for (int i = 0; i < 10; i++) // { // cpu.write_screen_pixel(state, cpu.ScreenWidth - i - 1, cpu.ScreenHeight - i - 1, 1); // } } test "SKP" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.VA)] = 0x0F; state.keyState = 0x8000; execution.execute_instruction(&state, 0xEA9E); try expectEqual(state.pc, cpu.MinProgramAddress + 4); // Skipped execution.execute_instruction(&state, 0xEB9E); try expectEqual(state.pc, cpu.MinProgramAddress + 6); // Did not skip } test "SKNP" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.VA)] = 0xF; state.keyState = 0x8000; execution.execute_instruction(&state, 0xEBA1); try expectEqual(state.pc, cpu.MinProgramAddress + 4); // Skipped execution.execute_instruction(&state, 0xEAA1); try expectEqual(state.pc, cpu.MinProgramAddress + 6); // Did not skip } test "LDT" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.delayTimer = 42; state.vRegisters[@enumToInt(cpu.Register.V4)] = 0; execution.execute_instruction(&state, 0xF407); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V4)], 42); } test "LDK" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); try expect(!state.isWaitingForKey); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V1)], 0); execution.execute_instruction(&state, 0xF10A); try expect(state.isWaitingForKey); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V1)], 0); keyboard.set_key_pressed(&state, 0xA, true); execution.execute_instruction(&state, 0xF10A); try expect(!state.isWaitingForKey); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V1)], 0xA); } test "LDDT" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.V5)] = 66; execution.execute_instruction(&state, 0xF515); try expectEqual(state.delayTimer, 66); } test "LDST" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.V6)] = 33; execution.execute_instruction(&state, 0xF618); try expectEqual(state.soundTimer, 33); } test "ADDI" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.V9)] = 10; state.i = cpu.MinProgramAddress; execution.execute_instruction(&state, 0xF91E); try expectEqual(state.i, cpu.MinProgramAddress + 10); } test "LDF" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.vRegisters[@enumToInt(cpu.Register.V0)] = 9; execution.execute_instruction(&state, 0xF029); try expectEqual(state.i, state.fontTableOffsets[9]); state.vRegisters[@enumToInt(cpu.Register.V0)] = 0xF; execution.execute_instruction(&state, 0xF029); try expectEqual(state.i, state.fontTableOffsets[0xF]); } test "LDB" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.i = cpu.MinProgramAddress; state.vRegisters[@enumToInt(cpu.Register.V7)] = 109; execution.execute_instruction(&state, 0xF733); try expectEqual(state.memory[state.i + 0], 1); try expectEqual(state.memory[state.i + 1], 0); try expectEqual(state.memory[state.i + 2], 9); state.vRegisters[@enumToInt(cpu.Register.V7)] = 255; execution.execute_instruction(&state, 0xF733); try expectEqual(state.memory[state.i + 0], 2); try expectEqual(state.memory[state.i + 1], 5); try expectEqual(state.memory[state.i + 2], 5); } test "LDAI" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.i = cpu.MinProgramAddress; state.memory[state.i + 0] = 0xF4; state.memory[state.i + 1] = 0x33; state.memory[state.i + 2] = 0x82; state.memory[state.i + 3] = 0x73; state.vRegisters[@enumToInt(cpu.Register.V0)] = 0xE4; state.vRegisters[@enumToInt(cpu.Register.V1)] = 0x23; state.vRegisters[@enumToInt(cpu.Register.V2)] = 0x00; execution.execute_instruction(&state, 0xF155); try expectEqual(state.memory[state.i + 0], 0xE4); try expectEqual(state.memory[state.i + 1], 0x23); try expectEqual(state.memory[state.i + 2], 0x82); try expectEqual(state.memory[state.i + 3], 0x73); } test "LDM" { var state = try cpu.createCPUState(); defer cpu.destroyCPUState(&state); state.i = cpu.MinProgramAddress; state.vRegisters[@enumToInt(cpu.Register.V0)] = 0xF4; state.vRegisters[@enumToInt(cpu.Register.V1)] = 0x33; state.vRegisters[@enumToInt(cpu.Register.V2)] = 0x82; state.vRegisters[@enumToInt(cpu.Register.V3)] = 0x73; state.memory[state.i + 0] = 0xE4; state.memory[state.i + 1] = 0x23; state.memory[state.i + 2] = 0x00; execution.execute_instruction(&state, 0xF165); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V0)], 0xE4); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V1)], 0x23); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V2)], 0x82); try expectEqual(state.vRegisters[@enumToInt(cpu.Register.V3)], 0x73); }
src/chip8/test.zig
pub const MimeMapping = struct { extension: []const u8, mime_type: []const u8, }; /// List of mappings between extensions and its mime type pub const mime_database = [_]MimeMapping{ MimeMapping{ .extension = ".123", .mime_type = "application/vnd.lotus-1-2-3" }, MimeMapping{ .extension = ".3dml", .mime_type = "text/vnd.in3d.3dml" }, MimeMapping{ .extension = ".3g2", .mime_type = "video/3gpp2" }, MimeMapping{ .extension = ".3gp", .mime_type = "video/3gpp" }, MimeMapping{ .extension = ".a", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".aab", .mime_type = "application/x-authorware-bin" }, MimeMapping{ .extension = ".aac", .mime_type = "audio/x-aac" }, MimeMapping{ .extension = ".aam", .mime_type = "application/x-authorware-map" }, MimeMapping{ .extension = ".aas", .mime_type = "application/x-authorware-seg" }, MimeMapping{ .extension = ".abw", .mime_type = "application/x-abiword" }, MimeMapping{ .extension = ".acc", .mime_type = "application/vnd.americandynamics.acc" }, MimeMapping{ .extension = ".ace", .mime_type = "application/x-ace-compressed" }, MimeMapping{ .extension = ".acu", .mime_type = "application/vnd.acucobol" }, MimeMapping{ .extension = ".acutc", .mime_type = "application/vnd.acucorp" }, MimeMapping{ .extension = ".adp", .mime_type = "audio/adpcm" }, MimeMapping{ .extension = ".aep", .mime_type = "application/vnd.audiograph" }, MimeMapping{ .extension = ".afm", .mime_type = "application/x-font-type1" }, MimeMapping{ .extension = ".afp", .mime_type = "application/vnd.ibm.modcap" }, MimeMapping{ .extension = ".ai", .mime_type = "application/postscript" }, MimeMapping{ .extension = ".aif", .mime_type = "audio/x-aiff" }, MimeMapping{ .extension = ".aifc", .mime_type = "audio/x-aiff" }, MimeMapping{ .extension = ".aiff", .mime_type = "audio/x-aiff" }, MimeMapping{ .extension = ".air", .mime_type = "application/vnd.adobe.air-application-installer-package+zip" }, MimeMapping{ .extension = ".ami", .mime_type = "application/vnd.amiga.ami" }, MimeMapping{ .extension = ".apk", .mime_type = "application/vnd.android.package-archive" }, MimeMapping{ .extension = ".application", .mime_type = "application/x-ms-application" }, MimeMapping{ .extension = ".apr", .mime_type = "application/vnd.lotus-approach" }, MimeMapping{ .extension = ".asc", .mime_type = "application/pgp-signature" }, MimeMapping{ .extension = ".asf", .mime_type = "video/x-ms-asf" }, MimeMapping{ .extension = ".asm", .mime_type = "text/x-asm" }, MimeMapping{ .extension = ".aso", .mime_type = "application/vnd.accpac.simply.aso" }, MimeMapping{ .extension = ".asx", .mime_type = "video/x-ms-asf" }, MimeMapping{ .extension = ".atc", .mime_type = "application/vnd.acucorp" }, MimeMapping{ .extension = ".atom", .mime_type = "application/atom+xml" }, MimeMapping{ .extension = ".atomcat", .mime_type = "application/atomcat+xml" }, MimeMapping{ .extension = ".atomsvc", .mime_type = "application/atomsvc+xml" }, MimeMapping{ .extension = ".atx", .mime_type = "application/vnd.antix.game-component" }, MimeMapping{ .extension = ".au", .mime_type = "audio/basic" }, MimeMapping{ .extension = ".avi", .mime_type = "video/x-msvideo" }, MimeMapping{ .extension = ".aw", .mime_type = "application/applixware" }, MimeMapping{ .extension = ".azf", .mime_type = "application/vnd.airzip.filesecure.azf" }, MimeMapping{ .extension = ".azs", .mime_type = "application/vnd.airzip.filesecure.azs" }, MimeMapping{ .extension = ".azw", .mime_type = "application/vnd.amazon.ebook" }, MimeMapping{ .extension = ".bat", .mime_type = "application/x-msdownload" }, MimeMapping{ .extension = ".bcpio", .mime_type = "application/x-bcpio" }, MimeMapping{ .extension = ".bdf", .mime_type = "application/x-font-bdf" }, MimeMapping{ .extension = ".bdm", .mime_type = "application/vnd.syncml.dm+wbxml" }, MimeMapping{ .extension = ".bh2", .mime_type = "application/vnd.fujitsu.oasysprs" }, MimeMapping{ .extension = ".bin", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".bmi", .mime_type = "application/vnd.bmi" }, MimeMapping{ .extension = ".bmp", .mime_type = "image/bmp" }, MimeMapping{ .extension = ".book", .mime_type = "application/vnd.framemaker" }, MimeMapping{ .extension = ".box", .mime_type = "application/vnd.previewsystems.box" }, MimeMapping{ .extension = ".boz", .mime_type = "application/x-bzip2" }, MimeMapping{ .extension = ".bpk", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".btif", .mime_type = "image/prs.btif" }, MimeMapping{ .extension = ".bz", .mime_type = "application/x-bzip" }, MimeMapping{ .extension = ".bz2", .mime_type = "application/x-bzip2" }, MimeMapping{ .extension = ".c", .mime_type = "text/x-c" }, MimeMapping{ .extension = ".c4d", .mime_type = "application/vnd.clonk.c4group" }, MimeMapping{ .extension = ".c4f", .mime_type = "application/vnd.clonk.c4group" }, MimeMapping{ .extension = ".c4g", .mime_type = "application/vnd.clonk.c4group" }, MimeMapping{ .extension = ".c4p", .mime_type = "application/vnd.clonk.c4group" }, MimeMapping{ .extension = ".c4u", .mime_type = "application/vnd.clonk.c4group" }, MimeMapping{ .extension = ".cab", .mime_type = "application/vnd.ms-cab-compressed" }, MimeMapping{ .extension = ".car", .mime_type = "application/vnd.curl.car" }, MimeMapping{ .extension = ".cat", .mime_type = "application/vnd.ms-pki.seccat" }, MimeMapping{ .extension = ".cc", .mime_type = "text/x-c" }, MimeMapping{ .extension = ".cct", .mime_type = "application/x-director" }, MimeMapping{ .extension = ".ccxml", .mime_type = "application/ccxml+xml" }, MimeMapping{ .extension = ".cdbcmsg", .mime_type = "application/vnd.contact.cmsg" }, MimeMapping{ .extension = ".cdf", .mime_type = "application/x-netcdf" }, MimeMapping{ .extension = ".cdkey", .mime_type = "application/vnd.mediastation.cdkey" }, MimeMapping{ .extension = ".cdx", .mime_type = "chemical/x-cdx" }, MimeMapping{ .extension = ".cdxml", .mime_type = "application/vnd.chemdraw+xml" }, MimeMapping{ .extension = ".cdy", .mime_type = "application/vnd.cinderella" }, MimeMapping{ .extension = ".cer", .mime_type = "application/pkix-cert" }, MimeMapping{ .extension = ".cgm", .mime_type = "image/cgm" }, MimeMapping{ .extension = ".chat", .mime_type = "application/x-chat" }, MimeMapping{ .extension = ".chm", .mime_type = "application/vnd.ms-htmlhelp" }, MimeMapping{ .extension = ".chrt", .mime_type = "application/vnd.kde.kchart" }, MimeMapping{ .extension = ".cif", .mime_type = "chemical/x-cif" }, MimeMapping{ .extension = ".cii", .mime_type = "application/vnd.anser-web-certificate-issue-initiation" }, MimeMapping{ .extension = ".cil", .mime_type = "application/vnd.ms-artgalry" }, MimeMapping{ .extension = ".cla", .mime_type = "application/vnd.claymore" }, MimeMapping{ .extension = ".class", .mime_type = "application/java-vm" }, MimeMapping{ .extension = ".clkk", .mime_type = "application/vnd.crick.clicker.keyboard" }, MimeMapping{ .extension = ".clkp", .mime_type = "application/vnd.crick.clicker.palette" }, MimeMapping{ .extension = ".clkt", .mime_type = "application/vnd.crick.clicker.template" }, MimeMapping{ .extension = ".clkw", .mime_type = "application/vnd.crick.clicker.wordbank" }, MimeMapping{ .extension = ".clkx", .mime_type = "application/vnd.crick.clicker" }, MimeMapping{ .extension = ".clp", .mime_type = "application/x-msclip" }, MimeMapping{ .extension = ".cmc", .mime_type = "application/vnd.cosmocaller" }, MimeMapping{ .extension = ".cmdf", .mime_type = "chemical/x-cmdf" }, MimeMapping{ .extension = ".cml", .mime_type = "chemical/x-cml" }, MimeMapping{ .extension = ".cmp", .mime_type = "application/vnd.yellowriver-custom-menu" }, MimeMapping{ .extension = ".cmx", .mime_type = "image/x-cmx" }, MimeMapping{ .extension = ".cod", .mime_type = "application/vnd.rim.cod" }, MimeMapping{ .extension = ".com", .mime_type = "application/x-msdownload" }, MimeMapping{ .extension = ".conf", .mime_type = "text/plain" }, MimeMapping{ .extension = ".cpio", .mime_type = "application/x-cpio" }, MimeMapping{ .extension = ".cpp", .mime_type = "text/x-c" }, MimeMapping{ .extension = ".cpt", .mime_type = "application/mac-compactpro" }, MimeMapping{ .extension = ".crd", .mime_type = "application/x-mscardfile" }, MimeMapping{ .extension = ".crl", .mime_type = "application/pkix-crl" }, MimeMapping{ .extension = ".crt", .mime_type = "application/x-x509-ca-cert" }, MimeMapping{ .extension = ".csh", .mime_type = "application/x-csh" }, MimeMapping{ .extension = ".csml", .mime_type = "chemical/x-csml" }, MimeMapping{ .extension = ".csp", .mime_type = "application/vnd.commonspace" }, MimeMapping{ .extension = ".css", .mime_type = "text/css" }, MimeMapping{ .extension = ".cst", .mime_type = "application/x-director" }, MimeMapping{ .extension = ".csv", .mime_type = "text/csv" }, MimeMapping{ .extension = ".cu", .mime_type = "application/cu-seeme" }, MimeMapping{ .extension = ".curl", .mime_type = "text/vnd.curl" }, MimeMapping{ .extension = ".cww", .mime_type = "application/prs.cww" }, MimeMapping{ .extension = ".cxt", .mime_type = "application/x-director" }, MimeMapping{ .extension = ".cxx", .mime_type = "text/x-c" }, MimeMapping{ .extension = ".daf", .mime_type = "application/vnd.mobius.daf" }, MimeMapping{ .extension = ".dataless", .mime_type = "application/vnd.fdsn.seed" }, MimeMapping{ .extension = ".davmount", .mime_type = "application/davmount+xml" }, MimeMapping{ .extension = ".dcr", .mime_type = "application/x-director" }, MimeMapping{ .extension = ".dcurl", .mime_type = "text/vnd.curl.dcurl" }, MimeMapping{ .extension = ".dd2", .mime_type = "application/vnd.oma.dd2+xml" }, MimeMapping{ .extension = ".ddd", .mime_type = "application/vnd.fujixerox.ddd" }, MimeMapping{ .extension = ".deb", .mime_type = "application/x-debian-package" }, MimeMapping{ .extension = ".def", .mime_type = "text/plain" }, MimeMapping{ .extension = ".deploy", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".der", .mime_type = "application/x-x509-ca-cert" }, MimeMapping{ .extension = ".dfac", .mime_type = "application/vnd.dreamfactory" }, MimeMapping{ .extension = ".dic", .mime_type = "text/x-c" }, MimeMapping{ .extension = ".diff", .mime_type = "text/plain" }, MimeMapping{ .extension = ".dir", .mime_type = "application/x-director" }, MimeMapping{ .extension = ".dis", .mime_type = "application/vnd.mobius.dis" }, MimeMapping{ .extension = ".dist", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".distz", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".djv", .mime_type = "image/vnd.djvu" }, MimeMapping{ .extension = ".djvu", .mime_type = "image/vnd.djvu" }, MimeMapping{ .extension = ".dll", .mime_type = "application/x-msdownload" }, MimeMapping{ .extension = ".dmg", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".dms", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".dna", .mime_type = "application/vnd.dna" }, MimeMapping{ .extension = ".doc", .mime_type = "application/msword" }, MimeMapping{ .extension = ".docm", .mime_type = "application/vnd.ms-word.document.macroenabled.12" }, MimeMapping{ .extension = ".docx", .mime_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }, MimeMapping{ .extension = ".dot", .mime_type = "application/msword" }, MimeMapping{ .extension = ".dotm", .mime_type = "application/vnd.ms-word.template.macroenabled.12" }, MimeMapping{ .extension = ".dotx", .mime_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.template" }, MimeMapping{ .extension = ".dp", .mime_type = "application/vnd.osgi.dp" }, MimeMapping{ .extension = ".dpg", .mime_type = "application/vnd.dpgraph" }, MimeMapping{ .extension = ".dsc", .mime_type = "text/prs.lines.tag" }, MimeMapping{ .extension = ".dtb", .mime_type = "application/x-dtbook+xml" }, MimeMapping{ .extension = ".dtd", .mime_type = "application/xml-dtd" }, MimeMapping{ .extension = ".dts", .mime_type = "audio/vnd.dts" }, MimeMapping{ .extension = ".dtshd", .mime_type = "audio/vnd.dts.hd" }, MimeMapping{ .extension = ".dump", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".dvi", .mime_type = "application/x-dvi" }, MimeMapping{ .extension = ".dwf", .mime_type = "model/vnd.dwf" }, MimeMapping{ .extension = ".dwg", .mime_type = "image/vnd.dwg" }, MimeMapping{ .extension = ".dxf", .mime_type = "image/vnd.dxf" }, MimeMapping{ .extension = ".dxp", .mime_type = "application/vnd.spotfire.dxp" }, MimeMapping{ .extension = ".dxr", .mime_type = "application/x-director" }, MimeMapping{ .extension = ".ecelp4800", .mime_type = "audio/vnd.nuera.ecelp4800" }, MimeMapping{ .extension = ".ecelp7470", .mime_type = "audio/vnd.nuera.ecelp7470" }, MimeMapping{ .extension = ".ecelp9600", .mime_type = "audio/vnd.nuera.ecelp9600" }, MimeMapping{ .extension = ".ecma", .mime_type = "application/ecmascript" }, MimeMapping{ .extension = ".edm", .mime_type = "application/vnd.novadigm.edm" }, MimeMapping{ .extension = ".edx", .mime_type = "application/vnd.novadigm.edx" }, MimeMapping{ .extension = ".efif", .mime_type = "application/vnd.picsel" }, MimeMapping{ .extension = ".ei6", .mime_type = "application/vnd.pg.osasli" }, MimeMapping{ .extension = ".elc", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".eml", .mime_type = "message/rfc822" }, MimeMapping{ .extension = ".emma", .mime_type = "application/emma+xml" }, MimeMapping{ .extension = ".eol", .mime_type = "audio/vnd.digital-winds" }, MimeMapping{ .extension = ".eot", .mime_type = "application/vnd.ms-fontobject" }, MimeMapping{ .extension = ".eps", .mime_type = "application/postscript" }, MimeMapping{ .extension = ".epub", .mime_type = "application/epub+zip" }, MimeMapping{ .extension = ".es3", .mime_type = "application/vnd.eszigno3+xml" }, MimeMapping{ .extension = ".esf", .mime_type = "application/vnd.epson.esf" }, MimeMapping{ .extension = ".et3", .mime_type = "application/vnd.eszigno3+xml" }, MimeMapping{ .extension = ".etx", .mime_type = "text/x-setext" }, MimeMapping{ .extension = ".exe", .mime_type = "application/x-msdownload" }, MimeMapping{ .extension = ".ext", .mime_type = "application/vnd.novadigm.ext" }, MimeMapping{ .extension = ".ez", .mime_type = "application/andrew-inset" }, MimeMapping{ .extension = ".ez2", .mime_type = "application/vnd.ezpix-album" }, MimeMapping{ .extension = ".ez3", .mime_type = "application/vnd.ezpix-package" }, MimeMapping{ .extension = ".f", .mime_type = "text/x-fortran" }, MimeMapping{ .extension = ".f4v", .mime_type = "video/x-f4v" }, MimeMapping{ .extension = ".f77", .mime_type = "text/x-fortran" }, MimeMapping{ .extension = ".f90", .mime_type = "text/x-fortran" }, MimeMapping{ .extension = ".fbs", .mime_type = "image/vnd.fastbidsheet" }, MimeMapping{ .extension = ".fdf", .mime_type = "application/vnd.fdf" }, MimeMapping{ .extension = ".fe_launch", .mime_type = "application/vnd.denovo.fcselayout-link" }, MimeMapping{ .extension = ".fg5", .mime_type = "application/vnd.fujitsu.oasysgp" }, MimeMapping{ .extension = ".fgd", .mime_type = "application/x-director" }, MimeMapping{ .extension = ".fh", .mime_type = "image/x-freehand" }, MimeMapping{ .extension = ".fh4", .mime_type = "image/x-freehand" }, MimeMapping{ .extension = ".fh5", .mime_type = "image/x-freehand" }, MimeMapping{ .extension = ".fh7", .mime_type = "image/x-freehand" }, MimeMapping{ .extension = ".fhc", .mime_type = "image/x-freehand" }, MimeMapping{ .extension = ".fig", .mime_type = "application/x-xfig" }, MimeMapping{ .extension = ".fli", .mime_type = "video/x-fli" }, MimeMapping{ .extension = ".flo", .mime_type = "application/vnd.micrografx.flo" }, MimeMapping{ .extension = ".flv", .mime_type = "video/x-flv" }, MimeMapping{ .extension = ".flw", .mime_type = "application/vnd.kde.kivio" }, MimeMapping{ .extension = ".flx", .mime_type = "text/vnd.fmi.flexstor" }, MimeMapping{ .extension = ".fly", .mime_type = "text/vnd.fly" }, MimeMapping{ .extension = ".fm", .mime_type = "application/vnd.framemaker" }, MimeMapping{ .extension = ".fnc", .mime_type = "application/vnd.frogans.fnc" }, MimeMapping{ .extension = ".for", .mime_type = "text/x-fortran" }, MimeMapping{ .extension = ".fpx", .mime_type = "image/vnd.fpx" }, MimeMapping{ .extension = ".frame", .mime_type = "application/vnd.framemaker" }, MimeMapping{ .extension = ".fsc", .mime_type = "application/vnd.fsc.weblaunch" }, MimeMapping{ .extension = ".fst", .mime_type = "image/vnd.fst" }, MimeMapping{ .extension = ".ftc", .mime_type = "application/vnd.fluxtime.clip" }, MimeMapping{ .extension = ".fti", .mime_type = "application/vnd.anser-web-funds-transfer-initiation" }, MimeMapping{ .extension = ".fvt", .mime_type = "video/vnd.fvt" }, MimeMapping{ .extension = ".fzs", .mime_type = "application/vnd.fuzzysheet" }, MimeMapping{ .extension = ".g3", .mime_type = "image/g3fax" }, MimeMapping{ .extension = ".gac", .mime_type = "application/vnd.groove-account" }, MimeMapping{ .extension = ".gdl", .mime_type = "model/vnd.gdl" }, MimeMapping{ .extension = ".geo", .mime_type = "application/vnd.dynageo" }, MimeMapping{ .extension = ".gex", .mime_type = "application/vnd.geometry-explorer" }, MimeMapping{ .extension = ".ggb", .mime_type = "application/vnd.geogebra.file" }, MimeMapping{ .extension = ".ggt", .mime_type = "application/vnd.geogebra.tool" }, MimeMapping{ .extension = ".ghf", .mime_type = "application/vnd.groove-help" }, MimeMapping{ .extension = ".gif", .mime_type = "image/gif" }, MimeMapping{ .extension = ".gim", .mime_type = "application/vnd.groove-identity-message" }, MimeMapping{ .extension = ".gmx", .mime_type = "application/vnd.gmx" }, MimeMapping{ .extension = ".gnumeric", .mime_type = "application/x-gnumeric" }, MimeMapping{ .extension = ".gph", .mime_type = "application/vnd.flographit" }, MimeMapping{ .extension = ".gqf", .mime_type = "application/vnd.grafeq" }, MimeMapping{ .extension = ".gqs", .mime_type = "application/vnd.grafeq" }, MimeMapping{ .extension = ".gram", .mime_type = "application/srgs" }, MimeMapping{ .extension = ".gre", .mime_type = "application/vnd.geometry-explorer" }, MimeMapping{ .extension = ".grv", .mime_type = "application/vnd.groove-injector" }, MimeMapping{ .extension = ".grxml", .mime_type = "application/srgs+xml" }, MimeMapping{ .extension = ".gsf", .mime_type = "application/x-font-ghostscript" }, MimeMapping{ .extension = ".gtar", .mime_type = "application/x-gtar" }, MimeMapping{ .extension = ".gtm", .mime_type = "application/vnd.groove-tool-message" }, MimeMapping{ .extension = ".gtw", .mime_type = "model/vnd.gtw" }, MimeMapping{ .extension = ".gv", .mime_type = "text/vnd.graphviz" }, MimeMapping{ .extension = ".gz", .mime_type = "application/x-gzip" }, MimeMapping{ .extension = ".h", .mime_type = "text/x-c" }, MimeMapping{ .extension = ".h261", .mime_type = "video/h261" }, MimeMapping{ .extension = ".h263", .mime_type = "video/h263" }, MimeMapping{ .extension = ".h264", .mime_type = "video/h264" }, MimeMapping{ .extension = ".hbci", .mime_type = "application/vnd.hbci" }, MimeMapping{ .extension = ".hdf", .mime_type = "application/x-hdf" }, MimeMapping{ .extension = ".hh", .mime_type = "text/x-c" }, MimeMapping{ .extension = ".hlp", .mime_type = "application/winhlp" }, MimeMapping{ .extension = ".hpgl", .mime_type = "application/vnd.hp-hpgl" }, MimeMapping{ .extension = ".hpid", .mime_type = "application/vnd.hp-hpid" }, MimeMapping{ .extension = ".hps", .mime_type = "application/vnd.hp-hps" }, MimeMapping{ .extension = ".hqx", .mime_type = "application/mac-binhex40" }, MimeMapping{ .extension = ".htke", .mime_type = "application/vnd.kenameaapp" }, MimeMapping{ .extension = ".htm", .mime_type = "text/html" }, MimeMapping{ .extension = ".html", .mime_type = "text/html" }, MimeMapping{ .extension = ".hvd", .mime_type = "application/vnd.yamaha.hv-dic" }, MimeMapping{ .extension = ".hvp", .mime_type = "application/vnd.yamaha.hv-voice" }, MimeMapping{ .extension = ".hvs", .mime_type = "application/vnd.yamaha.hv-script" }, MimeMapping{ .extension = ".icc", .mime_type = "application/vnd.iccprofile" }, MimeMapping{ .extension = ".ice", .mime_type = "x-conference/x-cooltalk" }, MimeMapping{ .extension = ".icm", .mime_type = "application/vnd.iccprofile" }, MimeMapping{ .extension = ".ico", .mime_type = "image/x-icon" }, MimeMapping{ .extension = ".ics", .mime_type = "text/calendar" }, MimeMapping{ .extension = ".ief", .mime_type = "image/ief" }, MimeMapping{ .extension = ".ifb", .mime_type = "text/calendar" }, MimeMapping{ .extension = ".ifm", .mime_type = "application/vnd.shana.informed.formdata" }, MimeMapping{ .extension = ".iges", .mime_type = "model/iges" }, MimeMapping{ .extension = ".igl", .mime_type = "application/vnd.igloader" }, MimeMapping{ .extension = ".igs", .mime_type = "model/iges" }, MimeMapping{ .extension = ".igx", .mime_type = "application/vnd.micrografx.igx" }, MimeMapping{ .extension = ".iif", .mime_type = "application/vnd.shana.informed.interchange" }, MimeMapping{ .extension = ".imp", .mime_type = "application/vnd.accpac.simply.imp" }, MimeMapping{ .extension = ".ims", .mime_type = "application/vnd.ms-ims" }, MimeMapping{ .extension = ".in", .mime_type = "text/plain" }, MimeMapping{ .extension = ".ipk", .mime_type = "application/vnd.shana.informed.package" }, MimeMapping{ .extension = ".irm", .mime_type = "application/vnd.ibm.rights-management" }, MimeMapping{ .extension = ".irp", .mime_type = "application/vnd.irepository.package+xml" }, MimeMapping{ .extension = ".iso", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".itp", .mime_type = "application/vnd.shana.informed.formtemplate" }, MimeMapping{ .extension = ".ivp", .mime_type = "application/vnd.immervision-ivp" }, MimeMapping{ .extension = ".ivu", .mime_type = "application/vnd.immervision-ivu" }, MimeMapping{ .extension = ".jad", .mime_type = "text/vnd.sun.j2me.app-descriptor" }, MimeMapping{ .extension = ".jam", .mime_type = "application/vnd.jam" }, MimeMapping{ .extension = ".jar", .mime_type = "application/java-archive" }, MimeMapping{ .extension = ".java", .mime_type = "text/x-java-source" }, MimeMapping{ .extension = ".jisp", .mime_type = "application/vnd.jisp" }, MimeMapping{ .extension = ".jlt", .mime_type = "application/vnd.hp-jlyt" }, MimeMapping{ .extension = ".jnlp", .mime_type = "application/x-java-jnlp-file" }, MimeMapping{ .extension = ".joda", .mime_type = "application/vnd.joost.joda-archive" }, MimeMapping{ .extension = ".jpe", .mime_type = "image/jpeg" }, MimeMapping{ .extension = ".jpeg", .mime_type = "image/jpeg" }, MimeMapping{ .extension = ".jpg", .mime_type = "image/jpeg" }, MimeMapping{ .extension = ".jpgm", .mime_type = "video/jpm" }, MimeMapping{ .extension = ".jpgv", .mime_type = "video/jpeg" }, MimeMapping{ .extension = ".jpm", .mime_type = "video/jpm" }, MimeMapping{ .extension = ".js", .mime_type = "application/javascript" }, MimeMapping{ .extension = ".json", .mime_type = "application/json" }, MimeMapping{ .extension = ".kar", .mime_type = "audio/midi" }, MimeMapping{ .extension = ".karbon", .mime_type = "application/vnd.kde.karbon" }, MimeMapping{ .extension = ".kfo", .mime_type = "application/vnd.kde.kformula" }, MimeMapping{ .extension = ".kia", .mime_type = "application/vnd.kidspiration" }, MimeMapping{ .extension = ".kil", .mime_type = "application/x-killustrator" }, MimeMapping{ .extension = ".kml", .mime_type = "application/vnd.google-earth.kml+xml" }, MimeMapping{ .extension = ".kmz", .mime_type = "application/vnd.google-earth.kmz" }, MimeMapping{ .extension = ".kne", .mime_type = "application/vnd.kinar" }, MimeMapping{ .extension = ".knp", .mime_type = "application/vnd.kinar" }, MimeMapping{ .extension = ".kon", .mime_type = "application/vnd.kde.kontour" }, MimeMapping{ .extension = ".kpr", .mime_type = "application/vnd.kde.kpresenter" }, MimeMapping{ .extension = ".kpt", .mime_type = "application/vnd.kde.kpresenter" }, MimeMapping{ .extension = ".ksh", .mime_type = "text/plain" }, MimeMapping{ .extension = ".ksp", .mime_type = "application/vnd.kde.kspread" }, MimeMapping{ .extension = ".ktr", .mime_type = "application/vnd.kahootz" }, MimeMapping{ .extension = ".ktz", .mime_type = "application/vnd.kahootz" }, MimeMapping{ .extension = ".kwd", .mime_type = "application/vnd.kde.kword" }, MimeMapping{ .extension = ".kwt", .mime_type = "application/vnd.kde.kword" }, MimeMapping{ .extension = ".latex", .mime_type = "application/x-latex" }, MimeMapping{ .extension = ".lbd", .mime_type = "application/vnd.llamagraphics.life-balance.desktop" }, MimeMapping{ .extension = ".lbe", .mime_type = "application/vnd.llamagraphics.life-balance.exchange+xml" }, MimeMapping{ .extension = ".les", .mime_type = "application/vnd.hhe.lesson-player" }, MimeMapping{ .extension = ".lha", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".link66", .mime_type = "application/vnd.route66.link66+xml" }, MimeMapping{ .extension = ".list", .mime_type = "text/plain" }, MimeMapping{ .extension = ".list3820", .mime_type = "application/vnd.ibm.modcap" }, MimeMapping{ .extension = ".listafp", .mime_type = "application/vnd.ibm.modcap" }, MimeMapping{ .extension = ".log", .mime_type = "text/plain" }, MimeMapping{ .extension = ".lostxml", .mime_type = "application/lost+xml" }, MimeMapping{ .extension = ".lrf", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".lrm", .mime_type = "application/vnd.ms-lrm" }, MimeMapping{ .extension = ".ltf", .mime_type = "application/vnd.frogans.ltf" }, MimeMapping{ .extension = ".lvp", .mime_type = "audio/vnd.lucent.voice" }, MimeMapping{ .extension = ".lwp", .mime_type = "application/vnd.lotus-wordpro" }, MimeMapping{ .extension = ".lzh", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".m13", .mime_type = "application/x-msmediaview" }, MimeMapping{ .extension = ".m14", .mime_type = "application/x-msmediaview" }, MimeMapping{ .extension = ".m1v", .mime_type = "video/mpeg" }, MimeMapping{ .extension = ".m2a", .mime_type = "audio/mpeg" }, MimeMapping{ .extension = ".m2v", .mime_type = "video/mpeg" }, MimeMapping{ .extension = ".m3a", .mime_type = "audio/mpeg" }, MimeMapping{ .extension = ".m3u", .mime_type = "audio/x-mpegurl" }, MimeMapping{ .extension = ".m4u", .mime_type = "video/vnd.mpegurl" }, MimeMapping{ .extension = ".m4v", .mime_type = "video/x-m4v" }, MimeMapping{ .extension = ".ma", .mime_type = "application/mathematica" }, MimeMapping{ .extension = ".mag", .mime_type = "application/vnd.ecowin.chart" }, MimeMapping{ .extension = ".maker", .mime_type = "application/vnd.framemaker" }, MimeMapping{ .extension = ".man", .mime_type = "text/troff" }, MimeMapping{ .extension = ".mathml", .mime_type = "application/mathml+xml" }, MimeMapping{ .extension = ".mb", .mime_type = "application/mathematica" }, MimeMapping{ .extension = ".mbk", .mime_type = "application/vnd.mobius.mbk" }, MimeMapping{ .extension = ".mbox", .mime_type = "application/mbox" }, MimeMapping{ .extension = ".mc1", .mime_type = "application/vnd.medcalcdata" }, MimeMapping{ .extension = ".mcd", .mime_type = "application/vnd.mcd" }, MimeMapping{ .extension = ".mcurl", .mime_type = "text/vnd.curl.mcurl" }, MimeMapping{ .extension = ".mdb", .mime_type = "application/x-msaccess" }, MimeMapping{ .extension = ".mdi", .mime_type = "image/vnd.ms-modi" }, MimeMapping{ .extension = ".me", .mime_type = "text/troff" }, MimeMapping{ .extension = ".mesh", .mime_type = "model/mesh" }, MimeMapping{ .extension = ".mfm", .mime_type = "application/vnd.mfmp" }, MimeMapping{ .extension = ".mgz", .mime_type = "application/vnd.proteus.magazine" }, MimeMapping{ .extension = ".mht", .mime_type = "message/rfc822" }, MimeMapping{ .extension = ".mhtml", .mime_type = "message/rfc822" }, MimeMapping{ .extension = ".mid", .mime_type = "audio/midi" }, MimeMapping{ .extension = ".midi", .mime_type = "audio/midi" }, MimeMapping{ .extension = ".mif", .mime_type = "application/vnd.mif" }, MimeMapping{ .extension = ".mime", .mime_type = "message/rfc822" }, MimeMapping{ .extension = ".mj2", .mime_type = "video/mj2" }, MimeMapping{ .extension = ".mjp2", .mime_type = "video/mj2" }, MimeMapping{ .extension = ".mlp", .mime_type = "application/vnd.dolby.mlp" }, MimeMapping{ .extension = ".mmd", .mime_type = "application/vnd.chipnuts.karaoke-mmd" }, MimeMapping{ .extension = ".mmf", .mime_type = "application/vnd.smaf" }, MimeMapping{ .extension = ".mmr", .mime_type = "image/vnd.fujixerox.edmics-mmr" }, MimeMapping{ .extension = ".mny", .mime_type = "application/x-msmoney" }, MimeMapping{ .extension = ".mobi", .mime_type = "application/x-mobipocket-ebook" }, MimeMapping{ .extension = ".mov", .mime_type = "video/quicktime" }, MimeMapping{ .extension = ".movie", .mime_type = "video/x-sgi-movie" }, MimeMapping{ .extension = ".mp2", .mime_type = "audio/mpeg" }, MimeMapping{ .extension = ".mp2a", .mime_type = "audio/mpeg" }, MimeMapping{ .extension = ".mp3", .mime_type = "audio/mpeg" }, MimeMapping{ .extension = ".mp4", .mime_type = "video/mp4" }, MimeMapping{ .extension = ".mp4a", .mime_type = "audio/mp4" }, MimeMapping{ .extension = ".mp4s", .mime_type = "application/mp4" }, MimeMapping{ .extension = ".mp4v", .mime_type = "video/mp4" }, MimeMapping{ .extension = ".mpa", .mime_type = "video/mpeg" }, MimeMapping{ .extension = ".mpc", .mime_type = "application/vnd.mophun.certificate" }, MimeMapping{ .extension = ".mpe", .mime_type = "video/mpeg" }, MimeMapping{ .extension = ".mpeg", .mime_type = "video/mpeg" }, MimeMapping{ .extension = ".mpg", .mime_type = "video/mpeg" }, MimeMapping{ .extension = ".mpg4", .mime_type = "video/mp4" }, MimeMapping{ .extension = ".mpga", .mime_type = "audio/mpeg" }, MimeMapping{ .extension = ".mpkg", .mime_type = "application/vnd.apple.installer+xml" }, MimeMapping{ .extension = ".mpm", .mime_type = "application/vnd.blueice.multipass" }, MimeMapping{ .extension = ".mpn", .mime_type = "application/vnd.mophun.application" }, MimeMapping{ .extension = ".mpp", .mime_type = "application/vnd.ms-project" }, MimeMapping{ .extension = ".mpt", .mime_type = "application/vnd.ms-project" }, MimeMapping{ .extension = ".mpy", .mime_type = "application/vnd.ibm.minipay" }, MimeMapping{ .extension = ".mqy", .mime_type = "application/vnd.mobius.mqy" }, MimeMapping{ .extension = ".mrc", .mime_type = "application/marc" }, MimeMapping{ .extension = ".ms", .mime_type = "text/troff" }, MimeMapping{ .extension = ".mscml", .mime_type = "application/mediaservercontrol+xml" }, MimeMapping{ .extension = ".mseed", .mime_type = "application/vnd.fdsn.mseed" }, MimeMapping{ .extension = ".mseq", .mime_type = "application/vnd.mseq" }, MimeMapping{ .extension = ".msf", .mime_type = "application/vnd.epson.msf" }, MimeMapping{ .extension = ".msh", .mime_type = "model/mesh" }, MimeMapping{ .extension = ".msi", .mime_type = "application/x-msdownload" }, MimeMapping{ .extension = ".msl", .mime_type = "application/vnd.mobius.msl" }, MimeMapping{ .extension = ".msty", .mime_type = "application/vnd.muvee.style" }, MimeMapping{ .extension = ".mts", .mime_type = "model/vnd.mts" }, MimeMapping{ .extension = ".mus", .mime_type = "application/vnd.musician" }, MimeMapping{ .extension = ".musicxml", .mime_type = "application/vnd.recordare.musicxml+xml" }, MimeMapping{ .extension = ".mvb", .mime_type = "application/x-msmediaview" }, MimeMapping{ .extension = ".mwf", .mime_type = "application/vnd.mfer" }, MimeMapping{ .extension = ".mxf", .mime_type = "application/mxf" }, MimeMapping{ .extension = ".mxl", .mime_type = "application/vnd.recordare.musicxml" }, MimeMapping{ .extension = ".mxml", .mime_type = "application/xv+xml" }, MimeMapping{ .extension = ".mxs", .mime_type = "application/vnd.triscape.mxs" }, MimeMapping{ .extension = ".mxu", .mime_type = "video/vnd.mpegurl" }, MimeMapping{ .extension = ".n-gage", .mime_type = "application/vnd.nokia.n-gage.symbian.install" }, MimeMapping{ .extension = ".nb", .mime_type = "application/mathematica" }, MimeMapping{ .extension = ".nc", .mime_type = "application/x-netcdf" }, MimeMapping{ .extension = ".ncx", .mime_type = "application/x-dtbncx+xml" }, MimeMapping{ .extension = ".ngdat", .mime_type = "application/vnd.nokia.n-gage.data" }, MimeMapping{ .extension = ".nlu", .mime_type = "application/vnd.neurolanguage.nlu" }, MimeMapping{ .extension = ".nml", .mime_type = "application/vnd.enliven" }, MimeMapping{ .extension = ".nnd", .mime_type = "application/vnd.noblenet-directory" }, MimeMapping{ .extension = ".nns", .mime_type = "application/vnd.noblenet-sealer" }, MimeMapping{ .extension = ".nnw", .mime_type = "application/vnd.noblenet-web" }, MimeMapping{ .extension = ".npx", .mime_type = "image/vnd.net-fpx" }, MimeMapping{ .extension = ".nsf", .mime_type = "application/vnd.lotus-notes" }, MimeMapping{ .extension = ".nws", .mime_type = "message/rfc822" }, MimeMapping{ .extension = ".o", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".oa2", .mime_type = "application/vnd.fujitsu.oasys2" }, MimeMapping{ .extension = ".oa3", .mime_type = "application/vnd.fujitsu.oasys3" }, MimeMapping{ .extension = ".oas", .mime_type = "application/vnd.fujitsu.oasys" }, MimeMapping{ .extension = ".obd", .mime_type = "application/x-msbinder" }, MimeMapping{ .extension = ".obj", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".oda", .mime_type = "application/oda" }, MimeMapping{ .extension = ".odb", .mime_type = "application/vnd.oasis.opendocument.database" }, MimeMapping{ .extension = ".odc", .mime_type = "application/vnd.oasis.opendocument.chart" }, MimeMapping{ .extension = ".odf", .mime_type = "application/vnd.oasis.opendocument.formula" }, MimeMapping{ .extension = ".odft", .mime_type = "application/vnd.oasis.opendocument.formula-template" }, MimeMapping{ .extension = ".odg", .mime_type = "application/vnd.oasis.opendocument.graphics" }, MimeMapping{ .extension = ".odi", .mime_type = "application/vnd.oasis.opendocument.image" }, MimeMapping{ .extension = ".odp", .mime_type = "application/vnd.oasis.opendocument.presentation" }, MimeMapping{ .extension = ".ods", .mime_type = "application/vnd.oasis.opendocument.spreadsheet" }, MimeMapping{ .extension = ".odt", .mime_type = "application/vnd.oasis.opendocument.text" }, MimeMapping{ .extension = ".oga", .mime_type = "audio/ogg" }, MimeMapping{ .extension = ".ogg", .mime_type = "audio/ogg" }, MimeMapping{ .extension = ".ogv", .mime_type = "video/ogg" }, MimeMapping{ .extension = ".ogx", .mime_type = "application/ogg" }, MimeMapping{ .extension = ".onepkg", .mime_type = "application/onenote" }, MimeMapping{ .extension = ".onetmp", .mime_type = "application/onenote" }, MimeMapping{ .extension = ".onetoc", .mime_type = "application/onenote" }, MimeMapping{ .extension = ".onetoc2", .mime_type = "application/onenote" }, MimeMapping{ .extension = ".opf", .mime_type = "application/oebps-package+xml" }, MimeMapping{ .extension = ".oprc", .mime_type = "application/vnd.palm" }, MimeMapping{ .extension = ".org", .mime_type = "application/vnd.lotus-organizer" }, MimeMapping{ .extension = ".osf", .mime_type = "application/vnd.yamaha.openscoreformat" }, MimeMapping{ .extension = ".osfpvg", .mime_type = "application/vnd.yamaha.openscoreformat.osfpvg+xml" }, MimeMapping{ .extension = ".otc", .mime_type = "application/vnd.oasis.opendocument.chart-template" }, MimeMapping{ .extension = ".otf", .mime_type = "application/x-font-otf" }, MimeMapping{ .extension = ".otg", .mime_type = "application/vnd.oasis.opendocument.graphics-template" }, MimeMapping{ .extension = ".oth", .mime_type = "application/vnd.oasis.opendocument.text-web" }, MimeMapping{ .extension = ".oti", .mime_type = "application/vnd.oasis.opendocument.image-template" }, MimeMapping{ .extension = ".otm", .mime_type = "application/vnd.oasis.opendocument.text-master" }, MimeMapping{ .extension = ".otp", .mime_type = "application/vnd.oasis.opendocument.presentation-template" }, MimeMapping{ .extension = ".ots", .mime_type = "application/vnd.oasis.opendocument.spreadsheet-template" }, MimeMapping{ .extension = ".ott", .mime_type = "application/vnd.oasis.opendocument.text-template" }, MimeMapping{ .extension = ".oxt", .mime_type = "application/vnd.openofficeorg.extension" }, MimeMapping{ .extension = ".p", .mime_type = "text/x-pascal" }, MimeMapping{ .extension = ".p10", .mime_type = "application/pkcs10" }, MimeMapping{ .extension = ".p12", .mime_type = "application/x-pkcs12" }, MimeMapping{ .extension = ".p7b", .mime_type = "application/x-pkcs7-certificates" }, MimeMapping{ .extension = ".p7c", .mime_type = "application/pkcs7-mime" }, MimeMapping{ .extension = ".p7m", .mime_type = "application/pkcs7-mime" }, MimeMapping{ .extension = ".p7r", .mime_type = "application/x-pkcs7-certreqresp" }, MimeMapping{ .extension = ".p7s", .mime_type = "application/pkcs7-signature" }, MimeMapping{ .extension = ".pas", .mime_type = "text/x-pascal" }, MimeMapping{ .extension = ".pbd", .mime_type = "application/vnd.powerbuilder6" }, MimeMapping{ .extension = ".pbm", .mime_type = "image/x-portable-bitmap" }, MimeMapping{ .extension = ".pcf", .mime_type = "application/x-font-pcf" }, MimeMapping{ .extension = ".pcl", .mime_type = "application/vnd.hp-pcl" }, MimeMapping{ .extension = ".pclxl", .mime_type = "application/vnd.hp-pclxl" }, MimeMapping{ .extension = ".pct", .mime_type = "image/x-pict" }, MimeMapping{ .extension = ".pcurl", .mime_type = "application/vnd.curl.pcurl" }, MimeMapping{ .extension = ".pcx", .mime_type = "image/x-pcx" }, MimeMapping{ .extension = ".pdb", .mime_type = "application/vnd.palm" }, MimeMapping{ .extension = ".pdf", .mime_type = "application/pdf" }, MimeMapping{ .extension = ".pfa", .mime_type = "application/x-font-type1" }, MimeMapping{ .extension = ".pfb", .mime_type = "application/x-font-type1" }, MimeMapping{ .extension = ".pfm", .mime_type = "application/x-font-type1" }, MimeMapping{ .extension = ".pfr", .mime_type = "application/font-tdpfr" }, MimeMapping{ .extension = ".pfx", .mime_type = "application/x-pkcs12" }, MimeMapping{ .extension = ".pgm", .mime_type = "image/x-portable-graymap" }, MimeMapping{ .extension = ".pgn", .mime_type = "application/x-chess-pgn" }, MimeMapping{ .extension = ".pgp", .mime_type = "application/pgp-encrypted" }, MimeMapping{ .extension = ".pic", .mime_type = "image/x-pict" }, MimeMapping{ .extension = ".pkg", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".pki", .mime_type = "application/pkixcmp" }, MimeMapping{ .extension = ".pkipath", .mime_type = "application/pkix-pkipath" }, MimeMapping{ .extension = ".pl", .mime_type = "text/plain" }, MimeMapping{ .extension = ".plb", .mime_type = "application/vnd.3gpp.pic-bw-large" }, MimeMapping{ .extension = ".plc", .mime_type = "application/vnd.mobius.plc" }, MimeMapping{ .extension = ".plf", .mime_type = "application/vnd.pocketlearn" }, MimeMapping{ .extension = ".pls", .mime_type = "application/pls+xml" }, MimeMapping{ .extension = ".pml", .mime_type = "application/vnd.ctc-posml" }, MimeMapping{ .extension = ".png", .mime_type = "image/png" }, MimeMapping{ .extension = ".pnm", .mime_type = "image/x-portable-anymap" }, MimeMapping{ .extension = ".portpkg", .mime_type = "application/vnd.macports.portpkg" }, MimeMapping{ .extension = ".pot", .mime_type = "application/vnd.ms-powerpoint" }, MimeMapping{ .extension = ".potm", .mime_type = "application/vnd.ms-powerpoint.template.macroenabled.12" }, MimeMapping{ .extension = ".potx", .mime_type = "application/vnd.openxmlformats-officedocument.presentationml.template" }, MimeMapping{ .extension = ".ppa", .mime_type = "application/vnd.ms-powerpoint" }, MimeMapping{ .extension = ".ppam", .mime_type = "application/vnd.ms-powerpoint.addin.macroenabled.12" }, MimeMapping{ .extension = ".ppd", .mime_type = "application/vnd.cups-ppd" }, MimeMapping{ .extension = ".ppm", .mime_type = "image/x-portable-pixmap" }, MimeMapping{ .extension = ".pps", .mime_type = "application/vnd.ms-powerpoint" }, MimeMapping{ .extension = ".ppsm", .mime_type = "application/vnd.ms-powerpoint.slideshow.macroenabled.12" }, MimeMapping{ .extension = ".ppsx", .mime_type = "application/vnd.openxmlformats-officedocument.presentationml.slideshow" }, MimeMapping{ .extension = ".ppt", .mime_type = "application/vnd.ms-powerpoint" }, MimeMapping{ .extension = ".pptm", .mime_type = "application/vnd.ms-powerpoint.presentation.macroenabled.12" }, MimeMapping{ .extension = ".pptx", .mime_type = "application/vnd.openxmlformats-officedocument.presentationml.presentation" }, MimeMapping{ .extension = ".pqa", .mime_type = "application/vnd.palm" }, MimeMapping{ .extension = ".prc", .mime_type = "application/x-mobipocket-ebook" }, MimeMapping{ .extension = ".pre", .mime_type = "application/vnd.lotus-freelance" }, MimeMapping{ .extension = ".prf", .mime_type = "application/pics-rules" }, MimeMapping{ .extension = ".ps", .mime_type = "application/postscript" }, MimeMapping{ .extension = ".psb", .mime_type = "application/vnd.3gpp.pic-bw-small" }, MimeMapping{ .extension = ".psd", .mime_type = "image/vnd.adobe.photoshop" }, MimeMapping{ .extension = ".psf", .mime_type = "application/x-font-linux-psf" }, MimeMapping{ .extension = ".ptid", .mime_type = "application/vnd.pvi.ptid1" }, MimeMapping{ .extension = ".pub", .mime_type = "application/x-mspublisher" }, MimeMapping{ .extension = ".pvb", .mime_type = "application/vnd.3gpp.pic-bw-var" }, MimeMapping{ .extension = ".pwn", .mime_type = "application/vnd.3m.post-it-notes" }, MimeMapping{ .extension = ".pwz", .mime_type = "application/vnd.ms-powerpoint" }, MimeMapping{ .extension = ".py", .mime_type = "text/x-python" }, MimeMapping{ .extension = ".pya", .mime_type = "audio/vnd.ms-playready.media.pya" }, MimeMapping{ .extension = ".pyc", .mime_type = "application/x-python-code" }, MimeMapping{ .extension = ".pyo", .mime_type = "application/x-python-code" }, MimeMapping{ .extension = ".pyv", .mime_type = "video/vnd.ms-playready.media.pyv" }, MimeMapping{ .extension = ".qam", .mime_type = "application/vnd.epson.quickanime" }, MimeMapping{ .extension = ".qbo", .mime_type = "application/vnd.intu.qbo" }, MimeMapping{ .extension = ".qfx", .mime_type = "application/vnd.intu.qfx" }, MimeMapping{ .extension = ".qps", .mime_type = "application/vnd.publishare-delta-tree" }, MimeMapping{ .extension = ".qt", .mime_type = "video/quicktime" }, MimeMapping{ .extension = ".qwd", .mime_type = "application/vnd.quark.quarkxpress" }, MimeMapping{ .extension = ".qwt", .mime_type = "application/vnd.quark.quarkxpress" }, MimeMapping{ .extension = ".qxb", .mime_type = "application/vnd.quark.quarkxpress" }, MimeMapping{ .extension = ".qxd", .mime_type = "application/vnd.quark.quarkxpress" }, MimeMapping{ .extension = ".qxl", .mime_type = "application/vnd.quark.quarkxpress" }, MimeMapping{ .extension = ".qxt", .mime_type = "application/vnd.quark.quarkxpress" }, MimeMapping{ .extension = ".ra", .mime_type = "audio/x-pn-realaudio" }, MimeMapping{ .extension = ".ram", .mime_type = "audio/x-pn-realaudio" }, MimeMapping{ .extension = ".rar", .mime_type = "application/x-rar-compressed" }, MimeMapping{ .extension = ".ras", .mime_type = "image/x-cmu-raster" }, MimeMapping{ .extension = ".rcprofile", .mime_type = "application/vnd.ipunplugged.rcprofile" }, MimeMapping{ .extension = ".rdf", .mime_type = "application/rdf+xml" }, MimeMapping{ .extension = ".rdz", .mime_type = "application/vnd.data-vision.rdz" }, MimeMapping{ .extension = ".rep", .mime_type = "application/vnd.businessobjects" }, MimeMapping{ .extension = ".res", .mime_type = "application/x-dtbresource+xml" }, MimeMapping{ .extension = ".rgb", .mime_type = "image/x-rgb" }, MimeMapping{ .extension = ".rif", .mime_type = "application/reginfo+xml" }, MimeMapping{ .extension = ".rl", .mime_type = "application/resource-lists+xml" }, MimeMapping{ .extension = ".rlc", .mime_type = "image/vnd.fujixerox.edmics-rlc" }, MimeMapping{ .extension = ".rld", .mime_type = "application/resource-lists-diff+xml" }, MimeMapping{ .extension = ".rm", .mime_type = "application/vnd.rn-realmedia" }, MimeMapping{ .extension = ".rmi", .mime_type = "audio/midi" }, MimeMapping{ .extension = ".rmp", .mime_type = "audio/x-pn-realaudio-plugin" }, MimeMapping{ .extension = ".rms", .mime_type = "application/vnd.jcp.javame.midlet-rms" }, MimeMapping{ .extension = ".rnc", .mime_type = "application/relax-ng-compact-syntax" }, MimeMapping{ .extension = ".roff", .mime_type = "text/troff" }, MimeMapping{ .extension = ".rpm", .mime_type = "application/x-rpm" }, MimeMapping{ .extension = ".rpss", .mime_type = "application/vnd.nokia.radio-presets" }, MimeMapping{ .extension = ".rpst", .mime_type = "application/vnd.nokia.radio-preset" }, MimeMapping{ .extension = ".rq", .mime_type = "application/sparql-query" }, MimeMapping{ .extension = ".rs", .mime_type = "application/rls-services+xml" }, MimeMapping{ .extension = ".rsd", .mime_type = "application/rsd+xml" }, MimeMapping{ .extension = ".rss", .mime_type = "application/rss+xml" }, MimeMapping{ .extension = ".rtf", .mime_type = "application/rtf" }, MimeMapping{ .extension = ".rtx", .mime_type = "text/richtext" }, MimeMapping{ .extension = ".s", .mime_type = "text/x-asm" }, MimeMapping{ .extension = ".saf", .mime_type = "application/vnd.yamaha.smaf-audio" }, MimeMapping{ .extension = ".sbml", .mime_type = "application/sbml+xml" }, MimeMapping{ .extension = ".sc", .mime_type = "application/vnd.ibm.secure-container" }, MimeMapping{ .extension = ".scd", .mime_type = "application/x-msschedule" }, MimeMapping{ .extension = ".scm", .mime_type = "application/vnd.lotus-screencam" }, MimeMapping{ .extension = ".scq", .mime_type = "application/scvp-cv-request" }, MimeMapping{ .extension = ".scs", .mime_type = "application/scvp-cv-response" }, MimeMapping{ .extension = ".scurl", .mime_type = "text/vnd.curl.scurl" }, MimeMapping{ .extension = ".sda", .mime_type = "application/vnd.stardivision.draw" }, MimeMapping{ .extension = ".sdc", .mime_type = "application/vnd.stardivision.calc" }, MimeMapping{ .extension = ".sdd", .mime_type = "application/vnd.stardivision.impress" }, MimeMapping{ .extension = ".sdkd", .mime_type = "application/vnd.solent.sdkm+xml" }, MimeMapping{ .extension = ".sdkm", .mime_type = "application/vnd.solent.sdkm+xml" }, MimeMapping{ .extension = ".sdp", .mime_type = "application/sdp" }, MimeMapping{ .extension = ".sdw", .mime_type = "application/vnd.stardivision.writer" }, MimeMapping{ .extension = ".see", .mime_type = "application/vnd.seemail" }, MimeMapping{ .extension = ".seed", .mime_type = "application/vnd.fdsn.seed" }, MimeMapping{ .extension = ".sema", .mime_type = "application/vnd.sema" }, MimeMapping{ .extension = ".semd", .mime_type = "application/vnd.semd" }, MimeMapping{ .extension = ".semf", .mime_type = "application/vnd.semf" }, MimeMapping{ .extension = ".ser", .mime_type = "application/java-serialized-object" }, MimeMapping{ .extension = ".setpay", .mime_type = "application/set-payment-initiation" }, MimeMapping{ .extension = ".setreg", .mime_type = "application/set-registration-initiation" }, MimeMapping{ .extension = ".sfd-hdstx", .mime_type = "application/vnd.hydrostatix.sof-data" }, MimeMapping{ .extension = ".sfs", .mime_type = "application/vnd.spotfire.sfs" }, MimeMapping{ .extension = ".sgl", .mime_type = "application/vnd.stardivision.writer-global" }, MimeMapping{ .extension = ".sgm", .mime_type = "text/sgml" }, MimeMapping{ .extension = ".sgml", .mime_type = "text/sgml" }, MimeMapping{ .extension = ".sh", .mime_type = "application/x-sh" }, MimeMapping{ .extension = ".shar", .mime_type = "application/x-shar" }, MimeMapping{ .extension = ".shf", .mime_type = "application/shf+xml" }, MimeMapping{ .extension = ".si", .mime_type = "text/vnd.wap.si" }, MimeMapping{ .extension = ".sic", .mime_type = "application/vnd.wap.sic" }, MimeMapping{ .extension = ".sig", .mime_type = "application/pgp-signature" }, MimeMapping{ .extension = ".silo", .mime_type = "model/mesh" }, MimeMapping{ .extension = ".sis", .mime_type = "application/vnd.symbian.install" }, MimeMapping{ .extension = ".sisx", .mime_type = "application/vnd.symbian.install" }, MimeMapping{ .extension = ".sit", .mime_type = "application/x-stuffit" }, MimeMapping{ .extension = ".sitx", .mime_type = "application/x-stuffitx" }, MimeMapping{ .extension = ".skd", .mime_type = "application/vnd.koan" }, MimeMapping{ .extension = ".skm", .mime_type = "application/vnd.koan" }, MimeMapping{ .extension = ".skp", .mime_type = "application/vnd.koan" }, MimeMapping{ .extension = ".skt", .mime_type = "application/vnd.koan" }, MimeMapping{ .extension = ".sl", .mime_type = "text/vnd.wap.sl" }, MimeMapping{ .extension = ".slc", .mime_type = "application/vnd.wap.slc" }, MimeMapping{ .extension = ".sldm", .mime_type = "application/vnd.ms-powerpoint.slide.macroenabled.12" }, MimeMapping{ .extension = ".sldx", .mime_type = "application/vnd.openxmlformats-officedocument.presentationml.slide" }, MimeMapping{ .extension = ".slt", .mime_type = "application/vnd.epson.salt" }, MimeMapping{ .extension = ".smf", .mime_type = "application/vnd.stardivision.math" }, MimeMapping{ .extension = ".smi", .mime_type = "application/smil+xml" }, MimeMapping{ .extension = ".smil", .mime_type = "application/smil+xml" }, MimeMapping{ .extension = ".snd", .mime_type = "audio/basic" }, MimeMapping{ .extension = ".snf", .mime_type = "application/x-font-snf" }, MimeMapping{ .extension = ".so", .mime_type = "application/octet-stream" }, MimeMapping{ .extension = ".spc", .mime_type = "application/x-pkcs7-certificates" }, MimeMapping{ .extension = ".spf", .mime_type = "application/vnd.yamaha.smaf-phrase" }, MimeMapping{ .extension = ".spl", .mime_type = "application/x-futuresplash" }, MimeMapping{ .extension = ".spot", .mime_type = "text/vnd.in3d.spot" }, MimeMapping{ .extension = ".spp", .mime_type = "application/scvp-vp-response" }, MimeMapping{ .extension = ".spq", .mime_type = "application/scvp-vp-request" }, MimeMapping{ .extension = ".spx", .mime_type = "audio/ogg" }, MimeMapping{ .extension = ".src", .mime_type = "application/x-wais-source" }, MimeMapping{ .extension = ".srx", .mime_type = "application/sparql-results+xml" }, MimeMapping{ .extension = ".sse", .mime_type = "application/vnd.kodak-descriptor" }, MimeMapping{ .extension = ".ssf", .mime_type = "application/vnd.epson.ssf" }, MimeMapping{ .extension = ".ssml", .mime_type = "application/ssml+xml" }, MimeMapping{ .extension = ".stc", .mime_type = "application/vnd.sun.xml.calc.template" }, MimeMapping{ .extension = ".std", .mime_type = "application/vnd.sun.xml.draw.template" }, MimeMapping{ .extension = ".stf", .mime_type = "application/vnd.wt.stf" }, MimeMapping{ .extension = ".sti", .mime_type = "application/vnd.sun.xml.impress.template" }, MimeMapping{ .extension = ".stk", .mime_type = "application/hyperstudio" }, MimeMapping{ .extension = ".stl", .mime_type = "application/vnd.ms-pki.stl" }, MimeMapping{ .extension = ".str", .mime_type = "application/vnd.pg.format" }, MimeMapping{ .extension = ".stw", .mime_type = "application/vnd.sun.xml.writer.template" }, MimeMapping{ .extension = ".sus", .mime_type = "application/vnd.sus-calendar" }, MimeMapping{ .extension = ".susp", .mime_type = "application/vnd.sus-calendar" }, MimeMapping{ .extension = ".sv4cpio", .mime_type = "application/x-sv4cpio" }, MimeMapping{ .extension = ".sv4crc", .mime_type = "application/x-sv4crc" }, MimeMapping{ .extension = ".svd", .mime_type = "application/vnd.svd" }, MimeMapping{ .extension = ".svg", .mime_type = "image/svg+xml" }, MimeMapping{ .extension = ".svgz", .mime_type = "image/svg+xml" }, MimeMapping{ .extension = ".swa", .mime_type = "application/x-director" }, MimeMapping{ .extension = ".swf", .mime_type = "application/x-shockwave-flash" }, MimeMapping{ .extension = ".swi", .mime_type = "application/vnd.arastra.swi" }, MimeMapping{ .extension = ".sxc", .mime_type = "application/vnd.sun.xml.calc" }, MimeMapping{ .extension = ".sxd", .mime_type = "application/vnd.sun.xml.draw" }, MimeMapping{ .extension = ".sxg", .mime_type = "application/vnd.sun.xml.writer.global" }, MimeMapping{ .extension = ".sxi", .mime_type = "application/vnd.sun.xml.impress" }, MimeMapping{ .extension = ".sxm", .mime_type = "application/vnd.sun.xml.math" }, MimeMapping{ .extension = ".sxw", .mime_type = "application/vnd.sun.xml.writer" }, MimeMapping{ .extension = ".t", .mime_type = "text/troff" }, MimeMapping{ .extension = ".tao", .mime_type = "application/vnd.tao.intent-module-archive" }, MimeMapping{ .extension = ".tar", .mime_type = "application/x-tar" }, MimeMapping{ .extension = ".tcap", .mime_type = "application/vnd.3gpp2.tcap" }, MimeMapping{ .extension = ".tcl", .mime_type = "application/x-tcl" }, MimeMapping{ .extension = ".teacher", .mime_type = "application/vnd.smart.teacher" }, MimeMapping{ .extension = ".tex", .mime_type = "application/x-tex" }, MimeMapping{ .extension = ".texi", .mime_type = "application/x-texinfo" }, MimeMapping{ .extension = ".texinfo", .mime_type = "application/x-texinfo" }, MimeMapping{ .extension = ".text", .mime_type = "text/plain" }, MimeMapping{ .extension = ".tfm", .mime_type = "application/x-tex-tfm" }, MimeMapping{ .extension = ".tgz", .mime_type = "application/x-gzip" }, MimeMapping{ .extension = ".tif", .mime_type = "image/tiff" }, MimeMapping{ .extension = ".tiff", .mime_type = "image/tiff" }, MimeMapping{ .extension = ".tmo", .mime_type = "application/vnd.tmobile-livetv" }, MimeMapping{ .extension = ".torrent", .mime_type = "application/x-bittorrent" }, MimeMapping{ .extension = ".tpl", .mime_type = "application/vnd.groove-tool-template" }, MimeMapping{ .extension = ".tpt", .mime_type = "application/vnd.trid.tpt" }, MimeMapping{ .extension = ".tr", .mime_type = "text/troff" }, MimeMapping{ .extension = ".tra", .mime_type = "application/vnd.trueapp" }, MimeMapping{ .extension = ".trm", .mime_type = "application/x-msterminal" }, MimeMapping{ .extension = ".tsv", .mime_type = "text/tab-separated-values" }, MimeMapping{ .extension = ".ttc", .mime_type = "application/x-font-ttf" }, MimeMapping{ .extension = ".ttf", .mime_type = "application/x-font-ttf" }, MimeMapping{ .extension = ".twd", .mime_type = "application/vnd.simtech-mindmapper" }, MimeMapping{ .extension = ".twds", .mime_type = "application/vnd.simtech-mindmapper" }, MimeMapping{ .extension = ".txd", .mime_type = "application/vnd.genomatix.tuxedo" }, MimeMapping{ .extension = ".txf", .mime_type = "application/vnd.mobius.txf" }, MimeMapping{ .extension = ".txt", .mime_type = "text/plain" }, MimeMapping{ .extension = ".u32", .mime_type = "application/x-authorware-bin" }, MimeMapping{ .extension = ".udeb", .mime_type = "application/x-debian-package" }, MimeMapping{ .extension = ".ufd", .mime_type = "application/vnd.ufdl" }, MimeMapping{ .extension = ".ufdl", .mime_type = "application/vnd.ufdl" }, MimeMapping{ .extension = ".umj", .mime_type = "application/vnd.umajin" }, MimeMapping{ .extension = ".unityweb", .mime_type = "application/vnd.unity" }, MimeMapping{ .extension = ".uoml", .mime_type = "application/vnd.uoml+xml" }, MimeMapping{ .extension = ".uri", .mime_type = "text/uri-list" }, MimeMapping{ .extension = ".uris", .mime_type = "text/uri-list" }, MimeMapping{ .extension = ".urls", .mime_type = "text/uri-list" }, MimeMapping{ .extension = ".ustar", .mime_type = "application/x-ustar" }, MimeMapping{ .extension = ".utz", .mime_type = "application/vnd.uiq.theme" }, MimeMapping{ .extension = ".uu", .mime_type = "text/x-uuencode" }, MimeMapping{ .extension = ".vcd", .mime_type = "application/x-cdlink" }, MimeMapping{ .extension = ".vcf", .mime_type = "text/x-vcard" }, MimeMapping{ .extension = ".vcg", .mime_type = "application/vnd.groove-vcard" }, MimeMapping{ .extension = ".vcs", .mime_type = "text/x-vcalendar" }, MimeMapping{ .extension = ".vcx", .mime_type = "application/vnd.vcx" }, MimeMapping{ .extension = ".vis", .mime_type = "application/vnd.visionary" }, MimeMapping{ .extension = ".viv", .mime_type = "video/vnd.vivo" }, MimeMapping{ .extension = ".vor", .mime_type = "application/vnd.stardivision.writer" }, MimeMapping{ .extension = ".vox", .mime_type = "application/x-authorware-bin" }, MimeMapping{ .extension = ".vrml", .mime_type = "model/vrml" }, MimeMapping{ .extension = ".vsd", .mime_type = "application/vnd.visio" }, MimeMapping{ .extension = ".vsf", .mime_type = "application/vnd.vsf" }, MimeMapping{ .extension = ".vss", .mime_type = "application/vnd.visio" }, MimeMapping{ .extension = ".vst", .mime_type = "application/vnd.visio" }, MimeMapping{ .extension = ".vsw", .mime_type = "application/vnd.visio" }, MimeMapping{ .extension = ".vtu", .mime_type = "model/vnd.vtu" }, MimeMapping{ .extension = ".vxml", .mime_type = "application/voicexml+xml" }, MimeMapping{ .extension = ".w3d", .mime_type = "application/x-director" }, MimeMapping{ .extension = ".wad", .mime_type = "application/x-doom" }, MimeMapping{ .extension = ".wasm", .mime_type = "application/wasm" }, MimeMapping{ .extension = ".wav", .mime_type = "audio/x-wav" }, MimeMapping{ .extension = ".wax", .mime_type = "audio/x-ms-wax" }, MimeMapping{ .extension = ".wbmp", .mime_type = "image/vnd.wap.wbmp" }, MimeMapping{ .extension = ".wbs", .mime_type = "application/vnd.criticaltools.wbs+xml" }, MimeMapping{ .extension = ".wbxml", .mime_type = "application/vnd.wap.wbxml" }, MimeMapping{ .extension = ".wcm", .mime_type = "application/vnd.ms-works" }, MimeMapping{ .extension = ".wdb", .mime_type = "application/vnd.ms-works" }, MimeMapping{ .extension = ".wiz", .mime_type = "application/msword" }, MimeMapping{ .extension = ".wks", .mime_type = "application/vnd.ms-works" }, MimeMapping{ .extension = ".wm", .mime_type = "video/x-ms-wm" }, MimeMapping{ .extension = ".wma", .mime_type = "audio/x-ms-wma" }, MimeMapping{ .extension = ".wmd", .mime_type = "application/x-ms-wmd" }, MimeMapping{ .extension = ".wmf", .mime_type = "application/x-msmetafile" }, MimeMapping{ .extension = ".wml", .mime_type = "text/vnd.wap.wml" }, MimeMapping{ .extension = ".wmlc", .mime_type = "application/vnd.wap.wmlc" }, MimeMapping{ .extension = ".wmls", .mime_type = "text/vnd.wap.wmlscript" }, MimeMapping{ .extension = ".wmlsc", .mime_type = "application/vnd.wap.wmlscriptc" }, MimeMapping{ .extension = ".wmv", .mime_type = "video/x-ms-wmv" }, MimeMapping{ .extension = ".wmx", .mime_type = "video/x-ms-wmx" }, MimeMapping{ .extension = ".wmz", .mime_type = "application/x-ms-wmz" }, MimeMapping{ .extension = ".wpd", .mime_type = "application/vnd.wordperfect" }, MimeMapping{ .extension = ".wpl", .mime_type = "application/vnd.ms-wpl" }, MimeMapping{ .extension = ".wps", .mime_type = "application/vnd.ms-works" }, MimeMapping{ .extension = ".wqd", .mime_type = "application/vnd.wqd" }, MimeMapping{ .extension = ".wri", .mime_type = "application/x-mswrite" }, MimeMapping{ .extension = ".wrl", .mime_type = "model/vrml" }, MimeMapping{ .extension = ".wsdl", .mime_type = "application/wsdl+xml" }, MimeMapping{ .extension = ".wspolicy", .mime_type = "application/wspolicy+xml" }, MimeMapping{ .extension = ".wtb", .mime_type = "application/vnd.webturbo" }, MimeMapping{ .extension = ".wvx", .mime_type = "video/x-ms-wvx" }, MimeMapping{ .extension = ".x32", .mime_type = "application/x-authorware-bin" }, MimeMapping{ .extension = ".x3d", .mime_type = "application/vnd.hzn-3d-crossword" }, MimeMapping{ .extension = ".xap", .mime_type = "application/x-silverlight-app" }, MimeMapping{ .extension = ".xar", .mime_type = "application/vnd.xara" }, MimeMapping{ .extension = ".xbap", .mime_type = "application/x-ms-xbap" }, MimeMapping{ .extension = ".xbd", .mime_type = "application/vnd.fujixerox.docuworks.binder" }, MimeMapping{ .extension = ".xbm", .mime_type = "image/x-xbitmap" }, MimeMapping{ .extension = ".xdm", .mime_type = "application/vnd.syncml.dm+xml" }, MimeMapping{ .extension = ".xdp", .mime_type = "application/vnd.adobe.xdp+xml" }, MimeMapping{ .extension = ".xdw", .mime_type = "application/vnd.fujixerox.docuworks" }, MimeMapping{ .extension = ".xenc", .mime_type = "application/xenc+xml" }, MimeMapping{ .extension = ".xer", .mime_type = "application/patch-ops-error+xml" }, MimeMapping{ .extension = ".xfdf", .mime_type = "application/vnd.adobe.xfdf" }, MimeMapping{ .extension = ".xfdl", .mime_type = "application/vnd.xfdl" }, MimeMapping{ .extension = ".xht", .mime_type = "application/xhtml+xml" }, MimeMapping{ .extension = ".xhtml", .mime_type = "application/xhtml+xml" }, MimeMapping{ .extension = ".xhvml", .mime_type = "application/xv+xml" }, MimeMapping{ .extension = ".xif", .mime_type = "image/vnd.xiff" }, MimeMapping{ .extension = ".xla", .mime_type = "application/vnd.ms-excel" }, MimeMapping{ .extension = ".xlam", .mime_type = "application/vnd.ms-excel.addin.macroenabled.12" }, MimeMapping{ .extension = ".xlb", .mime_type = "application/vnd.ms-excel" }, MimeMapping{ .extension = ".xlc", .mime_type = "application/vnd.ms-excel" }, MimeMapping{ .extension = ".xlm", .mime_type = "application/vnd.ms-excel" }, MimeMapping{ .extension = ".xls", .mime_type = "application/vnd.ms-excel" }, MimeMapping{ .extension = ".xlsb", .mime_type = "application/vnd.ms-excel.sheet.binary.macroenabled.12" }, MimeMapping{ .extension = ".xlsm", .mime_type = "application/vnd.ms-excel.sheet.macroenabled.12" }, MimeMapping{ .extension = ".xlsx", .mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }, MimeMapping{ .extension = ".xlt", .mime_type = "application/vnd.ms-excel" }, MimeMapping{ .extension = ".xltm", .mime_type = "application/vnd.ms-excel.template.macroenabled.12" }, MimeMapping{ .extension = ".xltx", .mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.template" }, MimeMapping{ .extension = ".xlw", .mime_type = "application/vnd.ms-excel" }, MimeMapping{ .extension = ".xml", .mime_type = "application/xml" }, MimeMapping{ .extension = ".xo", .mime_type = "application/vnd.olpc-sugar" }, MimeMapping{ .extension = ".xop", .mime_type = "application/xop+xml" }, MimeMapping{ .extension = ".xpdl", .mime_type = "application/xml" }, MimeMapping{ .extension = ".xpi", .mime_type = "application/x-xpinstall" }, MimeMapping{ .extension = ".xpm", .mime_type = "image/x-xpixmap" }, MimeMapping{ .extension = ".xpr", .mime_type = "application/vnd.is-xpr" }, MimeMapping{ .extension = ".xps", .mime_type = "application/vnd.ms-xpsdocument" }, MimeMapping{ .extension = ".xpw", .mime_type = "application/vnd.intercon.formnet" }, MimeMapping{ .extension = ".xpx", .mime_type = "application/vnd.intercon.formnet" }, MimeMapping{ .extension = ".xsl", .mime_type = "application/xml" }, MimeMapping{ .extension = ".xslt", .mime_type = "application/xslt+xml" }, MimeMapping{ .extension = ".xsm", .mime_type = "application/vnd.syncml+xml" }, MimeMapping{ .extension = ".xspf", .mime_type = "application/xspf+xml" }, MimeMapping{ .extension = ".xul", .mime_type = "application/vnd.mozilla.xul+xml" }, MimeMapping{ .extension = ".xvm", .mime_type = "application/xv+xml" }, MimeMapping{ .extension = ".xvml", .mime_type = "application/xv+xml" }, MimeMapping{ .extension = ".xwd", .mime_type = "image/x-xwindowdump" }, MimeMapping{ .extension = ".xyz", .mime_type = "chemical/x-xyz" }, MimeMapping{ .extension = ".zaz", .mime_type = "application/vnd.zzazz.deck+xml" }, MimeMapping{ .extension = ".zip", .mime_type = "application/zip" }, MimeMapping{ .extension = ".zir", .mime_type = "application/vnd.zul" }, MimeMapping{ .extension = ".zirz", .mime_type = "application/vnd.zul" }, MimeMapping{ .extension = ".zmm", .mime_type = "application/vnd.handheld-entertainment+xml" }, };
src/mime_db.zig
const std = @import("std"); const Game = @import("game.zig"); const Board = Game.Board; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const split = std.mem.split; const print = std.debug.print; const Data = struct { numbers: []i32, boards: []*Board, }; fn load(allocator: *Allocator, filename: []const u8) !Data { const file = try std.fs.cwd().openFile(filename, .{}); defer file.close(); const reader = file.reader(); // Longest line is 291, round up to 300 anyway var buf = [_]u8{0} ** 300; // Read numbers in const firstLine = try reader.readUntilDelimiter(&buf, '\n'); // Convert the line to an iterator var rawNumbers = std.mem.split(u8, firstLine, ","); var numbers = std.ArrayList(i32).init(allocator); // It's kinda silly to discard the iterator just to build another one, // but I wanted the game methods to receive a list of numbers, not strings while (rawNumbers.next()) |next| { // I tried my hardest to make this less hacky but I gave up const number = std.fmt.parseInt(i32, next, 10) catch { break; }; try numbers.append(number); } var boards = std.ArrayList(*Board).init(allocator); while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |_| { var board = try Board.fromReader(allocator, reader); try boards.append(board); } return Data { .numbers = numbers.toOwnedSlice(), .boards = boards.toOwnedSlice() }; } fn part1(allocator: *Allocator, filename: []const u8) !i32 { var data = try load(allocator, filename); defer allocator.free(data.boards); defer allocator.free(data.numbers); const winner = Game.run(data.boards, data.numbers); const score = winner.board.score(winner.number); return score; } fn part2(allocator: *Allocator, filename: []const u8) !i32 { var data = try load(allocator, filename); defer allocator.free(data.boards); defer allocator.free(data.numbers); const winner = try Game.findLastBoard(allocator, data.boards, data.numbers); const score = winner.board.score(winner.number); return score; } pub fn main() anyerror!void { const filename = "input.txt"; var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); print("Part 1: {d}\n", .{try part1(&arena.allocator, filename)}); print("Part 2: {d}", .{try part2(&arena.allocator, filename)}); } test "Returns the correct winning score in test file" { const filename = "test.txt"; var test_allocator = std.testing.allocator; const result = try part1(test_allocator, filename); try std.testing.expect(result == 4512); } test "Returns the score for the last winning board in test file" { const filename = "test.txt"; var test_allocator = std.testing.allocator; const result = try part2(test_allocator, filename); try std.testing.expect(result == 1924); }
Day4/src/main.zig
const std = @import("std"); const eql = std.mem.eql; const min = std.math.min; const max = std.math.max; const mem = std.mem; const parseInt = std.fmt.parseInt; const print = std.debug.print; const testing = std.testing; const tokenize = std.mem.tokenize; var gpa_impl = std.heap.GeneralPurposeAllocator(.{}){}; const gpa = gpa_impl.allocator(); const input = @embedFile("./input.txt"); // const input = @embedFile("./input-sample.txt"); const Dot = [2]u32; const Dots = std.AutoHashMap(Dot, bool); const Folds = std.ArrayList(Dot); pub fn main() anyerror!void { print("--- Part One ---\n", .{}); print("Result: {d}\n", .{part1()}); print("--- Part Two ---\n", .{}); print("Result:\n{s}\n", .{part2()}); } /// /// --- Part One --- /// fn part1() !u32 { var dots = try parseDots(); defer dots.deinit(); var folds = try parseFolds(); defer folds.deinit(); var new_dots = try foldOnce(dots, folds.items[0]); defer new_dots.deinit(); return new_dots.count(); } test "day13.part1" { try testing.expectEqual(@as(u32, 827), try part1()); } /// /// --- Part Two --- /// fn part2() ![]u8 { var dots = try parseDots(); defer dots.deinit(); var folds = try parseFolds(); defer folds.deinit(); for (folds.items) |fold| { var new_dots = try foldOnce(dots, fold); dots.deinit(); dots = new_dots; } return try dotsToString(dots, 2); } test "day13.part2" { const eahkrecp = \\######## #### ## ## ## ## ###### ######## #### ###### . \\## ## ## ## ## ## ## ## ## ## ## ## ## ##. \\###### ## ## ######## #### ## ## ###### ## ## ##. \\## ######## ## ## ## ## ###### ## ## ###### . \\## ## ## ## ## ## ## ## ## ## ## ## ## . \\######## ## ## ## ## ## ## ## ## ######## #### ## . ; var expected: [eahkrecp.len]u8 = undefined; _ = mem.replace(u8, eahkrecp, ".", "", expected[0..]); const actual = try part2(); try testing.expect(eql(u8, actual, expected[0..actual.len])); } /// /// parseDots parses the input into a Dots /// fn parseDots() !Dots { var dots = Dots.init(gpa); var input_iter = tokenize(u8, input, ",\n"); while (true) { var x = parseInt(u32, input_iter.next().?, 10) catch break; var y = try parseInt(u32, input_iter.next().?, 10); try dots.put(.{ x, y }, true); } return dots; } /// /// parseFolds parses the input into a Folds /// fn parseFolds() !Folds { var folds = Folds.init(gpa); var input_iter = tokenize(u8, input, " \n"); while (true) { var fold = input_iter.next() orelse break; var x: u32 = 0; var y: u32 = 0; if (fold[0] == 'x') { x = try parseInt(u32, fold[2..], 10); } else if (fold[0] == 'y') { y = try parseInt(u32, fold[2..], 10); } else { continue; } try folds.append(.{ x, y }); } return folds; } /// /// foldOnce folds the dots at a given line /// fn foldOnce(dots: Dots, fold: Dot) !Dots { var new_dots = Dots.init(gpa); var it = dots.keyIterator(); while (it.next()) |d| { var dot = d.*; if (fold[0] == 0) { // fold along y try new_dots.put(.{ dot[0], min(dot[1], 2 * fold[1] - dot[1]) }, true); } else { // fold along x try new_dots.put(.{ min(dot[0], 2 * fold[0] - dot[0]), dot[1] }, true); } } return new_dots; } /// /// dotsToString the dots at a given line /// fn dotsToString(dots: Dots, thickness: u8) ![]u8 { var cols: u32 = 0; var rows: u32 = 0; var it = dots.keyIterator(); while (it.next()) |d| { var dot = d.*; cols = max(cols, dot[0]); rows = max(rows, dot[1]); } cols += 1; rows += 1; const length = thickness * cols * rows + rows; const string = try gpa.alloc(u8, length); mem.set(u8, string, ' '); var row: usize = 1; while (row < rows) : (row += 1) { string[row * (thickness * cols + 1)] = '\n'; } it = dots.keyIterator(); while (it.next()) |d| { var dot = d.*; const x = thickness * dot[0] + 1; const y = dot[1]; var xi: u32 = x; while (xi < x + thickness) : (xi += 1) { string[y * (thickness * cols + 1) + xi] = '#'; } } return string[1..length]; }
src/day13/day13.zig
const std = @import("std"); const c = @import("internal/c.zig"); const internal = @import("internal/internal.zig"); const log = std.log.scoped(.git); const git = @import("git.zig"); const bitjuggle = @import("internal/bitjuggle.zig"); pub const Index = opaque { pub fn deinit(self: *Index) void { log.debug("Index.deinit called", .{}); c.git_index_free(@ptrCast(*c.git_index, self)); log.debug("index freed successfully", .{}); } pub fn versionGet(self: *Index) !IndexVersion { log.debug("Index.versionGet called", .{}); const raw_value = c.git_index_version(@ptrCast(*c.git_index, self)); if (std.meta.intToEnum(IndexVersion, raw_value)) |version| { log.debug("successfully fetched index version: {s}", .{@tagName(version)}); return version; } else |_| { log.debug("failed to fetch valid index version, recieved: {}", .{raw_value}); return error.InvalidVersion; } } pub fn versionSet(self: *Index, version: IndexVersion) !void { log.debug("Index.setVersion called, version: {s}", .{@tagName(version)}); try internal.wrapCall("git_index_set_version", .{ @ptrCast(*c.git_index, self), @enumToInt(version) }); log.debug("successfully set index version", .{}); } pub const IndexVersion = enum(c_uint) { @"2" = 2, @"3" = 3, @"4" = 4, }; /// Update the contents of this index by reading from the hard disk. /// /// If `force` is true, in-memory changes are discarded. pub fn readIndexFromDisk(self: *Index, force: bool) !void { log.debug("Index.readIndexFromDisk called, force: {}", .{force}); try internal.wrapCall("git_index_read", .{ @ptrCast(*c.git_index, self), @boolToInt(force) }); log.debug("successfully read index data from disk", .{}); } pub fn writeToDisk(self: *Index) !void { log.debug("Index.writeToDisk called", .{}); try internal.wrapCall("git_index_write", .{@ptrCast(*c.git_index, self)}); log.debug("successfully wrote index data to disk", .{}); } pub fn pathGet(self: *const Index) ?[:0]const u8 { log.debug("Index.pathGet called", .{}); if (c.git_index_path(@ptrCast(*const c.git_index, self))) |ptr| { const slice = std.mem.sliceTo(ptr, 0); log.debug("successfully fetched index path: {s}", .{slice}); return slice; } log.debug("in-memory index has no path", .{}); return null; } pub fn repositoryGet(self: *const Index) ?*git.Repository { log.debug("Index.repositoryGet called", .{}); return @ptrCast( ?*git.Repository, c.git_index_owner(@ptrCast(*const c.git_index, self)), ); } /// Get the checksum of the index /// /// This checksum is the SHA-1 hash over the index file (except the last 20 bytes which are the checksum itself). In cases /// where the index does not exist on-disk, it will be zeroed out. pub fn checksum(self: *Index) !*const git.Oid { log.debug("Index.checksum called", .{}); const oid = @ptrCast( *const git.Oid, c.git_index_checksum(@ptrCast(*c.git_index, self)), ); // This check is to prevent formating the oid when we are not going to print anything if (@enumToInt(std.log.Level.debug) <= @enumToInt(std.log.level)) { var buf: [git.Oid.hex_buffer_size]u8 = undefined; const slice = try oid.formatHex(&buf); log.debug("index checksum acquired successfully, checksum: {s}", .{slice}); } return oid; } pub fn setToTree(self: *Index, tree: *const git.Tree) !void { log.debug("Index.setToTree called, tree: {*}", .{tree}); try internal.wrapCall("git_index_read_tree", .{ @ptrCast(*c.git_index, self), @ptrCast(*const c.git_tree, tree), }); log.debug("successfully set index to tree", .{}); } pub fn writeToTreeOnDisk(self: *Index) !git.Oid { log.debug("Index.writeToTreeOnDisk called", .{}); var oid: git.Oid = undefined; try internal.wrapCall("git_index_write_tree", .{ @ptrCast(*c.git_oid, &oid), @ptrCast(*c.git_index, self) }); log.debug("successfully wrote index tree to disk", .{}); return oid; } pub fn entryCount(self: *const Index) usize { log.debug("Index.entryCount called", .{}); const ret = c.git_index_entrycount(@ptrCast(*const c.git_index, self)); log.debug("index entry count: {}", .{ret}); return ret; } /// Clear the contents of this index. /// /// This clears the index in memory; changes must be written to disk for them to be persistent. pub fn clear(self: *Index) !void { log.debug("Index.clear called", .{}); try internal.wrapCall("git_index_clear", .{@ptrCast(*c.git_index, self)}); log.debug("successfully cleared index", .{}); } pub fn writeToTreeInRepository(self: *Index, repository: *git.Repository) !git.Oid { log.debug("Index.writeToTreeIngit.Repository called, repository: {*}", .{repository}); var oid: git.Oid = undefined; try internal.wrapCall("git_index_write_tree_to", .{ @ptrCast(*c.git_oid, &oid), @ptrCast(*c.git_index, self), @ptrCast(*c.git_repository, repository), }); log.debug("successfully wrote index tree to repository", .{}); return oid; } pub fn indexCapabilities(self: *const Index) IndexCapabilities { log.debug("Index.indexCapabilities called", .{}); const cap = @bitCast(IndexCapabilities, c.git_index_caps(@ptrCast(*const c.git_index, self))); log.debug("successfully fetched index capabilities: {}", .{cap}); return cap; } /// If you pass `IndexCapabilities.from_owner` for the capabilities, then capabilities will be read from the config of the /// owner object, looking at `core.ignorecase`, `core.filemode`, `core.symlinks`. pub fn indexCapabilitiesSet(self: *Index, capabilities: IndexCapabilities) !void { log.debug("Index.getIndexCapabilities called, capabilities: {}", .{capabilities}); try internal.wrapCall("git_index_set_caps", .{ @ptrCast(*c.git_index, self), @bitCast(c_int, capabilities) }); log.debug("successfully set index capabilities", .{}); } pub const IndexCapabilities = packed struct { ignore_case: bool = false, no_filemode: bool = false, no_symlinks: bool = false, z_padding1: u13 = 0, z_padding2: u16 = 0, pub fn isGetCapabilitiesFromOwner(self: IndexCapabilities) bool { return @bitCast(c_int, self) == -1; } pub const get_capabilities_from_owner: IndexCapabilities = @bitCast(IndexCapabilities, @as(c_int, -1)); pub fn format( value: IndexCapabilities, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { _ = fmt; return internal.formatWithoutFields( value, options, writer, &.{ "z_padding1", "z_padding2" }, ); } test { try std.testing.expectEqual(@sizeOf(c_int), @sizeOf(IndexCapabilities)); try std.testing.expectEqual(@bitSizeOf(c_int), @bitSizeOf(IndexCapabilities)); } comptime { std.testing.refAllDecls(@This()); } }; pub fn entryByIndex(self: *Index, index: usize) ?*const IndexEntry { log.debug("Index.entryByIndex called, index: {}", .{index}); return @ptrCast( ?*const IndexEntry, c.git_index_get_byindex(@ptrCast(*c.git_index, self), index), ); } pub fn entryByPath(self: *Index, path: [:0]const u8, stage: c_int) ?*const IndexEntry { log.debug("Index.entryByPath called, path: {s}, stage: {}", .{ path, stage }); return @ptrCast( ?*const IndexEntry, c.git_index_get_bypath(@ptrCast(*c.git_index, self), path.ptr, stage), ); } pub fn remove(self: *Index, path: [:0]const u8, stage: c_int) !void { log.debug("Index.remove called, path: {s}, stage: {}", .{ path, stage }); try internal.wrapCall("git_index_remove", .{ @ptrCast(*c.git_index, self), path.ptr, stage }); log.debug("successfully removed from index", .{}); } pub fn directoryRemove(self: *Index, path: [:0]const u8, stage: c_int) !void { log.debug("Index.directoryRemove called, path: {s}, stage: {}", .{ path, stage }); try internal.wrapCall("git_index_remove_directory", .{ @ptrCast(*c.git_index, self), path.ptr, stage }); log.debug("successfully removed from index", .{}); } pub fn add(self: *Index, entry: *const IndexEntry) !void { log.debug("Index.add called, entry: {*}", .{entry}); try internal.wrapCall("git_index_add", .{ @ptrCast(*c.git_index, self), @ptrCast(*const c.git_index_entry, entry) }); log.debug("successfully added to index", .{}); } /// The `path` must be relative to the repository's working folder. /// /// This forces the file to be added to the index, not looking at gitignore rules. Those rules can be evaluated using /// `git.Repository.statusShouldIgnore`. pub fn addByPath(self: *Index, path: [:0]const u8) !void { log.debug("Index.addByPath called, path: {s}", .{path}); try internal.wrapCall("git_index_add_bypath", .{ @ptrCast(*c.git_index, self), path.ptr }); log.debug("successfully added to index", .{}); } pub fn addFromBuffer(self: *Index, index_entry: *const IndexEntry, buffer: []const u8) !void { log.debug("Index.addFromBuffer called, index_entry: {*}, buffer.ptr: {*}, buffer.len: {}", .{ index_entry, buffer.ptr, buffer.len, }); if (@hasDecl(c, "git_index_add_from_buffer")) { try internal.wrapCall( "git_index_add_from_buffer", .{ @ptrCast(*c.git_index, self), @ptrCast(*const c.git_index_entry, index_entry), buffer.ptr, buffer.len }, ); } else { try internal.wrapCall( "git_index_add_frombuffer", .{ @ptrCast(*c.git_index, self), @ptrCast(*const c.git_index_entry, index_entry), buffer.ptr, buffer.len }, ); } log.debug("successfully added to index", .{}); } pub fn removeByPath(self: *Index, path: [:0]const u8) !void { log.debug("Index.removeByPath called, path: {s}", .{path}); try internal.wrapCall("git_index_remove_bypath", .{ @ptrCast(*c.git_index, self), path.ptr }); log.debug("successfully remove from index", .{}); } pub fn iterate(self: *Index) !*IndexIterator { log.debug("Index.iterate called", .{}); var iterator: *IndexIterator = undefined; try internal.wrapCall("git_index_iterator_new", .{ @ptrCast(*?*c.git_index_iterator, &iterator), @ptrCast(*c.git_index, self), }); log.debug("index iterator created successfully", .{}); return iterator; } pub const IndexIterator = opaque { pub fn next(self: *IndexIterator) !?*const IndexEntry { log.debug("IndexIterator.next called", .{}); var index_entry: *const IndexEntry = undefined; internal.wrapCall("git_index_iterator_next", .{ @ptrCast(*?*c.git_index_entry, &index_entry), @ptrCast(*c.git_index_iterator, self), }) catch |err| switch (err) { git.GitError.IterOver => { log.debug("end of iteration reached", .{}); return null; }, else => return err, }; log.debug("successfully fetched index entry: {}", .{index_entry}); return index_entry; } pub fn deinit(self: *IndexIterator) void { log.debug("IndexIterator.deinit called", .{}); c.git_index_iterator_free(@ptrCast(*c.git_index_iterator, self)); log.debug("index iterator freed successfully", .{}); } comptime { std.testing.refAllDecls(@This()); } }; /// Remove all matching index entries. /// /// If you provide a callback function, it will be invoked on each matching item in the working directory immediately *before* /// it is removed. Returning zero will remove the item, greater than zero will skip the item, and less than zero will abort /// the scan and return that value to the caller. /// /// ## Parameters /// * `pathspec` - Array of path patterns /// * `callback_fn` - The callback function; return 0 to remove, < 0 to abort, > 0 to skip. /// /// ## Callback Parameters /// * `path` - The reference name /// * `matched_pathspec` - The remote URL pub fn removeAll( self: *Index, pathspec: *const git.StrArray, comptime callback_fn: ?fn ( path: [:0]const u8, matched_pathspec: [:0]const u8, ) c_int, ) !c_int { if (callback_fn) |callback| { const cb = struct { pub fn cb( path: [:0]const u8, matched_pathspec: [:0]const u8, _: *u8, ) c_int { return callback(path, matched_pathspec); } }.cb; var dummy_data: u8 = undefined; return self.removeAllWithUserData(pathspec, &dummy_data, cb); } else { return self.removeAllWithUserData(pathspec, null, null); } } /// Remove all matching index entries. /// /// If you provide a callback function, it will be invoked on each matching item in the working directory immediately *before* /// it is removed. Returning zero will remove the item, greater than zero will skip the item, and less than zero will abort /// the scan and return that value to the caller. /// /// ## Parameters /// * `pathspec` - Array of path patterns /// * `user_data` - Pointer to user data to be passed to the callback /// * `callback_fn` - The callback function; return 0 to remove, < 0 to abort, > 0 to skip. /// /// ## Callback Parameters /// * `path` - The reference name /// * `matched_pathspec` - The remote URL /// * `user_data_ptr` - The user data pub fn removeAllWithUserData( self: *Index, pathspec: *const git.StrArray, user_data: anytype, comptime callback_fn: ?fn ( path: [:0]const u8, matched_pathspec: [:0]const u8, user_data_ptr: @TypeOf(user_data), ) void, ) !c_int { if (callback_fn) |callback| { const UserDataType = @TypeOf(user_data); const cb = struct { pub fn cb( path: [*:0]const u8, matched_pathspec: [*:0]const u8, payload: ?*anyopaque, ) callconv(.C) c_int { return callback( std.mem.sliceTo(path, 0), std.mem.sliceTo(matched_pathspec, 0), @ptrCast(UserDataType, payload), ); } }.cb; log.debug("Index.removeAllWithUserData called", .{}); const ret = try internal.wrapCallWithReturn("git_index_remove_all", .{ @ptrCast(*const c.git_index, self), @ptrCast(*const c.git_strarray, pathspec), cb, user_data, }); log.debug("callback returned: {}", .{ret}); return ret; } else { log.debug("Index.removeAllWithUserData called", .{}); try internal.wrapCall("git_index_remove_all", .{ @ptrCast(*const c.git_index, self), @ptrCast(*const c.git_strarray, pathspec), null, null, }); return 0; } } /// Update all index entries to match the working directory /// /// If you provide a callback function, it will be invoked on each matching item in the working directory immediately *before* /// it is updated. Returning zero will update the item, greater than zero will skip the item, and less than zero will abort /// the scan and return that value to the caller. /// /// ## Parameters /// * `pathspec` - Array of path patterns /// * `callback_fn` - The callback function; return 0 to update, < 0 to abort, > 0 to skip. /// /// ## Callback Parameters /// * `path` - The reference name /// * `matched_pathspec` - The remote URL pub fn updateAll( self: *Index, pathspec: *const git.StrArray, comptime callback_fn: ?fn ( path: [:0]const u8, matched_pathspec: [:0]const u8, ) c_int, ) !c_int { if (callback_fn) |callback| { const cb = struct { pub fn cb( path: [:0]const u8, matched_pathspec: [:0]const u8, _: *u8, ) c_int { return callback(path, matched_pathspec); } }.cb; var dummy_data: u8 = undefined; return self.updateAllWithUserData(pathspec, &dummy_data, cb); } else { return self.updateAllWithUserData(pathspec, null, null); } } /// Update all index entries to match the working directory /// /// If you provide a callback function, it will be invoked on each matching item in the working directory immediately *before* /// it is updated. Returning zero will update the item, greater than zero will skip the item, and less than zero will abort /// the scan and return that value to the caller. /// /// ## Parameters /// * `pathspec` - Array of path patterns /// * `user_data` - Pointer to user data to be passed to the callback /// * `callback_fn` - The callback function; return 0 to update, < 0 to abort, > 0 to skip. /// /// ## Callback Parameters /// * `path` - The reference name /// * `matched_pathspec` - The remote URL /// * `user_data_ptr` - The user data pub fn updateAllWithUserData( self: *Index, pathspec: *const git.StrArray, user_data: anytype, comptime callback_fn: ?fn ( path: [:0]const u8, matched_pathspec: [:0]const u8, user_data_ptr: @TypeOf(user_data), ) void, ) !c_int { if (callback_fn) |callback| { const UserDataType = @TypeOf(user_data); const cb = struct { pub fn cb( path: [*:0]const u8, matched_pathspec: [*:0]const u8, payload: ?*anyopaque, ) callconv(.C) c_int { return callback( std.mem.sliceTo(path, 0), std.mem.sliceTo(matched_pathspec, 0), @ptrCast(UserDataType, payload), ); } }.cb; log.debug("Index.updateAllWithUserData called", .{}); const ret = try internal.wrapCallWithReturn("git_index_update_all", .{ @ptrCast(*const c.git_index, self), @ptrCast(*const c.git_strarray, pathspec), cb, user_data, }); log.debug("callback returned: {}", .{ret}); return ret; } else { log.debug("Index.updateAllWithUserData called", .{}); try internal.wrapCall("git_index_update_all", .{ @ptrCast(*const c.git_index, self), @ptrCast(*const c.git_strarray, pathspec), null, null, }); return 0; } } /// Add or update index entries matching files in the working directory. /// /// The `pathspec` is a list of file names or shell glob patterns that will be matched against files in the repository's /// working directory. Each file that matches will be added to the index (either updating an existing entry or adding a new /// entry). You can disable glob expansion and force exact matching with the `IndexAddFlags.disable_pathspec_match` flag. /// Invoke `callback_fn` for each entry in the given FETCH_HEAD file. /// /// Files that are ignored will be skipped (unlike `Index.AddByPath`). If a file is already tracked in the index, then it /// *will* be updated even if it is ignored. Pass the `IndexAddFlags.force` flag to skip the checking of ignore rules. /// /// If you provide a callback function, it will be invoked on each matching item in the working directory immediately *before* /// it is added to/updated in the index. Returning zero will add the item to the index, greater than zero will skip the item, /// and less than zero will abort the scan and return that value to the caller. /// /// ## Parameters /// * `pathspec` - Array of path patterns /// * `flags` - Flags controlling how the add is performed /// * `callback_fn` - The callback function; return 0 to add, < 0 to abort, > 0 to skip. /// /// ## Callback Parameters /// * `path` - The reference name /// * `matched_pathspec` - The remote URL pub fn addAll( self: *Index, pathspec: *const git.StrArray, flags: IndexAddFlags, comptime callback_fn: ?fn ( path: [:0]const u8, matched_pathspec: [:0]const u8, ) c_int, ) !c_int { if (callback_fn) |callback| { const cb = struct { pub fn cb( path: [:0]const u8, matched_pathspec: [:0]const u8, _: *u8, ) c_int { return callback(path, matched_pathspec); } }.cb; var dummy_data: u8 = undefined; return self.addAllWithUserData(pathspec, flags, &dummy_data, cb); } else { return self.addAllWithUserData(pathspec, flags, null, null); } } /// Add or update index entries matching files in the working directory. /// /// The `pathspec` is a list of file names or shell glob patterns that will be matched against files in the repository's /// working directory. Each file that matches will be added to the index (either updating an existing entry or adding a new /// entry). You can disable glob expansion and force exact matching with the `IndexAddFlags.disable_pathspec_match` flag. /// Invoke `callback_fn` for each entry in the given FETCH_HEAD file. /// /// Files that are ignored will be skipped (unlike `Index.AddByPath`). If a file is already tracked in the index, then it /// *will* be updated even if it is ignored. Pass the `IndexAddFlags.force` flag to skip the checking of ignore rules. /// /// If you provide a callback function, it will be invoked on each matching item in the working directory immediately *before* /// it is added to/updated in the index. Returning zero will add the item to the index, greater than zero will skip the item, /// and less than zero will abort the scan and return that value to the caller. /// /// ## Parameters /// * `pathspec` - Array of path patterns /// * `flags` - Flags controlling how the add is performed /// * `user_data` - Pointer to user data to be passed to the callback /// * `callback_fn` - The callback function; return 0 to add, < 0 to abort, > 0 to skip. /// /// ## Callback Parameters /// * `path` - The reference name /// * `matched_pathspec` - The remote URL /// * `user_data_ptr` - The user data pub fn addAllWithUserData( self: *Index, pathspec: *const git.StrArray, flags: IndexAddFlags, user_data: anytype, comptime callback_fn: ?fn ( path: [:0]const u8, matched_pathspec: [:0]const u8, user_data_ptr: @TypeOf(user_data), ) void, ) !c_int { if (callback_fn) |callback| { const UserDataType = @TypeOf(user_data); const cb = struct { pub fn cb( path: [*:0]const u8, matched_pathspec: [*:0]const u8, payload: ?*anyopaque, ) callconv(.C) c_int { return callback( std.mem.sliceTo(path, 0), std.mem.sliceTo(matched_pathspec, 0), @ptrCast(UserDataType, payload), ); } }.cb; log.debug("Index.addAllWithUserData called", .{}); const ret = try internal.wrapCallWithReturn("git_index_add_all", .{ @ptrCast(*const c.git_index, self), @ptrCast(*const c.git_strarray, pathspec), @bitCast(c_int, flags), cb, user_data, }); log.debug("callback returned: {}", .{ret}); return ret; } else { log.debug("Index.addAllWithUserData called", .{}); try internal.wrapCall("git_index_add_all", .{ @ptrCast(*const c.git_index, self), @ptrCast(*const c.git_strarray, pathspec), @bitCast(c_int, flags), null, null, }); return 0; } } pub fn find(self: *Index, path: [:0]const u8) !usize { log.debug("Index.find called, path: {s}", .{path}); var position: usize = 0; try internal.wrapCall("git_index_find", .{ &position, @ptrCast(*c.git_index, self), path.ptr }); log.debug("successfully fetched position: {}", .{position}); return position; } pub fn findPrefix(self: *Index, prefix: [:0]const u8) !usize { log.debug("Index.find called, prefix: {s}", .{prefix}); var position: usize = 0; try internal.wrapCall("git_index_find_prefix", .{ &position, @ptrCast(*c.git_index, self), prefix.ptr }); log.debug("successfully fetched position: {}", .{position}); return position; } /// Add or update index entries to represent a conflict. Any staged entries that exist at the given paths will be removed. /// /// The entries are the entries from the tree included in the merge. Any entry may be null to indicate that that file was not /// present in the trees during the merge. For example, `ancestor_entry` may be `null` to indicate that a file was added in /// both branches and must be resolved. pub fn conflictAdd( self: *Index, ancestor_entry: ?*const IndexEntry, our_entry: ?*const IndexEntry, their_entry: ?*const IndexEntry, ) !void { log.debug("Index.conflictAdd called, ancestor_entry: {*}, our_entry: {*}, their_entry: {*}", .{ ancestor_entry, our_entry, their_entry, }); try internal.wrapCall("git_index_conflict_add", .{ @ptrCast(*c.git_index, self), @ptrCast(?*const c.git_index_entry, ancestor_entry), @ptrCast(?*const c.git_index_entry, our_entry), @ptrCast(?*const c.git_index_entry, their_entry), }); log.debug("successfully wrote index data to disk", .{}); } /// Get the index entries that represent a conflict of a single file. /// /// *IMPORTANT*: These entries should *not* be freed. pub fn conflictGet(self: *Index, path: [:0]const u8) !Conflicts { log.debug("Index.conflictGet called, path: {s}", .{path}); var ancestor_out: *const IndexEntry = undefined; var our_out: *const IndexEntry = undefined; var their_out: *const IndexEntry = undefined; try internal.wrapCall("git_index_conflict_get", .{ @ptrCast(*?*const c.git_index_entry, &ancestor_out), @ptrCast(*?*const c.git_index_entry, &our_out), @ptrCast(*?*const c.git_index_entry, &their_out), @ptrCast(*c.git_index, self), path.ptr, }); log.debug("successfully fetched conflict entries", .{}); return Conflicts{ .ancestor = ancestor_out, .our = our_out, .their = their_out, }; } pub fn conlfictRemove(self: *Index, path: [:0]const u8) !void { log.debug("Index.conlfictRemove called, path: {s}", .{path}); try internal.wrapCall("git_index_conflict_remove", .{ @ptrCast(*c.git_index, self), path.ptr }); log.debug("successfully removed conflict", .{}); } /// Remove all conflicts in the index pub fn conflictCleanup(self: *Index) !void { log.debug("Index.conflictCleanup called", .{}); try internal.wrapCall("git_index_conflict_cleanup", .{@ptrCast(*c.git_index, self)}); log.debug("successfully cleaned up all conflicts", .{}); } pub fn hasConflicts(self: *const Index) bool { log.debug("Index.hasConflicts called", .{}); const ret = c.git_index_has_conflicts(@ptrCast(*const c.git_index, self)) == 1; log.debug("index had conflicts: {}", .{ret}); return ret; } pub const IndexConflictIterator = opaque { pub fn next(self: *IndexConflictIterator) !?Conflicts { log.debug("IndexConflictIterator.next called", .{}); var ancestor_out: *const IndexEntry = undefined; var our_out: *const IndexEntry = undefined; var their_out: *const IndexEntry = undefined; internal.wrapCall("git_index_conflict_next", .{ @ptrCast(*?*const c.git_index_entry, &ancestor_out), @ptrCast(*?*const c.git_index_entry, &our_out), @ptrCast(*?*const c.git_index_entry, &their_out), @ptrCast(*c.git_index_conflict_iterator, self), }) catch |err| switch (err) { git.GitError.IterOver => { log.debug("end of iteration reached", .{}); return null; }, else => return err, }; log.debug("successfully fetched conflicts", .{}); return Conflicts{ .ancestor = ancestor_out, .our = our_out, .their = their_out, }; } pub fn deinit(self: *IndexConflictIterator) void { log.debug("IndexConflictIterator.deinit called", .{}); c.git_index_conflict_iterator_free(@ptrCast(*c.git_index_conflict_iterator, self)); log.debug("index conflict iterator freed successfully", .{}); } comptime { std.testing.refAllDecls(@This()); } }; pub const Conflicts = struct { ancestor: *const IndexEntry, our: *const IndexEntry, their: *const IndexEntry, }; pub const IndexEntry = extern struct { ctime: IndexTime, mtime: IndexTime, dev: u32, ino: u32, mode: u32, uid: u32, gid: u32, file_size: u32, id: git.Oid, flags: Flags, flags_extended: ExtendedFlags, raw_path: [*:0]const u8, pub fn path(self: IndexEntry) [:0]const u8 { return std.mem.sliceTo(self.raw_path, 0); } pub fn stage(self: IndexEntry) c_int { return @intCast(c_int, self.flags.stage.read()); } pub fn isConflict(self: IndexEntry) bool { return self.stage() > 0; } pub const IndexTime = extern struct { seconds: i32, nanoseconds: u32, test { try std.testing.expectEqual(@sizeOf(c.git_index_time), @sizeOf(IndexTime)); try std.testing.expectEqual(@bitSizeOf(c.git_index_time), @bitSizeOf(IndexTime)); } comptime { std.testing.refAllDecls(@This()); } }; pub const Flags = extern union { name: bitjuggle.Bitfield(u16, 0, 12), stage: bitjuggle.Bitfield(u16, 12, 2), extended: bitjuggle.Bit(u16, 14), valid: bitjuggle.Bit(u16, 15), test { try std.testing.expectEqual(@sizeOf(u16), @sizeOf(Flags)); try std.testing.expectEqual(@bitSizeOf(u16), @bitSizeOf(Flags)); } }; pub const ExtendedFlags = extern union { intent_to_add: bitjuggle.Bit(u16, 13), skip_worktree: bitjuggle.Bit(u16, 14), uptodate: bitjuggle.Bit(u16, 2), test { try std.testing.expectEqual(@sizeOf(u16), @sizeOf(ExtendedFlags)); try std.testing.expectEqual(@bitSizeOf(u16), @bitSizeOf(ExtendedFlags)); } }; test { try std.testing.expectEqual(@sizeOf(c.git_index_entry), @sizeOf(IndexEntry)); try std.testing.expectEqual(@bitSizeOf(c.git_index_entry), @bitSizeOf(IndexEntry)); } comptime { std.testing.refAllDecls(@This()); } }; /// Match a pathspec against entries in an index. /// /// This matches the pathspec against the files in the repository index. /// /// NOTE: At the moment, the case sensitivity of this match is controlled by the current case-sensitivity of the index object /// itself and the `MatchOptions.use_case` and `MatchOptions.ignore_case` options will have no effect. /// This behavior will be corrected in a future release. /// /// If `match_list` is not `null`, this returns a `git.PathspecMatchList`. That contains the list of all matched filenames /// (unless you pass the `MatchOptions.failures_only` options) and may also contain the list of pathspecs with no match (if /// you used the `MatchOptions.find_failures` option). /// You must call `PathspecMatchList.deinit()` on this object. /// /// ## Parameters /// * `pathspec` - Pathspec to be matched /// * `options` - Options to control match /// * `match_list` - Output list of matches; pass `null` to just get return value pub fn pathspecMatch( self: *Index, pathspec: *git.Pathspec, options: git.PathspecMatchOptions, match_list: ?**git.PathspecMatchList, ) !bool { log.debug("Index.pathspecMatch called, options: {}, pathspec: {*}", .{ options, pathspec }); const ret = (try internal.wrapCallWithReturn("git_pathspec_match_index", .{ @ptrCast(?*?*c.git_pathspec_match_list, match_list), @ptrCast(*c.git_index, self), @bitCast(c.git_pathspec_flag_t, options), @ptrCast(*c.git_pathspec, pathspec), })) != 0; log.debug("match: {}", .{ret}); return ret; } comptime { std.testing.refAllDecls(@This()); } }; pub const IndexAddFlags = packed struct { force: bool = false, disable_pathspec_match: bool = false, check_pathspec: bool = false, z_padding: u29 = 0, pub fn format( value: IndexAddFlags, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { _ = fmt; return internal.formatWithoutFields( value, options, writer, &.{"z_padding"}, ); } test { try std.testing.expectEqual(@sizeOf(c_uint), @sizeOf(IndexAddFlags)); try std.testing.expectEqual(@bitSizeOf(c_uint), @bitSizeOf(IndexAddFlags)); } comptime { std.testing.refAllDecls(@This()); } }; comptime { std.testing.refAllDecls(@This()); }
src/index.zig
const std = @import("std"); const mi = @import("mi.zig"); const changeScreen = @import("n64.zig").changeScreen; const InterruptSource = mi.InterruptSource; const setPending = mi.setPending; const clearPending = mi.clearPending; const VIReg = enum(u64) { VIControl = 0x00, VIOrigin = 0x04, VIWidth = 0x08, VIIntr = 0x0C, VICurrentV = 0x10, }; const FBMode = enum(u2) { Blank = 0, Reserved = 1, RGBA5553 = 2, RGBA8888 = 3, }; const VIControl = packed struct { fbMode : u2 = @enumToInt(FBMode.Blank), gammaDitherEnable: bool = false, gammaEnable: bool = false, divotEnable: bool = false, _pad0 : u1 = 0, serrate: bool = false, _pad1 : u1 = 0, aaMode : u2 = 0, _pad2 : u6 = 0, _pad3 : u16 = 0, }; pub var viControl = VIControl{}; var viOrigin : u32 = 0; var viWidth : u32 = 0; var viIntr : u10 = 0; var viCurrentV: u10 = 0; pub fn init() void { } pub fn getOrigin() usize { return @intCast(usize, viOrigin); } pub fn read32(pAddr: u64) u32 { var data: u32 = undefined; switch (pAddr & 0xFF) { @enumToInt(VIReg.VICurrentV) => { //std.log.info("[VI] Read32 @ pAddr {X}h (VI Current V).", .{pAddr}); data = @intCast(u32, viCurrentV); }, else => { std.log.warn("[VI] Unhandled read32 @ pAddr {X}h.", .{pAddr}); } } return data; } pub fn write32(pAddr: u64, data: u32) void { switch (pAddr & 0xFF) { @enumToInt(VIReg.VIControl) => { std.log.info("[VI] Write32 @ pAddr {X}h (VI Control), data: {X}h.", .{pAddr, data}); viControl = @bitCast(VIControl, data); }, @enumToInt(VIReg.VIOrigin) => { std.log.info("[VI] Write32 @ pAddr {X}h (VI Origin), data: {X}h.", .{pAddr, data}); viOrigin = data & 0xFF_FFFF; }, @enumToInt(VIReg.VIWidth) => { std.log.info("[VI] Write32 @ pAddr {X}h (VI Width), data: {X}h.", .{pAddr, data}); viWidth = data; changeScreen(@bitCast(c_int, viWidth), viControl.fbMode); }, @enumToInt(VIReg.VIIntr) => { std.log.info("[VI] Write32 @ pAddr {X}h (VI Interrupt), data: {X}h.", .{pAddr, data}); viIntr = @truncate(u10, data); }, @enumToInt(VIReg.VICurrentV) => { std.log.info("[VI] Write32 @ pAddr {X}h (VI Current V), data: {X}h.", .{pAddr, data}); mi.clearPending(InterruptSource.VI); }, else => { std.log.warn("[VI] Unhandled write32 @ pAddr {X}h, data: {X}h.", .{pAddr, data}); } } } pub fn incCurrentV() void { viCurrentV +%= 2; if (viCurrentV == viIntr) { std.log.info("[VI] VI interrupt pending.", .{}); mi.setPending(InterruptSource.VI); } }
src/core/vi.zig
const std = @import("std"); const math = std.math; const assert = std.debug.assert; const L = std.unicode.utf8ToUtf16LeStringLiteral; const zwin32 = @import("zwin32"); const w32 = zwin32.base; const d3d12 = zwin32.d3d12; const hrPanic = zwin32.hrPanic; const hrPanicOnFail = zwin32.hrPanicOnFail; const zd3d12 = @import("zd3d12"); const common = @import("common"); const GuiRenderer = common.GuiRenderer; const c = common.c; const zm = @import("zmath"); const zmesh = @import("zmesh"); const znoise = @import("znoise"); pub export const D3D12SDKVersion: u32 = 4; pub export const D3D12SDKPath: [*:0]const u8 = ".\\d3d12\\"; const content_dir = @import("build_options").content_dir; const window_name = "zig-gamedev: procedural mesh"; const window_width = 1920; const window_height = 1080; const Pso_DrawConst = struct { object_to_world: [16]f32, basecolor_roughness: [4]f32, }; const Pso_FrameConst = struct { world_to_clip: [16]f32, camera_position: [3]f32, }; const Pso_Vertex = struct { position: [3]f32, normal: [3]f32, }; const Mesh = struct { index_offset: u32, vertex_offset: i32, num_indices: u32, num_vertices: u32, }; const Drawable = struct { mesh_index: u32, position: [3]f32, basecolor_roughness: [4]f32, }; const DemoState = struct { gctx: zd3d12.GraphicsContext, guir: GuiRenderer, frame_stats: common.FrameStats, simple_entity_pso: zd3d12.PipelineHandle, vertex_buffer: zd3d12.ResourceHandle, index_buffer: zd3d12.ResourceHandle, depth_texture: zd3d12.ResourceHandle, depth_texture_dsv: d3d12.CPU_DESCRIPTOR_HANDLE, meshes: std.ArrayList(Mesh), drawables: std.ArrayList(Drawable), camera: struct { position: [3]f32 = .{ 0.0, 4.0, -4.0 }, forward: [3]f32 = .{ 0.0, 0.0, 1.0 }, pitch: f32 = 0.15 * math.pi, yaw: f32 = 0.0, } = .{}, mouse: struct { cursor_prev_x: i32 = 0, cursor_prev_y: i32 = 0, } = .{}, }; fn appendMesh( mesh: zmesh.Shape, meshes: *std.ArrayList(Mesh), meshes_indices: *std.ArrayList(u16), meshes_positions: *std.ArrayList([3]f32), meshes_normals: *std.ArrayList([3]f32), ) void { meshes.append(.{ .index_offset = @intCast(u32, meshes_indices.items.len), .vertex_offset = @intCast(i32, meshes_positions.items.len), .num_indices = @intCast(u32, mesh.indices.len), .num_vertices = @intCast(u32, mesh.positions.len), }) catch unreachable; meshes_indices.appendSlice(mesh.indices) catch unreachable; meshes_positions.appendSlice(mesh.positions) catch unreachable; meshes_normals.appendSlice(mesh.normals.?) catch unreachable; } fn initScene( allocator: std.mem.Allocator, drawables: *std.ArrayList(Drawable), meshes: *std.ArrayList(Mesh), meshes_indices: *std.ArrayList(u16), meshes_positions: *std.ArrayList([3]f32), meshes_normals: *std.ArrayList([3]f32), ) void { var arena_allocator_state = std.heap.ArenaAllocator.init(allocator); defer arena_allocator_state.deinit(); const arena_allocator = arena_allocator_state.allocator(); zmesh.init(arena_allocator); defer zmesh.deinit(); // Trefoil knot. { var mesh = zmesh.Shape.initTrefoilKnot(10, 128, 0.8); defer mesh.deinit(); mesh.rotate(math.pi * 0.5, 1.0, 0.0, 0.0); mesh.unweld(); mesh.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ 0, 1, 0 }, .basecolor_roughness = .{ 0.0, 0.7, 0.0, 0.6 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Parametric sphere. { var mesh = zmesh.Shape.initParametricSphere(20, 20); defer mesh.deinit(); mesh.rotate(math.pi * 0.5, 1.0, 0.0, 0.0); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ 3, 1, 0 }, .basecolor_roughness = .{ 0.7, 0.0, 0.0, 0.2 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Icosahedron. { var mesh = zmesh.Shape.initIcosahedron(); defer mesh.deinit(); mesh.unweld(); mesh.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ -3, 1, 0 }, .basecolor_roughness = .{ 0.7, 0.6, 0.0, 0.4 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Dodecahedron. { var mesh = zmesh.Shape.initDodecahedron(); defer mesh.deinit(); mesh.unweld(); mesh.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ 0, 1, 3 }, .basecolor_roughness = .{ 0.0, 0.1, 1.0, 0.2 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Cylinder with top and bottom caps. { var disk = zmesh.Shape.initParametricDisk(10, 2); defer disk.deinit(); disk.invert(0, 0); var cylinder = zmesh.Shape.initCylinder(10, 4); defer cylinder.deinit(); cylinder.merge(disk); cylinder.translate(0, 0, -1); disk.invert(0, 0); cylinder.merge(disk); cylinder.scale(0.5, 0.5, 2); cylinder.rotate(math.pi * 0.5, 1.0, 0.0, 0.0); cylinder.unweld(); cylinder.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ -3, 0, 3 }, .basecolor_roughness = .{ 1.0, 0.0, 0.0, 0.3 }, }) catch unreachable; appendMesh(cylinder, meshes, meshes_indices, meshes_positions, meshes_normals); } // Torus. { var mesh = zmesh.Shape.initTorus(10, 20, 0.2); defer mesh.deinit(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ 3, 1.5, 3 }, .basecolor_roughness = .{ 1.0, 0.5, 0.0, 0.2 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Subdivided sphere. { var mesh = zmesh.Shape.initSubdividedSphere(3); defer mesh.deinit(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ 3, 1, 6 }, .basecolor_roughness = .{ 0.0, 1.0, 0.0, 0.2 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Tetrahedron. { var mesh = zmesh.Shape.initTetrahedron(); defer mesh.deinit(); mesh.unweld(); mesh.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ 0, 0.5, 6 }, .basecolor_roughness = .{ 1.0, 0.0, 1.0, 0.2 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Octahedron. { var mesh = zmesh.Shape.initOctahedron(); defer mesh.deinit(); mesh.unweld(); mesh.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ -3, 1, 6 }, .basecolor_roughness = .{ 0.2, 0.0, 1.0, 0.2 }, }) catch unreachable; appendMesh(mesh, meshes, meshes_indices, meshes_positions, meshes_normals); } // Rock. { var rock = zmesh.Shape.initRock(123, 4); defer rock.deinit(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ -6, 0, 3 }, .basecolor_roughness = .{ 1.0, 1.0, 1.0, 1.0 }, }) catch unreachable; appendMesh(rock, meshes, meshes_indices, meshes_positions, meshes_normals); } // Custom parametric (simple terrain). { const gen = znoise.FnlGenerator{ .fractal_type = .fbm, .frequency = 2.0, .octaves = 5, .lacunarity = 2.02, }; const local = struct { fn terrain(uv: *const [2]f32, position: *[3]f32, userdata: ?*anyopaque) callconv(.C) void { _ = userdata; position[0] = uv[0]; position[1] = 0.025 * gen.noise2(uv[0], uv[1]); position[2] = uv[1]; } }; var ground = zmesh.Shape.initParametric(local.terrain, 40, 40, null); defer ground.deinit(); ground.translate(-0.5, -0.0, -0.5); ground.invert(0, 0); ground.scale(20, 20, 20); ground.computeNormals(); drawables.append(.{ .mesh_index = @intCast(u32, meshes.items.len), .position = .{ 0, 0, 0 }, .basecolor_roughness = .{ 0.1, 0.1, 0.1, 1.0 }, }) catch unreachable; appendMesh(ground, meshes, meshes_indices, meshes_positions, meshes_normals); } } fn init(allocator: std.mem.Allocator) !DemoState { const window = try common.initWindow(allocator, window_name, window_width, window_height); var arena_allocator_state = std.heap.ArenaAllocator.init(allocator); defer arena_allocator_state.deinit(); const arena_allocator = arena_allocator_state.allocator(); var gctx = zd3d12.GraphicsContext.init(allocator, window); const barycentrics_supported = blk: { var options3: d3d12.FEATURE_DATA_D3D12_OPTIONS3 = undefined; const res = gctx.device.CheckFeatureSupport( .OPTIONS3, &options3, @sizeOf(d3d12.FEATURE_DATA_D3D12_OPTIONS3), ); break :blk options3.BarycentricsSupported == w32.TRUE and res == w32.S_OK; }; const simple_entity_pso = blk: { const input_layout_desc = [_]d3d12.INPUT_ELEMENT_DESC{ d3d12.INPUT_ELEMENT_DESC.init("POSITION", 0, .R32G32B32_FLOAT, 0, 0, .PER_VERTEX_DATA, 0), d3d12.INPUT_ELEMENT_DESC.init("_Normal", 0, .R32G32B32_FLOAT, 0, 12, .PER_VERTEX_DATA, 0), }; var pso_desc = d3d12.GRAPHICS_PIPELINE_STATE_DESC.initDefault(); pso_desc.InputLayout = .{ .pInputElementDescs = &input_layout_desc, .NumElements = input_layout_desc.len, }; pso_desc.RTVFormats[0] = .R8G8B8A8_UNORM; pso_desc.NumRenderTargets = 1; pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf; pso_desc.PrimitiveTopologyType = .TRIANGLE; pso_desc.DSVFormat = .D32_FLOAT; if (!barycentrics_supported) { break :blk gctx.createGraphicsShaderPipelineVsGsPs( arena_allocator, &pso_desc, content_dir ++ "shaders/simple_entity.vs.cso", content_dir ++ "shaders/simple_entity.gs.cso", content_dir ++ "shaders/simple_entity_with_gs.ps.cso", ); } else { break :blk gctx.createGraphicsShaderPipeline( arena_allocator, &pso_desc, content_dir ++ "shaders/simple_entity.vs.cso", content_dir ++ "shaders/simple_entity.ps.cso", ); } }; var drawables = std.ArrayList(Drawable).init(allocator); var meshes = std.ArrayList(Mesh).init(allocator); var meshes_indices = std.ArrayList(u16).init(arena_allocator); var meshes_positions = std.ArrayList([3]f32).init(arena_allocator); var meshes_normals = std.ArrayList([3]f32).init(arena_allocator); initScene(allocator, &drawables, &meshes, &meshes_indices, &meshes_positions, &meshes_normals); const num_vertices = @intCast(u32, meshes_positions.items.len); const num_indices = @intCast(u32, meshes_indices.items.len); const vertex_buffer = gctx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(num_vertices * @sizeOf(Pso_Vertex)), d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err); const index_buffer = gctx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(num_indices * @sizeOf(u16)), d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err); // Create depth texture resource. const depth_texture = gctx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &blk: { var desc = d3d12.RESOURCE_DESC.initTex2d(.D32_FLOAT, gctx.viewport_width, gctx.viewport_height, 1); desc.Flags = d3d12.RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | d3d12.RESOURCE_FLAG_DENY_SHADER_RESOURCE; break :blk desc; }, d3d12.RESOURCE_STATE_DEPTH_WRITE, &d3d12.CLEAR_VALUE.initDepthStencil(.D32_FLOAT, 1.0, 0), ) catch |err| hrPanic(err); // Create depth texture view. const depth_texture_dsv = gctx.allocateCpuDescriptors(.DSV, 1); gctx.device.CreateDepthStencilView( gctx.lookupResource(depth_texture).?, null, depth_texture_dsv, ); // // Begin frame to init/upload resources to the GPU. // gctx.beginFrame(); var guir = GuiRenderer.init(arena_allocator, &gctx, 1, content_dir); // Fill vertex buffer with vertex data. { const verts = gctx.allocateUploadBufferRegion(Pso_Vertex, num_vertices); for (meshes_positions.items) |_, i| { verts.cpu_slice[i].position = meshes_positions.items[i]; verts.cpu_slice[i].normal = meshes_normals.items[i]; } gctx.cmdlist.CopyBufferRegion( gctx.lookupResource(vertex_buffer).?, 0, verts.buffer, verts.buffer_offset, verts.cpu_slice.len * @sizeOf(@TypeOf(verts.cpu_slice[0])), ); } // Fill index buffer with index data. { const indices = gctx.allocateUploadBufferRegion(u16, num_indices); for (meshes_indices.items) |_, i| { indices.cpu_slice[i] = meshes_indices.items[i]; } gctx.cmdlist.CopyBufferRegion( gctx.lookupResource(index_buffer).?, 0, indices.buffer, indices.buffer_offset, indices.cpu_slice.len * @sizeOf(@TypeOf(indices.cpu_slice[0])), ); } gctx.endFrame(); gctx.finishGpuCommands(); return DemoState{ .gctx = gctx, .guir = guir, .frame_stats = common.FrameStats.init(), .simple_entity_pso = simple_entity_pso, .vertex_buffer = vertex_buffer, .index_buffer = index_buffer, .depth_texture = depth_texture, .depth_texture_dsv = depth_texture_dsv, .meshes = meshes, .drawables = drawables, }; } fn deinit(demo: *DemoState, allocator: std.mem.Allocator) void { demo.gctx.finishGpuCommands(); demo.meshes.deinit(); demo.drawables.deinit(); demo.guir.deinit(&demo.gctx); demo.gctx.deinit(allocator); common.deinitWindow(allocator); demo.* = undefined; } fn update(demo: *DemoState) void { demo.frame_stats.update(demo.gctx.window, window_name); const dt = demo.frame_stats.delta_time; common.newImGuiFrame(dt); c.igSetNextWindowPos( c.ImVec2{ .x = @intToFloat(f32, demo.gctx.viewport_width) - 600.0 - 20, .y = 20.0 }, c.ImGuiCond_FirstUseEver, c.ImVec2{ .x = 0.0, .y = 0.0 }, ); c.igSetNextWindowSize(.{ .x = 600.0, .y = -1 }, c.ImGuiCond_Always); _ = c.igBegin( "Demo Settings", null, c.ImGuiWindowFlags_NoMove | c.ImGuiWindowFlags_NoResize | c.ImGuiWindowFlags_NoSavedSettings, ); c.igBulletText("", ""); c.igSameLine(0, -1); c.igTextColored(.{ .x = 0, .y = 0.8, .z = 0, .w = 1 }, "Right Mouse Button + drag", ""); c.igSameLine(0, -1); c.igText(" : rotate camera", ""); c.igBulletText("", ""); c.igSameLine(0, -1); c.igTextColored(.{ .x = 0, .y = 0.8, .z = 0, .w = 1 }, "W, A, S, D", ""); c.igSameLine(0, -1); c.igText(" : move camera", ""); c.igEnd(); // Handle camera rotation with mouse. { var pos: w32.POINT = undefined; _ = w32.GetCursorPos(&pos); const delta_x = @intToFloat(f32, pos.x) - @intToFloat(f32, demo.mouse.cursor_prev_x); const delta_y = @intToFloat(f32, pos.y) - @intToFloat(f32, demo.mouse.cursor_prev_y); demo.mouse.cursor_prev_x = pos.x; demo.mouse.cursor_prev_y = pos.y; if (w32.GetAsyncKeyState(w32.VK_RBUTTON) < 0) { demo.camera.pitch += 0.0025 * delta_y; demo.camera.yaw += 0.0025 * delta_x; demo.camera.pitch = math.min(demo.camera.pitch, 0.48 * math.pi); demo.camera.pitch = math.max(demo.camera.pitch, -0.48 * math.pi); demo.camera.yaw = zm.modAngle(demo.camera.yaw); } } // Handle camera movement with 'WASD' keys. { const speed = zm.f32x4s(2.0); const delta_time = zm.f32x4s(demo.frame_stats.delta_time); const transform = zm.mul(zm.rotationX(demo.camera.pitch), zm.rotationY(demo.camera.yaw)); var forward = zm.normalize3(zm.mul(zm.f32x4(0.0, 0.0, 1.0, 0.0), transform)); zm.store(demo.camera.forward[0..], forward, 3); const right = speed * delta_time * zm.normalize3(zm.cross3(zm.f32x4(0.0, 1.0, 0.0, 0.0), forward)); forward = speed * delta_time * forward; var cpos = zm.load(demo.camera.position[0..], zm.Vec, 3); if (w32.GetAsyncKeyState('W') < 0) { cpos += forward; } else if (w32.GetAsyncKeyState('S') < 0) { cpos -= forward; } if (w32.GetAsyncKeyState('D') < 0) { cpos += right; } else if (w32.GetAsyncKeyState('A') < 0) { cpos -= right; } zm.store(demo.camera.position[0..], cpos, 3); } } fn draw(demo: *DemoState) void { var gctx = &demo.gctx; const cam_world_to_view = zm.lookToLh( zm.load(demo.camera.position[0..], zm.Vec, 3), zm.load(demo.camera.forward[0..], zm.Vec, 3), zm.f32x4(0.0, 1.0, 0.0, 0.0), ); const cam_view_to_clip = zm.perspectiveFovLh( 0.25 * math.pi, @intToFloat(f32, gctx.viewport_width) / @intToFloat(f32, gctx.viewport_height), 0.01, 200.0, ); const cam_world_to_clip = zm.mul(cam_world_to_view, cam_view_to_clip); gctx.beginFrame(); const back_buffer = gctx.getBackBuffer(); gctx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_RENDER_TARGET); gctx.flushResourceBarriers(); gctx.cmdlist.OMSetRenderTargets( 1, &[_]d3d12.CPU_DESCRIPTOR_HANDLE{back_buffer.descriptor_handle}, w32.TRUE, &demo.depth_texture_dsv, ); gctx.cmdlist.ClearRenderTargetView( back_buffer.descriptor_handle, &[4]f32{ 0.2, 0.4, 0.8, 1.0 }, 0, null, ); gctx.cmdlist.ClearDepthStencilView(demo.depth_texture_dsv, d3d12.CLEAR_FLAG_DEPTH, 1.0, 0, 0, null); gctx.cmdlist.IASetVertexBuffers(0, 1, &[_]d3d12.VERTEX_BUFFER_VIEW{.{ .BufferLocation = gctx.lookupResource(demo.vertex_buffer).?.GetGPUVirtualAddress(), .SizeInBytes = @intCast(u32, gctx.getResourceSize(demo.vertex_buffer)), .StrideInBytes = @sizeOf(Pso_Vertex), }}); gctx.cmdlist.IASetIndexBuffer(&.{ .BufferLocation = gctx.lookupResource(demo.index_buffer).?.GetGPUVirtualAddress(), .SizeInBytes = @intCast(u32, gctx.getResourceSize(demo.index_buffer)), .Format = .R16_UINT, }); gctx.cmdlist.IASetPrimitiveTopology(.TRIANGLELIST); gctx.setCurrentPipeline(demo.simple_entity_pso); // Upload per-frame constant data (camera xform). { const mem = gctx.allocateUploadMemory(Pso_FrameConst, 1); zm.storeMat(mem.cpu_slice[0].world_to_clip[0..], zm.transpose(cam_world_to_clip)); mem.cpu_slice[0].camera_position = demo.camera.position; gctx.cmdlist.SetGraphicsRootConstantBufferView(1, mem.gpu_base); } for (demo.drawables.items) |drawable| { const mem = gctx.allocateUploadMemory(Pso_DrawConst, 1); const object_to_world = zm.translationV(zm.load(drawable.position[0..], zm.Vec, 3)); zm.storeMat(mem.cpu_slice[0].object_to_world[0..], zm.transpose(object_to_world)); mem.cpu_slice[0].basecolor_roughness = drawable.basecolor_roughness; gctx.cmdlist.SetGraphicsRootConstantBufferView(0, mem.gpu_base); gctx.cmdlist.DrawIndexedInstanced( demo.meshes.items[drawable.mesh_index].num_indices, 1, demo.meshes.items[drawable.mesh_index].index_offset, demo.meshes.items[drawable.mesh_index].vertex_offset, 0, ); } demo.guir.draw(gctx); gctx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_PRESENT); gctx.flushResourceBarriers(); gctx.endFrame(); } pub fn main() !void { common.init(); defer common.deinit(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var demo = try init(allocator); defer deinit(&demo, allocator); while (common.handleWindowEvents()) { update(&demo); draw(&demo); } }
samples/procedural_mesh/src/procedural_mesh.zig
const graphics = @import("didot-graphics"); const objects = @import("didot-objects"); const std = @import("std"); const single_threaded = @import("builtin").single_threaded; const Allocator = std.mem.Allocator; const Window = graphics.Window; const Scene = objects.Scene; pub const Application = struct { /// How many time per second updates should be called, defaults to 60 updates/s. updateTarget: u32 = 60, window: Window = undefined, /// The current scene, this is set by init() and start(). /// It can also be set manually to change scene in-game. scene: *Scene = undefined, title: [:0]const u8 = "Didot Game", allocator: *Allocator = undefined, /// Optional function to be called on application init. initFn: ?fn(allocator: *Allocator, app: *Application) anyerror!void = null, closing: bool = false, /// Initialize the application using the given allocator and scene. /// This creates a window, init primitives and call the init function if set. pub fn init(self: *Application, allocator: *Allocator, scene: *Scene) !void { var window = try Window.create(); window.setTitle(self.title); self.scene = scene; self.window = window; self.allocator = allocator; objects.initPrimitives(); try scene.assetManager.put("Mesh/Cube", .{ .objectPtr = @ptrToInt(&objects.PrimitiveCubeMesh), .unloadable = false, .objectType = .Mesh }); try scene.assetManager.put("Mesh/Plane", .{ .objectPtr = @ptrToInt(&objects.PrimitivePlaneMesh), .unloadable = false, .objectType = .Mesh }); if (self.initFn) |func| { try func(allocator, self); } } fn updateLoop(self: *Application) void { var lastTime: i64 = std.time.milliTimestamp(); while (!self.closing) { var arena = std.heap.ArenaAllocator.init(self.allocator); const allocator = &arena.allocator; const s_per_frame = (1 / @intToFloat(f64, self.updateTarget)) * 1000; const time = std.time.milliTimestamp(); const delta = @floatCast(f32, @intToFloat(f64, time-lastTime) / s_per_frame); self.scene.gameObject.update(self.allocator, delta) catch |err| { // TODO: correctly handle errors std.debug.warn("{}", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } //@panic("error"); }; const wait = @floatToInt(u64, @floor((1.0/@intToFloat(f64, self.updateTarget))*1000000000.0) ); lastTime = std.time.milliTimestamp(); std.time.sleep(wait); arena.deinit(); } } /// Start the game loop, that is doing rendering. /// It is also ensuring game updates and updating the window. pub fn loop(self: *Application) !void { var thread: *std.Thread = undefined; if (!single_threaded) { thread = try std.Thread.spawn(self, updateLoop); } while (self.window.update()) { if (single_threaded) { var arena = std.heap.ArenaAllocator.init(self.allocator); const allocator = &arena.allocator; try self.scene.gameObject.update(allocator, 1); arena.deinit(); } try self.scene.render(self.window); } self.closing = true; if (!single_threaded) { thread.wait(); // thread must be closed before scene is de-init (to avoid use-after-free) } self.closing = false; self.window.deinit(); self.scene.deinitAll(); } /// Helper method to call both init() and loop(). pub fn start(self: *Application, allocator: *Allocator, scene: *Scene) !void { try self.init(allocator, scene); try self.loop(); } }; comptime { std.testing.refAllDecls(Application); }
didot-app/app.zig
const std = @import("std"); const StateType = enum(i32) { Match = 256, Split = 257, }; const State = struct { c: i32, out: ?*State, out1: ?*State, lastlist: int32 }; const Frag = struct { start: ?*State, out: ?*Ptrlist }; const Ptrlist = union { next: ?*Ptrlist, s: ?*State }; fn push(stack: *Frag, s: *State) void { *stack += 1; *stack = s; } fn pop(stack: *Frag) void { *stack -= 1; } fn list1(outp: **State) *Ptrlist { const l: *Ptrlist = *outp; l.next = Null; return l; } fn append(l1: *Ptrlist, l2: *Ptrlist) @TypeOf(l1) { const oldl1 = l1; while (l1.next) { l1 = l1.next; } l1.next = l2; return old1; } fn patch(l: *Ptrlist, s: *State) void { var next: *Ptrlist; for (l) |ele| { next = ele.next; ele.s = s; } } fn post2nfa(postfix: *u8) *State { var p: *u8 = undefined; var stack: [1000]Frag = undefined; var stackp: *Frag = undefined; var e: Frag = undefined; var e1: Frag = undefined; var e2: Frag = undefined; stackp = stack; for (postfix) |char| { switch (*char) { '.' => { e2 = pop(stackp); e1 = pop(stackp); patch(e1.out, e2.start); push(Frag{ .start = e1.start, .out = e2.out }); }, '|' => { e2 = pop(stackp); e1 = pop(stackp); s = State{ .c = StateType.Split, .out = e1.start, .out1 = e2.start }; push(Frag{ .state = s, .out = append(e1.out, e2.out) }); }, '?' => { e = pop(stackp); s = State{ .c = StateType.Split, .out = e.start, .out1 = undefiend }; push(Frag{ .state = s, .out = append(e.out, list1(&s.out1)) }); }, '*' => { e = pop(stackp); s = State{ .c = StateType.Split, .out = e.start, .out1 = undefined }; patch(e.out, s); push(Frag{ .state = s, .out = list1(&s.out1) }); }, '+' => { e = pop(); s = State{ .c = StateType.Split, .out = e.start, .out1 = undefined }; patch(e.out, s); push(Frag{ .state = e.start, .out = list1(&s.out1) }); }, else => { s = State{ .c = *p, .out = undefined, .out1 = undefined }; push(Frag{ .state = s, .out = list1(&s.out) }); }, } } e = pop(stackp); patch(e.out, matchState); return e.start; } pub fn main() anyerror!void { std.log.info("All your codebase are belong to us.", .{}); }
src/main.zig
pub const SYS = enum(usize) { // BSD's syscalls exit = 0x2000001, fork = 0x2000002, read = 0x2000003, write = 0x2000004, open = 0x2000005, close = 0x2000006, wait4 = 0x2000007, link = 0x2000009, unlink = 0x200000a, chdir = 0x200000c, fchdir = 0x200000d, mknod = 0x200000e, chmod = 0x200000f, chown = 0x2000010, getfsstat = 0x2000012, getpid = 0x2000014, setuid = 0x2000017, getuid = 0x2000018, geteuid = 0x2000019, ptrace = 0x200001a, recvmsg = 0x200001b, sendmsg = 0x200001c, recvfrom = 0x200001d, accept = 0x200001e, getpeername = 0x200001f, getsockname = 0x2000020, access = 0x2000021, chflags = 0x2000022, fchflags = 0x2000023, sync = 0x2000024, kill = 0x2000025, getppid = 0x2000027, dup = 0x2000029, pipe = 0x200002a, getegid = 0x200002b, sigaction = 0x200002e, getgid = 0x200002f, sigprocmask = 0x2000030, getlogin = 0x2000031, setlogin = 0x2000032, acct = 0x2000033, sigpending = 0x2000034, sigaltstack = 0x2000035, ioctl = 0x2000036, reboot = 0x2000037, revoke = 0x2000038, symlink = 0x2000039, readlink = 0x200003a, execve = 0x200003b, umask = 0x200003c, chroot = 0x200003d, msync = 0x2000041, vfork = 0x2000042, munmap = 0x2000049, mprotect = 0x200004a, madvise = 0x200004b, mincore = 0x200004e, getgroups = 0x200004f, setgroups = 0x2000050, getpgrp = 0x2000051, setpgid = 0x2000052, setitimer = 0x2000053, swapon = 0x2000055, getitimer = 0x2000056, getdtablesize = 0x2000059, dup2 = 0x200005a, fcntl = 0x200005c, select = 0x200005d, fsync = 0x200005f, setpriority = 0x2000060, socket = 0x2000061, connect = 0x2000062, getpriority = 0x2000064, bind = 0x2000068, setsockopt = 0x2000069, listen = 0x200006a, sigsuspend = 0x200006f, gettimeofday = 0x2000074, getrusage = 0x2000075, getsockopt = 0x2000076, readv = 0x2000078, writev = 0x2000079, settimeofday = 0x200007a, fchown = 0x200007b, fchmod = 0x200007c, setreuid = 0x200007e, setregid = 0x200007f, rename = 0x2000080, flock = 0x2000083, mkfifo = 0x2000084, sendto = 0x2000085, shutdown = 0x2000086, socketpair = 0x2000087, mkdir = 0x2000088, rmdir = 0x2000089, utimes = 0x200008a, futimes = 0x200008b, adjtime = 0x200008c, gethostuuid = 0x200008e, setsid = 0x2000093, getpgid = 0x2000097, setprivexec = 0x2000098, pread = 0x2000099, pwrite = 0x200009a, nfssvc = 0x200009b, statfs = 0x200009d, fstatfs = 0x200009e, unmount = 0x200009f, getfh = 0x20000a1, quotactl = 0x20000a5, mount = 0x20000a7, csops = 0x20000a9, csops_audittoken = 0x2<PASSWORD>, waitid = 0x20000ad, kdebug_typefilter = 0x20000b1, kdebug_trace_string = 0x20000b2, kdebug_trace64 = 0x20000b3, kdebug_trace = 0x20000b4, setgid = 0x20000b5, setegid = 0x20000b6, seteuid = 0x20000b7, sigreturn = 0x20000b8, thread_selfcounts = 0x20000ba, fdatasync = 0x20000bb, stat = 0x20000bc, fstat = 0x20000bd, lstat = 0x20000be, pathconf = 0x20000bf, fpathconf = 0x20000c0, getrlimit = 0x20000c2, setrlimit = 0x20000c3, getdirentries = 0x20000c4, mmap = 0x20000c5, lseek = 0x20000c7, truncate = 0x20000c8, ftruncate = 0x20000c9, sysctl = 0x20000ca, mlock = 0x20000cb, munlock = 0x20000cc, undelete = 0x20000cd, open_dprotected_np = 0x20000d8, fsgetpath_ext = 0x20000d9, getattrlist = 0x20000dc, setattrlist = 0x20000dd, getdirentriesattr = 0x20000de, exchangedata = 0x20000df, searchfs = 0x20000e1, delete = 0x20000e2, copyfile = 0x20000e3, fgetattrlist = 0x20000e4, fsetattrlist = 0x20000e5, poll = 0x20000e6, getxattr = 0x20000ea, fgetxattr = 0x20000eb, setxattr = 0x20000ec, fsetxattr = 0x20000ed, removexattr = 0x20000ee, fremovexattr = 0x20000ef, listxattr = 0x20000f0, flistxattr = 0x20000f1, fsctl = 0x20000f2, initgroups = 0x20000f3, posix_spawn = 0x20000f4, ffsctl = 0x20000f5, nfsclnt = 0x20000f7, fhopen = 0x20000f8, minherit = 0x20000fa, semsys = 0x20000fb, msgsys = 0x20000fc, shmsys = 0x20000fd, semctl = 0x20000fe, semget = 0x20000ff, semop = 0x2000100, msgctl = 0x2000102, msgget = 0x2000103, msgsnd = 0x2000104, msgrcv = 0x2000105, shmat = 0x2000106, shmctl = 0x2000107, shmdt = 0x2000108, shmget = 0x2000109, shm_open = 0x200010a, shm_unlink = 0x200010b, sem_open = 0x200010c, sem_close = 0x200010d, sem_unlink = 0x200010e, sem_wait = 0x200010f, sem_trywait = 0x2000110, sem_post = 0x2000111, sysctlbyname = 0x2000112, open_extended = 0x2000115, umask_extended = 0x2000116, stat_extended = 0x2000117, lstat_extended = 0x2000118, fstat_extended = 0x2000119, chmod_extended = 0x200011a, fchmod_extended = 0x200011b, access_extended = 0x200011c, settid = 0x200011d, gettid = 0x200011e, setsgroups = 0x200011f, getsgroups = 0x2000120, setwgroups = 0x2000121, getwgroups = 0x2000122, mkfifo_extended = 0x2000123, mkdir_extended = 0x2000124, identitysvc = 0x2000125, shared_region_check_np = 0x2000126, vm_pressure_monitor = 0x2000128, psynch_rw_longrdlock = 0x2000129, psynch_rw_yieldwrlock = 0x200012a, psynch_rw_downgrade = 0x200012b, psynch_rw_upgrade = 0x200012c, psynch_mutexwait = 0x200012d, psynch_mutexdrop = 0x200012e, psynch_cvbroad = 0x200012f, psynch_cvsignal = 0x2000130, psynch_cvwait = 0x2000131, psynch_rw_rdlock = 0x2000132, psynch_rw_wrlock = 0x2000133, psynch_rw_unlock = 0x2000134, psynch_rw_unlock2 = 0x2000135, getsid = 0x2000136, settid_with_pid = 0x2000137, psynch_cvclrprepost = 0x2000138, aio_fsync = 0x2000139, aio_return = 0x200013a, aio_suspend = 0x200013b, aio_cancel = 0x200013c, aio_error = 0x200013d, aio_read = 0x200013e, aio_write = 0x200013f, lio_listio = 0x2000140, iopolicysys = 0x2000142, process_policy = 0x2000143, mlockall = 0x2000144, munlockall = 0x2000145, issetugid = 0x2000147, __pthread_kill = 0x2000148, __pthread_sigmask = 0x2000149, __sigwait = 0x200014a, __disable_threadsignal = 0x200014b, __pthread_markcancel = 0x200014c, __pthread_canceled = 0x200014d, __semwait_signal = 0x200014e, proc_info = 0x2000150, sendfile = 0x2000151, stat64 = 0x2000152, fstat64 = 0x2000153, lstat64 = 0x2000154, stat64_extended = 0x2000155, lstat64_extended = 0x2000156, fstat64_extended = 0x2000157, getdirentries64 = 0x2000158, statfs64 = 0x2000159, fstatfs64 = 0x200015a, getfsstat64 = 0x200015b, __pthread_chdir = 0x200015c, __pthread_fchdir = 0x200015d, audit = 0x200015e, auditon = 0x200015f, getauid = 0x2000161, setauid = 0x2000162, getaudit_addr = 0x2000165, setaudit_addr = 0x2000166, auditctl = 0x2000167, bsdthread_create = 0x2000168, bsdthread_terminate = 0x2000169, kqueue = 0x200016a, kevent = 0x200016b, lchown = 0x200016c, bsdthread_register = 0x200016e, workq_open = 0x200016f, workq_kernreturn = 0x2000170, kevent64 = 0x2000171, __old_semwait_signal = 0x2000172, __old_semwait_signal_nocancel = 0x2000173, thread_selfid = 0x2000174, ledger = 0x2000175, kevent_qos = 0x2000176, kevent_id = 0x2000177, __mac_execve = 0x200017c, __mac_syscall = 0x200017d, __mac_get_file = 0x200017e, __mac_set_file = 0x200017f, __mac_get_link = 0x2000180, __mac_set_link = 0x2000181, __mac_get_proc = 0x2000182, __mac_set_proc = 0x2000183, __mac_get_fd = 0x2000184, __mac_set_fd = 0x2000185, __mac_get_pid = 0x2000186, pselect = 0x200018a, pselect_nocancel = 0x200018b, read_nocancel = 0x200018c, write_nocancel = 0x200018d, open_nocancel = 0x200018e, close_nocancel = 0x200018f, wait4_nocancel = 0x2000190, recvmsg_nocancel = 0x2000191, sendmsg_nocancel = 0x2000192, recvfrom_nocancel = 0x2000193, accept_nocancel = 0x2000194, msync_nocancel = 0x2000195, fcntl_nocancel = 0x2000196, select_nocancel = 0x2000197, fsync_nocancel = 0x2000198, connect_nocancel = 0x2000199, sigsuspend_nocancel = 0x200019a, readv_nocancel = 0x200019b, writev_nocancel = 0x200019c, sendto_nocancel = 0x200019d, pread_nocancel = 0x200019e, pwrite_nocancel = 0x200019f, waitid_nocancel = 0x20001a0, poll_nocancel = 0x20001a1, msgsnd_nocancel = 0x20001a2, msgrcv_nocancel = 0x20001a3, sem_wait_nocancel = 0x20001a4, aio_suspend_nocancel = 0x20001a5, __sigwait_nocancel = 0x20001a6, __semwait_signal_nocancel = 0x20001a7, __mac_mount = 0x20001a8, __mac_get_mount = 0x20001a9, __mac_getfsstat = 0x20001aa, fsgetpath = 0x20001ab, audit_session_self = 0x20001ac, audit_session_join = 0x20001ad, fileport_makeport = 0x20001ae, fileport_makefd = 0x20001af, audit_session_port = 0x20001b0, pid_suspend = 0x20001b1, pid_resume = 0x20001b2, pid_hibernate = 0x20001b3, pid_shutdown_sockets = 0x20001b4, shared_region_map_and_slide_np = 0x20001b6, kas_info = 0x20001b7, memorystatus_control = 0x20001b8, guarded_open_np = 0x20001b9, guarded_close_np = 0x20001ba, guarded_kqueue_np = 0x20001bb, change_fdguard_np = 0x20001bc, usrctl = 0x20001bd, proc_rlimit_control = 0x20001be, connectx = 0x20001bf, disconnectx = 0x20001c0, peeloff = 0x20001c1, socket_delegate = 0x20001c2, telemetry = 0x20001c3, proc_uuid_policy = 0x20001c4, memorystatus_get_level = 0x20001c5, system_override = 0x20001c6, vfs_purge = 0x20001c7, sfi_ctl = 0x20001c8, sfi_pidctl = 0x20001c9, coalition = 0x20001ca, coalition_info = 0x20001cb, necp_match_policy = 0x20001cc, getattrlistbulk = 0x20001cd, clonefileat = 0x20001ce, openat = 0x20001cf, openat_nocancel = 0x20001d0, renameat = 0x20001d1, faccessat = 0x20001d2, fchmodat = 0x20001d3, fchownat = 0x20001d4, fstatat = 0x20001d5, fstatat64 = 0x20001d6, linkat = 0x20001d7, unlinkat = 0x20001d8, readlinkat = 0x20001d9, symlinkat = 0x20001da, mkdirat = 0x20001db, getattrlistat = 0x20001dc, proc_trace_log = 0x20001dd, bsdthread_ctl = 0x20001de, openbyid_np = 0x20001df, recvmsg_x = 0x20001e0, sendmsg_x = 0x20001e1, thread_selfusage = 0x20001e2, csrctl = 0x20001e3, guarded_open_dprotected_np = 0x20001e4, guarded_write_np = 0x20001e5, guarded_pwrite_np = 0x20001e6, guarded_writev_np = 0x20001e7, renameatx_np = 0x20001e8, mremap_encrypted = 0x20001e9, netagent_trigger = 0x20001ea, stack_snapshot_with_config = 0x20001eb, microstackshot = 0x20001ec, grab_pgo_data = 0x20001ed, persona = 0x20001ee, mach_eventlink_signal = 0x20001f0, mach_eventlink_wait_until = 0x20001f1, mach_eventlink_signal_wait_until = 0x20001f2, work_interval_ctl = 0x20001f3, getentropy = 0x20001f4, necp_open = 0x20001f5, necp_client_action = 0x20001f6, ulock_wait = 0x2000203, ulock_wake = 0x2000204, fclonefileat = 0x2000205, fs_snapshot = 0x2000206, terminate_with_payload = 0x2000208, abort_with_payload = 0x2000209, necp_session_open = 0x200020a, necp_session_action = 0x200020b, setattrlistat = 0x200020c, net_qos_guideline = 0x200020d, fmount = 0x200020e, ntp_adjtime = 0x200020f, ntp_gettime = 0x2000210, os_fault_with_payload = 0x2000211, kqueue_workloop_ctl = 0x2000212, __mach_bridge_remote_time = 0x2000213, coalition_ledger = 0x2000214, log_data = 0x2000215, memorystatus_available_memory = 0x2000216, shared_region_map_and_slide_2_np = 0x2000218, pivot_root = 0x2000219, task_inspect_for_pid = 0x200021a, task_read_for_pid = 0x200021b, preadv = 0x200021c, pwritev = 0x200021d, preadv_nocancel = 0x200021e, pwritev_nocancel = 0x200021f, ulock_wait2 = 0x2000220, proc_info_extended_id = 0x2000221, // Mach traps _kernelrpc_mach_vm_allocate_trap = 0x100000a, _kernelrpc_mach_vm_deallocate_trap = 0x100000c, _kernelrpc_mach_vm_protect_trap = 0x100000e, _kernelrpc_mach_vm_map_trap = 0x100000f, _kernelrpc_mach_port_allocate_trap = 0x1000010, _kernelrpc_mach_port_destroy_trap = 0x1000011, _kernelrpc_mach_port_deallocate_trap = 0x1000012, _kernelrpc_mach_port_mod_refs_trap = 0x1000013, _kernelrpc_mach_port_move_member_trap = 0x1000014, _kernelrpc_mach_port_insert_right_trap = 0x1000015, _kernelrpc_mach_port_insert_member_trap = 0x1000016, _kernelrpc_mach_port_extract_member_trap = 0x1000017, _kernelrpc_mach_port_construct_trap = 0x1000018, _kernelrpc_mach_port_destruct_trap = 0x1000019, mach_reply_port = 0x100001a, thread_self_trap = 0x100001b, task_self_trap = 0x100001c, host_self_trap = 0x100001d, mach_msg_trap = 0x100001f, mach_msg_overwrite_trap = 0x1000020, semaphore_signal_trap = 0x1000021, semaphore_signal_all_trap = 0x1000022, semaphore_signal_thread_trap = 0x1000023, semaphore_wait_trap = 0x1000024, semaphore_wait_signal_trap = 0x1000025, semaphore_timedwait_trap = 0x1000026, semaphore_timedwait_signal_trap = 0x1000027, _kernelrpc_mach_port_guard_trap = 0x1000029, _kernelrpc_mach_port_unguard_trap = 0x100002a, mach_generate_activity_id = 0x100002b, task_name_for_pid = 0x100002c, task_for_pid = 0x100002d, pid_for_task = 0x100002e, macx_swapon = 0x1000030, macx_swapoff = 0x1000031, thread_get_special_reply_port = 0x1000032, macx_triggers = 0x1000033, macx_backing_store_suspend = 0x1000034, macx_backing_store_recovery = 0x1000035, pfz_exit = 0x100003a, swtch_pri = 0x100003b, swtch = 0x100003c, thread_switch = 0x100003d, clock_sleep_trap = 0x100003e, host_create_mach_voucher_trap = 0x1000046, mach_voucher_extract_attr_recipe_trap = 0x1000048, mach_timebase_info_trap = 0x1000059, mach_wait_until_trap = 0x100005a, mk_timer_create_trap = 0x100005b, mk_timer_destroy_trap = 0x100005c, mk_timer_arm_trap = 0x100005d, mk_timer_cancel_trap = 0x100005e, iokit_user_client_trap = 0x1000064, };
src/apple/consts.zig
const std = @import("std"); var allocator_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); pub const default_allocator = &allocator_arena.allocator; extern fn wngx_log(level: u32, msg: [*]const u8, msglen: u32) void; extern fn wngx_request_size() u32; extern fn wngx_get_request(buf: [*]u8, buflen: u32) void; extern fn wngx_add_header(key: [*]const u8, key_len: u32, val: [*]const u8, val_len: u32) void; extern fn wngx_subrequest(req: *w_subrequest_params, cb: fn (req: *w_subrequest_params) u32) u32; pub fn log(level: u32, comptime fmt: []const u8, args: var) void { const bufsize = 4096; var buf: [bufsize]u8 = undefined; var ostrm = std.io.fixedBufferStream(&buf); ostrm.outStream().print(fmt, args) catch return; wngx_log(level, &buf, ostrm.pos); } const w_string = extern struct { d: ?[*]u8, len: u32, fn new(s: []const u8) w_string { return w_string { .d = s.ptr, .len = s.len, }; } fn toSlice(self: w_string) ?[]const u8 { const d = self.d orelse return null; return d[0..self.len]; } }; const w_header = extern struct { name: w_string, value: w_string, }; const w_request = extern struct { n_headers: u32, buf_start: *u8, total_size: u32, request_line: w_string, method: w_string, uri: w_string, http_version: w_string, uri_path: w_string, uri_args: w_string, uri_exten: w_string, }; pub const Request = struct { const HeaderMap = std.StringHashMap([]const u8); request_line: []const u8, method: []const u8, uri: []const u8, http_version: []const u8, uri_path: []const u8, uri_args: []const u8, uri_exten: []const u8, headers: HeaderMap, pub fn init(allocator: *std.mem.Allocator) !Request { var request_bytes = try allocator.alignedAlloc(u8, @alignOf(w_request), wngx_request_size()); wngx_get_request(request_bytes.ptr, request_bytes.len); var w_req = @ptrCast(*w_request, request_bytes.ptr); var w_hd = @ptrCast([*]w_header, request_bytes.ptr + @sizeOf(w_request))[0..w_req.n_headers]; return Request { .request_line = w_req.request_line.toSlice() orelse "", .method = w_req.method.toSlice() orelse "", .uri = w_req.uri.toSlice() orelse "", .http_version = w_req.http_version.toSlice() orelse "", .uri_path = w_req.uri_path.toSlice() orelse "", .uri_args = w_req.uri_args.toSlice() orelse "", .uri_exten = w_req.uri_exten.toSlice() orelse "", .headers = header_hash(allocator, w_hd), }; } fn header_hash(allocator: *std.mem.Allocator, w_hdrs: []const w_header) HeaderMap { var headers = HeaderMap.init(allocator); for (w_hdrs) |w_h| { const key = w_h.name.toSlice() orelse continue; const val = w_h.value.toSlice() orelse continue; _ = headers.put(key, val) catch return headers; } return headers; } }; pub fn add_header(key: []const u8, val: []const u8) void { wngx_add_header(key.ptr, key.len, val.ptr, val.len); } export fn on_callback( w_d: ?*u8 ) u32 { log(0x100, "on_callback: w_d: {}", .{w_d}); const d = @ptrCast(*w_subrequest_params, @alignCast(4, w_d)); return d.callback.f(d); } const w_subrequest_params = extern struct { callback: *cb_wrapper, uri: w_string, args: w_string, ref: u32, data: *SubRequest, }; const cb_wrapper = struct { f: fn (data: *w_subrequest_params) u32, }; pub const SubRequest = struct { ref: u32, pub fn fetch(uri: []const u8, args: []const u8) !SubRequest { var self = SubRequest{}; var params = w_subrequest_params { .callback = .{ .f = self.callback }, .uri = w_string.new(uri), .args = w_string.new(args), .data = self, }; self.ref = wngx_subrequest(&params); if (self.ref == 0) return error.SubRequestFail; return self; } pub fn callback(req: *w_subrequest_params) u32 { log(0x100, "callback req: {}, data: {}", .{req, data}); return 1; } };
wngx.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const print = std.debug.print; /// This input file has been preprocesed with find-and-replace operations /// Example of the input after preprocessing: /// /// vibrant orange:3 striped olive,1 muted olive /// light lime:1 dotted red,5 bright red /// shiny olive:5 vibrant black,2 dotted violet /// wavy blue:2 dull blue,4 dark violet /// dark black:4 drab cyan /// faded orange: /// mirrored magenta:2 bright crimson,5 mirrored fuchsia,4 plaid green,4 plaid gold /// const data = @embedFile("data/day07.txt"); const EntriesList = std.ArrayList(Record); const Child = struct { count: usize, color: []const u8, }; const Record = struct { color: []const u8, rules: []Child, gold: bool = false, done: bool = false, subcount: usize = 0, }; const Entries = std.ArrayList(Record); pub fn main() !void { const timer = try std.time.Timer.start(); var arena = std.heap.GeneralPurposeAllocator(.{}){}; const ally = &arena.allocator; var lines = std.mem.tokenize(data, "\r\n"); var map = Entries.init(ally); var result: usize = 0; while (lines.next()) |line| { if (line.len == 0) continue; var parts = std.mem.tokenize(line, ":,"); var color = parts.next().?; var list = std.ArrayList(Child).init(ally); while (parts.next()) |part| { const split = std.mem.indexOfAny(u8, part, " ").?; const count = try std.fmt.parseInt(usize, part[0..split], 10); const incolor = part[split+1..]; try list.append(.{ .count = count, .color = incolor }); } try map.append(.{ .color = color, .rules = list.toOwnedSlice(), .gold = std.mem.eql(u8, "shiny gold", color), }); } var totalGold: usize = 0; var modifiedAny = true; while (modifiedAny) { modifiedAny = false; nextItem: for (map.items) |*item| { if (item.done) continue; var childTotal: usize = 0; for (item.rules) |rule| { var match: ?*Record = null; for (map.items) |*item2| { if (std.mem.eql(u8, rule.color, item2.color)) { match = item2; break; } } if (!item.gold and match.?.gold) { item.gold = true; totalGold += 1; modifiedAny = true; } if (!match.?.done) continue :nextItem; childTotal += (match.?.subcount + 1) * rule.count; } item.done = true; item.subcount = childTotal; modifiedAny = true; } } var match: ?*Record = null; for (map.items) |*item2| { if (std.mem.eql(u8, "shiny gold", item2.color)) { match = item2; break; } } var elapsed = timer.read(); print("part1: {}, part2: {}, time: {}\n", .{totalGold, match.?.subcount, elapsed}); }
src/day07.zig
pub const Keysym = enum(u32) { NoSymbol = 0x000000, VoidSymbol = 0xffffff, _, pub const BackSpace = 0xff08; pub const Tab = 0xff09; pub const Linefeed = 0xff0a; pub const Clear = 0xff0b; pub const Return = 0xff0d; pub const Pause = 0xff13; pub const Scroll_Lock = 0xff14; pub const Sys_Req = 0xff15; pub const Escape = 0xff1b; pub const Delete = 0xffff; pub const Multi_key = 0xff20; pub const Codeinput = 0xff37; pub const SingleCandidate = 0xff3c; pub const MultipleCandidate = 0xff3d; pub const PreviousCandidate = 0xff3e; pub const Kanji = 0xff21; pub const Muhenkan = 0xff22; pub const Henkan_Mode = 0xff23; pub const Henkan = 0xff23; pub const Romaji = 0xff24; pub const Hiragana = 0xff25; pub const Katakana = 0xff26; pub const Hiragana_Katakana = 0xff27; pub const Zenkaku = 0xff28; pub const Hankaku = 0xff29; pub const Zenkaku_Hankaku = 0xff2a; pub const Touroku = 0xff2b; pub const Massyo = 0xff2c; pub const Kana_Lock = 0xff2d; pub const Kana_Shift = 0xff2e; pub const Eisu_Shift = 0xff2f; pub const Eisu_toggle = 0xff30; pub const Kanji_Bangou = 0xff37; pub const Zen_Koho = 0xff3d; pub const Mae_Koho = 0xff3e; pub const Home = 0xff50; pub const Left = 0xff51; pub const Up = 0xff52; pub const Right = 0xff53; pub const Down = 0xff54; pub const Prior = 0xff55; pub const Page_Up = 0xff55; pub const Next = 0xff56; pub const Page_Down = 0xff56; pub const End = 0xff57; pub const Begin = 0xff58; pub const Select = 0xff60; pub const Print = 0xff61; pub const Execute = 0xff62; pub const Insert = 0xff63; pub const Undo = 0xff65; pub const Redo = 0xff66; pub const Menu = 0xff67; pub const Find = 0xff68; pub const Cancel = 0xff69; pub const Help = 0xff6a; pub const Break = 0xff6b; pub const Mode_switch = 0xff7e; pub const script_switch = 0xff7e; pub const Num_Lock = 0xff7f; pub const KP_Space = 0xff80; pub const KP_Tab = 0xff89; pub const KP_Enter = 0xff8d; pub const KP_F1 = 0xff91; pub const KP_F2 = 0xff92; pub const KP_F3 = 0xff93; pub const KP_F4 = 0xff94; pub const KP_Home = 0xff95; pub const KP_Left = 0xff96; pub const KP_Up = 0xff97; pub const KP_Right = 0xff98; pub const KP_Down = 0xff99; pub const KP_Prior = 0xff9a; pub const KP_Page_Up = 0xff9a; pub const KP_Next = 0xff9b; pub const KP_Page_Down = 0xff9b; pub const KP_End = 0xff9c; pub const KP_Begin = 0xff9d; pub const KP_Insert = 0xff9e; pub const KP_Delete = 0xff9f; pub const KP_Equal = 0xffbd; pub const KP_Multiply = 0xffaa; pub const KP_Add = 0xffab; pub const KP_Separator = 0xffac; pub const KP_Subtract = 0xffad; pub const KP_Decimal = 0xffae; pub const KP_Divide = 0xffaf; pub const KP_0 = 0xffb0; pub const KP_1 = 0xffb1; pub const KP_2 = 0xffb2; pub const KP_3 = 0xffb3; pub const KP_4 = 0xffb4; pub const KP_5 = 0xffb5; pub const KP_6 = 0xffb6; pub const KP_7 = 0xffb7; pub const KP_8 = 0xffb8; pub const KP_9 = 0xffb9; pub const F1 = 0xffbe; pub const F2 = 0xffbf; pub const F3 = 0xffc0; pub const F4 = 0xffc1; pub const F5 = 0xffc2; pub const F6 = 0xffc3; pub const F7 = 0xffc4; pub const F8 = 0xffc5; pub const F9 = 0xffc6; pub const F10 = 0xffc7; pub const F11 = 0xffc8; pub const L1 = 0xffc8; pub const F12 = 0xffc9; pub const L2 = 0xffc9; pub const F13 = 0xffca; pub const L3 = 0xffca; pub const F14 = 0xffcb; pub const L4 = 0xffcb; pub const F15 = 0xffcc; pub const L5 = 0xffcc; pub const F16 = 0xffcd; pub const L6 = 0xffcd; pub const F17 = 0xffce; pub const L7 = 0xffce; pub const F18 = 0xffcf; pub const L8 = 0xffcf; pub const F19 = 0xffd0; pub const L9 = 0xffd0; pub const F20 = 0xffd1; pub const L10 = 0xffd1; pub const F21 = 0xffd2; pub const R1 = 0xffd2; pub const F22 = 0xffd3; pub const R2 = 0xffd3; pub const F23 = 0xffd4; pub const R3 = 0xffd4; pub const F24 = 0xffd5; pub const R4 = 0xffd5; pub const F25 = 0xffd6; pub const R5 = 0xffd6; pub const F26 = 0xffd7; pub const R6 = 0xffd7; pub const F27 = 0xffd8; pub const R7 = 0xffd8; pub const F28 = 0xffd9; pub const R8 = 0xffd9; pub const F29 = 0xffda; pub const R9 = 0xffda; pub const F30 = 0xffdb; pub const R10 = 0xffdb; pub const F31 = 0xffdc; pub const R11 = 0xffdc; pub const F32 = 0xffdd; pub const R12 = 0xffdd; pub const F33 = 0xffde; pub const R13 = 0xffde; pub const F34 = 0xffdf; pub const R14 = 0xffdf; pub const F35 = 0xffe0; pub const R15 = 0xffe0; pub const Shift_L = 0xffe1; pub const Shift_R = 0xffe2; pub const Control_L = 0xffe3; pub const Control_R = 0xffe4; pub const Caps_Lock = 0xffe5; pub const Shift_Lock = 0xffe6; pub const Meta_L = 0xffe7; pub const Meta_R = 0xffe8; pub const Alt_L = 0xffe9; pub const Alt_R = 0xffea; pub const Super_L = 0xffeb; pub const Super_R = 0xffec; pub const Hyper_L = 0xffed; pub const Hyper_R = 0xffee; pub const ISO_Lock = 0xfe01; pub const ISO_Level2_Latch = 0xfe02; pub const ISO_Level3_Shift = 0xfe03; pub const ISO_Level3_Latch = 0xfe04; pub const ISO_Level3_Lock = 0xfe05; pub const ISO_Level5_Shift = 0xfe11; pub const ISO_Level5_Latch = 0xfe12; pub const ISO_Level5_Lock = 0xfe13; pub const ISO_Group_Shift = 0xff7e; pub const ISO_Group_Latch = 0xfe06; pub const ISO_Group_Lock = 0xfe07; pub const ISO_Next_Group = 0xfe08; pub const ISO_Next_Group_Lock = 0xfe09; pub const ISO_Prev_Group = 0xfe0a; pub const ISO_Prev_Group_Lock = 0xfe0b; pub const ISO_First_Group = 0xfe0c; pub const ISO_First_Group_Lock = 0xfe0d; pub const ISO_Last_Group = 0xfe0e; pub const ISO_Last_Group_Lock = 0xfe0f; pub const ISO_Left_Tab = 0xfe20; pub const ISO_Move_Line_Up = 0xfe21; pub const ISO_Move_Line_Down = 0xfe22; pub const ISO_Partial_Line_Up = 0xfe23; pub const ISO_Partial_Line_Down = 0xfe24; pub const ISO_Partial_Space_Left = 0xfe25; pub const ISO_Partial_Space_Right = 0xfe26; pub const ISO_Set_Margin_Left = 0xfe27; pub const ISO_Set_Margin_Right = 0xfe28; pub const ISO_Release_Margin_Left = 0xfe29; pub const ISO_Release_Margin_Right = 0xfe2a; pub const ISO_Release_Both_Margins = 0xfe2b; pub const ISO_Fast_Cursor_Left = 0xfe2c; pub const ISO_Fast_Cursor_Right = 0xfe2d; pub const ISO_Fast_Cursor_Up = 0xfe2e; pub const ISO_Fast_Cursor_Down = 0xfe2f; pub const ISO_Continuous_Underline = 0xfe30; pub const ISO_Discontinuous_Underline = 0xfe31; pub const ISO_Emphasize = 0xfe32; pub const ISO_Center_Object = 0xfe33; pub const ISO_Enter = 0xfe34; pub const dead_grave = 0xfe50; pub const dead_acute = 0xfe51; pub const dead_circumflex = 0xfe52; pub const dead_tilde = 0xfe53; pub const dead_perispomeni = 0xfe53; pub const dead_macron = 0xfe54; pub const dead_breve = 0xfe55; pub const dead_abovedot = 0xfe56; pub const dead_diaeresis = 0xfe57; pub const dead_abovering = 0xfe58; pub const dead_doubleacute = 0xfe59; pub const dead_caron = 0xfe5a; pub const dead_cedilla = 0xfe5b; pub const dead_ogonek = 0xfe5c; pub const dead_iota = 0xfe5d; pub const dead_voiced_sound = 0xfe5e; pub const dead_semivoiced_sound = 0xfe5f; pub const dead_belowdot = 0xfe60; pub const dead_hook = 0xfe61; pub const dead_horn = 0xfe62; pub const dead_stroke = 0xfe63; pub const dead_abovecomma = 0xfe64; pub const dead_psili = 0xfe64; pub const dead_abovereversedcomma = 0xfe65; pub const dead_dasia = 0xfe65; pub const dead_doublegrave = 0xfe66; pub const dead_belowring = 0xfe67; pub const dead_belowmacron = 0xfe68; pub const dead_belowcircumflex = 0xfe69; pub const dead_belowtilde = 0xfe6a; pub const dead_belowbreve = 0xfe6b; pub const dead_belowdiaeresis = 0xfe6c; pub const dead_invertedbreve = 0xfe6d; pub const dead_belowcomma = 0xfe6e; pub const dead_currency = 0xfe6f; pub const dead_lowline = 0xfe90; pub const dead_aboveverticalline = 0xfe91; pub const dead_belowverticalline = 0xfe92; pub const dead_longsolidusoverlay = 0xfe93; pub const dead_a = 0xfe80; pub const dead_A = 0xfe81; pub const dead_e = 0xfe82; pub const dead_E = 0xfe83; pub const dead_i = 0xfe84; pub const dead_I = 0xfe85; pub const dead_o = 0xfe86; pub const dead_O = 0xfe87; pub const dead_u = 0xfe88; pub const dead_U = 0xfe89; pub const dead_small_schwa = 0xfe8a; pub const dead_capital_schwa = 0xfe8b; pub const dead_greek = 0xfe8c; pub const First_Virtual_Screen = 0xfed0; pub const Prev_Virtual_Screen = 0xfed1; pub const Next_Virtual_Screen = 0xfed2; pub const Last_Virtual_Screen = 0xfed4; pub const Terminate_Server = 0xfed5; pub const AccessX_Enable = 0xfe70; pub const AccessX_Feedback_Enable = 0xfe71; pub const RepeatKeys_Enable = 0xfe72; pub const SlowKeys_Enable = 0xfe73; pub const BounceKeys_Enable = 0xfe74; pub const StickyKeys_Enable = 0xfe75; pub const MouseKeys_Enable = 0xfe76; pub const MouseKeys_Accel_Enable = 0xfe77; pub const Overlay1_Enable = 0xfe78; pub const Overlay2_Enable = 0xfe79; pub const AudibleBell_Enable = 0xfe7a; pub const Pointer_Left = 0xfee0; pub const Pointer_Right = 0xfee1; pub const Pointer_Up = 0xfee2; pub const Pointer_Down = 0xfee3; pub const Pointer_UpLeft = 0xfee4; pub const Pointer_UpRight = 0xfee5; pub const Pointer_DownLeft = 0xfee6; pub const Pointer_DownRight = 0xfee7; pub const Pointer_Button_Dflt = 0xfee8; pub const Pointer_Button1 = 0xfee9; pub const Pointer_Button2 = 0xfeea; pub const Pointer_Button3 = 0xfeeb; pub const Pointer_Button4 = 0xfeec; pub const Pointer_Button5 = 0xfeed; pub const Pointer_DblClick_Dflt = 0xfeee; pub const Pointer_DblClick1 = 0xfeef; pub const Pointer_DblClick2 = 0xfef0; pub const Pointer_DblClick3 = 0xfef1; pub const Pointer_DblClick4 = 0xfef2; pub const Pointer_DblClick5 = 0xfef3; pub const Pointer_Drag_Dflt = 0xfef4; pub const Pointer_Drag1 = 0xfef5; pub const Pointer_Drag2 = 0xfef6; pub const Pointer_Drag3 = 0xfef7; pub const Pointer_Drag4 = 0xfef8; pub const Pointer_Drag5 = 0xfefd; pub const Pointer_EnableKeys = 0xfef9; pub const Pointer_Accelerate = 0xfefa; pub const Pointer_DfltBtnNext = 0xfefb; pub const Pointer_DfltBtnPrev = 0xfefc; pub const ch = 0xfea0; pub const Ch = 0xfea1; pub const CH = 0xfea2; pub const c_h = 0xfea3; pub const C_h = 0xfea4; pub const C_H = 0xfea5; pub const @"3270_Duplicate" = 0xfd01; pub const @"3270_FieldMark" = 0xfd02; pub const @"3270_Right2" = 0xfd03; pub const @"3270_Left2" = 0xfd04; pub const @"3270_BackTab" = 0xfd05; pub const @"3270_EraseEOF" = 0xfd06; pub const @"3270_EraseInput" = 0xfd07; pub const @"3270_Reset" = 0xfd08; pub const @"3270_Quit" = 0xfd09; pub const @"3270_PA1" = 0xfd0a; pub const @"3270_PA2" = 0xfd0b; pub const @"3270_PA3" = 0xfd0c; pub const @"3270_Test" = 0xfd0d; pub const @"3270_Attn" = 0xfd0e; pub const @"3270_CursorBlink" = 0xfd0f; pub const @"3270_AltCursor" = 0xfd10; pub const @"3270_KeyClick" = 0xfd11; pub const @"3270_Jump" = 0xfd12; pub const @"3270_Ident" = 0xfd13; pub const @"3270_Rule" = 0xfd14; pub const @"3270_Copy" = 0xfd15; pub const @"3270_Play" = 0xfd16; pub const @"3270_Setup" = 0xfd17; pub const @"3270_Record" = 0xfd18; pub const @"3270_ChangeScreen" = 0xfd19; pub const @"3270_DeleteWord" = 0xfd1a; pub const @"3270_ExSelect" = 0xfd1b; pub const @"3270_CursorSelect" = 0xfd1c; pub const @"3270_PrintScreen" = 0xfd1d; pub const @"3270_Enter" = 0xfd1e; pub const space = 0x0020; pub const exclam = 0x0021; pub const quotedbl = 0x0022; pub const numbersign = 0x0023; pub const dollar = 0x0024; pub const percent = 0x0025; pub const ampersand = 0x0026; pub const apostrophe = 0x0027; pub const quoteright = 0x0027; pub const parenleft = 0x0028; pub const parenright = 0x0029; pub const asterisk = 0x002a; pub const plus = 0x002b; pub const comma = 0x002c; pub const minus = 0x002d; pub const period = 0x002e; pub const slash = 0x002f; pub const @"0" = 0x0030; pub const @"1" = 0x0031; pub const @"2" = 0x0032; pub const @"3" = 0x0033; pub const @"4" = 0x0034; pub const @"5" = 0x0035; pub const @"6" = 0x0036; pub const @"7" = 0x0037; pub const @"8" = 0x0038; pub const @"9" = 0x0039; pub const colon = 0x003a; pub const semicolon = 0x003b; pub const less = 0x003c; pub const equal = 0x003d; pub const greater = 0x003e; pub const question = 0x003f; pub const at = 0x0040; pub const A = 0x0041; pub const B = 0x0042; pub const C = 0x0043; pub const D = 0x0044; pub const E = 0x0045; pub const F = 0x0046; pub const G = 0x0047; pub const H = 0x0048; pub const I = 0x0049; pub const J = 0x004a; pub const K = 0x004b; pub const L = 0x004c; pub const M = 0x004d; pub const N = 0x004e; pub const O = 0x004f; pub const P = 0x0050; pub const Q = 0x0051; pub const R = 0x0052; pub const S = 0x0053; pub const T = 0x0054; pub const U = 0x0055; pub const V = 0x0056; pub const W = 0x0057; pub const X = 0x0058; pub const Y = 0x0059; pub const Z = 0x005a; pub const bracketleft = 0x005b; pub const backslash = 0x005c; pub const bracketright = 0x005d; pub const asciicircum = 0x005e; pub const underscore = 0x005f; pub const grave = 0x0060; pub const quoteleft = 0x0060; pub const a = 0x0061; pub const b = 0x0062; pub const c = 0x0063; pub const d = 0x0064; pub const e = 0x0065; pub const f = 0x0066; pub const g = 0x0067; pub const h = 0x0068; pub const i = 0x0069; pub const j = 0x006a; pub const k = 0x006b; pub const l = 0x006c; pub const m = 0x006d; pub const n = 0x006e; pub const o = 0x006f; pub const p = 0x0070; pub const q = 0x0071; pub const r = 0x0072; pub const s = 0x0073; pub const t = 0x0074; pub const u = 0x0075; pub const v = 0x0076; pub const w = 0x0077; pub const x = 0x0078; pub const y = 0x0079; pub const z = 0x007a; pub const braceleft = 0x007b; pub const bar = 0x007c; pub const braceright = 0x007d; pub const asciitilde = 0x007e; pub const nobreakspace = 0x00a0; pub const exclamdown = 0x00a1; pub const cent = 0x00a2; pub const sterling = 0x00a3; pub const currency = 0x00a4; pub const yen = 0x00a5; pub const brokenbar = 0x00a6; pub const section = 0x00a7; pub const diaeresis = 0x00a8; pub const copyright = 0x00a9; pub const ordfeminine = 0x00aa; pub const guillemotleft = 0x00ab; pub const notsign = 0x00ac; pub const hyphen = 0x00ad; pub const registered = 0x00ae; pub const macron = 0x00af; pub const degree = 0x00b0; pub const plusminus = 0x00b1; pub const twosuperior = 0x00b2; pub const threesuperior = 0x00b3; pub const acute = 0x00b4; pub const mu = 0x00b5; pub const paragraph = 0x00b6; pub const periodcentered = 0x00b7; pub const cedilla = 0x00b8; pub const onesuperior = 0x00b9; pub const masculine = 0x00ba; pub const guillemotright = 0x00bb; pub const onequarter = 0x00bc; pub const onehalf = 0x00bd; pub const threequarters = 0x00be; pub const questiondown = 0x00bf; pub const Agrave = 0x00c0; pub const Aacute = 0x00c1; pub const Acircumflex = 0x00c2; pub const Atilde = 0x00c3; pub const Adiaeresis = 0x00c4; pub const Aring = 0x00c5; pub const AE = 0x00c6; pub const Ccedilla = 0x00c7; pub const Egrave = 0x00c8; pub const Eacute = 0x00c9; pub const Ecircumflex = 0x00ca; pub const Ediaeresis = 0x00cb; pub const Igrave = 0x00cc; pub const Iacute = 0x00cd; pub const Icircumflex = 0x00ce; pub const Idiaeresis = 0x00cf; pub const ETH = 0x00d0; pub const Eth = 0x00d0; pub const Ntilde = 0x00d1; pub const Ograve = 0x00d2; pub const Oacute = 0x00d3; pub const Ocircumflex = 0x00d4; pub const Otilde = 0x00d5; pub const Odiaeresis = 0x00d6; pub const multiply = 0x00d7; pub const Oslash = 0x00d8; pub const Ooblique = 0x00d8; pub const Ugrave = 0x00d9; pub const Uacute = 0x00da; pub const Ucircumflex = 0x00db; pub const Udiaeresis = 0x00dc; pub const Yacute = 0x00dd; pub const THORN = 0x00de; pub const Thorn = 0x00de; pub const ssharp = 0x00df; pub const agrave = 0x00e0; pub const aacute = 0x00e1; pub const acircumflex = 0x00e2; pub const atilde = 0x00e3; pub const adiaeresis = 0x00e4; pub const aring = 0x00e5; pub const ae = 0x00e6; pub const ccedilla = 0x00e7; pub const egrave = 0x00e8; pub const eacute = 0x00e9; pub const ecircumflex = 0x00ea; pub const ediaeresis = 0x00eb; pub const igrave = 0x00ec; pub const iacute = 0x00ed; pub const icircumflex = 0x00ee; pub const idiaeresis = 0x00ef; pub const eth = 0x00f0; pub const ntilde = 0x00f1; pub const ograve = 0x00f2; pub const oacute = 0x00f3; pub const ocircumflex = 0x00f4; pub const otilde = 0x00f5; pub const odiaeresis = 0x00f6; pub const division = 0x00f7; pub const oslash = 0x00f8; pub const ooblique = 0x00f8; pub const ugrave = 0x00f9; pub const uacute = 0x00fa; pub const ucircumflex = 0x00fb; pub const udiaeresis = 0x00fc; pub const yacute = 0x00fd; pub const thorn = 0x00fe; pub const ydiaeresis = 0x00ff; pub const Aogonek = 0x01a1; pub const breve = 0x01a2; pub const Lstroke = 0x01a3; pub const Lcaron = 0x01a5; pub const Sacute = 0x01a6; pub const Scaron = 0x01a9; pub const Scedilla = 0x01aa; pub const Tcaron = 0x01ab; pub const Zacute = 0x01ac; pub const Zcaron = 0x01ae; pub const Zabovedot = 0x01af; pub const aogonek = 0x01b1; pub const ogonek = 0x01b2; pub const lstroke = 0x01b3; pub const lcaron = 0x01b5; pub const sacute = 0x01b6; pub const caron = 0x01b7; pub const scaron = 0x01b9; pub const scedilla = 0x01ba; pub const tcaron = 0x01bb; pub const zacute = 0x01bc; pub const doubleacute = 0x01bd; pub const zcaron = 0x01be; pub const zabovedot = 0x01bf; pub const Racute = 0x01c0; pub const Abreve = 0x01c3; pub const Lacute = 0x01c5; pub const Cacute = 0x01c6; pub const Ccaron = 0x01c8; pub const Eogonek = 0x01ca; pub const Ecaron = 0x01cc; pub const Dcaron = 0x01cf; pub const Dstroke = 0x01d0; pub const Nacute = 0x01d1; pub const Ncaron = 0x01d2; pub const Odoubleacute = 0x01d5; pub const Rcaron = 0x01d8; pub const Uring = 0x01d9; pub const Udoubleacute = 0x01db; pub const Tcedilla = 0x01de; pub const racute = 0x01e0; pub const abreve = 0x01e3; pub const lacute = 0x01e5; pub const cacute = 0x01e6; pub const ccaron = 0x01e8; pub const eogonek = 0x01ea; pub const ecaron = 0x01ec; pub const dcaron = 0x01ef; pub const dstroke = 0x01f0; pub const nacute = 0x01f1; pub const ncaron = 0x01f2; pub const odoubleacute = 0x01f5; pub const rcaron = 0x01f8; pub const uring = 0x01f9; pub const udoubleacute = 0x01fb; pub const tcedilla = 0x01fe; pub const abovedot = 0x01ff; pub const Hstroke = 0x02a1; pub const Hcircumflex = 0x02a6; pub const Iabovedot = 0x02a9; pub const Gbreve = 0x02ab; pub const Jcircumflex = 0x02ac; pub const hstroke = 0x02b1; pub const hcircumflex = 0x02b6; pub const idotless = 0x02b9; pub const gbreve = 0x02bb; pub const jcircumflex = 0x02bc; pub const Cabovedot = 0x02c5; pub const Ccircumflex = 0x02c6; pub const Gabovedot = 0x02d5; pub const Gcircumflex = 0x02d8; pub const Ubreve = 0x02dd; pub const Scircumflex = 0x02de; pub const cabovedot = 0x02e5; pub const ccircumflex = 0x02e6; pub const gabovedot = 0x02f5; pub const gcircumflex = 0x02f8; pub const ubreve = 0x02fd; pub const scircumflex = 0x02fe; pub const kra = 0x03a2; pub const kappa = 0x03a2; pub const Rcedilla = 0x03a3; pub const Itilde = 0x03a5; pub const Lcedilla = 0x03a6; pub const Emacron = 0x03aa; pub const Gcedilla = 0x03ab; pub const Tslash = 0x03ac; pub const rcedilla = 0x03b3; pub const itilde = 0x03b5; pub const lcedilla = 0x03b6; pub const emacron = 0x03ba; pub const gcedilla = 0x03bb; pub const tslash = 0x03bc; pub const ENG = 0x03bd; pub const eng = 0x03bf; pub const Amacron = 0x03c0; pub const Iogonek = 0x03c7; pub const Eabovedot = 0x03cc; pub const Imacron = 0x03cf; pub const Ncedilla = 0x03d1; pub const Omacron = 0x03d2; pub const Kcedilla = 0x03d3; pub const Uogonek = 0x03d9; pub const Utilde = 0x03dd; pub const Umacron = 0x03de; pub const amacron = 0x03e0; pub const iogonek = 0x03e7; pub const eabovedot = 0x03ec; pub const imacron = 0x03ef; pub const ncedilla = 0x03f1; pub const omacron = 0x03f2; pub const kcedilla = 0x03f3; pub const uogonek = 0x03f9; pub const utilde = 0x03fd; pub const umacron = 0x03fe; pub const Wcircumflex = 0x1000174; pub const wcircumflex = 0x1000175; pub const Ycircumflex = 0x1000176; pub const ycircumflex = 0x1000177; pub const Babovedot = 0x1001e02; pub const babovedot = 0x1001e03; pub const Dabovedot = 0x1001e0a; pub const dabovedot = 0x1001e0b; pub const Fabovedot = 0x1001e1e; pub const fabovedot = 0x1001e1f; pub const Mabovedot = 0x1001e40; pub const mabovedot = 0x1001e41; pub const Pabovedot = 0x1001e56; pub const pabovedot = 0x1001e57; pub const Sabovedot = 0x1001e60; pub const sabovedot = 0x1001e61; pub const Tabovedot = 0x1001e6a; pub const tabovedot = 0x1001e6b; pub const Wgrave = 0x1001e80; pub const wgrave = 0x1001e81; pub const Wacute = 0x1001e82; pub const wacute = 0x1001e83; pub const Wdiaeresis = 0x1001e84; pub const wdiaeresis = 0x1001e85; pub const Ygrave = 0x1001ef2; pub const ygrave = 0x1001ef3; pub const OE = 0x13bc; pub const oe = 0x13bd; pub const Ydiaeresis = 0x13be; pub const overline = 0x047e; pub const kana_fullstop = 0x04a1; pub const kana_openingbracket = 0x04a2; pub const kana_closingbracket = 0x04a3; pub const kana_comma = 0x04a4; pub const kana_conjunctive = 0x04a5; pub const kana_middledot = 0x04a5; pub const kana_WO = 0x04a6; pub const kana_a = 0x04a7; pub const kana_i = 0x04a8; pub const kana_u = 0x04a9; pub const kana_e = 0x04aa; pub const kana_o = 0x04ab; pub const kana_ya = 0x04ac; pub const kana_yu = 0x04ad; pub const kana_yo = 0x04ae; pub const kana_tsu = 0x04af; pub const kana_tu = 0x04af; pub const prolongedsound = 0x04b0; pub const kana_A = 0x04b1; pub const kana_I = 0x04b2; pub const kana_U = 0x04b3; pub const kana_E = 0x04b4; pub const kana_O = 0x04b5; pub const kana_KA = 0x04b6; pub const kana_KI = 0x04b7; pub const kana_KU = 0x04b8; pub const kana_KE = 0x04b9; pub const kana_KO = 0x04ba; pub const kana_SA = 0x04bb; pub const kana_SHI = 0x04bc; pub const kana_SU = 0x04bd; pub const kana_SE = 0x04be; pub const kana_SO = 0x04bf; pub const kana_TA = 0x04c0; pub const kana_CHI = 0x04c1; pub const kana_TI = 0x04c1; pub const kana_TSU = 0x04c2; pub const kana_TU = 0x04c2; pub const kana_TE = 0x04c3; pub const kana_TO = 0x04c4; pub const kana_NA = 0x04c5; pub const kana_NI = 0x04c6; pub const kana_NU = 0x04c7; pub const kana_NE = 0x04c8; pub const kana_NO = 0x04c9; pub const kana_HA = 0x04ca; pub const kana_HI = 0x04cb; pub const kana_FU = 0x04cc; pub const kana_HU = 0x04cc; pub const kana_HE = 0x04cd; pub const kana_HO = 0x04ce; pub const kana_MA = 0x04cf; pub const kana_MI = 0x04d0; pub const kana_MU = 0x04d1; pub const kana_ME = 0x04d2; pub const kana_MO = 0x04d3; pub const kana_YA = 0x04d4; pub const kana_YU = 0x04d5; pub const kana_YO = 0x04d6; pub const kana_RA = 0x04d7; pub const kana_RI = 0x04d8; pub const kana_RU = 0x04d9; pub const kana_RE = 0x04da; pub const kana_RO = 0x04db; pub const kana_WA = 0x04dc; pub const kana_N = 0x04dd; pub const voicedsound = 0x04de; pub const semivoicedsound = 0x04df; pub const kana_switch = 0xff7e; pub const Farsi_0 = 0x10006f0; pub const Farsi_1 = 0x10006f1; pub const Farsi_2 = 0x10006f2; pub const Farsi_3 = 0x10006f3; pub const Farsi_4 = 0x10006f4; pub const Farsi_5 = 0x10006f5; pub const Farsi_6 = 0x10006f6; pub const Farsi_7 = 0x10006f7; pub const Farsi_8 = 0x10006f8; pub const Farsi_9 = 0x10006f9; pub const Arabic_percent = 0x100066a; pub const Arabic_superscript_alef = 0x1000670; pub const Arabic_tteh = 0x1000679; pub const Arabic_peh = 0x100067e; pub const Arabic_tcheh = 0x1000686; pub const Arabic_ddal = 0x1000688; pub const Arabic_rreh = 0x1000691; pub const Arabic_comma = 0x05ac; pub const Arabic_fullstop = 0x10006d4; pub const Arabic_0 = 0x1000660; pub const Arabic_1 = 0x1000661; pub const Arabic_2 = 0x1000662; pub const Arabic_3 = 0x1000663; pub const Arabic_4 = 0x1000664; pub const Arabic_5 = 0x1000665; pub const Arabic_6 = 0x1000666; pub const Arabic_7 = 0x1000667; pub const Arabic_8 = 0x1000668; pub const Arabic_9 = 0x1000669; pub const Arabic_semicolon = 0x05bb; pub const Arabic_question_mark = 0x05bf; pub const Arabic_hamza = 0x05c1; pub const Arabic_maddaonalef = 0x05c2; pub const Arabic_hamzaonalef = 0x05c3; pub const Arabic_hamzaonwaw = 0x05c4; pub const Arabic_hamzaunderalef = 0x05c5; pub const Arabic_hamzaonyeh = 0x05c6; pub const Arabic_alef = 0x05c7; pub const Arabic_beh = 0x05c8; pub const Arabic_tehmarbuta = 0x05c9; pub const Arabic_teh = 0x05ca; pub const Arabic_theh = 0x05cb; pub const Arabic_jeem = 0x05cc; pub const Arabic_hah = 0x05cd; pub const Arabic_khah = 0x05ce; pub const Arabic_dal = 0x05cf; pub const Arabic_thal = 0x05d0; pub const Arabic_ra = 0x05d1; pub const Arabic_zain = 0x05d2; pub const Arabic_seen = 0x05d3; pub const Arabic_sheen = 0x05d4; pub const Arabic_sad = 0x05d5; pub const Arabic_dad = 0x05d6; pub const Arabic_tah = 0x05d7; pub const Arabic_zah = 0x05d8; pub const Arabic_ain = 0x05d9; pub const Arabic_ghain = 0x05da; pub const Arabic_tatweel = 0x05e0; pub const Arabic_feh = 0x05e1; pub const Arabic_qaf = 0x05e2; pub const Arabic_kaf = 0x05e3; pub const Arabic_lam = 0x05e4; pub const Arabic_meem = 0x05e5; pub const Arabic_noon = 0x05e6; pub const Arabic_ha = 0x05e7; pub const Arabic_heh = 0x05e7; pub const Arabic_waw = 0x05e8; pub const Arabic_alefmaksura = 0x05e9; pub const Arabic_yeh = 0x05ea; pub const Arabic_fathatan = 0x05eb; pub const Arabic_dammatan = 0x05ec; pub const Arabic_kasratan = 0x05ed; pub const Arabic_fatha = 0x05ee; pub const Arabic_damma = 0x05ef; pub const Arabic_kasra = 0x05f0; pub const Arabic_shadda = 0x05f1; pub const Arabic_sukun = 0x05f2; pub const Arabic_madda_above = 0x1000653; pub const Arabic_hamza_above = 0x1000654; pub const Arabic_hamza_below = 0x1000655; pub const Arabic_jeh = 0x1000698; pub const Arabic_veh = 0x10006a4; pub const Arabic_keheh = 0x10006a9; pub const Arabic_gaf = 0x10006af; pub const Arabic_noon_ghunna = 0x10006ba; pub const Arabic_heh_doachashmee = 0x10006be; pub const Farsi_yeh = 0x10006cc; pub const Arabic_farsi_yeh = 0x10006cc; pub const Arabic_yeh_baree = 0x10006d2; pub const Arabic_heh_goal = 0x10006c1; pub const Arabic_switch = 0xff7e; pub const Cyrillic_GHE_bar = 0x1000492; pub const Cyrillic_ghe_bar = 0x1000493; pub const Cyrillic_ZHE_descender = 0x1000496; pub const Cyrillic_zhe_descender = 0x1000497; pub const Cyrillic_KA_descender = 0x100049a; pub const Cyrillic_ka_descender = 0x100049b; pub const Cyrillic_KA_vertstroke = 0x100049c; pub const Cyrillic_ka_vertstroke = 0x100049d; pub const Cyrillic_EN_descender = 0x10004a2; pub const Cyrillic_en_descender = 0x10004a3; pub const Cyrillic_U_straight = 0x10004ae; pub const Cyrillic_u_straight = 0x10004af; pub const Cyrillic_U_straight_bar = 0x10004b0; pub const Cyrillic_u_straight_bar = 0x10004b1; pub const Cyrillic_HA_descender = 0x10004b2; pub const Cyrillic_ha_descender = 0x10004b3; pub const Cyrillic_CHE_descender = 0x10004b6; pub const Cyrillic_che_descender = 0x10004b7; pub const Cyrillic_CHE_vertstroke = 0x10004b8; pub const Cyrillic_che_vertstroke = 0x10004b9; pub const Cyrillic_SHHA = 0x10004ba; pub const Cyrillic_shha = 0x10004bb; pub const Cyrillic_SCHWA = 0x10004d8; pub const Cyrillic_schwa = 0x10004d9; pub const Cyrillic_I_macron = 0x10004e2; pub const Cyrillic_i_macron = 0x10004e3; pub const Cyrillic_O_bar = 0x10004e8; pub const Cyrillic_o_bar = 0x10004e9; pub const Cyrillic_U_macron = 0x10004ee; pub const Cyrillic_u_macron = 0x10004ef; pub const Serbian_dje = 0x06a1; pub const Macedonia_gje = 0x06a2; pub const Cyrillic_io = 0x06a3; pub const Ukrainian_ie = 0x06a4; pub const Ukranian_je = 0x06a4; pub const Macedonia_dse = 0x06a5; pub const Ukrainian_i = 0x06a6; pub const Ukranian_i = 0x06a6; pub const Ukrainian_yi = 0x06a7; pub const Ukranian_yi = 0x06a7; pub const Cyrillic_je = 0x06a8; pub const Serbian_je = 0x06a8; pub const Cyrillic_lje = 0x06a9; pub const Serbian_lje = 0x06a9; pub const Cyrillic_nje = 0x06aa; pub const Serbian_nje = 0x06aa; pub const Serbian_tshe = 0x06ab; pub const Macedonia_kje = 0x06ac; pub const Ukrainian_ghe_with_upturn = 0x06ad; pub const Byelorussian_shortu = 0x06ae; pub const Cyrillic_dzhe = 0x06af; pub const Serbian_dze = 0x06af; pub const numerosign = 0x06b0; pub const Serbian_DJE = 0x06b1; pub const Macedonia_GJE = 0x06b2; pub const Cyrillic_IO = 0x06b3; pub const Ukrainian_IE = 0x06b4; pub const Ukranian_JE = 0x06b4; pub const Macedonia_DSE = 0x06b5; pub const Ukrainian_I = 0x06b6; pub const Ukranian_I = 0x06b6; pub const Ukrainian_YI = 0x06b7; pub const Ukranian_YI = 0x06b7; pub const Cyrillic_JE = 0x06b8; pub const Serbian_JE = 0x06b8; pub const Cyrillic_LJE = 0x06b9; pub const Serbian_LJE = 0x06b9; pub const Cyrillic_NJE = 0x06ba; pub const Serbian_NJE = 0x06ba; pub const Serbian_TSHE = 0x06bb; pub const Macedonia_KJE = 0x06bc; pub const Ukrainian_GHE_WITH_UPTURN = 0x06bd; pub const Byelorussian_SHORTU = 0x06be; pub const Cyrillic_DZHE = 0x06bf; pub const Serbian_DZE = 0x06bf; pub const Cyrillic_yu = 0x06c0; pub const Cyrillic_a = 0x06c1; pub const Cyrillic_be = 0x06c2; pub const Cyrillic_tse = 0x06c3; pub const Cyrillic_de = 0x06c4; pub const Cyrillic_ie = 0x06c5; pub const Cyrillic_ef = 0x06c6; pub const Cyrillic_ghe = 0x06c7; pub const Cyrillic_ha = 0x06c8; pub const Cyrillic_i = 0x06c9; pub const Cyrillic_shorti = 0x06ca; pub const Cyrillic_ka = 0x06cb; pub const Cyrillic_el = 0x06cc; pub const Cyrillic_em = 0x06cd; pub const Cyrillic_en = 0x06ce; pub const Cyrillic_o = 0x06cf; pub const Cyrillic_pe = 0x06d0; pub const Cyrillic_ya = 0x06d1; pub const Cyrillic_er = 0x06d2; pub const Cyrillic_es = 0x06d3; pub const Cyrillic_te = 0x06d4; pub const Cyrillic_u = 0x06d5; pub const Cyrillic_zhe = 0x06d6; pub const Cyrillic_ve = 0x06d7; pub const Cyrillic_softsign = 0x06d8; pub const Cyrillic_yeru = 0x06d9; pub const Cyrillic_ze = 0x06da; pub const Cyrillic_sha = 0x06db; pub const Cyrillic_e = 0x06dc; pub const Cyrillic_shcha = 0x06dd; pub const Cyrillic_che = 0x06de; pub const Cyrillic_hardsign = 0x06df; pub const Cyrillic_YU = 0x06e0; pub const Cyrillic_A = 0x06e1; pub const Cyrillic_BE = 0x06e2; pub const Cyrillic_TSE = 0x06e3; pub const Cyrillic_DE = 0x06e4; pub const Cyrillic_IE = 0x06e5; pub const Cyrillic_EF = 0x06e6; pub const Cyrillic_GHE = 0x06e7; pub const Cyrillic_HA = 0x06e8; pub const Cyrillic_I = 0x06e9; pub const Cyrillic_SHORTI = 0x06ea; pub const Cyrillic_KA = 0x06eb; pub const Cyrillic_EL = 0x06ec; pub const Cyrillic_EM = 0x06ed; pub const Cyrillic_EN = 0x06ee; pub const Cyrillic_O = 0x06ef; pub const Cyrillic_PE = 0x06f0; pub const Cyrillic_YA = 0x06f1; pub const Cyrillic_ER = 0x06f2; pub const Cyrillic_ES = 0x06f3; pub const Cyrillic_TE = 0x06f4; pub const Cyrillic_U = 0x06f5; pub const Cyrillic_ZHE = 0x06f6; pub const Cyrillic_VE = 0x06f7; pub const Cyrillic_SOFTSIGN = 0x06f8; pub const Cyrillic_YERU = 0x06f9; pub const Cyrillic_ZE = 0x06fa; pub const Cyrillic_SHA = 0x06fb; pub const Cyrillic_E = 0x06fc; pub const Cyrillic_SHCHA = 0x06fd; pub const Cyrillic_CHE = 0x06fe; pub const Cyrillic_HARDSIGN = 0x06ff; pub const Greek_ALPHAaccent = 0x07a1; pub const Greek_EPSILONaccent = 0x07a2; pub const Greek_ETAaccent = 0x07a3; pub const Greek_IOTAaccent = 0x07a4; pub const Greek_IOTAdieresis = 0x07a5; pub const Greek_IOTAdiaeresis = 0x07a5; pub const Greek_OMICRONaccent = 0x07a7; pub const Greek_UPSILONaccent = 0x07a8; pub const Greek_UPSILONdieresis = 0x07a9; pub const Greek_OMEGAaccent = 0x07ab; pub const Greek_accentdieresis = 0x07ae; pub const Greek_horizbar = 0x07af; pub const Greek_alphaaccent = 0x07b1; pub const Greek_epsilonaccent = 0x07b2; pub const Greek_etaaccent = 0x07b3; pub const Greek_iotaaccent = 0x07b4; pub const Greek_iotadieresis = 0x07b5; pub const Greek_iotaaccentdieresis = 0x07b6; pub const Greek_omicronaccent = 0x07b7; pub const Greek_upsilonaccent = 0x07b8; pub const Greek_upsilondieresis = 0x07b9; pub const Greek_upsilonaccentdieresis = 0x07ba; pub const Greek_omegaaccent = 0x07bb; pub const Greek_ALPHA = 0x07c1; pub const Greek_BETA = 0x07c2; pub const Greek_GAMMA = 0x07c3; pub const Greek_DELTA = 0x07c4; pub const Greek_EPSILON = 0x07c5; pub const Greek_ZETA = 0x07c6; pub const Greek_ETA = 0x07c7; pub const Greek_THETA = 0x07c8; pub const Greek_IOTA = 0x07c9; pub const Greek_KAPPA = 0x07ca; pub const Greek_LAMDA = 0x07cb; pub const Greek_LAMBDA = 0x07cb; pub const Greek_MU = 0x07cc; pub const Greek_NU = 0x07cd; pub const Greek_XI = 0x07ce; pub const Greek_OMICRON = 0x07cf; pub const Greek_PI = 0x07d0; pub const Greek_RHO = 0x07d1; pub const Greek_SIGMA = 0x07d2; pub const Greek_TAU = 0x07d4; pub const Greek_UPSILON = 0x07d5; pub const Greek_PHI = 0x07d6; pub const Greek_CHI = 0x07d7; pub const Greek_PSI = 0x07d8; pub const Greek_OMEGA = 0x07d9; pub const Greek_alpha = 0x07e1; pub const Greek_beta = 0x07e2; pub const Greek_gamma = 0x07e3; pub const Greek_delta = 0x07e4; pub const Greek_epsilon = 0x07e5; pub const Greek_zeta = 0x07e6; pub const Greek_eta = 0x07e7; pub const Greek_theta = 0x07e8; pub const Greek_iota = 0x07e9; pub const Greek_kappa = 0x07ea; pub const Greek_lamda = 0x07eb; pub const Greek_lambda = 0x07eb; pub const Greek_mu = 0x07ec; pub const Greek_nu = 0x07ed; pub const Greek_xi = 0x07ee; pub const Greek_omicron = 0x07ef; pub const Greek_pi = 0x07f0; pub const Greek_rho = 0x07f1; pub const Greek_sigma = 0x07f2; pub const Greek_finalsmallsigma = 0x07f3; pub const Greek_tau = 0x07f4; pub const Greek_upsilon = 0x07f5; pub const Greek_phi = 0x07f6; pub const Greek_chi = 0x07f7; pub const Greek_psi = 0x07f8; pub const Greek_omega = 0x07f9; pub const Greek_switch = 0xff7e; pub const leftradical = 0x08a1; pub const topleftradical = 0x08a2; pub const horizconnector = 0x08a3; pub const topintegral = 0x08a4; pub const botintegral = 0x08a5; pub const vertconnector = 0x08a6; pub const topleftsqbracket = 0x08a7; pub const botleftsqbracket = 0x08a8; pub const toprightsqbracket = 0x08a9; pub const botrightsqbracket = 0x08aa; pub const topleftparens = 0x08ab; pub const botleftparens = 0x08ac; pub const toprightparens = 0x08ad; pub const botrightparens = 0x08ae; pub const leftmiddlecurlybrace = 0x08af; pub const rightmiddlecurlybrace = 0x08b0; pub const topleftsummation = 0x08b1; pub const botleftsummation = 0x08b2; pub const topvertsummationconnector = 0x08b3; pub const botvertsummationconnector = 0x08b4; pub const toprightsummation = 0x08b5; pub const botrightsummation = 0x08b6; pub const rightmiddlesummation = 0x08b7; pub const lessthanequal = 0x08bc; pub const notequal = 0x08bd; pub const greaterthanequal = 0x08be; pub const integral = 0x08bf; pub const therefore = 0x08c0; pub const variation = 0x08c1; pub const infinity = 0x08c2; pub const nabla = 0x08c5; pub const approximate = 0x08c8; pub const similarequal = 0x08c9; pub const ifonlyif = 0x08cd; pub const implies = 0x08ce; pub const identical = 0x08cf; pub const radical = 0x08d6; pub const includedin = 0x08da; pub const includes = 0x08db; pub const intersection = 0x08dc; pub const @"union" = 0x08dd; pub const logicaland = 0x08de; pub const logicalor = 0x08df; pub const partialderivative = 0x08ef; pub const function = 0x08f6; pub const leftarrow = 0x08fb; pub const uparrow = 0x08fc; pub const rightarrow = 0x08fd; pub const downarrow = 0x08fe; pub const blank = 0x09df; pub const soliddiamond = 0x09e0; pub const checkerboard = 0x09e1; pub const ht = 0x09e2; pub const ff = 0x09e3; pub const cr = 0x09e4; pub const lf = 0x09e5; pub const nl = 0x09e8; pub const vt = 0x09e9; pub const lowrightcorner = 0x09ea; pub const uprightcorner = 0x09eb; pub const upleftcorner = 0x09ec; pub const lowleftcorner = 0x09ed; pub const crossinglines = 0x09ee; pub const horizlinescan1 = 0x09ef; pub const horizlinescan3 = 0x09f0; pub const horizlinescan5 = 0x09f1; pub const horizlinescan7 = 0x09f2; pub const horizlinescan9 = 0x09f3; pub const leftt = 0x09f4; pub const rightt = 0x09f5; pub const bott = 0x09f6; pub const topt = 0x09f7; pub const vertbar = 0x09f8; pub const emspace = 0x0aa1; pub const enspace = 0x0aa2; pub const em3space = 0x0aa3; pub const em4space = 0x0aa4; pub const digitspace = 0x0aa5; pub const punctspace = 0x0aa6; pub const thinspace = 0x0aa7; pub const hairspace = 0x0aa8; pub const emdash = 0x0aa9; pub const endash = 0x0aaa; pub const signifblank = 0x0aac; pub const ellipsis = 0x0aae; pub const doubbaselinedot = 0x0aaf; pub const onethird = 0x0ab0; pub const twothirds = 0x0ab1; pub const onefifth = 0x0ab2; pub const twofifths = 0x0ab3; pub const threefifths = 0x0ab4; pub const fourfifths = 0x0ab5; pub const onesixth = 0x0ab6; pub const fivesixths = 0x0ab7; pub const careof = 0x0ab8; pub const figdash = 0x0abb; pub const leftanglebracket = 0x0abc; pub const decimalpoint = 0x0abd; pub const rightanglebracket = 0x0abe; pub const marker = 0x0abf; pub const oneeighth = 0x0ac3; pub const threeeighths = 0x0ac4; pub const fiveeighths = 0x0ac5; pub const seveneighths = 0x0ac6; pub const trademark = 0x0ac9; pub const signaturemark = 0x0aca; pub const trademarkincircle = 0x0acb; pub const leftopentriangle = 0x0acc; pub const rightopentriangle = 0x0acd; pub const emopencircle = 0x0ace; pub const emopenrectangle = 0x0acf; pub const leftsinglequotemark = 0x0ad0; pub const rightsinglequotemark = 0x0ad1; pub const leftdoublequotemark = 0x0ad2; pub const rightdoublequotemark = 0x0ad3; pub const prescription = 0x0ad4; pub const permille = 0x0ad5; pub const minutes = 0x0ad6; pub const seconds = 0x0ad7; pub const latincross = 0x0ad9; pub const hexagram = 0x0ada; pub const filledrectbullet = 0x0adb; pub const filledlefttribullet = 0x0adc; pub const filledrighttribullet = 0x0add; pub const emfilledcircle = 0x0ade; pub const emfilledrect = 0x0adf; pub const enopencircbullet = 0x0ae0; pub const enopensquarebullet = 0x0ae1; pub const openrectbullet = 0x0ae2; pub const opentribulletup = 0x0ae3; pub const opentribulletdown = 0x0ae4; pub const openstar = 0x0ae5; pub const enfilledcircbullet = 0x0ae6; pub const enfilledsqbullet = 0x0ae7; pub const filledtribulletup = 0x0ae8; pub const filledtribulletdown = 0x0ae9; pub const leftpointer = 0x0aea; pub const rightpointer = 0x0aeb; pub const club = 0x0aec; pub const diamond = 0x0aed; pub const heart = 0x0aee; pub const maltesecross = 0x0af0; pub const dagger = 0x0af1; pub const doubledagger = 0x0af2; pub const checkmark = 0x0af3; pub const ballotcross = 0x0af4; pub const musicalsharp = 0x0af5; pub const musicalflat = 0x0af6; pub const malesymbol = 0x0af7; pub const femalesymbol = 0x0af8; pub const telephone = 0x0af9; pub const telephonerecorder = 0x0afa; pub const phonographcopyright = 0x0afb; pub const caret = 0x0afc; pub const singlelowquotemark = 0x0afd; pub const doublelowquotemark = 0x0afe; pub const cursor = 0x0aff; pub const leftcaret = 0x0ba3; pub const rightcaret = 0x0ba6; pub const downcaret = 0x0ba8; pub const upcaret = 0x0ba9; pub const overbar = 0x0bc0; pub const downtack = 0x0bc2; pub const upshoe = 0x0bc3; pub const downstile = 0x0bc4; pub const underbar = 0x0bc6; pub const jot = 0x0bca; pub const quad = 0x0bcc; pub const uptack = 0x0bce; pub const circle = 0x0bcf; pub const upstile = 0x0bd3; pub const downshoe = 0x0bd6; pub const rightshoe = 0x0bd8; pub const leftshoe = 0x0bda; pub const lefttack = 0x0bdc; pub const righttack = 0x0bfc; pub const hebrew_doublelowline = 0x0cdf; pub const hebrew_aleph = 0x0ce0; pub const hebrew_bet = 0x0ce1; pub const hebrew_beth = 0x0ce1; pub const hebrew_gimel = 0x0ce2; pub const hebrew_gimmel = 0x0ce2; pub const hebrew_dalet = 0x0ce3; pub const hebrew_daleth = 0x0ce3; pub const hebrew_he = 0x0ce4; pub const hebrew_waw = 0x0ce5; pub const hebrew_zain = 0x0ce6; pub const hebrew_zayin = 0x0ce6; pub const hebrew_chet = 0x0ce7; pub const hebrew_het = 0x0ce7; pub const hebrew_tet = 0x0ce8; pub const hebrew_teth = 0x0ce8; pub const hebrew_yod = 0x0ce9; pub const hebrew_finalkaph = 0x0cea; pub const hebrew_kaph = 0x0ceb; pub const hebrew_lamed = 0x0cec; pub const hebrew_finalmem = 0x0ced; pub const hebrew_mem = 0x0cee; pub const hebrew_finalnun = 0x0cef; pub const hebrew_nun = 0x0cf0; pub const hebrew_samech = 0x0cf1; pub const hebrew_samekh = 0x0cf1; pub const hebrew_ayin = 0x0cf2; pub const hebrew_finalpe = 0x0cf3; pub const hebrew_pe = 0x0cf4; pub const hebrew_finalzade = 0x0cf5; pub const hebrew_finalzadi = 0x0cf5; pub const hebrew_zade = 0x0cf6; pub const hebrew_zadi = 0x0cf6; pub const hebrew_qoph = 0x0cf7; pub const hebrew_kuf = 0x0cf7; pub const hebrew_resh = 0x0cf8; pub const hebrew_shin = 0x0cf9; pub const hebrew_taw = 0x0cfa; pub const hebrew_taf = 0x0cfa; pub const Hebrew_switch = 0xff7e; pub const Thai_kokai = 0x0da1; pub const Thai_khokhai = 0x0da2; pub const Thai_khokhuat = 0x0da3; pub const Thai_khokhwai = 0x0da4; pub const Thai_khokhon = 0x0da5; pub const Thai_khorakhang = 0x0da6; pub const Thai_ngongu = 0x0da7; pub const Thai_chochan = 0x0da8; pub const Thai_choching = 0x0da9; pub const Thai_chochang = 0x0daa; pub const Thai_soso = 0x0dab; pub const Thai_chochoe = 0x0dac; pub const Thai_yoying = 0x0dad; pub const Thai_dochada = 0x0dae; pub const Thai_topatak = 0x0daf; pub const Thai_thothan = 0x0db0; pub const Thai_thonangmontho = 0x0db1; pub const Thai_thophuthao = 0x0db2; pub const Thai_nonen = 0x0db3; pub const Thai_dodek = 0x0db4; pub const Thai_totao = 0x0db5; pub const Thai_thothung = 0x0db6; pub const Thai_thothahan = 0x0db7; pub const Thai_thothong = 0x0db8; pub const Thai_nonu = 0x0db9; pub const Thai_bobaimai = 0x0dba; pub const Thai_popla = 0x0dbb; pub const Thai_phophung = 0x0dbc; pub const Thai_fofa = 0x0dbd; pub const Thai_phophan = 0x0dbe; pub const Thai_fofan = 0x0dbf; pub const Thai_phosamphao = 0x0dc0; pub const Thai_moma = 0x0dc1; pub const Thai_yoyak = 0x0dc2; pub const Thai_rorua = 0x0dc3; pub const Thai_ru = 0x0dc4; pub const Thai_loling = 0x0dc5; pub const Thai_lu = 0x0dc6; pub const Thai_wowaen = 0x0dc7; pub const Thai_sosala = 0x0dc8; pub const Thai_sorusi = 0x0dc9; pub const Thai_sosua = 0x0dca; pub const Thai_hohip = 0x0dcb; pub const Thai_lochula = 0x0dcc; pub const Thai_oang = 0x0dcd; pub const Thai_honokhuk = 0x0dce; pub const Thai_paiyannoi = 0x0dcf; pub const Thai_saraa = 0x0dd0; pub const Thai_maihanakat = 0x0dd1; pub const Thai_saraaa = 0x0dd2; pub const Thai_saraam = 0x0dd3; pub const Thai_sarai = 0x0dd4; pub const Thai_saraii = 0x0dd5; pub const Thai_saraue = 0x0dd6; pub const Thai_sarauee = 0x0dd7; pub const Thai_sarau = 0x0dd8; pub const Thai_sarauu = 0x0dd9; pub const Thai_phinthu = 0x0dda; pub const Thai_maihanakat_maitho = 0x0dde; pub const Thai_baht = 0x0ddf; pub const Thai_sarae = 0x0de0; pub const Thai_saraae = 0x0de1; pub const Thai_sarao = 0x0de2; pub const Thai_saraaimaimuan = 0x0de3; pub const Thai_saraaimaimalai = 0x0de4; pub const Thai_lakkhangyao = 0x0de5; pub const Thai_maiyamok = 0x0de6; pub const Thai_maitaikhu = 0x0de7; pub const Thai_maiek = 0x0de8; pub const Thai_maitho = 0x0de9; pub const Thai_maitri = 0x0dea; pub const Thai_maichattawa = 0x0deb; pub const Thai_thanthakhat = 0x0dec; pub const Thai_nikhahit = 0x0ded; pub const Thai_leksun = 0x0df0; pub const Thai_leknung = 0x0df1; pub const Thai_leksong = 0x0df2; pub const Thai_leksam = 0x0df3; pub const Thai_leksi = 0x0df4; pub const Thai_lekha = 0x0df5; pub const Thai_lekhok = 0x0df6; pub const Thai_lekchet = 0x0df7; pub const Thai_lekpaet = 0x0df8; pub const Thai_lekkao = 0x0df9; pub const Hangul = 0xff31; pub const Hangul_Start = 0xff32; pub const Hangul_End = 0xff33; pub const Hangul_Hanja = 0xff34; pub const Hangul_Jamo = 0xff35; pub const Hangul_Romaja = 0xff36; pub const Hangul_Codeinput = 0xff37; pub const Hangul_Jeonja = 0xff38; pub const Hangul_Banja = 0xff39; pub const Hangul_PreHanja = 0xff3a; pub const Hangul_PostHanja = 0xff3b; pub const Hangul_SingleCandidate = 0xff3c; pub const Hangul_MultipleCandidate = 0xff3d; pub const Hangul_PreviousCandidate = 0xff3e; pub const Hangul_Special = 0xff3f; pub const Hangul_switch = 0xff7e; pub const Hangul_Kiyeog = 0x0ea1; pub const Hangul_SsangKiyeog = 0x0ea2; pub const Hangul_KiyeogSios = 0x0ea3; pub const Hangul_Nieun = 0x0ea4; pub const Hangul_NieunJieuj = 0x0ea5; pub const Hangul_NieunHieuh = 0x0ea6; pub const Hangul_Dikeud = 0x0ea7; pub const Hangul_SsangDikeud = 0x0ea8; pub const Hangul_Rieul = 0x0ea9; pub const Hangul_RieulKiyeog = 0x0eaa; pub const Hangul_RieulMieum = 0x0eab; pub const Hangul_RieulPieub = 0x0eac; pub const Hangul_RieulSios = 0x0ead; pub const Hangul_RieulTieut = 0x0eae; pub const Hangul_RieulPhieuf = 0x0eaf; pub const Hangul_RieulHieuh = 0x0eb0; pub const Hangul_Mieum = 0x0eb1; pub const Hangul_Pieub = 0x0eb2; pub const Hangul_SsangPieub = 0x0eb3; pub const Hangul_PieubSios = 0x0eb4; pub const Hangul_Sios = 0x0eb5; pub const Hangul_SsangSios = 0x0eb6; pub const Hangul_Ieung = 0x0eb7; pub const Hangul_Jieuj = 0x0eb8; pub const Hangul_SsangJieuj = 0x0eb9; pub const Hangul_Cieuc = 0x0eba; pub const Hangul_Khieuq = 0x0ebb; pub const Hangul_Tieut = 0x0ebc; pub const Hangul_Phieuf = 0x0ebd; pub const Hangul_Hieuh = 0x0ebe; pub const Hangul_A = 0x0ebf; pub const Hangul_AE = 0x0ec0; pub const Hangul_YA = 0x0ec1; pub const Hangul_YAE = 0x0ec2; pub const Hangul_EO = 0x0ec3; pub const Hangul_E = 0x0ec4; pub const Hangul_YEO = 0x0ec5; pub const Hangul_YE = 0x0ec6; pub const Hangul_O = 0x0ec7; pub const Hangul_WA = 0x0ec8; pub const Hangul_WAE = 0x0ec9; pub const Hangul_OE = 0x0eca; pub const Hangul_YO = 0x0ecb; pub const Hangul_U = 0x0ecc; pub const Hangul_WEO = 0x0ecd; pub const Hangul_WE = 0x0ece; pub const Hangul_WI = 0x0ecf; pub const Hangul_YU = 0x0ed0; pub const Hangul_EU = 0x0ed1; pub const Hangul_YI = 0x0ed2; pub const Hangul_I = 0x0ed3; pub const Hangul_J_Kiyeog = 0x0ed4; pub const Hangul_J_SsangKiyeog = 0x0ed5; pub const Hangul_J_KiyeogSios = 0x0ed6; pub const Hangul_J_Nieun = 0x0ed7; pub const Hangul_J_NieunJieuj = 0x0ed8; pub const Hangul_J_NieunHieuh = 0x0ed9; pub const Hangul_J_Dikeud = 0x0eda; pub const Hangul_J_Rieul = 0x0edb; pub const Hangul_J_RieulKiyeog = 0x0edc; pub const Hangul_J_RieulMieum = 0x0edd; pub const Hangul_J_RieulPieub = 0x0ede; pub const Hangul_J_RieulSios = 0x0edf; pub const Hangul_J_RieulTieut = 0x0ee0; pub const Hangul_J_RieulPhieuf = 0x0ee1; pub const Hangul_J_RieulHieuh = 0x0ee2; pub const Hangul_J_Mieum = 0x0ee3; pub const Hangul_J_Pieub = 0x0ee4; pub const Hangul_J_PieubSios = 0x0ee5; pub const Hangul_J_Sios = 0x0ee6; pub const Hangul_J_SsangSios = 0x0ee7; pub const Hangul_J_Ieung = 0x0ee8; pub const Hangul_J_Jieuj = 0x0ee9; pub const Hangul_J_Cieuc = 0x0eea; pub const Hangul_J_Khieuq = 0x0eeb; pub const Hangul_J_Tieut = 0x0eec; pub const Hangul_J_Phieuf = 0x0eed; pub const Hangul_J_Hieuh = 0x0eee; pub const Hangul_RieulYeorinHieuh = 0x0eef; pub const Hangul_SunkyeongeumMieum = 0x0ef0; pub const Hangul_SunkyeongeumPieub = 0x0ef1; pub const Hangul_PanSios = 0x0ef2; pub const Hangul_KkogjiDalrinIeung = 0x0ef3; pub const Hangul_SunkyeongeumPhieuf = 0x0ef4; pub const Hangul_YeorinHieuh = 0x0ef5; pub const Hangul_AraeA = 0x0ef6; pub const Hangul_AraeAE = 0x0ef7; pub const Hangul_J_PanSios = 0x0ef8; pub const Hangul_J_KkogjiDalrinIeung = 0x0ef9; pub const Hangul_J_YeorinHieuh = 0x0efa; pub const Korean_Won = 0x0eff; pub const Armenian_ligature_ew = 0x1000587; pub const Armenian_full_stop = 0x1000589; pub const Armenian_verjaket = 0x1000589; pub const Armenian_separation_mark = 0x100055d; pub const Armenian_but = 0x100055d; pub const Armenian_hyphen = 0x100058a; pub const Armenian_yentamna = 0x100058a; pub const Armenian_exclam = 0x100055c; pub const Armenian_amanak = 0x100055c; pub const Armenian_accent = 0x100055b; pub const Armenian_shesht = 0x100055b; pub const Armenian_question = 0x100055e; pub const Armenian_paruyk = 0x100055e; pub const Armenian_AYB = 0x1000531; pub const Armenian_ayb = 0x1000561; pub const Armenian_BEN = 0x1000532; pub const Armenian_ben = 0x1000562; pub const Armenian_GIM = 0x1000533; pub const Armenian_gim = 0x1000563; pub const Armenian_DA = 0x1000534; pub const Armenian_da = 0x1000564; pub const Armenian_YECH = 0x1000535; pub const Armenian_yech = 0x1000565; pub const Armenian_ZA = 0x1000536; pub const Armenian_za = 0x1000566; pub const Armenian_E = 0x1000537; pub const Armenian_e = 0x1000567; pub const Armenian_AT = 0x1000538; pub const Armenian_at = 0x1000568; pub const Armenian_TO = 0x1000539; pub const Armenian_to = 0x1000569; pub const Armenian_ZHE = 0x100053a; pub const Armenian_zhe = 0x100056a; pub const Armenian_INI = 0x100053b; pub const Armenian_ini = 0x100056b; pub const Armenian_LYUN = 0x100053c; pub const Armenian_lyun = 0x100056c; pub const Armenian_KHE = 0x100053d; pub const Armenian_khe = 0x100056d; pub const Armenian_TSA = 0x100053e; pub const Armenian_tsa = 0x100056e; pub const Armenian_KEN = 0x100053f; pub const Armenian_ken = 0x100056f; pub const Armenian_HO = 0x1000540; pub const Armenian_ho = 0x1000570; pub const Armenian_DZA = 0x1000541; pub const Armenian_dza = 0x1000571; pub const Armenian_GHAT = 0x1000542; pub const Armenian_ghat = 0x1000572; pub const Armenian_TCHE = 0x1000543; pub const Armenian_tche = 0x1000573; pub const Armenian_MEN = 0x1000544; pub const Armenian_men = 0x1000574; pub const Armenian_HI = 0x1000545; pub const Armenian_hi = 0x1000575; pub const Armenian_NU = 0x1000546; pub const Armenian_nu = 0x1000576; pub const Armenian_SHA = 0x1000547; pub const Armenian_sha = 0x1000577; pub const Armenian_VO = 0x1000548; pub const Armenian_vo = 0x1000578; pub const Armenian_CHA = 0x1000549; pub const Armenian_cha = 0x1000579; pub const Armenian_PE = 0x100054a; pub const Armenian_pe = 0x100057a; pub const Armenian_JE = 0x100054b; pub const Armenian_je = 0x100057b; pub const Armenian_RA = 0x100054c; pub const Armenian_ra = 0x100057c; pub const Armenian_SE = 0x100054d; pub const Armenian_se = 0x100057d; pub const Armenian_VEV = 0x100054e; pub const Armenian_vev = 0x100057e; pub const Armenian_TYUN = 0x100054f; pub const Armenian_tyun = 0x100057f; pub const Armenian_RE = 0x1000550; pub const Armenian_re = 0x1000580; pub const Armenian_TSO = 0x1000551; pub const Armenian_tso = 0x1000581; pub const Armenian_VYUN = 0x1000552; pub const Armenian_vyun = 0x1000582; pub const Armenian_PYUR = 0x1000553; pub const Armenian_pyur = 0x1000583; pub const Armenian_KE = 0x1000554; pub const Armenian_ke = 0x1000584; pub const Armenian_O = 0x1000555; pub const Armenian_o = 0x1000585; pub const Armenian_FE = 0x1000556; pub const Armenian_fe = 0x1000586; pub const Armenian_apostrophe = 0x100055a; pub const Georgian_an = 0x10010d0; pub const Georgian_ban = 0x10010d1; pub const Georgian_gan = 0x10010d2; pub const Georgian_don = 0x10010d3; pub const Georgian_en = 0x10010d4; pub const Georgian_vin = 0x10010d5; pub const Georgian_zen = 0x10010d6; pub const Georgian_tan = 0x10010d7; pub const Georgian_in = 0x10010d8; pub const Georgian_kan = 0x10010d9; pub const Georgian_las = 0x10010da; pub const Georgian_man = 0x10010db; pub const Georgian_nar = 0x10010dc; pub const Georgian_on = 0x10010dd; pub const Georgian_par = 0x10010de; pub const Georgian_zhar = 0x10010df; pub const Georgian_rae = 0x10010e0; pub const Georgian_san = 0x10010e1; pub const Georgian_tar = 0x10010e2; pub const Georgian_un = 0x10010e3; pub const Georgian_phar = 0x10010e4; pub const Georgian_khar = 0x10010e5; pub const Georgian_ghan = 0x10010e6; pub const Georgian_qar = 0x10010e7; pub const Georgian_shin = 0x10010e8; pub const Georgian_chin = 0x10010e9; pub const Georgian_can = 0x10010ea; pub const Georgian_jil = 0x10010eb; pub const Georgian_cil = 0x10010ec; pub const Georgian_char = 0x10010ed; pub const Georgian_xan = 0x10010ee; pub const Georgian_jhan = 0x10010ef; pub const Georgian_hae = 0x10010f0; pub const Georgian_he = 0x10010f1; pub const Georgian_hie = 0x10010f2; pub const Georgian_we = 0x10010f3; pub const Georgian_har = 0x10010f4; pub const Georgian_hoe = 0x10010f5; pub const Georgian_fi = 0x10010f6; pub const Xabovedot = 0x1001e8a; pub const Ibreve = 0x100012c; pub const Zstroke = 0x10001b5; pub const Gcaron = 0x10001e6; pub const Ocaron = 0x10001d1; pub const Obarred = 0x100019f; pub const xabovedot = 0x1001e8b; pub const ibreve = 0x100012d; pub const zstroke = 0x10001b6; pub const gcaron = 0x10001e7; pub const ocaron = 0x10001d2; pub const obarred = 0x1000275; pub const SCHWA = 0x100018f; pub const schwa = 0x1000259; pub const EZH = 0x10001b7; pub const ezh = 0x1000292; pub const Lbelowdot = 0x1001e36; pub const lbelowdot = 0x1001e37; pub const Abelowdot = 0x1001ea0; pub const abelowdot = 0x1001ea1; pub const Ahook = 0x1001ea2; pub const ahook = 0x1001ea3; pub const Acircumflexacute = 0x1001ea4; pub const acircumflexacute = 0x1001ea5; pub const Acircumflexgrave = 0x1001ea6; pub const acircumflexgrave = 0x1001ea7; pub const Acircumflexhook = 0x1001ea8; pub const acircumflexhook = 0x1001ea9; pub const Acircumflextilde = 0x1001eaa; pub const acircumflextilde = 0x1001eab; pub const Acircumflexbelowdot = 0x1001eac; pub const acircumflexbelowdot = 0x1001ead; pub const Abreveacute = 0x1001eae; pub const abreveacute = 0x1001eaf; pub const Abrevegrave = 0x1001eb0; pub const abrevegrave = 0x1001eb1; pub const Abrevehook = 0x1001eb2; pub const abrevehook = 0x1001eb3; pub const Abrevetilde = 0x1001eb4; pub const abrevetilde = 0x1001eb5; pub const Abrevebelowdot = 0x1001eb6; pub const abrevebelowdot = 0x1001eb7; pub const Ebelowdot = 0x1001eb8; pub const ebelowdot = 0x1001eb9; pub const Ehook = 0x1001eba; pub const ehook = 0x1001ebb; pub const Etilde = 0x1001ebc; pub const etilde = 0x1001ebd; pub const Ecircumflexacute = 0x1001ebe; pub const ecircumflexacute = 0x1001ebf; pub const Ecircumflexgrave = 0x1001ec0; pub const ecircumflexgrave = 0x1001ec1; pub const Ecircumflexhook = 0x1001ec2; pub const ecircumflexhook = 0x1001ec3; pub const Ecircumflextilde = 0x1001ec4; pub const ecircumflextilde = 0x1001ec5; pub const Ecircumflexbelowdot = 0x1001ec6; pub const ecircumflexbelowdot = 0x1001ec7; pub const Ihook = 0x1001ec8; pub const ihook = 0x1001ec9; pub const Ibelowdot = 0x1001eca; pub const ibelowdot = 0x1001ecb; pub const Obelowdot = 0x1001ecc; pub const obelowdot = 0x1001ecd; pub const Ohook = 0x1001ece; pub const ohook = 0x1001ecf; pub const Ocircumflexacute = 0x1001ed0; pub const ocircumflexacute = 0x1001ed1; pub const Ocircumflexgrave = 0x1001ed2; pub const ocircumflexgrave = 0x1001ed3; pub const Ocircumflexhook = 0x1001ed4; pub const ocircumflexhook = 0x1001ed5; pub const Ocircumflextilde = 0x1001ed6; pub const ocircumflextilde = 0x1001ed7; pub const Ocircumflexbelowdot = 0x1001ed8; pub const ocircumflexbelowdot = 0x1001ed9; pub const Ohornacute = 0x1001eda; pub const ohornacute = 0x1001edb; pub const Ohorngrave = 0x1001edc; pub const ohorngrave = 0x1001edd; pub const Ohornhook = 0x1001ede; pub const ohornhook = 0x1001edf; pub const Ohorntilde = 0x1001ee0; pub const ohorntilde = 0x1001ee1; pub const Ohornbelowdot = 0x1001ee2; pub const ohornbelowdot = 0x1001ee3; pub const Ubelowdot = 0x1001ee4; pub const ubelowdot = 0x1001ee5; pub const Uhook = 0x1001ee6; pub const uhook = 0x1001ee7; pub const Uhornacute = 0x1001ee8; pub const uhornacute = 0x1001ee9; pub const Uhorngrave = 0x1001eea; pub const uhorngrave = 0x1001eeb; pub const Uhornhook = 0x1001eec; pub const uhornhook = 0x1001eed; pub const Uhorntilde = 0x1001eee; pub const uhorntilde = 0x1001eef; pub const Uhornbelowdot = 0x1001ef0; pub const uhornbelowdot = 0x1001ef1; pub const Ybelowdot = 0x1001ef4; pub const ybelowdot = 0x1001ef5; pub const Yhook = 0x1001ef6; pub const yhook = 0x1001ef7; pub const Ytilde = 0x1001ef8; pub const ytilde = 0x1001ef9; pub const Ohorn = 0x10001a0; pub const ohorn = 0x10001a1; pub const Uhorn = 0x10001af; pub const uhorn = 0x10001b0; pub const EcuSign = 0x10020a0; pub const ColonSign = 0x10020a1; pub const CruzeiroSign = 0x10020a2; pub const FFrancSign = 0x10020a3; pub const LiraSign = 0x10020a4; pub const MillSign = 0x10020a5; pub const NairaSign = 0x10020a6; pub const PesetaSign = 0x10020a7; pub const RupeeSign = 0x10020a8; pub const WonSign = 0x10020a9; pub const NewSheqelSign = 0x10020aa; pub const DongSign = 0x10020ab; pub const EuroSign = 0x20ac; pub const zerosuperior = 0x1002070; pub const foursuperior = 0x1002074; pub const fivesuperior = 0x1002075; pub const sixsuperior = 0x1002076; pub const sevensuperior = 0x1002077; pub const eightsuperior = 0x1002078; pub const ninesuperior = 0x1002079; pub const zerosubscript = 0x1002080; pub const onesubscript = 0x1002081; pub const twosubscript = 0x1002082; pub const threesubscript = 0x1002083; pub const foursubscript = 0x1002084; pub const fivesubscript = 0x1002085; pub const sixsubscript = 0x1002086; pub const sevensubscript = 0x1002087; pub const eightsubscript = 0x1002088; pub const ninesubscript = 0x1002089; pub const partdifferential = 0x1002202; pub const emptyset = 0x1002205; pub const elementof = 0x1002208; pub const notelementof = 0x1002209; pub const containsas = 0x100220B; pub const squareroot = 0x100221A; pub const cuberoot = 0x100221B; pub const fourthroot = 0x100221C; pub const dintegral = 0x100222C; pub const tintegral = 0x100222D; pub const because = 0x1002235; pub const approxeq = 0x1002248; pub const notapproxeq = 0x1002247; pub const notidentical = 0x1002262; pub const stricteq = 0x1002263; pub const braille_dot_1 = 0xfff1; pub const braille_dot_2 = 0xfff2; pub const braille_dot_3 = 0xfff3; pub const braille_dot_4 = 0xfff4; pub const braille_dot_5 = 0xfff5; pub const braille_dot_6 = 0xfff6; pub const braille_dot_7 = 0xfff7; pub const braille_dot_8 = 0xfff8; pub const braille_dot_9 = 0xfff9; pub const braille_dot_10 = 0xfffa; pub const braille_blank = 0x1002800; pub const braille_dots_1 = 0x1002801; pub const braille_dots_2 = 0x1002802; pub const braille_dots_12 = 0x1002803; pub const braille_dots_3 = 0x1002804; pub const braille_dots_13 = 0x1002805; pub const braille_dots_23 = 0x1002806; pub const braille_dots_123 = 0x1002807; pub const braille_dots_4 = 0x1002808; pub const braille_dots_14 = 0x1002809; pub const braille_dots_24 = 0x100280a; pub const braille_dots_124 = 0x100280b; pub const braille_dots_34 = 0x100280c; pub const braille_dots_134 = 0x100280d; pub const braille_dots_234 = 0x100280e; pub const braille_dots_1234 = 0x100280f; pub const braille_dots_5 = 0x1002810; pub const braille_dots_15 = 0x1002811; pub const braille_dots_25 = 0x1002812; pub const braille_dots_125 = 0x1002813; pub const braille_dots_35 = 0x1002814; pub const braille_dots_135 = 0x1002815; pub const braille_dots_235 = 0x1002816; pub const braille_dots_1235 = 0x1002817; pub const braille_dots_45 = 0x1002818; pub const braille_dots_145 = 0x1002819; pub const braille_dots_245 = 0x100281a; pub const braille_dots_1245 = 0x100281b; pub const braille_dots_345 = 0x100281c; pub const braille_dots_1345 = 0x100281d; pub const braille_dots_2345 = 0x100281e; pub const braille_dots_12345 = 0x100281f; pub const braille_dots_6 = 0x1002820; pub const braille_dots_16 = 0x1002821; pub const braille_dots_26 = 0x1002822; pub const braille_dots_126 = 0x1002823; pub const braille_dots_36 = 0x1002824; pub const braille_dots_136 = 0x1002825; pub const braille_dots_236 = 0x1002826; pub const braille_dots_1236 = 0x1002827; pub const braille_dots_46 = 0x1002828; pub const braille_dots_146 = 0x1002829; pub const braille_dots_246 = 0x100282a; pub const braille_dots_1246 = 0x100282b; pub const braille_dots_346 = 0x100282c; pub const braille_dots_1346 = 0x100282d; pub const braille_dots_2346 = 0x100282e; pub const braille_dots_12346 = 0x100282f; pub const braille_dots_56 = 0x1002830; pub const braille_dots_156 = 0x1002831; pub const braille_dots_256 = 0x1002832; pub const braille_dots_1256 = 0x1002833; pub const braille_dots_356 = 0x1002834; pub const braille_dots_1356 = 0x1002835; pub const braille_dots_2356 = 0x1002836; pub const braille_dots_12356 = 0x1002837; pub const braille_dots_456 = 0x1002838; pub const braille_dots_1456 = 0x1002839; pub const braille_dots_2456 = 0x100283a; pub const braille_dots_12456 = 0x100283b; pub const braille_dots_3456 = 0x100283c; pub const braille_dots_13456 = 0x100283d; pub const braille_dots_23456 = 0x100283e; pub const braille_dots_123456 = 0x100283f; pub const braille_dots_7 = 0x1002840; pub const braille_dots_17 = 0x1002841; pub const braille_dots_27 = 0x1002842; pub const braille_dots_127 = 0x1002843; pub const braille_dots_37 = 0x1002844; pub const braille_dots_137 = 0x1002845; pub const braille_dots_237 = 0x1002846; pub const braille_dots_1237 = 0x1002847; pub const braille_dots_47 = 0x1002848; pub const braille_dots_147 = 0x1002849; pub const braille_dots_247 = 0x100284a; pub const braille_dots_1247 = 0x100284b; pub const braille_dots_347 = 0x100284c; pub const braille_dots_1347 = 0x100284d; pub const braille_dots_2347 = 0x100284e; pub const braille_dots_12347 = 0x100284f; pub const braille_dots_57 = 0x1002850; pub const braille_dots_157 = 0x1002851; pub const braille_dots_257 = 0x1002852; pub const braille_dots_1257 = 0x1002853; pub const braille_dots_357 = 0x1002854; pub const braille_dots_1357 = 0x1002855; pub const braille_dots_2357 = 0x1002856; pub const braille_dots_12357 = 0x1002857; pub const braille_dots_457 = 0x1002858; pub const braille_dots_1457 = 0x1002859; pub const braille_dots_2457 = 0x100285a; pub const braille_dots_12457 = 0x100285b; pub const braille_dots_3457 = 0x100285c; pub const braille_dots_13457 = 0x100285d; pub const braille_dots_23457 = 0x100285e; pub const braille_dots_123457 = 0x100285f; pub const braille_dots_67 = 0x1002860; pub const braille_dots_167 = 0x1002861; pub const braille_dots_267 = 0x1002862; pub const braille_dots_1267 = 0x1002863; pub const braille_dots_367 = 0x1002864; pub const braille_dots_1367 = 0x1002865; pub const braille_dots_2367 = 0x1002866; pub const braille_dots_12367 = 0x1002867; pub const braille_dots_467 = 0x1002868; pub const braille_dots_1467 = 0x1002869; pub const braille_dots_2467 = 0x100286a; pub const braille_dots_12467 = 0x100286b; pub const braille_dots_3467 = 0x100286c; pub const braille_dots_13467 = 0x100286d; pub const braille_dots_23467 = 0x100286e; pub const braille_dots_123467 = 0x100286f; pub const braille_dots_567 = 0x1002870; pub const braille_dots_1567 = 0x1002871; pub const braille_dots_2567 = 0x1002872; pub const braille_dots_12567 = 0x1002873; pub const braille_dots_3567 = 0x1002874; pub const braille_dots_13567 = 0x1002875; pub const braille_dots_23567 = 0x1002876; pub const braille_dots_123567 = 0x1002877; pub const braille_dots_4567 = 0x1002878; pub const braille_dots_14567 = 0x1002879; pub const braille_dots_24567 = 0x100287a; pub const braille_dots_124567 = 0x100287b; pub const braille_dots_34567 = 0x100287c; pub const braille_dots_134567 = 0x100287d; pub const braille_dots_234567 = 0x100287e; pub const braille_dots_1234567 = 0x100287f; pub const braille_dots_8 = 0x1002880; pub const braille_dots_18 = 0x1002881; pub const braille_dots_28 = 0x1002882; pub const braille_dots_128 = 0x1002883; pub const braille_dots_38 = 0x1002884; pub const braille_dots_138 = 0x1002885; pub const braille_dots_238 = 0x1002886; pub const braille_dots_1238 = 0x1002887; pub const braille_dots_48 = 0x1002888; pub const braille_dots_148 = 0x1002889; pub const braille_dots_248 = 0x100288a; pub const braille_dots_1248 = 0x100288b; pub const braille_dots_348 = 0x100288c; pub const braille_dots_1348 = 0x100288d; pub const braille_dots_2348 = 0x100288e; pub const braille_dots_12348 = 0x100288f; pub const braille_dots_58 = 0x1002890; pub const braille_dots_158 = 0x1002891; pub const braille_dots_258 = 0x1002892; pub const braille_dots_1258 = 0x1002893; pub const braille_dots_358 = 0x1002894; pub const braille_dots_1358 = 0x1002895; pub const braille_dots_2358 = 0x1002896; pub const braille_dots_12358 = 0x1002897; pub const braille_dots_458 = 0x1002898; pub const braille_dots_1458 = 0x1002899; pub const braille_dots_2458 = 0x100289a; pub const braille_dots_12458 = 0x100289b; pub const braille_dots_3458 = 0x100289c; pub const braille_dots_13458 = 0x100289d; pub const braille_dots_23458 = 0x100289e; pub const braille_dots_123458 = 0x100289f; pub const braille_dots_68 = 0x10028a0; pub const braille_dots_168 = 0x10028a1; pub const braille_dots_268 = 0x10028a2; pub const braille_dots_1268 = 0x10028a3; pub const braille_dots_368 = 0x10028a4; pub const braille_dots_1368 = 0x10028a5; pub const braille_dots_2368 = 0x10028a6; pub const braille_dots_12368 = 0x10028a7; pub const braille_dots_468 = 0x10028a8; pub const braille_dots_1468 = 0x10028a9; pub const braille_dots_2468 = 0x10028aa; pub const braille_dots_12468 = 0x10028ab; pub const braille_dots_3468 = 0x10028ac; pub const braille_dots_13468 = 0x10028ad; pub const braille_dots_23468 = 0x10028ae; pub const braille_dots_123468 = 0x10028af; pub const braille_dots_568 = 0x10028b0; pub const braille_dots_1568 = 0x10028b1; pub const braille_dots_2568 = 0x10028b2; pub const braille_dots_12568 = 0x10028b3; pub const braille_dots_3568 = 0x10028b4; pub const braille_dots_13568 = 0x10028b5; pub const braille_dots_23568 = 0x10028b6; pub const braille_dots_123568 = 0x10028b7; pub const braille_dots_4568 = 0x10028b8; pub const braille_dots_14568 = 0x10028b9; pub const braille_dots_24568 = 0x10028ba; pub const braille_dots_124568 = 0x10028bb; pub const braille_dots_34568 = 0x10028bc; pub const braille_dots_134568 = 0x10028bd; pub const braille_dots_234568 = 0x10028be; pub const braille_dots_1234568 = 0x10028bf; pub const braille_dots_78 = 0x10028c0; pub const braille_dots_178 = 0x10028c1; pub const braille_dots_278 = 0x10028c2; pub const braille_dots_1278 = 0x10028c3; pub const braille_dots_378 = 0x10028c4; pub const braille_dots_1378 = 0x10028c5; pub const braille_dots_2378 = 0x10028c6; pub const braille_dots_12378 = 0x10028c7; pub const braille_dots_478 = 0x10028c8; pub const braille_dots_1478 = 0x10028c9; pub const braille_dots_2478 = 0x10028ca; pub const braille_dots_12478 = 0x10028cb; pub const braille_dots_3478 = 0x10028cc; pub const braille_dots_13478 = 0x10028cd; pub const braille_dots_23478 = 0x10028ce; pub const braille_dots_123478 = 0x10028cf; pub const braille_dots_578 = 0x10028d0; pub const braille_dots_1578 = 0x10028d1; pub const braille_dots_2578 = 0x10028d2; pub const braille_dots_12578 = 0x10028d3; pub const braille_dots_3578 = 0x10028d4; pub const braille_dots_13578 = 0x10028d5; pub const braille_dots_23578 = 0x10028d6; pub const braille_dots_123578 = 0x10028d7; pub const braille_dots_4578 = 0x10028d8; pub const braille_dots_14578 = 0x10028d9; pub const braille_dots_24578 = 0x10028da; pub const braille_dots_124578 = 0x10028db; pub const braille_dots_34578 = 0x10028dc; pub const braille_dots_134578 = 0x10028dd; pub const braille_dots_234578 = 0x10028de; pub const braille_dots_1234578 = 0x10028df; pub const braille_dots_678 = 0x10028e0; pub const braille_dots_1678 = 0x10028e1; pub const braille_dots_2678 = 0x10028e2; pub const braille_dots_12678 = 0x10028e3; pub const braille_dots_3678 = 0x10028e4; pub const braille_dots_13678 = 0x10028e5; pub const braille_dots_23678 = 0x10028e6; pub const braille_dots_123678 = 0x10028e7; pub const braille_dots_4678 = 0x10028e8; pub const braille_dots_14678 = 0x10028e9; pub const braille_dots_24678 = 0x10028ea; pub const braille_dots_124678 = 0x10028eb; pub const braille_dots_34678 = 0x10028ec; pub const braille_dots_134678 = 0x10028ed; pub const braille_dots_234678 = 0x10028ee; pub const braille_dots_1234678 = 0x10028ef; pub const braille_dots_5678 = 0x10028f0; pub const braille_dots_15678 = 0x10028f1; pub const braille_dots_25678 = 0x10028f2; pub const braille_dots_125678 = 0x10028f3; pub const braille_dots_35678 = 0x10028f4; pub const braille_dots_135678 = 0x10028f5; pub const braille_dots_235678 = 0x10028f6; pub const braille_dots_1235678 = 0x10028f7; pub const braille_dots_45678 = 0x10028f8; pub const braille_dots_145678 = 0x10028f9; pub const braille_dots_245678 = 0x10028fa; pub const braille_dots_1245678 = 0x10028fb; pub const braille_dots_345678 = 0x10028fc; pub const braille_dots_1345678 = 0x10028fd; pub const braille_dots_2345678 = 0x10028fe; pub const braille_dots_12345678 = 0x10028ff; pub const Sinh_ng = 0x1000d82; pub const Sinh_h2 = 0x1000d83; pub const Sinh_a = 0x1000d85; pub const Sinh_aa = 0x1000d86; pub const Sinh_ae = 0x1000d87; pub const Sinh_aee = 0x1000d88; pub const Sinh_i = 0x1000d89; pub const Sinh_ii = 0x1000d8a; pub const Sinh_u = 0x1000d8b; pub const Sinh_uu = 0x1000d8c; pub const Sinh_ri = 0x1000d8d; pub const Sinh_rii = 0x1000d8e; pub const Sinh_lu = 0x1000d8f; pub const Sinh_luu = 0x1000d90; pub const Sinh_e = 0x1000d91; pub const Sinh_ee = 0x1000d92; pub const Sinh_ai = 0x1000d93; pub const Sinh_o = 0x1000d94; pub const Sinh_oo = 0x1000d95; pub const Sinh_au = 0x1000d96; pub const Sinh_ka = 0x1000d9a; pub const Sinh_kha = 0x1000d9b; pub const Sinh_ga = 0x1000d9c; pub const Sinh_gha = 0x1000d9d; pub const Sinh_ng2 = 0x1000d9e; pub const Sinh_nga = 0x1000d9f; pub const Sinh_ca = 0x1000da0; pub const Sinh_cha = 0x1000da1; pub const Sinh_ja = 0x1000da2; pub const Sinh_jha = 0x1000da3; pub const Sinh_nya = 0x1000da4; pub const Sinh_jnya = 0x1000da5; pub const Sinh_nja = 0x1000da6; pub const Sinh_tta = 0x1000da7; pub const Sinh_ttha = 0x1000da8; pub const Sinh_dda = 0x1000da9; pub const Sinh_ddha = 0x1000daa; pub const Sinh_nna = 0x1000dab; pub const Sinh_ndda = 0x1000dac; pub const Sinh_tha = 0x1000dad; pub const Sinh_thha = 0x1000dae; pub const Sinh_dha = 0x1000daf; pub const Sinh_dhha = 0x1000db0; pub const Sinh_na = 0x1000db1; pub const Sinh_ndha = 0x1000db3; pub const Sinh_pa = 0x1000db4; pub const Sinh_pha = 0x1000db5; pub const Sinh_ba = 0x1000db6; pub const Sinh_bha = 0x1000db7; pub const Sinh_ma = 0x1000db8; pub const Sinh_mba = 0x1000db9; pub const Sinh_ya = 0x1000dba; pub const Sinh_ra = 0x1000dbb; pub const Sinh_la = 0x1000dbd; pub const Sinh_va = 0x1000dc0; pub const Sinh_sha = 0x1000dc1; pub const Sinh_ssha = 0x1000dc2; pub const Sinh_sa = 0x1000dc3; pub const Sinh_ha = 0x1000dc4; pub const Sinh_lla = 0x1000dc5; pub const Sinh_fa = 0x1000dc6; pub const Sinh_al = 0x1000dca; pub const Sinh_aa2 = 0x1000dcf; pub const Sinh_ae2 = 0x1000dd0; pub const Sinh_aee2 = 0x1000dd1; pub const Sinh_i2 = 0x1000dd2; pub const Sinh_ii2 = 0x1000dd3; pub const Sinh_u2 = 0x1000dd4; pub const Sinh_uu2 = 0x1000dd6; pub const Sinh_ru2 = 0x1000dd8; pub const Sinh_e2 = 0x1000dd9; pub const Sinh_ee2 = 0x1000dda; pub const Sinh_ai2 = 0x1000ddb; pub const Sinh_o2 = 0x1000ddc; pub const Sinh_oo2 = 0x1000ddd; pub const Sinh_au2 = 0x1000dde; pub const Sinh_lu2 = 0x1000ddf; pub const Sinh_ruu2 = 0x1000df2; pub const Sinh_luu2 = 0x1000df3; pub const Sinh_kunddaliya = 0x1000df4; pub const XF86ModeLock = 0x1008FF01; pub const XF86MonBrightnessUp = 0x1008FF02; pub const XF86MonBrightnessDown = 0x1008FF03; pub const XF86KbdLightOnOff = 0x1008FF04; pub const XF86KbdBrightnessUp = 0x1008FF05; pub const XF86KbdBrightnessDown = 0x1008FF06; pub const XF86MonBrightnessCycle = 0x1008FF07; pub const XF86Standby = 0x1008FF10; pub const XF86AudioLowerVolume = 0x1008FF11; pub const XF86AudioMute = 0x1008FF12; pub const XF86AudioRaiseVolume = 0x1008FF13; pub const XF86AudioPlay = 0x1008FF14; pub const XF86AudioStop = 0x1008FF15; pub const XF86AudioPrev = 0x1008FF16; pub const XF86AudioNext = 0x1008FF17; pub const XF86HomePage = 0x1008FF18; pub const XF86Mail = 0x1008FF19; pub const XF86Start = 0x1008FF1A; pub const XF86Search = 0x1008FF1B; pub const XF86AudioRecord = 0x1008FF1C; pub const XF86Calculator = 0x1008FF1D; pub const XF86Memo = 0x1008FF1E; pub const XF86ToDoList = 0x1008FF1F; pub const XF86Calendar = 0x1008FF20; pub const XF86PowerDown = 0x1008FF21; pub const XF86ContrastAdjust = 0x1008FF22; pub const XF86RockerUp = 0x1008FF23; pub const XF86RockerDown = 0x1008FF24; pub const XF86RockerEnter = 0x1008FF25; pub const XF86Back = 0x1008FF26; pub const XF86Forward = 0x1008FF27; pub const XF86Stop = 0x1008FF28; pub const XF86Refresh = 0x1008FF29; pub const XF86PowerOff = 0x1008FF2A; pub const XF86WakeUp = 0x1008FF2B; pub const XF86Eject = 0x1008FF2C; pub const XF86ScreenSaver = 0x1008FF2D; pub const XF86WWW = 0x1008FF2E; pub const XF86Sleep = 0x1008FF2F; pub const XF86Favorites = 0x1008FF30; pub const XF86AudioPause = 0x1008FF31; pub const XF86AudioMedia = 0x1008FF32; pub const XF86MyComputer = 0x1008FF33; pub const XF86VendorHome = 0x1008FF34; pub const XF86LightBulb = 0x1008FF35; pub const XF86Shop = 0x1008FF36; pub const XF86History = 0x1008FF37; pub const XF86OpenURL = 0x1008FF38; pub const XF86AddFavorite = 0x1008FF39; pub const XF86HotLinks = 0x1008FF3A; pub const XF86BrightnessAdjust = 0x1008FF3B; pub const XF86Finance = 0x1008FF3C; pub const XF86Community = 0x1008FF3D; pub const XF86AudioRewind = 0x1008FF3E; pub const XF86BackForward = 0x1008FF3F; pub const XF86Launch0 = 0x1008FF40; pub const XF86Launch1 = 0x1008FF41; pub const XF86Launch2 = 0x1008FF42; pub const XF86Launch3 = 0x1008FF43; pub const XF86Launch4 = 0x1008FF44; pub const XF86Launch5 = 0x1008FF45; pub const XF86Launch6 = 0x1008FF46; pub const XF86Launch7 = 0x1008FF47; pub const XF86Launch8 = 0x1008FF48; pub const XF86Launch9 = 0x1008FF49; pub const XF86LaunchA = 0x1008FF4A; pub const XF86LaunchB = 0x1008FF4B; pub const XF86LaunchC = 0x1008FF4C; pub const XF86LaunchD = 0x1008FF4D; pub const XF86LaunchE = 0x1008FF4E; pub const XF86LaunchF = 0x1008FF4F; pub const XF86ApplicationLeft = 0x1008FF50; pub const XF86ApplicationRight = 0x1008FF51; pub const XF86Book = 0x1008FF52; pub const XF86CD = 0x1008FF53; pub const XF86Calculater = 0x1008FF54; pub const XF86Clear = 0x1008FF55; pub const XF86Close = 0x1008FF56; pub const XF86Copy = 0x1008FF57; pub const XF86Cut = 0x1008FF58; pub const XF86Display = 0x1008FF59; pub const XF86DOS = 0x1008FF5A; pub const XF86Documents = 0x1008FF5B; pub const XF86Excel = 0x1008FF5C; pub const XF86Explorer = 0x1008FF5D; pub const XF86Game = 0x1008FF5E; pub const XF86Go = 0x1008FF5F; pub const XF86iTouch = 0x1008FF60; pub const XF86LogOff = 0x1008FF61; pub const XF86Market = 0x1008FF62; pub const XF86Meeting = 0x1008FF63; pub const XF86MenuKB = 0x1008FF65; pub const XF86MenuPB = 0x1008FF66; pub const XF86MySites = 0x1008FF67; pub const XF86New = 0x1008FF68; pub const XF86News = 0x1008FF69; pub const XF86OfficeHome = 0x1008FF6A; pub const XF86Open = 0x1008FF6B; pub const XF86Option = 0x1008FF6C; pub const XF86Paste = 0x1008FF6D; pub const XF86Phone = 0x1008FF6E; pub const XF86Q = 0x1008FF70; pub const XF86Reply = 0x1008FF72; pub const XF86Reload = 0x1008FF73; pub const XF86RotateWindows = 0x1008FF74; pub const XF86RotationPB = 0x1008FF75; pub const XF86RotationKB = 0x1008FF76; pub const XF86Save = 0x1008FF77; pub const XF86ScrollUp = 0x1008FF78; pub const XF86ScrollDown = 0x1008FF79; pub const XF86ScrollClick = 0x1008FF7A; pub const XF86Send = 0x1008FF7B; pub const XF86Spell = 0x1008FF7C; pub const XF86SplitScreen = 0x1008FF7D; pub const XF86Support = 0x1008FF7E; pub const XF86TaskPane = 0x1008FF7F; pub const XF86Terminal = 0x1008FF80; pub const XF86Tools = 0x1008FF81; pub const XF86Travel = 0x1008FF82; pub const XF86UserPB = 0x1008FF84; pub const XF86User1KB = 0x1008FF85; pub const XF86User2KB = 0x1008FF86; pub const XF86Video = 0x1008FF87; pub const XF86WheelButton = 0x1008FF88; pub const XF86Word = 0x1008FF89; pub const XF86Xfer = 0x1008FF8A; pub const XF86ZoomIn = 0x1008FF8B; pub const XF86ZoomOut = 0x1008FF8C; pub const XF86Away = 0x1008FF8D; pub const XF86Messenger = 0x1008FF8E; pub const XF86WebCam = 0x1008FF8F; pub const XF86MailForward = 0x1008FF90; pub const XF86Pictures = 0x1008FF91; pub const XF86Music = 0x1008FF92; pub const XF86Battery = 0x1008FF93; pub const XF86Bluetooth = 0x1008FF94; pub const XF86WLAN = 0x1008FF95; pub const XF86UWB = 0x1008FF96; pub const XF86AudioForward = 0x1008FF97; pub const XF86AudioRepeat = 0x1008FF98; pub const XF86AudioRandomPlay = 0x1008FF99; pub const XF86Subtitle = 0x1008FF9A; pub const XF86AudioCycleTrack = 0x1008FF9B; pub const XF86CycleAngle = 0x1008FF9C; pub const XF86FrameBack = 0x1008FF9D; pub const XF86FrameForward = 0x1008FF9E; pub const XF86Time = 0x1008FF9F; pub const XF86Select = 0x1008FFA0; pub const XF86View = 0x1008FFA1; pub const XF86TopMenu = 0x1008FFA2; pub const XF86Red = 0x1008FFA3; pub const XF86Green = 0x1008FFA4; pub const XF86Yellow = 0x1008FFA5; pub const XF86Blue = 0x1008FFA6; pub const XF86Suspend = 0x1008FFA7; pub const XF86Hibernate = 0x1008FFA8; pub const XF86TouchpadToggle = 0x1008FFA9; pub const XF86TouchpadOn = 0x1008FFB0; pub const XF86TouchpadOff = 0x1008FFB1; pub const XF86AudioMicMute = 0x1008FFB2; pub const XF86Keyboard = 0x1008FFB3; pub const XF86WWAN = 0x1008FFB4; pub const XF86RFKill = 0x1008FFB5; pub const XF86AudioPreset = 0x1008FFB6; pub const XF86RotationLockToggle = 0x1008FFB7; pub const XF86FullScreen = 0x1008FFB8; pub const XF86Switch_VT_1 = 0x1008FE01; pub const XF86Switch_VT_2 = 0x1008FE02; pub const XF86Switch_VT_3 = 0x1008FE03; pub const XF86Switch_VT_4 = 0x1008FE04; pub const XF86Switch_VT_5 = 0x1008FE05; pub const XF86Switch_VT_6 = 0x1008FE06; pub const XF86Switch_VT_7 = 0x1008FE07; pub const XF86Switch_VT_8 = 0x1008FE08; pub const XF86Switch_VT_9 = 0x1008FE09; pub const XF86Switch_VT_10 = 0x1008FE0A; pub const XF86Switch_VT_11 = 0x1008FE0B; pub const XF86Switch_VT_12 = 0x1008FE0C; pub const XF86Ungrab = 0x1008FE20; pub const XF86ClearGrab = 0x1008FE21; pub const XF86Next_VMode = 0x1008FE22; pub const XF86Prev_VMode = 0x1008FE23; pub const XF86LogWindowTree = 0x1008FE24; pub const XF86LogGrabInfo = 0x1008FE25; pub const SunFA_Grave = 0x1005FF00; pub const SunFA_Circum = 0x1005FF01; pub const SunFA_Tilde = 0x1005FF02; pub const SunFA_Acute = 0x1005FF03; pub const SunFA_Diaeresis = 0x1005FF04; pub const SunFA_Cedilla = 0x1005FF05; pub const SunF36 = 0x1005FF10; pub const SunF37 = 0x1005FF11; pub const SunSys_Req = 0x1005FF60; pub const SunPrint_Screen = 0x0000FF61; pub const SunCompose = 0x0000FF20; pub const SunAltGraph = 0x0000FF7E; pub const SunPageUp = 0x0000FF55; pub const SunPageDown = 0x0000FF56; pub const SunUndo = 0x0000FF65; pub const SunAgain = 0x0000FF66; pub const SunFind = 0x0000FF68; pub const SunStop = 0x0000FF69; pub const SunProps = 0x1005FF70; pub const SunFront = 0x1005FF71; pub const SunCopy = 0x1005FF72; pub const SunOpen = 0x1005FF73; pub const SunPaste = 0x1005FF74; pub const SunCut = 0x1005FF75; pub const SunPowerSwitch = 0x1005FF76; pub const SunAudioLowerVolume = 0x1005FF77; pub const SunAudioMute = 0x1005FF78; pub const SunAudioRaiseVolume = 0x1005FF79; pub const SunVideoDegauss = 0x1005FF7A; pub const SunVideoLowerBrightness = 0x1005FF7B; pub const SunVideoRaiseBrightness = 0x1005FF7C; pub const SunPowerSwitchShift = 0x1005FF7D; pub const Dring_accent = 0x1000FEB0; pub const Dcircumflex_accent = 0x1000FE5E; pub const Dcedilla_accent = 0x1000FE2C; pub const Dacute_accent = 0x1000FE27; pub const Dgrave_accent = 0x1000FE60; pub const Dtilde = 0x1000FE7E; pub const Ddiaeresis = 0x1000FE22; pub const DRemove = 0x1000FF00; pub const hpClearLine = 0x1000FF6F; pub const hpInsertLine = 0x1000FF70; pub const hpDeleteLine = 0x1000FF71; pub const hpInsertChar = 0x1000FF72; pub const hpDeleteChar = 0x1000FF73; pub const hpBackTab = 0x1000FF74; pub const hpKP_BackTab = 0x1000FF75; pub const hpModelock1 = 0x1000FF48; pub const hpModelock2 = 0x1000FF49; pub const hpReset = 0x1000FF6C; pub const hpSystem = 0x1000FF6D; pub const hpUser = 0x1000FF6E; pub const hpmute_acute = 0x100000A8; pub const hpmute_grave = 0x100000A9; pub const hpmute_asciicircum = 0x100000AA; pub const hpmute_diaeresis = 0x100000AB; pub const hpmute_asciitilde = 0x100000AC; pub const hplira = 0x100000AF; pub const hpguilder = 0x100000BE; pub const hpYdiaeresis = 0x100000EE; pub const hpIO = 0x100000EE; pub const hplongminus = 0x100000F6; pub const hpblock = 0x100000FC; pub const osfCopy = 0x1004FF02; pub const osfCut = 0x1004FF03; pub const osfPaste = 0x1004FF04; pub const osfBackTab = 0x1004FF07; pub const osfBackSpace = 0x1004FF08; pub const osfClear = 0x1004FF0B; pub const osfEscape = 0x1004FF1B; pub const osfAddMode = 0x1004FF31; pub const osfPrimaryPaste = 0x1004FF32; pub const osfQuickPaste = 0x1004FF33; pub const osfPageLeft = 0x1004FF40; pub const osfPageUp = 0x1004FF41; pub const osfPageDown = 0x1004FF42; pub const osfPageRight = 0x1004FF43; pub const osfActivate = 0x1004FF44; pub const osfMenuBar = 0x1004FF45; pub const osfLeft = 0x1004FF51; pub const osfUp = 0x1004FF52; pub const osfRight = 0x1004FF53; pub const osfDown = 0x1004FF54; pub const osfEndLine = 0x1004FF57; pub const osfBeginLine = 0x1004FF58; pub const osfEndData = 0x1004FF59; pub const osfBeginData = 0x1004FF5A; pub const osfPrevMenu = 0x1004FF5B; pub const osfNextMenu = 0x1004FF5C; pub const osfPrevField = 0x1004FF5D; pub const osfNextField = 0x1004FF5E; pub const osfSelect = 0x1004FF60; pub const osfInsert = 0x1004FF63; pub const osfUndo = 0x1004FF65; pub const osfMenu = 0x1004FF67; pub const osfCancel = 0x1004FF69; pub const osfHelp = 0x1004FF6A; pub const osfSelectAll = 0x1004FF71; pub const osfDeselectAll = 0x1004FF72; pub const osfReselect = 0x1004FF73; pub const osfExtend = 0x1004FF74; pub const osfRestore = 0x1004FF78; pub const osfDelete = 0x1004FFFF; pub const Reset = 0x1000FF6C; pub const System = 0x1000FF6D; pub const User = 0x1000FF6E; pub const ClearLine = 0x1000FF6F; pub const InsertLine = 0x1000FF70; pub const DeleteLine = 0x1000FF71; pub const InsertChar = 0x1000FF72; pub const DeleteChar = 0x1000FF73; pub const BackTab = 0x1000FF74; pub const KP_BackTab = 0x1000FF75; pub const Ext16bit_L = 0x1000FF76; pub const Ext16bit_R = 0x1000FF77; pub const mute_acute = 0x100000a8; pub const mute_grave = 0x100000a9; pub const mute_asciicircum = 0x100000aa; pub const mute_diaeresis = 0x100000ab; pub const mute_asciitilde = 0x100000ac; pub const lira = 0x100000af; pub const guilder = 0x100000be; pub const IO = 0x100000ee; pub const longminus = 0x100000f6; pub const block = 0x100000fc; pub const Flags = enum(c_int) { no_flags = 0, case_insensitive = 1 << 0, }; extern fn xkb_keysym_get_name(keysym: Keysym, buffer: [*]u8, size: usize) c_int; pub const getName = xkb_keysym_get_name; extern fn xkb_keysym_from_name(name: [*:0]const u8, flags: Flags) Keysym; pub const fromName = xkb_keysym_from_name; extern fn xkb_keysym_to_utf8(keysym: Keysym, buffer: [*]u8, size: usize) c_int; pub const toUTF8 = xkb_keysym_to_utf8; extern fn xkb_keysym_to_utf32(keysym: Keysym) u32; pub const toUTF32 = xkb_keysym_to_utf32; extern fn xkb_utf32_to_keysym(ucs: u32) Keysym; pub const fromUTF32 = xkb_utf32_to_keysym; extern fn xkb_keysym_to_upper(ks: Keysym) Keysym; pub const toUpper = xkb_keysym_to_upper; extern fn xkb_keysym_to_lower(ks: Keysym) Keysym; pub const toLower = xkb_keysym_to_lower; };
src/xkbcommon_keysyms.zig
const std = @import("std"); const pkmn = @import("pkmn"); const gen1 = pkmn.gen1.helpers; pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); if (args.len < 2) usageAndExit(args[0]); const gen = std.fmt.parseUnsigned(u8, args[1], 10) catch errorAndExit("gen", args[1], args[0]); if (gen < 1 or gen > 8) errorAndExit("gen", args[1], args[0]); const seed = if (args.len > 2) std.fmt.parseUnsigned(u64, args[2], 10) catch errorAndExit("seed", args[2], args[0]) else null; const out = std.io.getStdOut(); var buf = std.io.bufferedWriter(out.writer()); var w = buf.writer(); var battle = switch (gen) { 1 => if (seed) |s| gen1.Battle.random(&pkmn.PSRNG.init(s), false) else GEN1, else => unreachable, }; try w.writeStruct(battle); try buf.flush(); // print(battle); const serialized = std.mem.toBytes(battle); const deserialized = std.mem.bytesToValue(@TypeOf(battle), &serialized); try std.testing.expectEqual(battle, deserialized); } fn errorAndExit(msg: []const u8, arg: []const u8, cmd: []const u8) noreturn { const err = std.io.getStdErr().writer(); err.print("Invalid {s}: {s}\n", .{ msg, arg }) catch {}; usageAndExit(cmd); } fn usageAndExit(cmd: []const u8) noreturn { const err = std.io.getStdErr().writer(); err.print("Usage: {s} <GEN> <SEED?>\n", .{cmd}) catch {}; std.process.exit(1); } const GEN1: pkmn.gen1.Battle(pkmn.gen1.PRNG) = .{ .sides = .{ .{ .pokemon = .{ .{ .stats = .{ .hp = 233, .atk = 98, .def = 108, .spe = 128, .spc = 76 }, .moves = .{ .{ .id = .SonicBoom, .pp = 10 }, .{ .id = .Constrict, .pp = 24 }, .{ .id = .Clamp, .pp = 10 }, .{ .id = .HornDrill, .pp = 7 }, }, .hp = 208, .status = 8, .species = .Caterpie, .types = .{ .type1 = .Bug, .type2 = .Bug }, }, .{ .stats = .{ .hp = 217, .atk = 252, .def = 118, .spe = 186, .spc = 82 }, .moves = .{ .{ .id = .Stomp, .pp = 9 }, .{ .id = .PoisonSting, .pp = 55 }, .{ .id = .Bite, .pp = 22 }, .{ .id = .Bind, .pp = 10 }, }, .hp = 68, .species = .Hitmonlee, .types = .{ .type1 = .Fighting, .type2 = .Fighting }, }, .{ .stats = .{ .hp = 231, .atk = 134, .def = 168, .spe = 124, .spc = 138 }, .moves = .{ .{ .id = .Flamethrower, .pp = 0 }, .{ .id = .Disable, .pp = 2 }, .{ .id = .SpikeCannon, .pp = 4 }, .{ .id = .SuperFang, .pp = 0 }, }, .hp = 21, .status = 133, .species = .Squirtle, .types = .{ .type1 = .Water, .type2 = .Water }, }, .{ .stats = .{ .hp = 273, .atk = 158, .def = 178, .spe = 118, .spc = 188 }, .moves = .{ .{ .id = .PinMissile, .pp = 16 }, .{ .id = .Growl, .pp = 40 }, .{ .id = .MirrorMove, .pp = 22 }, .{ .id = .BoneClub, .pp = 4 }, }, .hp = 81, .species = .Porygon, .types = .{ .type1 = .Normal, .type2 = .Normal }, }, .{ .stats = .{ .hp = 335, .atk = 230, .def = 230, .spe = 230, .spc = 230 }, .moves = .{ .{ .id = .TriAttack, .pp = 9 }, .{ .id = .Kinesis, .pp = 0 }, .{ .id = .JumpKick, .pp = 15 }, .{ .id = .PoisonSting, .pp = 13 }, }, .hp = 114, .species = .Mew, .types = .{ .type1 = .Psychic, .type2 = .Psychic }, }, .{ .stats = .{ .hp = 462, .atk = 258, .def = 168, .spe = 98, .spc = 168 }, .moves = .{ .{ .id = .SonicBoom, .pp = 5 }, .{ .id = .PoisonPowder, .pp = 3 }, .{ .id = .Bide, .pp = 2 }, .{ .id = .Headbutt, .pp = 8 }, }, .hp = 135, .status = 2, .species = .Snorlax, .types = .{ .type1 = .Normal, .type2 = .Normal }, } }, .active = .{ .stats = .{ .hp = 233, .atk = 98, .def = 108, .spe = 128, .spc = 76 }, .species = .Caterpie, .types = .{ .type1 = .Bug, .type2 = .Bug }, .boosts = .{ .spc = -2 }, .volatiles = .{ .Thrashing = true, .Confusion = true, .Substitute = true, .LightScreen = true, .attacks = 3, .state = 235, .substitute = 42, .disabled = .{ .move = 2, .duration = 4 }, .confusion = 2, .toxic = 4, }, .moves = .{ .{ .id = .SonicBoom, .pp = 10 }, .{ .id = .Constrict, .pp = 24 }, .{ .id = .Clamp, .pp = 10 }, .{ .id = .HornDrill, .pp = 7 }, }, }, .order = .{ 1, 3, 2, 4, 5, 6 }, .last_selected_move = .JumpKick, .last_used_move = .SpikeCannon, }, .{ .pokemon = .{ .{ .stats = .{ .hp = 281, .atk = 256, .def = 196, .spe = 246, .spc = 146 }, .moves = .{ .{ .id = .Blizzard, .pp = 1 }, .{ .id = .Bind, .pp = 26 }, .{ .id = .DoubleEdge, .pp = 5 }, .{ .id = .Strength, .pp = 9 }, }, .hp = 230, .species = .Scyther, .types = .{ .type1 = .Bug, .type2 = .Flying }, }, .{ .stats = .{ .hp = 289, .atk = 190, .def = 188, .spe = 238, .spc = 238 }, .moves = .{ .{ .id = .HighJumpKick, .pp = 9 }, .{ .id = .NightShade, .pp = 5 }, .{ .id = .HyperFang, .pp = 4 }, .{ .id = .TakeDown, .pp = 26 }, }, .hp = 125, .species = .Ninetales, .types = .{ .type1 = .Fire, .type2 = .Fire }, }, .{ .stats = .{ .hp = 277, .atk = 222, .def = 242, .spe = 152, .spc = 132 }, .moves = .{ .{ .id = .ThunderWave, .pp = 1 }, .{ .id = .FuryAttack, .pp = 17 }, .{ .id = .StringShot, .pp = 52 }, .{ .id = .WingAttack, .pp = 30 }, }, .hp = 23, .species = .Sandslash, .types = .{ .type1 = .Ground, .type2 = .Ground }, }, .{ .stats = .{ .hp = 261, .atk = 146, .def = 136, .spe = 126, .spc = 116 }, .moves = .{ .{ .id = .DefenseCurl, .pp = 45 }, .{ .id = .PoisonGas, .pp = 39 }, .{ .id = .DrillPeck, .pp = 26 }, .{ .id = .Thunderbolt, .pp = 22 }, }, .hp = 133, .species = .Venonat, .types = .{ .type1 = .Bug, .type2 = .Poison }, }, .{ .stats = .{ .hp = 233, .atk = 138, .def = 148, .spe = 98, .spc = 188 }, .moves = .{ .{ .id = .SeismicToss, .pp = 11 }, .{ .id = .DragonRage, .pp = 1 }, .{ .id = .HornAttack, .pp = 6 }, .{ .id = .FirePunch, .pp = 11 }, }, .hp = 193, .status = 2, .species = .Oddish, .types = .{ .type1 = .Grass, .type2 = .Poison }, }, .{ .stats = .{ .hp = 223, .atk = 140, .def = 106, .spe = 126, .spc = 106 }, .moves = .{ .{ .id = .EggBomb, .pp = 6 }, .{ .id = .VineWhip, .pp = 0 }, .{ .id = .Struggle, .pp = 5 }, .{ .id = .IcePunch, .pp = 10 }, }, .hp = 130, .species = .NidoranM, .types = .{ .type1 = .Poison, .type2 = .Poison }, } }, .active = .{ .stats = .{ .hp = 281, .atk = 134, .def = 168, .spe = 124, .spc = 138 }, .species = .Squirtle, .types = .{ .type1 = .Water, .type2 = .Water }, .volatiles = .{ .Bide = true, .Trapping = true, .Transform = true, .attacks = 2, .state = 100, .transform = 0b0011, }, .moves = .{ .{ .id = .Flamethrower, .pp = 5 }, .{ .id = .Disable, .pp = 5 }, .{ .id = .SpikeCannon, .pp = 5 }, .{ .id = .SuperFang, .pp = 5 }, }, }, .order = .{ 1, 2, 3, 4, 5, 6 }, .last_selected_move = .DrillPeck, .last_used_move = .EggBomb, } }, .turn = 609, .last_damage = 84, .last_selected_indexes = .{ .p1 = 2, .p2 = 1 }, .rng = .{ .src = if (pkmn.options.showdown) .{ .seed = 0x31415926 } else .{ .seed = .{ 114, 155, 42, 78, 253, 19, 117, 37, 253, 105 }, .index = 8, } }, }; // DEBUG const assert = std.debug.assert; // https://en.wikipedia.org/wiki/ANSI_escape_code const GREEN = "\x1b[32m"; const YELLOW = "\x1b[33m"; const BOLD = "\x1b[1m"; const DIM = "\x1b[2m"; const RESET = "\x1b[0m"; const COMPACT = 8; const Ais = AutoIndentingStream(std.fs.File.Writer); pub fn elide(value: anytype) bool { return switch (@TypeOf(value)) { pkmn.gen1.MoveSlot => value.id != .None, pkmn.gen1.Pokemon => value.species != .None, else => return true, }; } // Limited and lazy version of NodeJS's util.inspect pub fn inspectN(value: anytype, ais: *Ais, max_depth: usize) !void { const T = @TypeOf(value); const options = std.fmt.FormatOptions{ .alignment = .Left }; switch (@typeInfo(T)) { .ComptimeInt, .Int, .ComptimeFloat, .Float, .Bool => { try ais.writer().writeAll(YELLOW); try std.fmt.formatType(value, "any", options, ais.writer(), max_depth); try ais.writer().writeAll(RESET); }, .Optional => { if (value) |payload| { try inspectN(payload, ais, max_depth); } else { try ais.writer().writeAll(BOLD); try std.fmt.formatBuf("null", options, ais.writer()); try ais.writer().writeAll(RESET); } }, .EnumLiteral => { const buffer = [_]u8{'.'} ++ @tagName(value); try ais.writer().writeAll(GREEN); try std.fmt.formatBuf(buffer, options, ais.writer()); try ais.writer().writeAll(RESET); }, .Null => { try ais.writer().writeAll(BOLD); try std.fmt.formatBuf("null", options, ais.writer()); try ais.writer().writeAll(RESET); }, .ErrorUnion => { if (value) |payload| { try inspectN(payload, ais, max_depth); } else |err| { try inspectN(err, ais, max_depth); } }, .Type => { try ais.writer().writeAll(DIM); try std.fmt.formatBuf(@typeName(value), options, ais.writer()); try ais.writer().writeAll(RESET); }, .Enum => |enumInfo| { try ais.writer().writeAll(GREEN); // try ais.writer().writeAll(@typeName(T)); if (enumInfo.is_exhaustive) { try ais.writer().writeAll("."); try ais.writer().writeAll(@tagName(value)); try ais.writer().writeAll(RESET); return; } // Use @tagName only if value is one of known fields @setEvalBranchQuota(3 * enumInfo.fields.len); inline for (enumInfo.fields) |enumField| { if (@enumToInt(value) == enumField.value) { try ais.writer().writeAll("."); try ais.writer().writeAll(@tagName(value)); try ais.writer().writeAll(RESET); return; } } try ais.writer().writeAll("("); try inspectN(@enumToInt(value), ais, max_depth); try ais.writer().writeAll(")"); try ais.writer().writeAll(RESET); }, .Union => |info| { try ais.writer().writeAll(DIM); try ais.writer().writeAll(@typeName(T)); try ais.writer().writeAll(RESET); if (max_depth == 0) return ais.writer().writeAll(".{ ... }"); if (info.tag_type) |UnionTagType| { try ais.writer().writeAll(".{ ."); try ais.writer().writeAll(@tagName(@as(UnionTagType, value))); try ais.writer().writeAll(" = "); inline for (info.fields) |u_field| { if (value == @field(UnionTagType, u_field.name)) { try inspectN(@field(value, u_field.name), ais, max_depth - 1); } } try ais.writer().writeAll(" }"); } else { try std.fmt.format(ais.writer(), "@{x}", .{@ptrToInt(&value)}); } }, .Struct => |info| { if (info.is_tuple) { // Skip the type and field names when formatting tuples. if (max_depth == 0) return ais.writer().writeAll(".{ ... }"); try ais.writer().writeAll(".{"); inline for (info.fields) |f, i| { if (i == 0) { try ais.writer().writeAll(" "); } else { try ais.writer().writeAll(", "); } try inspectN(@field(value, f.name), ais, max_depth - 1); } return ais.writer().writeAll(" }"); } try ais.writer().writeAll(DIM); try ais.writer().writeAll(@typeName(T)); try ais.writer().writeAll(RESET); if (max_depth == 0) return ais.writer().writeAll(".{ ... }"); const compact = if (info.fields.len > COMPACT) false else inline for (info.fields) |f| { if (!isPrimitive(f.field_type)) break false; } else true; if (compact) { try ais.writer().writeAll(".{ "); } else { try ais.writer().writeAll(".{"); try ais.insertNewline(); ais.pushIndent(); } inline for (info.fields) |f, i| { if (f.default_value) |dv| { // TODO: workaround for ziglang/zig#10766 removing anytype fields const default_value = if (@hasField(@import("std").zig.Ast.Node.Tag, "anytype")) dv else @ptrCast(*const f.field_type, @alignCast(@alignOf(f.field_type), dv)).*; switch (@typeInfo(f.field_type)) { .ComptimeInt, .Int, .ComptimeFloat, .Float, .Bool, .Optional, .ErrorUnion, .Enum, => { if (@field(value, f.name) != default_value) { try ais.writer().writeAll("."); try ais.writer().writeAll(f.name); try ais.writer().writeAll(" = "); try inspectN(@field(value, f.name), ais, max_depth - 1); if (i < info.fields.len - 1) { try ais.writer().writeAll(","); if (compact) { try ais.writer().writeAll(" "); } else { try ais.insertNewline(); } } } }, else => { try ais.writer().writeAll("."); try ais.writer().writeAll(f.name); try ais.writer().writeAll(" = "); try inspectN(@field(value, f.name), ais, max_depth - 1); if (i < info.fields.len - 1) { try ais.writer().writeAll(","); if (compact) { try ais.writer().writeAll(" "); } else { try ais.insertNewline(); } } }, } } else { try ais.writer().writeAll("."); try ais.writer().writeAll(f.name); try ais.writer().writeAll(" = "); try inspectN(@field(value, f.name), ais, max_depth - 1); if (i < info.fields.len - 1) { try ais.writer().writeAll(","); if (compact) { try ais.writer().writeAll(" "); } else { try ais.insertNewline(); } } } } if (compact) { try ais.writer().writeAll(" }"); } else { ais.popIndent(); try ais.insertNewline(); try ais.writer().writeAll("}"); } }, .Array => |info| { if (max_depth == 0) return ais.writer().writeAll(".{ ... }"); const compact = if (value.len > COMPACT) false else isPrimitive(info.child); if (compact) { try ais.writer().writeAll(".{ "); } else { try ais.writer().writeAll(".{"); try ais.insertNewline(); ais.pushIndent(); } for (value) |elem, i| { if (!elide(elem)) continue; try inspectN(elem, ais, max_depth - 1); if (i < value.len - 1) { try ais.writer().writeAll(","); if (compact) { try ais.writer().writeAll(" "); } else { try ais.insertNewline(); } } } if (compact) { try ais.writer().writeAll(" }"); } else { ais.popIndent(); try ais.insertNewline(); try ais.writer().writeAll("}"); } }, .Pointer => |ptr_info| switch (ptr_info.size) { .One => switch (@typeInfo(ptr_info.child)) { .Array => |info| { if (info.child == u8) { try ais.writer().writeAll(GREEN); try std.fmt.formatText(value, "s", options, ais.writer()); try ais.writer().writeAll(RESET); return; } if (comptime std.meta.trait.isZigString(info.child)) { for (value) |item, i| { if (i != 0) try std.fmt.formatText(", ", "s", options, ais.writer()); try std.fmt.formatText(item, "s", options, ais.writer()); } return; } @compileError("Unable to format '" ++ @typeName(T) ++ "'"); }, .Enum, .Union, .Struct => { return inspectN(value.*, ais, max_depth); }, else => return std.fmt.format( ais.writer(), "{s}@{x}", .{ @typeName(ptr_info.child), @ptrToInt(value) }, ), }, .Many, .C => { if (ptr_info.sentinel) |_| { return inspectN(std.mem.span(value), ais, max_depth); } if (ptr_info.child == u8) { try ais.writer().writeAll(GREEN); try std.fmt.formatText(std.mem.span(value), "s", options, ais.writer()); try ais.writer().writeAll(RESET); return; } @compileError("Unable to format '" ++ @typeName(T) ++ "'"); }, .Slice => { if (max_depth == 0) return ais.writer().writeAll(".{ ... }"); if (ptr_info.child == u8) { try ais.writer().writeAll(GREEN); try std.fmt.formatText(value, "s", options, ais.writer()); try ais.writer().writeAll(RESET); return; } // TODO compact try ais.writer().writeAll(".{ "); for (value) |elem, i| { try inspectN(elem, ais, max_depth - 1); if (i != value.len - 1) { try ais.writer().writeAll(", "); } } try ais.writer().writeAll(" }"); }, }, else => @compileError("Unable to format type '" ++ @typeName(T) ++ "'"), // else => { // try std.fmt.formatType(value, "any", options, ais.writer(), max_depth); // }, } } pub fn inspect(value: anytype, writer: anytype) @TypeOf(writer).Error!void { const ais = &Ais{ .indent_delta = 4, .underlying_writer = writer, }; try inspectN(value, ais, 10); } pub fn print(value: anytype) void { std.debug.getStderrMutex().lock(); defer std.debug.getStderrMutex().unlock(); const stderr = std.io.getStdErr().writer(); nosuspend stderr.writeByte('\n') catch return; nosuspend inspect(value, stderr) catch return; // nosuspend stderr.writeByte('\n') catch return; } fn isPrimitive(comptime t: type) bool { return switch (@typeInfo(t)) { .ComptimeInt, .Int, .ComptimeFloat, .Float, .Bool, .Optional, .ErrorUnion, .Enum => true, else => false, }; } // Stripped down version oflin/ std/zig/render.zig's AutoIndentingStream fn AutoIndentingStream(comptime UnderlyingWriter: type) type { return struct { const Self = @This(); pub const WriteError = UnderlyingWriter.Error; pub const Writer = std.io.Writer(*Self, WriteError, write); underlying_writer: UnderlyingWriter, indent_count: usize = 0, indent_delta: usize, current_line_empty: bool = true, pub fn writer(self: *Self) Writer { return .{ .context = self }; } pub fn write(self: *Self, bytes: []const u8) WriteError!usize { if (bytes.len == 0) return @as(usize, 0); try self.applyIndent(); return self.writeNoIndent(bytes); } fn writeNoIndent(self: *Self, bytes: []const u8) WriteError!usize { if (bytes.len == 0) return @as(usize, 0); try self.underlying_writer.writeAll(bytes); if (bytes[bytes.len - 1] == '\n') self.resetLine(); return bytes.len; } pub fn insertNewline(self: *Self) WriteError!void { _ = try self.writeNoIndent("\n"); } fn resetLine(self: *Self) void { self.current_line_empty = true; } pub fn pushIndent(self: *Self) void { self.indent_count += 1; } pub fn popIndent(self: *Self) void { assert(self.indent_count != 0); self.indent_count -= 1; } fn applyIndent(self: *Self) WriteError!void { const current_indent = self.currentIndent(); if (self.current_line_empty and current_indent > 0) { try self.underlying_writer.writeByteNTimes(' ', current_indent); } self.current_line_empty = false; } fn currentIndent(self: *Self) usize { var indent_current: usize = 0; if (self.indent_count > 0) indent_current = self.indent_count * self.indent_delta; return indent_current; } }; }
src/tools/serde.zig
const std = @import("std"); const tvg = @import("tvg"); // pub const everything_16 = blk: { // @setEvalBranchQuota(100_000); // comptime var buf: [2048]u8 = undefined; // var stream = std.io.fixedBufferStream(&buf); // writeEverything(stream.writer(), .default) catch unreachable; // break :blk stream.getWritten(); // }; pub fn main() !void { // try std.fs.cwd().writeFile("examples/app_menu.tvg", &app_menu); // try std.fs.cwd().writeFile("examples/workspace.tvg", &workspace); // try std.fs.cwd().writeFile("examples/workspace_add.tvg", &workspace_add); { var file = try std.fs.cwd().createFile("shield-8.tvg", .{}); defer file.close(); var writer = tvg.builder.create(file.writer()); try writer.writeHeader(24, 24, .@"1/4", .u8888, .reduced); try renderShield(&writer); } { var file = try std.fs.cwd().createFile("shield-16.tvg", .{}); defer file.close(); var writer = tvg.builder.create(file.writer()); try writer.writeHeader(24, 24, .@"1/32", .u8888, .default); try renderShield(&writer); } { var file = try std.fs.cwd().createFile("shield-32.tvg", .{}); defer file.close(); var writer = tvg.builder.create(file.writer()); try writer.writeHeader(24, 24, .@"1/2048", .u8888, .enhanced); try renderShield(&writer); } // try std.fs.cwd().writeFile("examples/arc-variants.tvg", &arc_variants); // try std.fs.cwd().writeFile("examples/feature-showcase.tvg", &feature_showcase); { var file = try std.fs.cwd().createFile("everything.tvg", .{}); defer file.close(); try writeEverything(file.writer(), .default); } { var file = try std.fs.cwd().createFile("everything-32.tvg", .{}); defer file.close(); try writeEverything(file.writer(), .enhanced); } } /// This function renders a new pub fn writeEverything(src_writer: anytype, range: tvg.Range) !void { var writer = tvg.builder.create(src_writer); const Writer = @TypeOf(writer); const padding = 25; const Emitter = struct { const width = 100; fn emitFillPolygon(w: *Writer, dx: f32, dy: f32, style: tvg.Style) !f32 { try w.writeFillPolygon( style, &[_]tvg.Point{ tvg.point(dx, dy), tvg.point(dx + width, dy + 10), tvg.point(dx + 10, dy + 20), tvg.point(dx + width, dy + 30), tvg.point(dx, dy + 40), }, ); return 40; } fn emitOutlineFillPolygon(w: *Writer, dx: f32, dy: f32, style: tvg.Style) !f32 { try w.writeOutlineFillPolygon( style, tvg.Style{ .flat = 3 }, 2.5, &[_]tvg.Point{ tvg.point(dx, dy), tvg.point(dx + width, dy + 10), tvg.point(dx + 10, dy + 20), tvg.point(dx + width, dy + 30), tvg.point(dx, dy + 40), }, ); return 40; } fn emitFillRectangles(w: *Writer, dx: f32, dy: f32, style: tvg.Style) !f32 { try w.writeFillRectangles(style, &[_]tvg.Rectangle{ tvg.rectangle(dx, dy, width, 15), tvg.rectangle(dx, dy + 20, width, 15), tvg.rectangle(dx, dy + 40, width, 15), }); return 55; } fn emitDrawLines(w: *Writer, dx: f32, dy: f32, style: tvg.Style) !f32 { try w.writeDrawLines( style, 2.5, &[_]tvg.Line{ tvg.line(tvg.point(dx, dy), tvg.point(dx + width, dy + 10)), tvg.line(tvg.point(dx, dy + 10), tvg.point(dx + width, dy + 20)), tvg.line(tvg.point(dx, dy + 20), tvg.point(dx + width, dy + 30)), tvg.line(tvg.point(dx, dy + 30), tvg.point(dx + width, dy + 40)), }, ); return 40; } fn emitDrawLineLoop(w: *Writer, dx: f32, dy: f32, style: tvg.Style) !f32 { try w.writeDrawLineLoop( style, 2.5, &[_]tvg.Point{ tvg.point(dx, dy), tvg.point(dx + width, dy + 10), tvg.point(dx + 10, dy + 20), tvg.point(dx + width, dy + 30), tvg.point(dx, dy + 40), }, ); return 40; } fn emitDrawLineStrip(w: *Writer, dx: f32, dy: f32, style: tvg.Style) !f32 { try w.writeDrawLineStrip( style, 2.5, &[_]tvg.Point{ tvg.point(dx, dy), tvg.point(dx + width, dy + 10), tvg.point(dx + 10, dy + 20), tvg.point(dx + width, dy + 30), tvg.point(dx, dy + 40), }, ); return 40; } fn emitOutlineFillRectangles(w: *Writer, dx: f32, dy: f32, style: tvg.Style) !f32 { try w.writeOutlineFillRectangles( style, tvg.Style{ .flat = 3 }, 2.5, &[_]tvg.Rectangle{ tvg.rectangle(dx, dy, width, 15), tvg.rectangle(dx, dy + 20, width, 15), tvg.rectangle(dx, dy + 40, width, 15), }, ); return 55; } fn emitDrawPath(w: *Writer, x: f32, y: f32, style: tvg.Style) !f32 { const Node = tvg.Path.Node; try w.writeDrawPath(style, 3.5, &[_]tvg.Path.Segment{ tvg.Path.Segment{ .start = tvg.point(x, y), .commands = &[_]Node{ Node{ .horiz = .{ .line_width = 3.5, .data = x + 10 } }, // H 10 Node{ .vert = .{ .line_width = 3.5, .data = y + 10 } }, // V 10 Node{ .horiz = .{ .line_width = 3.5, .data = x + 20 } }, // H 20 Node{ .line = .{ .line_width = 1.5, .data = tvg.point(x + 100, y) } }, // L 100 1 Node{ .bezier = .{ .line_width = 2.5, .data = .{ .c0 = tvg.point(x + 75, y + 20), .c1 = tvg.point(x + 90, y + 50), .p1 = tvg.point(x + 75, y + 50) } } }, // C 75 20 91 50 75 50 Node{ .quadratic_bezier = .{ .line_width = 4.5, .data = .{ .c = tvg.point(x + 50, y + 50), .p1 = tvg.point(x + 50, y + 25) } } }, // Q 50 50 50 25 Node{ .arc_ellipse = .{ .line_width = 2.5, .data = .{ .radius_x = 35.0, .radius_y = 50.0, .rotation = 1.5, .large_arc = false, .sweep = true, .target = tvg.point(x + 25, y + 35) } } }, // A 0.7 1 20 0 0 25 35 Node{ .arc_circle = .{ .line_width = 1.5, .data = .{ .radius = 14.0, .large_arc = false, .sweep = false, .target = tvg.point(x, y + 25) } } }, // A 1 1 0 0 1 0 35 Node{ .close = .{ .line_width = 3.5, .data = {} } }, // Z }, }, }); return 50; } fn emitFillPath(w: *Writer, x: f32, y: f32, style: tvg.Style) !f32 { const Node = tvg.Path.Node; try w.writeFillPath(style, &[_]tvg.Path.Segment{ tvg.Path.Segment{ .start = tvg.point(x, y), .commands = &[_]Node{ Node{ .horiz = .{ .data = x + 10 } }, // H 10 Node{ .vert = .{ .data = y + 10 } }, // V 10 Node{ .horiz = .{ .data = x + 20 } }, // H 20 Node{ .line = .{ .data = tvg.point(x + 100, y) } }, // L 100 1 Node{ .bezier = .{ .data = .{ .c0 = tvg.point(x + 75, y + 20), .c1 = tvg.point(x + 90, y + 50), .p1 = tvg.point(x + 75, y + 50) } } }, // C 75 20 91 50 75 50 Node{ .quadratic_bezier = .{ .data = .{ .c = tvg.point(x + 50, y + 50), .p1 = tvg.point(x + 50, y + 25) } } }, // Q 50 50 50 25 Node{ .arc_ellipse = .{ .data = .{ .radius_x = 35.0, .radius_y = 50.0, .rotation = 1.5, .large_arc = false, .sweep = true, .target = tvg.point(x + 25, y + 35) } } }, // A 0.7 1 20 0 0 25 35 Node{ .arc_circle = .{ .data = .{ .radius = 14.0, .large_arc = false, .sweep = false, .target = tvg.point(x, y + 25) } } }, // A 1 1 0 0 1 0 35 Node{ .close = .{ .data = {} } }, // Z }, }, }); return 50; } fn emitOutlineFillPath(w: *Writer, x: f32, y: f32, style: tvg.Style) !f32 { const Node = tvg.Path.Node; try w.writeOutlineFillPath(style, tvg.Style{ .flat = 3 }, 2.5, &[_]tvg.Path.Segment{ tvg.Path.Segment{ .start = tvg.point(x, y), .commands = &[_]Node{ Node{ .horiz = .{ .data = x + 10 } }, // H 10 Node{ .vert = .{ .data = y + 10 } }, // V 10 Node{ .horiz = .{ .data = x + 20 } }, // H 20 Node{ .line = .{ .data = tvg.point(x + 100, y) } }, // L 100 1 Node{ .bezier = .{ .data = .{ .c0 = tvg.point(x + 75, y + 20), .c1 = tvg.point(x + 90, y + 50), .p1 = tvg.point(x + 75, y + 50) } } }, // C 75 20 91 50 75 50 Node{ .quadratic_bezier = .{ .data = .{ .c = tvg.point(x + 50, y + 50), .p1 = tvg.point(x + 50, y + 25) } } }, // Q 50 50 50 25 Node{ .arc_ellipse = .{ .data = .{ .radius_x = 35.0, .radius_y = 50.0, .rotation = 1.5, .large_arc = false, .sweep = true, .target = tvg.point(x + 25, y + 35) } } }, // A 0.7 1 20 0 0 25 35 Node{ .arc_circle = .{ .data = .{ .radius = 14.0, .large_arc = false, .sweep = false, .target = tvg.point(x, y + 25) } } }, // A 1 1 0 0 1 0 35 Node{ .close = .{ .data = {} } }, // Z }, }, }); return 50; } }; const items = [_]fn (*Writer, f32, f32, tvg.Style) Writer.Error!f32{ Emitter.emitFillRectangles, Emitter.emitOutlineFillRectangles, Emitter.emitDrawLines, Emitter.emitDrawLineLoop, Emitter.emitDrawLineStrip, Emitter.emitFillPolygon, Emitter.emitOutlineFillPolygon, Emitter.emitDrawPath, Emitter.emitFillPath, Emitter.emitOutlineFillPath, }; var style_base = [_]tvg.Style{ tvg.Style{ .flat = 0 }, tvg.Style{ .linear = .{ .point_0 = tvg.point(0, 0), .point_1 = tvg.point(Emitter.width, 50), .color_0 = 1, .color_1 = 2, } }, tvg.Style{ .radial = .{ .point_0 = tvg.point(50, 25), .point_1 = tvg.point(Emitter.width, 50), .color_0 = 1, .color_1 = 2, } }, }; try writer.writeHeader(3 * Emitter.width + 4 * padding, 768, .@"1/32", .u8888, range); try writer.writeColorTable(&[_]tvg.Color{ try tvg.Color.fromString("e7a915"), // 0 yellow try tvg.Color.fromString("ff7800"), // 1 orange try tvg.Color.fromString("40ff00"), // 2 green try tvg.Color.fromString("ba004d"), // 3 reddish purple try tvg.Color.fromString("62009e"), // 4 blueish purple try tvg.Color.fromString("94e538"), // 5 grass green }); var dx: f32 = padding; for (style_base) |style_example| { var dy: f32 = padding; for (items) |item| { var style = style_example; switch (style) { .flat => {}, .linear, .radial => |*grad| { grad.point_0.x += dx; grad.point_0.y += dy; grad.point_1.x += dx; grad.point_1.y += dy; }, } const height = try item(&writer, dx, dy, style); dy += (height + padding); } dx += (Emitter.width + padding); } try writer.writeEndOfFile(); } pub fn renderShield(writer: anytype) !void { const Node = tvg.Path.Node; // header is already written here try writer.writeColorTable(&[_]tvg.Color{ try tvg.Color.fromString("29adff"), try tvg.Color.fromString("fff1e8"), }); try writer.writeFillPath( tvg.Style{ .flat = 0 }, &[_]tvg.Path.Segment{ tvg.Path.Segment{ .start = tvg.Point{ .x = 12, .y = 1 }, .commands = &[_]Node{ Node{ .line = .{ .data = tvg.point(3, 5) } }, Node{ .vert = .{ .data = 11 } }, Node{ .bezier = .{ .data = Node.Bezier{ .c0 = tvg.point(3, 16.55), .c1 = tvg.point(6.84, 21.74), .p1 = tvg.point(12, 23) } } }, Node{ .bezier = .{ .data = Node.Bezier{ .c0 = tvg.point(17.16, 21.74), .c1 = tvg.point(21, 16.55), .p1 = tvg.point(21, 11) } } }, Node{ .vert = .{ .data = 5 } }, }, }, tvg.Path.Segment{ .start = tvg.Point{ .x = 17.13, .y = 17 }, .commands = &[_]Node{ Node{ .bezier = .{ .data = Node.Bezier{ .c0 = tvg.point(15.92, 18.85), .c1 = tvg.point(14.11, 20.24), .p1 = tvg.point(12, 20.92) } } }, Node{ .bezier = .{ .data = Node.Bezier{ .c0 = tvg.point(9.89, 20.24), .c1 = tvg.point(8.08, 18.85), .p1 = tvg.point(6.87, 17) } } }, Node{ .bezier = .{ .data = Node.Bezier{ .c0 = tvg.point(6.53, 16.5), .c1 = tvg.point(6.24, 16), .p1 = tvg.point(6, 15.47) } } }, Node{ .bezier = .{ .data = Node.Bezier{ .c0 = tvg.point(6, 13.82), .c1 = tvg.point(8.71, 12.47), .p1 = tvg.point(12, 12.47) } } }, Node{ .bezier = .{ .data = Node.Bezier{ .c0 = tvg.point(15.29, 12.47), .c1 = tvg.point(18, 13.79), .p1 = tvg.point(18, 15.47) } } }, Node{ .bezier = .{ .data = Node.Bezier{ .c0 = tvg.point(17.76, 16), .c1 = tvg.point(17.47, 16.5), .p1 = tvg.point(17.13, 17) } } }, }, }, tvg.Path.Segment{ .start = tvg.Point{ .x = 12, .y = 5 }, .commands = &[_]Node{ Node{ .bezier = .{ .data = Node.Bezier{ .c0 = tvg.point(13.5, 5), .c1 = tvg.point(15, 6.2), .p1 = tvg.point(15, 8) } } }, Node{ .bezier = .{ .data = Node.Bezier{ .c0 = tvg.point(15, 9.5), .c1 = tvg.point(13.8, 10.998), .p1 = tvg.point(12, 11) } } }, Node{ .bezier = .{ .data = Node.Bezier{ .c0 = tvg.point(10.5, 11), .c1 = tvg.point(9, 9.8), .p1 = tvg.point(9, 8) } } }, Node{ .bezier = .{ .data = Node.Bezier{ .c0 = tvg.point(9, 6.4), .c1 = tvg.point(10.2, 5), .p1 = tvg.point(12, 5) } } }, }, }, }, ); try writer.writeEndOfFile(); } // const builder = tvg.comptime_builder(.@"1/256", .default); // const builder_16 = tvg.comptime_builder(.@"1/16", .default); // pub const app_menu = blk: { // @setEvalBranchQuota(10_000); // break :blk builder.header(48, 48) ++ // builder.colorTable(&[_]tvg.Color{ // tvg.Color.fromString("000000") catch unreachable, // }) ++ // builder.fillRectangles(3, .flat, 0) ++ // builder.rectangle(6, 12, 36, 4) ++ // builder.rectangle(6, 22, 36, 4) ++ // builder.rectangle(6, 32, 36, 4) ++ // builder.end_of_document; // }; // pub const workspace = blk: { // @setEvalBranchQuota(10_000); // break :blk builder.header(48, 48) ++ // builder.colorTable(&[_]tvg.Color{ // tvg.Color.fromString("008751") catch unreachable, // tvg.Color.fromString("83769c") catch unreachable, // tvg.Color.fromString("1d2b53") catch unreachable, // }) ++ // builder.fillRectangles(1, .flat, 0) ++ // builder.rectangle(6, 6, 16, 36) ++ // builder.fillRectangles(1, .flat, 1) ++ // builder.rectangle(26, 6, 16, 16) ++ // builder.fillRectangles(1, .flat, 2) ++ // builder.rectangle(26, 26, 16, 16) ++ // builder.end_of_document; // }; // pub const workspace_add = blk: { // @setEvalBranchQuota(10_000); // break :blk builder.header(48, 48) ++ // builder.colorTable(&[_]tvg.Color{ // tvg.Color.fromString("008751") catch unreachable, // tvg.Color.fromString("83769c") catch unreachable, // tvg.Color.fromString("ff004d") catch unreachable, // }) ++ // builder.fillRectangles(1, .flat, 0) ++ // builder.rectangle(6, 6, 16, 36) ++ // builder.fillRectangles(1, .flat, 1) ++ // builder.rectangle(26, 6, 16, 16) ++ // builder.fillPath(1, .flat, 2) ++ // builder.uint(11) ++ // builder.point(26, 32) ++ // builder.path.horiz(32) ++ // builder.path.vert(26) ++ // builder.path.horiz(36) ++ // builder.path.vert(32) ++ // builder.path.horiz(42) ++ // builder.path.vert(36) ++ // builder.path.horiz(36) ++ // builder.path.vert(42) ++ // builder.path.horiz(32) ++ // builder.path.vert(36) ++ // builder.path.horiz(26) ++ // builder.end_of_document; // }; // fn makeShield(comptime b: type) type { // @setEvalBranchQuota(10_000); // const icon = b.header(24, 24) ++ // b.colorTable(&[_]tvg.Color{ // tvg.Color.fromString("29adff") catch unreachable, // tvg.Color.fromString("fff1e8") catch unreachable, // }) ++ // // tests even_odd rule // b.fillPath(3, .flat, 0) ++ // b.uint(5) ++ // 0 // b.uint(6) ++ // 1 // b.uint(4) ++ // 2 // b.point(12, 1) ++ // M 12 1 // b.path.line(3, 5) ++ // L 3 5 // b.path.vert(11) ++ // V 11 // b.path.bezier(3, 16.55, 6.84, 21.74, 12, 23) ++ // C 3 16.55 6.84 21.74 12 23 // b.path.bezier(17.16, 21.74, 21, 16.55, 21, 11) ++ // C 17.16 21.74 21 16.55 21 11 // b.path.vert(5) ++ // V 5 // // b.fillPath(1, .flat, 1) ++ // // b.uint(6) ++ // b.point(17.13, 17) ++ // M 12 1 // b.path.bezier(15.92, 18.85, 14.11, 20.24, 12, 20.92) ++ // b.path.bezier(9.89, 20.24, 8.08, 18.85, 6.87, 17) ++ // b.path.bezier(6.53, 16.5, 6.24, 16, 6, 15.47) ++ // b.path.bezier(6, 13.82, 8.71, 12.47, 12, 12.47) ++ // b.path.bezier(15.29, 12.47, 18, 13.79, 18, 15.47) ++ // b.path.bezier(17.76, 16, 17.47, 16.5, 17.13, 17) ++ // // b.fillPath(1, .flat, 1) ++ // // b.uint(4) ++ // b.point(12, 5) ++ // b.path.bezier(13.5, 5, 15, 6.2, 15, 8) ++ // b.path.bezier(15, 9.5, 13.8, 10.998, 12, 11) ++ // b.path.bezier(10.5, 11, 9, 9.8, 9, 8) ++ // b.path.bezier(9, 6.4, 10.2, 5, 12, 5) ++ // b.end_of_document; // return struct { // const data = icon; // }; // } // pub const shield = makeShield(builder).data; // pub const shield_8 = makeShield(tvg.comptime_builder(.@"1/4", .reduced)).data; // pub const shield_32 = makeShield(tvg.comptime_builder(.@"1/2048", .enhanced)).data; // pub const arc_variants = builder.header(92, 92) ++ // builder.colorTable(&[_]tvg.Color{tvg.Color.fromString("40ff00") catch unreachable}) ++ // builder.fillPath(1, .flat, 0) ++ // builder.uint(8) ++ // builder.point(48, 32) ++ // builder.path.horiz(64) ++ // builder.path.arc_ellipse(18.5, 18.5, 0, false, true, 80, 48) ++ // builder.path.vert(64) ++ // builder.path.arc_ellipse(18.5, 18.5, 0, false, false, 64, 80) ++ // builder.path.horiz(48) ++ // builder.path.arc_ellipse(18.5, 18.5, 0, true, true, 32, 64) ++ // builder.path.vert(64) ++ // builder.path.arc_ellipse(18.5, 18.5, 0, true, false, 48, 32) ++ // builder.end_of_document; // pub const feature_showcase = blk: { // @setEvalBranchQuota(20_000); // break :blk builder_16.header(1024, 1024) ++ // builder_16.colorTable(&[_]tvg.Color{ // tvg.Color.fromString("e7a915") catch unreachable, // 0 yellow // tvg.Color.fromString("ff7800") catch unreachable, // 1 orange // tvg.Color.fromString("40ff00") catch unreachable, // 2 green // tvg.Color.fromString("ba004d") catch unreachable, // 3 reddish purple // tvg.Color.fromString("62009e") catch unreachable, // 4 blueish purple // tvg.Color.fromString("94e538") catch unreachable, // 5 grass green // }) ++ // // FILL RECTANGLE // builder_16.fillRectangles(2, .flat, 0) ++ // builder_16.rectangle(16, 16, 64, 48) ++ // builder_16.rectangle(96, 16, 64, 48) ++ // builder_16.fillRectangles(2, .linear, .{ // .point_0 = .{ .x = 32, .y = 80 }, // .point_1 = .{ .x = 144, .y = 128 }, // .color_0 = 1, // .color_1 = 2, // }) ++ // builder_16.rectangle(16, 80, 64, 48) ++ // builder_16.rectangle(96, 80, 64, 48) ++ // builder_16.fillRectangles(2, .radial, .{ // .point_0 = .{ .x = 80, .y = 144 }, // .point_1 = .{ .x = 48, .y = 176 }, // .color_0 = 1, // .color_1 = 2, // }) ++ // builder_16.rectangle(16, 144, 64, 48) ++ // builder_16.rectangle(96, 144, 64, 48) ++ // // FILL POLYGON // builder_16.fillPolygon(7, .flat, 3) ++ // builder_16.point(192, 32) ++ // builder_16.point(208, 16) ++ // builder_16.point(240, 16) ++ // builder_16.point(256, 32) ++ // builder_16.point(256, 64) ++ // builder_16.point(224, 48) ++ // builder_16.point(192, 64) ++ // builder_16.fillPolygon(7, .linear, .{ // .point_0 = .{ .x = 224, .y = 80 }, // .point_1 = .{ .x = 224, .y = 128 }, // .color_0 = 3, // .color_1 = 4, // }) ++ // builder_16.point(192, 96) ++ // builder_16.point(208, 80) ++ // builder_16.point(240, 80) ++ // builder_16.point(256, 96) ++ // builder_16.point(256, 128) ++ // builder_16.point(224, 112) ++ // builder_16.point(192, 128) ++ // builder_16.fillPolygon(7, .radial, .{ // .point_0 = .{ .x = 224, .y = 144 }, // .point_1 = .{ .x = 224, .y = 192 }, // .color_0 = 3, // .color_1 = 4, // }) ++ // builder_16.point(192, 160) ++ // builder_16.point(208, 144) ++ // builder_16.point(240, 144) ++ // builder_16.point(256, 160) ++ // builder_16.point(256, 192) ++ // builder_16.point(224, 176) ++ // builder_16.point(192, 192) ++ // // FILL PATH // builder_16.fillPath(1, .flat, 5) ++ // builder.uint(10) ++ // builder_16.point(288, 64) ++ // builder_16.path.vert(32) ++ // builder_16.path.bezier(288, 24, 288, 16, 304, 16) ++ // builder_16.path.horiz(336) ++ // builder_16.path.bezier(352, 16, 352, 24, 352, 32) ++ // builder_16.path.vert(64) ++ // builder_16.path.line(336, 48) ++ // this should be an arc segment // builder_16.path.line(320, 32) ++ // builder_16.path.line(312, 48) ++ // builder_16.path.line(304, 64) ++ // this should be an arc segment // builder_16.path.close() ++ // builder_16.fillPath(1, .linear, .{ // .point_0 = .{ .x = 320, .y = 80 }, // .point_1 = .{ .x = 320, .y = 128 }, // .color_0 = 3, // .color_1 = 4, // }) ++ // builder.uint(10) ++ // builder_16.point(288, 64 + 64) ++ // builder_16.path.vert(64 + 32) ++ // builder_16.path.bezier(288, 64 + 24, 288, 64 + 16, 304, 64 + 16) ++ // builder_16.path.horiz(336) ++ // builder_16.path.bezier(352, 64 + 16, 352, 64 + 24, 352, 64 + 32) ++ // builder_16.path.vert(64 + 64) ++ // builder_16.path.line(336, 64 + 48) ++ // this should be an arc segment // builder_16.path.line(320, 64 + 32) ++ // builder_16.path.line(312, 64 + 48) ++ // builder_16.path.line(304, 64 + 64) ++ // this should be an arc segment // builder_16.path.close() ++ // builder_16.fillPath(1, .radial, .{ // .point_0 = .{ .x = 320, .y = 144 }, // .point_1 = .{ .x = 320, .y = 192 }, // .color_0 = 3, // .color_1 = 4, // }) ++ // builder.uint(10) ++ // builder_16.point(288, 128 + 64) ++ // builder_16.path.vert(128 + 32) ++ // builder_16.path.bezier(288, 128 + 24, 288, 128 + 16, 304, 128 + 16) ++ // builder_16.path.horiz(336) ++ // builder_16.path.bezier(352, 128 + 16, 352, 128 + 24, 352, 128 + 32) ++ // builder_16.path.vert(128 + 64) ++ // builder_16.path.line(336, 128 + 48) ++ // this should be an arc segment // builder_16.path.line(320, 128 + 32) ++ // builder_16.path.line(312, 128 + 48) ++ // builder_16.path.line(304, 128 + 64) ++ // this should be an arc segment // builder_16.path.close() ++ // // DRAW LINES // builder_16.drawLines(4, 0.0, .flat, 1) ++ // builder_16.point(16 + 0, 224 + 0) ++ builder_16.point(16 + 64, 224 + 0) ++ // builder_16.point(16 + 0, 224 + 16) ++ builder_16.point(16 + 64, 224 + 16) ++ // builder_16.point(16 + 0, 224 + 32) ++ builder_16.point(16 + 64, 224 + 32) ++ // builder_16.point(16 + 0, 224 + 48) ++ builder_16.point(16 + 64, 224 + 48) ++ // builder_16.drawLines(4, 3.0, .linear, .{ // .point_0 = .{ .x = 48, .y = 304 }, // .point_1 = .{ .x = 48, .y = 352 }, // .color_0 = 3, // .color_1 = 4, // }) ++ // builder_16.point(16 + 0, 304 + 0) ++ builder_16.point(16 + 64, 304 + 0) ++ // builder_16.point(16 + 0, 304 + 16) ++ builder_16.point(16 + 64, 304 + 16) ++ // builder_16.point(16 + 0, 304 + 32) ++ builder_16.point(16 + 64, 304 + 32) ++ // builder_16.point(16 + 0, 304 + 48) ++ builder_16.point(16 + 64, 304 + 48) ++ // builder_16.drawLines(4, 6.0, .radial, .{ // .point_0 = .{ .x = 48, .y = 408 }, // .point_1 = .{ .x = 48, .y = 432 }, // .color_0 = 3, // .color_1 = 4, // }) ++ // builder_16.point(16 + 0, 384 + 0) ++ builder_16.point(16 + 64, 384 + 0) ++ // builder_16.point(16 + 0, 384 + 16) ++ builder_16.point(16 + 64, 384 + 16) ++ // builder_16.point(16 + 0, 384 + 32) ++ builder_16.point(16 + 64, 384 + 32) ++ // builder_16.point(16 + 0, 384 + 48) ++ builder_16.point(16 + 64, 384 + 48) ++ // // DRAW LINE STRIP // builder_16.drawLineStrip(8, 3.0, .flat, 1) ++ // builder_16.point(96 + 0, 224 + 0) ++ // builder_16.point(96 + 64, 224 + 0) ++ // builder_16.point(96 + 64, 224 + 16) ++ // builder_16.point(96 + 0, 224 + 16) ++ // builder_16.point(96 + 0, 224 + 32) ++ // builder_16.point(96 + 64, 224 + 32) ++ // builder_16.point(96 + 64, 224 + 48) ++ // builder_16.point(96 + 0, 224 + 48) ++ // builder_16.drawLineStrip(8, 6.0, .linear, .{ // .point_0 = .{ .x = 128, .y = 304 }, // .point_1 = .{ .x = 128, .y = 352 }, // .color_0 = 3, // .color_1 = 4, // }) ++ // builder_16.point(96 + 0, 304 + 0) ++ // builder_16.point(96 + 64, 304 + 0) ++ // builder_16.point(96 + 64, 304 + 16) ++ // builder_16.point(96 + 0, 304 + 16) ++ // builder_16.point(96 + 0, 304 + 32) ++ // builder_16.point(96 + 64, 304 + 32) ++ // builder_16.point(96 + 64, 304 + 48) ++ // builder_16.point(96 + 0, 304 + 48) ++ // builder_16.drawLineStrip(8, 0.0, .radial, .{ // .point_0 = .{ .x = 128, .y = 408 }, // .point_1 = .{ .x = 128, .y = 432 }, // .color_0 = 3, // .color_1 = 4, // }) ++ // builder_16.point(96 + 0, 384 + 0) ++ // builder_16.point(96 + 64, 384 + 0) ++ // builder_16.point(96 + 64, 384 + 16) ++ // builder_16.point(96 + 0, 384 + 16) ++ // builder_16.point(96 + 0, 384 + 32) ++ // builder_16.point(96 + 64, 384 + 32) ++ // builder_16.point(96 + 64, 384 + 48) ++ // builder_16.point(96 + 0, 384 + 48) ++ // // DRAW LINE LOOP // builder_16.drawLineLoop(8, 6.0, .flat, 1) ++ // builder_16.point(176 + 0, 224 + 0) ++ // builder_16.point(176 + 64, 224 + 0) ++ // builder_16.point(176 + 64, 224 + 16) ++ // builder_16.point(176 + 16, 224 + 16) ++ // builder_16.point(176 + 16, 224 + 32) ++ // builder_16.point(176 + 64, 224 + 32) ++ // builder_16.point(176 + 64, 224 + 48) ++ // builder_16.point(176 + 0, 224 + 48) ++ // builder_16.drawLineLoop(8, 0.0, .linear, .{ // .point_0 = .{ .x = 208, .y = 304 }, // .point_1 = .{ .x = 208, .y = 352 }, // .color_0 = 3, // .color_1 = 4, // }) ++ // builder_16.point(176 + 0, 304 + 0) ++ // builder_16.point(176 + 64, 304 + 0) ++ // builder_16.point(176 + 64, 304 + 16) ++ // builder_16.point(176 + 16, 304 + 16) ++ // builder_16.point(176 + 16, 304 + 32) ++ // builder_16.point(176 + 64, 304 + 32) ++ // builder_16.point(176 + 64, 304 + 48) ++ // builder_16.point(176 + 0, 304 + 48) ++ // builder_16.drawLineLoop(8, 3.0, .radial, .{ // .point_0 = .{ .x = 208, .y = 408 }, // .point_1 = .{ .x = 208, .y = 432 }, // .color_0 = 3, // .color_1 = 4, // }) ++ // builder_16.point(176 + 0, 384 + 0) ++ // builder_16.point(176 + 64, 384 + 0) ++ // builder_16.point(176 + 64, 384 + 16) ++ // builder_16.point(176 + 16, 384 + 16) ++ // builder_16.point(176 + 16, 384 + 32) ++ // builder_16.point(176 + 64, 384 + 32) ++ // builder_16.point(176 + 64, 384 + 48) ++ // builder_16.point(176 + 0, 384 + 48) ++ // // DRAW LINE PATH // builder_16.drawPath(1, 0.0, .flat, 1) ++ // builder.uint(10) ++ // builder_16.point(256 + 0, 224 + 0) ++ // builder_16.path.horiz(256 + 48) ++ // builder_16.path.bezier(256 + 64, 224 + 0, 256 + 64, 224 + 16, 256 + 48, 224 + 16) ++ // builder_16.path.horiz(256 + 32) ++ // builder_16.path.line(256 + 16, 224 + 24) ++ // builder_16.path.line(256 + 32, 224 + 32) ++ // builder_16.path.line(256 + 64, 224 + 32) ++ // this is arc-ellipse later // builder_16.path.line(256 + 48, 224 + 48) ++ // this is arc-circle later // builder_16.path.horiz(256 + 16) ++ // builder_16.path.line(256 + 0, 224 + 32) ++ // this is arc-circle later // builder_16.path.close() ++ // builder_16.drawPath(1, 6.0, .linear, .{ // .point_0 = .{ .x = 288, .y = 408 }, // .point_1 = .{ .x = 288, .y = 432 }, // .color_0 = 3, // .color_1 = 4, // }) ++ // builder.uint(10) ++ // builder_16.point(256 + 0, 304 + 0) ++ // builder_16.path.horiz(256 + 48) ++ // builder_16.path.bezier(256 + 64, 304 + 0, 256 + 64, 304 + 16, 256 + 48, 304 + 16) ++ // builder_16.path.horiz(256 + 32) ++ // builder_16.path.line(256 + 16, 304 + 24) ++ // builder_16.path.line(256 + 32, 304 + 32) ++ // builder_16.path.line(256 + 64, 304 + 32) ++ // this is arc-ellipse later // builder_16.path.line(256 + 48, 304 + 48) ++ // this is arc-circle later // builder_16.path.horiz(256 + 16) ++ // builder_16.path.line(256 + 0, 304 + 32) ++ // this is arc-circle later // builder_16.path.close() ++ // builder_16.drawPath(1, 3.0, .radial, .{ // .point_0 = .{ .x = 288, .y = 408 }, // .point_1 = .{ .x = 288, .y = 432 }, // .color_0 = 3, // .color_1 = 4, // }) ++ // builder.uint(10) ++ // builder_16.point(256 + 0, 384 + 0) ++ // builder_16.path.horiz(256 + 48) ++ // builder_16.path.bezier(256 + 64, 384 + 0, 256 + 64, 384 + 16, 256 + 48, 384 + 16) ++ // builder_16.path.horiz(256 + 32) ++ // builder_16.path.line(256 + 16, 384 + 24) ++ // builder_16.path.line(256 + 32, 384 + 32) ++ // builder_16.path.line(256 + 64, 384 + 32) ++ // this is arc-ellipse later // builder_16.path.line(256 + 48, 384 + 48) ++ // this is arc-circle later // builder_16.path.horiz(256 + 16) ++ // builder_16.path.line(256 + 0, 384 + 32) ++ // this is arc-circle later // builder_16.path.close() ++ // // Outline Fill Rectangle // builder_16.outlineFillRectangles(1, 0.0, .flat, 0, .flat, 3) ++ // builder_16.rectangle(384, 16, 64, 48) ++ // builder_16.outlineFillRectangles(1, 1.0, .flat, 0, .linear, .{ .point_0 = .{ .x = 416, .y = 80 }, .point_1 = .{ .x = 416, .y = 128 }, .color_0 = 3, .color_1 = 4 }) ++ // builder_16.rectangle(384, 80, 64, 48) ++ // builder_16.outlineFillRectangles(1, 2.0, .flat, 0, .radial, .{ .point_0 = .{ .x = 416, .y = 168 }, .point_1 = .{ .x = 416, .y = 216 }, .color_0 = 3, .color_1 = 4 }) ++ // builder_16.rectangle(384, 144, 64, 48) ++ // builder_16.outlineFillRectangles(1, 3.0, .linear, .{ .point_0 = .{ .x = 496, .y = 16 }, .point_1 = .{ .x = 496, .y = 64 }, .color_0 = 1, .color_1 = 2 }, .flat, 3) ++ // builder_16.rectangle(464, 16, 64, 48) ++ // builder_16.outlineFillRectangles(1, 4.0, .linear, .{ .point_0 = .{ .x = 496, .y = 80 }, .point_1 = .{ .x = 496, .y = 128 }, .color_0 = 1, .color_1 = 2 }, .linear, .{ .point_0 = .{ .x = 496, .y = 80 }, .point_1 = .{ .x = 496, .y = 128 }, .color_0 = 3, .color_1 = 4 }) ++ // builder_16.rectangle(464, 80, 64, 48) ++ // builder_16.outlineFillRectangles(1, 5.0, .linear, .{ .point_0 = .{ .x = 496, .y = 144 }, .point_1 = .{ .x = 496, .y = 192 }, .color_0 = 1, .color_1 = 2 }, .radial, .{ .point_0 = .{ .x = 496, .y = 168 }, .point_1 = .{ .x = 496, .y = 216 }, .color_0 = 3, .color_1 = 4 }) ++ // builder_16.rectangle(464, 144, 64, 48) ++ // builder_16.outlineFillRectangles(1, 6.0, .radial, .{ .point_0 = .{ .x = 576, .y = 40 }, .point_1 = .{ .x = 576, .y = 88 }, .color_0 = 1, .color_1 = 2 }, .flat, 3) ++ // builder_16.rectangle(544, 16, 64, 48) ++ // builder_16.outlineFillRectangles(1, 7.0, .radial, .{ .point_0 = .{ .x = 576, .y = 104 }, .point_1 = .{ .x = 576, .y = 150 }, .color_0 = 1, .color_1 = 2 }, .linear, .{ .point_0 = .{ .x = 576, .y = 80 }, .point_1 = .{ .x = 576, .y = 128 }, .color_0 = 3, .color_1 = 4 }) ++ // builder_16.rectangle(544, 80, 64, 48) ++ // builder_16.outlineFillRectangles(1, 8.0, .radial, .{ .point_0 = .{ .x = 576, .y = 168 }, .point_1 = .{ .x = 576, .y = 216 }, .color_0 = 1, .color_1 = 2 }, .radial, .{ .point_0 = .{ .x = 576, .y = 168 }, .point_1 = .{ .x = 576, .y = 216 }, .color_0 = 3, .color_1 = 4 }) ++ // builder_16.rectangle(544, 144, 64, 48) ++ // // Outline Fill Polygon // // TODO // // PATH WITH ARC (ELLIPSE) // builder_16.drawPath(1, 2.0, .flat, 1) ++ // builder.uint(3) ++ // builder_16.point(16 + 0, 464 + 0) ++ // builder_16.path.line(16 + 16, 464 + 16) ++ // builder_16.path.arc_ellipse(25, 45, 15, false, false, 16 + 48, 464 + 48) ++ // builder_16.path.line(16 + 64, 464 + 64) ++ // builder_16.drawPath(1, 2.0, .flat, 1) ++ // builder.uint(3) ++ // builder_16.point(96 + 0, 464 + 0) ++ // builder_16.path.line(96 + 16, 464 + 16) ++ // builder_16.path.arc_ellipse(25, 45, 15, false, true, 96 + 48, 464 + 48) ++ // builder_16.path.line(96 + 64, 464 + 64) ++ // builder_16.drawPath(1, 2.0, .flat, 1) ++ // builder.uint(3) ++ // builder_16.point(176 + 0, 464 + 0) ++ // builder_16.path.line(176 + 16, 464 + 16) ++ // builder_16.path.arc_ellipse(25, 45, -35, true, true, 176 + 48, 464 + 48) ++ // builder_16.path.line(176 + 64, 464 + 64) ++ // builder_16.drawPath(1, 2.0, .flat, 1) ++ // builder.uint(3) ++ // builder_16.point(256 + 0, 464 + 0) ++ // builder_16.path.line(256 + 16, 464 + 16) ++ // builder_16.path.arc_ellipse(25, 45, -35, true, false, 256 + 48, 464 + 48) ++ // builder_16.path.line(256 + 64, 464 + 64) ++ // // PATH WITH ARC (CIRCLE) // builder_16.drawPath(1, 2.0, .flat, 1) ++ // builder.uint(3) ++ // builder_16.point(16 + 0, 560 + 0) ++ // builder_16.path.line(16 + 16, 560 + 16) ++ // builder_16.path.arc_circle(30, false, false, 16 + 48, 560 + 48) ++ // builder_16.path.line(16 + 64, 560 + 64) ++ // builder_16.drawPath(1, 2.0, .flat, 1) ++ // builder.uint(3) ++ // builder_16.point(96 + 0, 560 + 0) ++ // builder_16.path.line(96 + 16, 560 + 16) ++ // builder_16.path.arc_circle(30, false, true, 96 + 48, 560 + 48) ++ // builder_16.path.line(96 + 64, 560 + 64) ++ // builder_16.drawPath(1, 2.0, .flat, 1) ++ // builder.uint(3) ++ // builder_16.point(176 + 0, 560 + 0) ++ // builder_16.path.line(176 + 16, 560 + 16) ++ // builder_16.path.arc_circle(30, true, true, 176 + 48, 560 + 48) ++ // builder_16.path.line(176 + 64, 560 + 64) ++ // builder_16.drawPath(1, 2.0, .flat, 1) ++ // builder.uint(3) ++ // builder_16.point(256 + 0, 560 + 0) ++ // builder_16.path.line(256 + 16, 560 + 16) ++ // builder_16.path.arc_circle(30, true, false, 256 + 48, 560 + 48) ++ // builder_16.path.line(256 + 64, 560 + 64) ++ // builder_16.end_of_document; // };
src/data/ground-truth.zig
const std = @import("std"); const mem = std.mem; const testing = std.testing; const vk = @import("vk"); pub const AllocationType = enum { Free, Buffer, Image, ImageLinear, ImageOptimal, }; pub const MemoryUsage = enum { GpuOnly, CpuOnly, CpuToGpu, GpuToCpu, }; pub const Allocation = struct { block_id: vk.DeviceSize, span_id: vk.DeviceSize, memory_type_index: u32, memory: vk.DeviceMemory, offset: vk.DeviceSize, size: vk.DeviceSize, data: []align(8) u8, }; pub const FunctionPointers = struct { getPhysicalDeviceProperties: vk.PfnGetPhysicalDeviceProperties, getPhysicalDeviceMemoryProperties: vk.PfnGetPhysicalDeviceMemoryProperties, allocateMemory: vk.PfnAllocateMemory, freeMemory: vk.PfnFreeMemory, mapMemory: vk.PfnMapMemory, unmapMemory: vk.PfnUnmapMemory, }; const Block = struct { const Layout = struct { offset: vk.DeviceSize, size: vk.DeviceSize, alloc_type: AllocationType, id: usize }; pfn: FunctionPointers, device: vk.Device, memory: vk.DeviceMemory, usage: MemoryUsage, size: vk.DeviceSize, allocated: vk.DeviceSize, data: []align(8) u8, layout: std.ArrayList(Layout), layout_id: usize, pub fn init(allocator: mem.Allocator, pfn: FunctionPointers, device: vk.Device, size: vk.DeviceSize, usage: MemoryUsage, memory_type_index: u32) !Block { var layout = std.ArrayList(Layout).init(allocator); try layout.append(.{ .offset = 0, .size = size, .alloc_type = .Free, .id = 0 }); const allocation_info = vk.MemoryAllocateInfo{ .allocation_size = size, .memory_type_index = memory_type_index, }; var memory: vk.DeviceMemory = undefined; if (pfn.allocateMemory(device, &allocation_info, null, &memory) != .success) return error.CannotMakeNewChunk; var data: []align(8) u8 = undefined; if (usage != .GpuOnly) if (pfn.mapMemory(device, memory, 0, size, 0, @ptrCast(*?*anyopaque, &data)) != .success) return error.MapMemoryFailed; return Block{ .pfn = pfn, .device = device, .memory = memory, .usage = usage, .size = size, .allocated = 0, .data = data, .layout = layout, .layout_id = 1, }; } pub fn deinit(self: Block) void { self.layout.deinit(); if (self.usage != .GpuOnly) { self.pfn.unmapMemory(self.device, self.memory); } self.pfn.freeMemory(self.device, self.memory, null); } }; const Pool = struct { allocator: mem.Allocator, pfn: FunctionPointers, device: vk.Device, image_granularity: vk.DeviceSize, min_block_size: vk.DeviceSize, memory_type_index: u32, blocks: std.ArrayList(?*Block), pub fn init(allocator: mem.Allocator, pfn: FunctionPointers, device: vk.Device, image_granularity: vk.DeviceSize, min_block_size: vk.DeviceSize, memory_type_index: u32) Pool { return Pool{ .allocator = allocator, .pfn = pfn, .device = device, .image_granularity = image_granularity, .min_block_size = min_block_size, .memory_type_index = memory_type_index, .blocks = std.ArrayList(?*Block).init(allocator), }; } pub fn deinit(self: Pool) void { for (self.blocks.items) |b| { if (b) |block| { block.deinit(); self.allocator.destroy(block); } } self.blocks.deinit(); } pub fn alloc(self: *Pool, size: vk.DeviceSize, alignment: vk.DeviceSize, usage: MemoryUsage, alloc_type: AllocationType) !Allocation { var found = false; var location: struct { bid: usize, sid: usize, offset: vk.DeviceSize, size: vk.DeviceSize } = undefined; outer: for (self.blocks.items) |b, i| if (b) |block| { if (block.usage == .GpuOnly and usage != .GpuOnly) continue; const block_free = block.size - block.allocated; var offset: vk.DeviceSize = 0; var aligned_size: vk.DeviceSize = 0; for (block.layout.items) |span, j| { if (span.alloc_type != .Free) continue; if (span.size < size) continue; offset = alignOffset(span.offset, alignment); if (j >= 1 and self.image_granularity > 1) { const prev = block.layout.items[j - 1]; if ((prev.offset + prev.size - 1) & ~(self.image_granularity - 1) == offset & ~(self.image_granularity - 1)) { const atype = if (@enumToInt(prev.alloc_type) > @enumToInt(alloc_type)) prev.alloc_type else alloc_type; switch (atype) { .Buffer => { if (alloc_type == .Image or alloc_type == .ImageOptimal) offset = alignOffset(offset, self.image_granularity); }, .Image => { if (alloc_type == .Image or alloc_type == .ImageLinear or alloc_type == .ImageOptimal) offset = alignOffset(offset, self.image_granularity); }, .ImageLinear => { if (alloc_type == .ImageOptimal) offset = alignOffset(offset, self.image_granularity); }, else => {}, } } } var padding = offset - span.offset; aligned_size = padding + size; if (aligned_size > span.size) continue; if (aligned_size > block_free) continue :outer; if (j + 1 < block.layout.items.len and self.image_granularity > 1) { const next = block.layout.items[j + 1]; if ((next.offset + next.size - 1) & ~(self.image_granularity - 1) == offset & ~(self.image_granularity - 1)) { const atype = if (@enumToInt(next.alloc_type) > @enumToInt(alloc_type)) next.alloc_type else alloc_type; switch (atype) { .Buffer => if (alloc_type == .Image or alloc_type == .ImageOptimal) continue, .Image => if (alloc_type == .Image or alloc_type == .ImageLinear or alloc_type == .ImageOptimal) continue, .ImageLinear => if (alloc_type == .ImageOptimal) continue, else => {}, } } } found = true; location = .{ .bid = i, .sid = j, .offset = offset, .size = aligned_size }; break :outer; } }; if (!found) { var block_size: usize = 0; while (block_size < size) { block_size += self.min_block_size; } var block = try self.allocator.create(Block); block.* = try Block.init(self.allocator, self.pfn, self.device, block_size, usage, self.memory_type_index); try self.blocks.append(block); location = .{ .bid = self.blocks.items.len - 1, .sid = 0, .offset = 0, .size = size }; } const allocation = Allocation{ .block_id = location.bid, .span_id = self.blocks.items[location.bid].?.layout.items[location.sid].id, .memory_type_index = self.memory_type_index, .memory = self.blocks.items[location.bid].?.memory, .offset = location.offset, .size = location.size, .data = if (usage != .GpuOnly) self.blocks.items[location.bid].?.data[location.offset .. location.offset + size] else undefined, }; var block = self.blocks.items[location.bid].?; try block.layout.append(.{ .offset = block.layout.items[location.sid].offset + location.size, .size = block.layout.items[location.sid].size - location.size, .alloc_type = .Free, .id = block.layout_id }); block.layout.items[location.sid].size = location.size; block.layout.items[location.sid].alloc_type = alloc_type; block.allocated += location.size; block.layout_id += 1; return allocation; } pub fn free(self: *Pool, allocation: Allocation) void { var block = self.blocks.items[allocation.block_id]; for (block.?.layout.items) |*layout| { if (layout.id == allocation.span_id) { layout.alloc_type = .Free; break; } } } }; pub const Allocator = struct { const Self = @This(); allocator: mem.Allocator, pfn: FunctionPointers, device: vk.Device, memory_types: [vk.MAX_MEMORY_TYPES]vk.MemoryType, memory_type_count: u32, min_block_size: vk.DeviceSize, pools: []*Pool, pub fn init(allocator: mem.Allocator, pfn: FunctionPointers, physical_device: vk.PhysicalDevice, device: vk.Device, min_block_size: vk.DeviceSize) !Self { var properties: vk.PhysicalDeviceProperties = undefined; pfn.getPhysicalDeviceProperties(physical_device, &properties); var mem_properties: vk.PhysicalDeviceMemoryProperties = undefined; pfn.getPhysicalDeviceMemoryProperties(physical_device, &mem_properties); var pools = try allocator.alloc(*Pool, mem_properties.memory_type_count); var i: usize = 0; while (i < mem_properties.memory_type_count) : (i += 1) { var pool = try allocator.create(Pool); pool.* = Pool.init(allocator, pfn, device, properties.limits.buffer_image_granularity, min_block_size * 1024 * 1024, @intCast(u32, i)); pools[i] = pool; } return Self{ .allocator = allocator, .pfn = pfn, .device = device, .memory_types = mem_properties.memory_types, .memory_type_count = mem_properties.memory_type_count, .min_block_size = min_block_size * 1024 * 1024, .pools = pools, }; } pub fn deinit(self: Self) void { for (self.pools) |pool| { pool.deinit(); self.allocator.destroy(pool); } self.allocator.free(self.pools); } pub fn alloc( self: *Self, size: vk.DeviceSize, alignment: vk.DeviceSize, memory_type_bits: u32, usage: MemoryUsage, alloc_type: AllocationType, user_required_flags: vk.MemoryPropertyFlags, ) !Allocation { var required_flags = user_required_flags; var preferred_flags: vk.MemoryPropertyFlags = .{}; switch (usage) { .GpuOnly => preferred_flags = preferred_flags.merge(vk.MemoryPropertyFlags{ .device_local_bit = true }), .CpuOnly => required_flags = required_flags.merge(vk.MemoryPropertyFlags{ .host_visible_bit = true, .host_coherent_bit = true }), .GpuToCpu => { required_flags = required_flags.merge(vk.MemoryPropertyFlags{ .host_visible_bit = true }); preferred_flags = preferred_flags.merge(vk.MemoryPropertyFlags{ .host_coherent_bit = true, .host_cached_bit = true }); }, .CpuToGpu => { required_flags = required_flags.merge(vk.MemoryPropertyFlags{ .host_visible_bit = true }); preferred_flags = preferred_flags.merge(vk.MemoryPropertyFlags{ .device_local_bit = true }); }, } var memory_type_index: u32 = 0; var index_found = false; while (memory_type_index < self.memory_type_count) : (memory_type_index += 1) { if ((memory_type_bits >> @intCast(u5, memory_type_index)) & 1 == 0) { continue; } const properties = self.memory_types[memory_type_index].property_flags; if (!properties.contains(required_flags)) continue; if (!properties.contains(preferred_flags)) continue; index_found = true; break; } if (!index_found) { memory_type_index = 0; while (memory_type_index < self.memory_type_count) : (memory_type_index += 1) { if ((memory_type_bits >> @intCast(u5, memory_type_index)) & 1 == 0) { continue; } const properties = self.memory_types[memory_type_index].property_flags; if (!properties.contains(required_flags)) continue; index_found = true; break; } } if (!index_found) return error.MemoryTypeIndexNotFound; var pool = self.pools[memory_type_index]; return pool.alloc(size, alignment, usage, alloc_type); } pub fn free(self: *Self, allocation: Allocation) void { self.pools[allocation.memory_type_index].free(allocation); } }; inline fn alignOffset(offset: vk.DeviceSize, alignment: vk.DeviceSize) vk.DeviceSize { return ((offset + (alignment - 1)) & ~(alignment - 1)); }
src/lib.zig
const std = @import("std"); const Builder = std.build.Builder; const Paths = struct { upnp_header_path: []const u8, ixml_header_superpath: []const u8, upnp_lib_path: []const u8, ixml_lib_path: []const u8, }; pub fn queryPaths(b: *Builder) Paths { return Paths { .upnp_header_path = b.option([]const u8, "UPNP_HEADER_PATH", "Path to libupnp headers") orelse "/usr/include/upnp", .ixml_header_superpath = b.option([]const u8, "IXML_HEADER_SUPERPATH", "Path to parent directory of libixml headers") orelse "/usr/include", .upnp_lib_path = b.option([]const u8, "UPNP_LIB_PATH", "Path to libupnp library") orelse "/usr/lib/x86_64-linux-gnu", .ixml_lib_path = b.option([]const u8, "IXML_LIB_PATH", "Path to libixml library") orelse "/usr/lib/x86_64-linux-gnu", }; } pub fn populateStep(step: *std.build.LibExeObjStep, paths: Paths) void { step.linkLibC(); step.linkSystemLibrary("upnp"); step.linkSystemLibrary("ixml"); step.addIncludeDir(paths.upnp_header_path); step.addIncludeDir(paths.ixml_header_superpath); step.addLibPath(paths.upnp_lib_path); step.addLibPath(paths.ixml_lib_path); } pub fn build(b: *Builder) void { const paths = queryPaths(b); const mode = b.standardReleaseOptions(); const lib = b.addStaticLibrary("zupnp", "src/lib.zig"); lib.setBuildMode(mode); lib.addPackagePath("xml", "vendor/xml/src/lib.zig"); lib.install(); var main_tests = addTest(b, mode, paths); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&main_tests.step); var docs_tests = addTest(b, mode, paths); docs_tests.emit_docs = .emit; docs_tests.emit_bin = .no_emit; docs_tests.output_dir = "docs"; const docs_step = b.step("docs", "Create documentation"); docs_step.dependOn(&docs_tests.step); } fn addTest(b: *Builder, mode: std.builtin.Mode, paths: Paths) *std.build.LibExeObjStep { var tests = b.addTest("test/tests.zig"); tests.setBuildMode(mode); // TODO https://github.com/ziglang/zig/issues/855 const xml_package = std.build.Pkg{ .name = "xml", .path = .{ .path = "vendor/xml/src/lib.zig" } }; const zupnp_package = std.build.Pkg{ .name = "zupnp", .path = .{ .path = "src/lib.zig" }, .dependencies = &[_]std.build.Pkg{ xml_package } }; tests.addPackage(zupnp_package); populateStep(tests, paths); return tests; }
build.zig
const std = @import("std"); const builtin = @import("builtin"); const log = std.log; const fs = @import("src/build/fs.zig"); const Builder = std.build.Builder; const building_os = builtin.target.os.tag; const current_arch = std.Target.Cpu.Arch.x86_64; const cache_dir = "zig-cache"; const kernel_name = "kernel.elf"; const kernel_path = cache_dir ++ "/" ++ kernel_name; const arch_source_dir = "src/kernel/arch/" ++ @tagName(current_arch) ++ "/"; const CPUFeatures = struct { enabled: std.Target.Cpu.Feature.Set, disabled: std.Target.Cpu.Feature.Set, }; fn get_riscv_base_features() CPUFeatures { var features = CPUFeatures{ .enabled = std.Target.Cpu.Feature.Set.empty, .disabled = std.Target.Cpu.Feature.Set.empty, }; const Feature = std.Target.riscv.Feature; features.enabled.addFeature(@enumToInt(Feature.a)); return features; } fn get_x86_base_features() CPUFeatures { var features = CPUFeatures{ .enabled = std.Target.Cpu.Feature.Set.empty, .disabled = std.Target.Cpu.Feature.Set.empty, }; const Feature = std.Target.x86.Feature; features.disabled.addFeature(@enumToInt(Feature.mmx)); features.disabled.addFeature(@enumToInt(Feature.sse)); features.disabled.addFeature(@enumToInt(Feature.sse2)); features.disabled.addFeature(@enumToInt(Feature.avx)); features.disabled.addFeature(@enumToInt(Feature.avx2)); features.enabled.addFeature(@enumToInt(Feature.soft_float)); return features; } fn get_target_base(comptime arch: std.Target.Cpu.Arch) std.zig.CrossTarget { const cpu_features = switch (current_arch) { .riscv64 => get_riscv_base_features(), .x86_64 => get_x86_base_features(), else => @compileError("CPU architecture notFeatureed\n"), }; const target = std.zig.CrossTarget{ .cpu_arch = arch, .os_tag = .freestanding, .abi = .none, .cpu_features_add = cpu_features.enabled, .cpu_features_sub = cpu_features.disabled, }; return target; } fn set_target_specific_parameters_for_kernel(kernel_exe: *std.build.LibExeObjStep) void { var target = get_target_base(current_arch); switch (current_arch) { .riscv64 => { target.cpu_features_sub.addFeature(@enumToInt(std.Target.riscv.Feature.d)); kernel_exe.code_model = .medium; const asssembly_files = [_][]const u8{ arch_source_dir ++ "start.S", arch_source_dir ++ "interrupt.S", }; for (asssembly_files) |asm_file| { kernel_exe.addAssemblyFile(asm_file); } const linker_path = arch_source_dir ++ "linker.ld"; kernel_exe.setLinkerScriptPath(std.build.FileSource.relative(linker_path)); }, .x86_64 => { kernel_exe.code_model = .kernel; //kernel_exe.pie = true; kernel_exe.force_pic = true; kernel_exe.disable_stack_probing = true; kernel_exe.strip = false; kernel_exe.code_model = .kernel; kernel_exe.red_zone = false; kernel_exe.omit_frame_pointer = false; const linker_script_file = @tagName(Limine.protocol) ++ ".ld"; const linker_script_path = Limine.base_path ++ linker_script_file; kernel_exe.setLinkerScriptPath(std.build.FileSource.relative(linker_script_path)); }, else => @compileError("CPU architecture not supported"), } kernel_exe.setTarget(target); } pub fn build(b: *Builder) void { var kernel = b.addExecutable(kernel_name, "src/kernel/root.zig"); set_target_specific_parameters_for_kernel(kernel); kernel.setMainPkgPath("src"); kernel.setBuildMode(b.standardReleaseOptions()); kernel.setOutputDir(cache_dir); b.default_step.dependOn(&kernel.step); const disassembly_kernel = b.addSystemCommand(&.{ "llvm-objdump", "-d", "-S", "-Mintel", kernel_path }); disassembly_kernel.step.dependOn(&kernel.step); const disassembly_kernel_step = b.step("disasm", "Disassembly the kernel ELF"); disassembly_kernel_step.dependOn(&disassembly_kernel.step); const minimal = b.addExecutable("minimal.elf", "src/user/minimal/main.zig"); minimal.setTarget(get_target_base(current_arch)); minimal.setOutputDir(cache_dir); b.default_step.dependOn(&minimal.step); const disk = HDD.create(b); disk.step.dependOn(&minimal.step); const qemu = qemu_command(b); switch (current_arch) { .x86_64 => { const image_step = Limine.create_image_step(b, kernel); qemu.step.dependOn(image_step); }, else => { qemu.step.dependOn(&kernel.step); }, } // TODO: as disk is not written, this dependency doesn't need to be executed for every time the run step is executed //qemu.step.dependOn(&disk.step); const debug = Debug.create(b); debug.step.dependOn(&kernel.step); debug.step.dependOn(&disk.step); } const HDD = struct { const block_size = 0x400; const block_count = 32; var buffer: [block_size * block_count]u8 align(0x1000) = undefined; const path = "zig-cache/hdd.bin"; step: std.build.Step, b: *std.build.Builder, fn create(b: *Builder) *HDD { const self = b.allocator.create(HDD) catch @panic("out of memory\n"); self.* = .{ .step = std.build.Step.init(.custom, "hdd_create", b.allocator, make), .b = b, }; const named_step = b.step("disk", "Create a disk blob to use with QEMU"); named_step.dependOn(&self.step); return self; } fn make(step: *std.build.Step) !void { const parent = @fieldParentPtr(HDD, "step", step); const allocator = parent.b.allocator; const font_file = try std.fs.cwd().readFileAlloc(allocator, "resources/zap-light16.psf", std.math.maxInt(usize)); std.debug.print("Font file size: {} bytes\n", .{font_file.len}); var disk = fs.MemoryDisk{ .bytes = buffer[0..], }; fs.add_file(disk, "font.psf", font_file); fs.read_debug(disk); //std.mem.copy(u8, &buffer, font_file); try std.fs.cwd().writeFile(HDD.path, &HDD.buffer); } }; fn qemu_command(b: *Builder) *std.build.RunStep { const run_step = b.addSystemCommand(get_qemu_command(current_arch)); const step = b.step("run", "run step"); step.dependOn(&run_step.step); return run_step; } fn get_qemu_command(comptime arch: std.Target.Cpu.Arch) []const []const u8 { return switch (arch) { .riscv64 => &riscv_qemu_command_str, .x86_64 => &x86_bios_qemu_cmd, else => unreachable, }; } const x86_bios_qemu_cmd = [_][]const u8{ // zig fmt: off "qemu-system-x86_64", "-no-reboot", "-no-shutdown", "-cdrom", image_path, "-debugcon", "stdio", "-vga", "std", "-m", "4G", "-machine", "q35", //"-smp", "4", "-d", "guest_errors,int,in_asm", "-D", "logfile", // zig fmt: on }; const Debug = struct { step: std.build.Step, b: *std.build.Builder, fn create(b: *std.build.Builder) *Debug { const self = b.allocator.create(@This()) catch @panic("out of memory\n"); self.* = Debug{ .step = std.build.Step.init(.custom, "_debug_", b.allocator, make), .b = b, }; const named_step = b.step("debug", "Debug the program with QEMU and GDB"); named_step.dependOn(&self.step); return self; } fn make(step: *std.build.Step) !void { const self = @fieldParentPtr(Debug, "step", step); const b = self.b; const qemu = get_qemu_command(current_arch) ++ [_][]const u8{ "-S", "-s" }; if (building_os == .windows) { unreachable; } else { const terminal_thread = try std.Thread.spawn(.{}, terminal_and_gdb_thread, .{b}); var process = std.ChildProcess.init(qemu, b.allocator); _ = try process.spawnAndWait(); terminal_thread.join(); _ = try process.kill(); } } fn terminal_and_gdb_thread(b: *std.build.Builder) void { _ = b; //zig fmt: off var kernel_elf = std.fs.realpathAlloc(b.allocator, "zig-cache/kernel.elf") catch unreachable; if (builtin.os.tag == .windows) { const buffer = b.allocator.create([512]u8) catch unreachable; var counter: u64 = 0; for (kernel_elf) |ch| { const is_separator = ch == '\\'; buffer[counter] = ch; buffer[counter + @boolToInt(is_separator)] = ch; counter += @as(u64, 1) + @boolToInt(is_separator); } kernel_elf = buffer[0..counter]; } const symbol_file = b.fmt("symbol-file {s}", .{kernel_elf}); const process_name = [_][]const u8{ "wezterm", "start", "--", get_gdb_name(current_arch), "-tui", "-ex", symbol_file, "-ex", "target remote :1234", "-ex", "b start", "-ex", "c", }; for (process_name) |arg, arg_i| { log.debug("Process[{}]: {s}", .{arg_i, arg}); } var process = std.ChildProcess.init(&process_name, b.allocator); // zig fmt: on _ = process.spawnAndWait() catch unreachable; } }; // zig fmt: off const riscv_qemu_command_str = [_][]const u8 { "qemu-system-riscv64", "-no-reboot", "-no-shutdown", "-machine", "virt", "-cpu", "rv64", "-m", "4G", "-bios", "default", "-kernel", kernel_path, "-serial", "mon:stdio", "-drive", "if=none,format=raw,file=zig-cache/hdd.bin,id=foo", "-global", "virtio-mmio.force-legacy=false", "-device", "virtio-blk-device,drive=foo", "-device", "virtio-gpu-device", "-d", "guest_errors,int", //"-D", "logfile", //"-trace", "virtio*", //"-S", "-s", }; // zig fmt: on const image_path = "zig-cache/universal.iso"; const Limine = struct { step: std.build.Step, b: *Builder, const Protocol = enum(u32) { stivale2, limine, }; const installer = @import("src/kernel/arch/x86_64/limine/installer.zig"); const protocol = Protocol.stivale2; const base_path = "src/kernel/arch/x86_64/limine/"; const to_install_path = base_path ++ "to_install/"; fn build(step: *std.build.Step) !void { const self = @fieldParentPtr(@This(), "step", step); const img_dir_path = self.b.fmt("{s}/img_dir", .{self.b.cache_root}); const cwd = std.fs.cwd(); cwd.deleteFile(image_path) catch {}; const img_dir = try cwd.makeOpenPath(img_dir_path, .{}); const img_efi_dir = try img_dir.makeOpenPath("EFI/BOOT", .{}); const limine_dir = try cwd.openDir(to_install_path, .{}); const limine_efi_bin_file = "limine-cd-efi.bin"; const files_to_copy_from_limine_dir = [_][]const u8{ "limine.cfg", "limine.sys", "limine-cd.bin", limine_efi_bin_file, }; for (files_to_copy_from_limine_dir) |filename| { log.debug("Trying to copy {s}", .{filename}); try std.fs.Dir.copyFile(limine_dir, filename, img_dir, filename, .{}); } try std.fs.Dir.copyFile(limine_dir, "BOOTX64.EFI", img_efi_dir, "BOOTX64.EFI", .{}); try std.fs.Dir.copyFile(cwd, kernel_path, img_dir, std.fs.path.basename(kernel_path), .{}); var xorriso_process = std.ChildProcess.init(&.{ "xorriso", "-as", "mkisofs", "-quiet", "-b", "limine-cd.bin", "-no-emul-boot", "-boot-load-size", "4", "-boot-info-table", "--efi-boot", limine_efi_bin_file, "-efi-boot-part", "--efi-boot-image", "--protective-msdos-label", img_dir_path, "-o", image_path }, self.b.allocator); // Ignore stderr and stdout xorriso_process.stdin_behavior = std.ChildProcess.StdIo.Ignore; xorriso_process.stdout_behavior = std.ChildProcess.StdIo.Ignore; xorriso_process.stderr_behavior = std.ChildProcess.StdIo.Ignore; _ = try xorriso_process.spawnAndWait(); try Limine.installer.install(image_path, false, null); } fn create_image_step(b: *Builder, kernel: *std.build.LibExeObjStep) *std.build.Step { var self = b.allocator.create(@This()) catch @panic("out of memory"); self.* = @This(){ .step = std.build.Step.init(.custom, "_limine_image_", b.allocator, @This().build), .b = b, }; self.step.dependOn(&kernel.step); const image_step = b.step("x86_64-universal-image", "Build the x86_64 universal (bios and uefi) image"); image_step.dependOn(&self.step); return image_step; } }; fn get_gdb_name(comptime arch: std.Target.Cpu.Arch) []const u8 { return switch (arch) { .riscv64 => "riscv64-elf-gdb", .x86_64 => blk: { switch (building_os) { .windows => break :blk "C:\\Users\\David\\programs\\gdb\\bin\\gdb", .macos => break :blk "x86_64-elf-gdb", else => break :blk "gdb", } }, else => @compileError("CPU architecture not supported"), }; }
build.zig
const builtin = @import("builtin"); const std = @import("std"); const core = @import("core.zig"); const draw = @import("draw.zig"); const input = @import("input.zig"); const terminal = @import("terminal.zig"); const vt100 = @import("vt100.zig"); const ascii = std.ascii; const debug = std.debug; const fs = std.fs; const heap = std.heap; const io = std.io; const math = std.math; const mem = std.mem; const process = std.process; const testing = std.testing; const Editor = core.Editor; const Key = input.Key; var keys_pressed: std.ArrayList(Key.Type) = undefined; // TODO: Our custom panic handler does not get called when the program // segfaults and Zig tries to dump a stacktrace from the segfault // point. This means, that our terminal wont be restored and the // segfault stacktrace wont be printed corrently :( pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn { // If we panic, then we should restore the terminal settings like // we closed the program. const stdin = io.getStdIn(); terminal.deinit(stdin) catch {}; terminal.clear(stdin.outStream()) catch {}; stdin.writeAll(vt100.cursor.show) catch {}; for (keys_pressed.items) |key| debug.warn("{}\n", .{mem.span(&Key.toStr(key, .NotCtrl))}); const first_trace_addr = @returnAddress(); std.debug.panicExtra(error_return_trace, first_trace_addr, "{}", .{msg}); } const modified_view = draw.visible(.Hide, draw.label(.Left, "(modified) ")); const file_name_view = draw.stack(.Horizontal, struct { modified: @TypeOf(modified_view) = modified_view, file_name: draw.Label = draw.label(.Left, ""), }{}); const info_view = draw.right(draw.value("", struct { hint: []const u8 = default_hint, key: Key.Type = Key.space, location: core.Location = core.Location{}, allocated_bytes: usize = 0, freed_bytes: usize = 0, text_size: usize = 0, pub fn format( self: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, context: var, ) !void { return std.fmt.format(context, "{}{} ('{s}') ({},{}) (t:{B:2} a:{B:2} f:{B:2})", .{ if (self.hint.len != 0) @as([]const u8, " ") else "", self.hint, &Key.toStr(self.key, .NotCtrl), self.location.line + 1, self.location.column + 1, self.text_size, self.allocated_bytes, self.freed_bytes, }); } }{})); const status_bar = draw.attributes(.Negative, draw.float(struct { file_name: @TypeOf(file_name_view) = file_name_view, info: @TypeOf(info_view) = info_view, }{})); const goto_prompt_bar = draw.visible(.Hide, draw.attributes(.Negative, draw.customRange(draw.Range{ .min = draw.Size{ .width = 0, .height = 1 }, .max = draw.Size{ .width = math.maxInt(usize), .height = 1 }, }, draw.stack(.Horizontal, struct { label: draw.Label = draw.label(.Left, "goto: "), text: draw.TextView = draw.textView(false, core.Text{ .allocator = undefined }), // We init this in main }{})))); const editor_view = draw.stack(.Vertical, struct { text: draw.TextView = draw.textView(true, core.Text{ .allocator = undefined }), // We init this in main goto_prompt_bar: @TypeOf(goto_prompt_bar) = goto_prompt_bar, status_bar: @TypeOf(status_bar) = status_bar, }{}); const help_popup = blk: { @setEvalBranchQuota(10000); break :blk draw.visible(.Hide, draw.center(draw.clear(draw.attributes(.Negative, draw.box(draw.label( .Left, "'" ++ mem.span(&Key.toStr(quit_key, .NotCtrl)) ++ "': quit\n" ++ "'" ++ mem.span(&Key.toStr(save_key, .NotCtrl)) ++ "': save\n" ++ "'" ++ mem.span(&Key.toStr(undo_key, .NotCtrl)) ++ "': undo\n" ++ "'" ++ mem.span(&Key.toStr(copy_key, .NotCtrl)) ++ "': copy\n" ++ "'" ++ mem.span(&Key.toStr(paste_key, .NotCtrl)) ++ "': paste\n" ++ "'" ++ mem.span(&Key.toStr(select_all_key, .NotCtrl)) ++ "': select all\n" ++ "'" ++ mem.span(&Key.toStr(jump_key, .NotCtrl)) ++ "': jump to line\n" ++ "'" ++ mem.span(&Key.toStr(help_key, .CtrlAlphaNum)) ++ "': hide or show this message\n" ++ "'" ++ mem.span(&Key.toStr(reset_key, .NotCtrl)) ++ "': general key to cancel/reset/stop the current action\n" ++ "'" ++ mem.span(&Key.toStr(delete_left_key, .NotCtrl)) ++ "': delete letter to the left of cursors\n" ++ "'" ++ mem.span(&Key.toStr(delete_right_key, .NotCtrl)) ++ "': delete letter to the right of cursors\n" ++ "'" ++ mem.span(&Key.toStr(move_page_up_key, .NotCtrl)) ++ "': move cursors up one screen\n" ++ "'" ++ mem.span(&Key.toStr(move_page_down_key, .NotCtrl)) ++ "': move cursors down one screen\n" ++ "'" ++ mem.span(&Key.toStr(move_start_key, .NotCtrl)) ++ "': move cursors to start of file\n" ++ "'" ++ mem.span(&Key.toStr(move_end_key, .NotCtrl)) ++ "': move cursors to end of file\n" ++ "'" ++ mem.span(&Key.toStr(move_up_key, .NotCtrl)) ++ "': move cursors up\n" ++ "'" ++ mem.span(&Key.toStr(move_down_key, .NotCtrl)) ++ "': move cursors down\n" ++ "'" ++ mem.span(&Key.toStr(move_left_key, .NotCtrl)) ++ "': move cursors left\n" ++ "'" ++ mem.span(&Key.toStr(move_right_key, .NotCtrl)) ++ "': move cursors right\n" ++ "'" ++ mem.span(&Key.toStr(move_select_up_key, .NotCtrl)) ++ "': move selections up\n" ++ "'" ++ mem.span(&Key.toStr(move_select_down_key, .NotCtrl)) ++ "': move selections down\n" ++ "'" ++ mem.span(&Key.toStr(move_select_left_key, .NotCtrl)) ++ "': move selections left\n" ++ "'" ++ mem.span(&Key.toStr(move_select_right_key, .NotCtrl)) ++ "': move selections right\n" ++ "'" ++ mem.span(&Key.toStr(spawn_cursor_up_key, .NotCtrl)) ++ "': spawn a cursor above the main cursor\n" ++ "'" ++ mem.span(&Key.toStr(spawn_cursor_down_key, .NotCtrl)) ++ "': spawn a cursor below the main cursor\n" ++ "'" ++ mem.span(&Key.toStr(spawn_cursor_left_key, .NotCtrl)) ++ "': spawn a cursor to the left of the main cursor\n" ++ "'" ++ mem.span(&Key.toStr(spawn_cursor_right_key, .NotCtrl)) ++ "': spawn a cursor to the right of the main cursor", )))))); }; const quit_popup = blk: { @setEvalBranchQuota(10000); break :blk draw.visible(.Hide, draw.center(draw.clear(draw.attributes(.Negative, draw.box(draw.label( .Center, "Warning!\n" ++ "You have unsaved changes.\n" ++ "Press '" ++ mem.span(&Key.toStr(quit_key, .NotCtrl)) ++ "' to forcefully quit", )))))); }; const window_view = draw.float(struct { editor: @TypeOf(editor_view) = editor_view, help_popup: @TypeOf(help_popup) = help_popup, quit_popup: @TypeOf(quit_popup) = quit_popup, }{}); pub fn main() !void { var failing = testing.FailingAllocator.init(heap.page_allocator, math.maxInt(usize)); var arena = heap.ArenaAllocator.init(&failing.allocator); const allocator = &arena.allocator; const stdin = io.getStdIn(); const stdout = io.getStdOut(); const stdout_stream = stdout.outStream(); var stdout_buf = io.bufferedOutStream(stdout_stream); const args = try process.argsAlloc(allocator); defer allocator.free(args); if (args.len <= 1) return error.NoFileFound; keys_pressed = std.ArrayList(Key.Type).init(allocator); var app = App{ .editor = try Editor.fromFile(allocator, args[1]), .view = window_view, }; app.view.children.editor.children.goto_prompt_bar.child.child.child.children.text = draw.textView(false, try core.Text.fromString(allocator, "")); var term = draw.Terminal{ .allocator = allocator }; try terminal.init(stdin); defer terminal.deinit(stdin) catch {}; while (true) { const text = app.editor.current(); const bar = &app.view.children.editor.children.status_bar.child.children; const info = &bar.info.children.child.value; info.location = text.mainCursor().index; info.allocated_bytes = failing.allocated_bytes; info.freed_bytes = failing.freed_bytes; info.text_size = text.content.len(); app.view.children.editor.children.text.text = text; bar.file_name.children.modified.visibility = if (app.editor.dirty()) draw.Visibility.Show else draw.Visibility.Hide; bar.file_name.children.file_name = if (app.editor.file) |file| draw.label(.Left, file.path) else draw.label(.Left, "???"); const size = try terminal.size(stdout, stdin); try term.update(draw.Size{ .width = size.columns, .height = size.rows, }); term.draw(&app.view); try terminal.clear(stdout_buf.outStream()); try term.output(stdout_buf.outStream()); try stdout_buf.flush(); const key = try input.readKey(stdin); try keys_pressed.append(key); info.key = key; app = (try handleInput(app, key)) orelse break; } try terminal.clear(stdout_buf.outStream()); try stdout_buf.outStream().writeAll(vt100.cursor.show); try stdout_buf.flush(); } const App = struct { editor: core.Editor, view: @TypeOf(window_view), }; const reset_key = Key.escape; const help_key = Key.alt | Key.ctrl_h; const quit_key = Key.ctrl_q; const save_key = Key.ctrl_s; const undo_key = Key.ctrl_z; const copy_key = Key.ctrl_c; const paste_key = Key.ctrl_v; const select_all_key = Key.ctrl_a; const jump_key = Key.ctrl_j; const delete_left_key = Key.backspace; const delete_left2_key = Key.backspace2; const delete_right_key = Key.delete; const move_page_up_key = Key.page_up; const move_page_down_key = Key.page_down; const move_start_key = Key.home; const move_end_key = Key.end; const move_up_key = Key.arrow_up; const move_down_key = Key.arrow_down; const move_left_key = Key.arrow_left; const move_right_key = Key.arrow_right; const move_select_up_key = Key.shift_arrow_up; const move_select_down_key = Key.shift_arrow_down; const move_select_left_key = Key.shift_arrow_left; const move_select_right_key = Key.shift_arrow_right; const spawn_cursor_up_key = Key.ctrl_arrow_up; const spawn_cursor_down_key = Key.ctrl_arrow_down; const spawn_cursor_left_key = Key.ctrl_arrow_left; const spawn_cursor_right_key = Key.ctrl_arrow_right; const default_hint = "'" ++ mem.span(&Key.toStr(help_key, .CtrlAlphaNum)) ++ "' for help"; fn handleInput(app: App, key: Key.Type) !?App { var editor = app.editor; var view = app.view; var text = editor.current(); if (view.children.editor.children.goto_prompt_bar.visibility == .Show) { const prompt = &view.children.editor.children.goto_prompt_bar; const prompt_text = &prompt.child.child.child.children.text.text; switch (key) { Key.enter, jump_key, reset_key => { prompt.visibility = .Hide; prompt_text.* = try core.Text.fromString(prompt_text.allocator, ""); }, select_all_key => { prompt_text.* = try prompt_text.moveCursors(math.maxInt(usize), .Selection, .Left); prompt_text.* = try prompt_text.moveCursors(math.maxInt(usize), .Index, .Right); }, // Simple move keys. Moves all cursors start and end locations move_left_key => prompt_text.* = try prompt_text.moveCursors(1, .Both, .Left), move_right_key => prompt_text.* = try prompt_text.moveCursors(1, .Both, .Right), // Select move keys. Moves only all cursors end location move_select_left_key => prompt_text.* = try prompt_text.*.moveCursors(1, .Index, .Left), move_select_right_key => prompt_text.* = try prompt_text.*.moveCursors(1, .Index, .Right), // Delete delete_left_key, delete_left2_key => prompt_text.* = try prompt_text.delete(.Left), delete_right_key => prompt_text.* = try prompt_text.delete(.Right), else => { if (ascii.isDigit(math.cast(u8, key) catch 0)) prompt_text.* = try prompt_text.insert(&[_]u8{@intCast(u8, key)}); }, } if (prompt_text.content.len() != 0) { var buf: [128]u8 = undefined; var fba = heap.FixedBufferAllocator.init(&buf); const line = if (prompt_text.content.toSlice(&fba.allocator)) |line| std.fmt.parseUnsigned(usize, line, 10) catch math.maxInt(usize) else |_| math.maxInt(usize); var cursor = text.mainCursor(); cursor.index = cursor.index.moveToLine(math.sub(usize, line, 1) catch 0, text.content); cursor.selection = cursor.index; text.cursors = core.Text.Cursors.fromSliceSmall(&[_]core.Cursor{cursor}); } // Add new undo point. editor = try editor.addUndo(text); return App{ .editor = editor, .view = view, }; } // clear then "You have unsaved changes popup const quit_popup_is_show = view.children.quit_popup.visibility; view.children.quit_popup.visibility = .Hide; //debug.warn("{}\n", Key.toStr(key)); switch (key) { reset_key => { text = text.removeAllButMainCursor(); view.children.help_popup.visibility = .Hide; }, help_key => view.children.help_popup.visibility = switch (view.children.help_popup.visibility) { .Show => draw.Visibility.Hide, .Hide => draw.Visibility.Show, }, // Quit. If there are unsaved changes, then you have to press the quit bottons // twice. quit_key => if (editor.dirty() and quit_popup_is_show != .Show) { view.children.quit_popup.visibility = .Show; } else { return null; }, save_key => editor = try editor.save(), undo_key => { editor = try editor.undo(); text = editor.current(); }, copy_key => try editor.copyClipboard(), paste_key => { editor = try editor.pasteClipboard(); text = editor.current(); }, select_all_key => { // It is faster to manually delete all cursors first // instead of letting the editor logic merge the cursors // for us. text = text.removeAllButMainCursor(); text = try text.moveCursors(math.maxInt(usize), .Selection, .Left); text = try text.moveCursors(math.maxInt(usize), .Index, .Right); }, // Simple move keys. Moves all cursors start and end locations move_up_key => text = try text.moveCursors(1, .Both, .Up), move_down_key => text = try text.moveCursors(1, .Both, .Down), move_left_key => text = try text.moveCursors(1, .Both, .Left), move_right_key => text = try text.moveCursors(1, .Both, .Right), move_page_up_key => text = try text.moveCursors(50, .Both, .Up), move_page_down_key => text = try text.moveCursors(50, .Both, .Down), move_start_key => text = try text.moveCursors(math.maxInt(usize), .Both, .Left), move_end_key => text = try text.moveCursors(math.maxInt(usize), .Both, .Right), // Select move keys. Moves only all cursors end location move_select_up_key => text = try text.moveCursors(1, .Index, .Up), move_select_down_key => text = try text.moveCursors(1, .Index, .Down), move_select_left_key => text = try text.moveCursors(1, .Index, .Left), move_select_right_key => text = try text.moveCursors(1, .Index, .Right), // Spawn cursor keys spawn_cursor_up_key => text = try text.spawnCursor(.Up), spawn_cursor_down_key => text = try text.spawnCursor(.Down), spawn_cursor_left_key => text = try text.spawnCursor(.Left), spawn_cursor_right_key => text = try text.spawnCursor(.Right), // Delete delete_left_key, delete_left2_key => text = try text.delete(.Left), delete_right_key => text = try text.delete(.Right), jump_key => view.children.editor.children.goto_prompt_bar.visibility = .Show, Key.enter => text = try text.insert("\n"), Key.space => text = try text.insert(" "), Key.tab => text = try text.indent(' ', 4), // Every other key is inserted if they are printable ascii else => { if (ascii.isPrint(math.cast(u8, key) catch 0)) text = try text.insert(&[_]u8{@intCast(u8, key)}); }, } // Add new undo point. editor = try editor.addUndo(text); return App{ .editor = editor, .view = view, }; }
src/main.zig
const std = @import("std"); const mem = std.mem; const NoncharacterCodePoint = @This(); allocator: *mem.Allocator, array: []bool, lo: u21 = 64976, hi: u21 = 1114111, pub fn init(allocator: *mem.Allocator) !NoncharacterCodePoint { var instance = NoncharacterCodePoint{ .allocator = allocator, .array = try allocator.alloc(bool, 1049136), }; mem.set(bool, instance.array, false); var index: u21 = 0; index = 0; while (index <= 31) : (index += 1) { instance.array[index] = true; } index = 558; while (index <= 559) : (index += 1) { instance.array[index] = true; } index = 66094; while (index <= 66095) : (index += 1) { instance.array[index] = true; } index = 131630; while (index <= 131631) : (index += 1) { instance.array[index] = true; } index = 197166; while (index <= 197167) : (index += 1) { instance.array[index] = true; } index = 262702; while (index <= 262703) : (index += 1) { instance.array[index] = true; } index = 328238; while (index <= 328239) : (index += 1) { instance.array[index] = true; } index = 393774; while (index <= 393775) : (index += 1) { instance.array[index] = true; } index = 459310; while (index <= 459311) : (index += 1) { instance.array[index] = true; } index = 524846; while (index <= 524847) : (index += 1) { instance.array[index] = true; } index = 590382; while (index <= 590383) : (index += 1) { instance.array[index] = true; } index = 655918; while (index <= 655919) : (index += 1) { instance.array[index] = true; } index = 721454; while (index <= 721455) : (index += 1) { instance.array[index] = true; } index = 786990; while (index <= 786991) : (index += 1) { instance.array[index] = true; } index = 852526; while (index <= 852527) : (index += 1) { instance.array[index] = true; } index = 918062; while (index <= 918063) : (index += 1) { instance.array[index] = true; } index = 983598; while (index <= 983599) : (index += 1) { instance.array[index] = true; } index = 1049134; while (index <= 1049135) : (index += 1) { instance.array[index] = true; } // Placeholder: 0. Struct name, 1. Code point kind return instance; } pub fn deinit(self: *NoncharacterCodePoint) void { self.allocator.free(self.array); } // isNoncharacterCodePoint checks if cp is of the kind Noncharacter_Code_Point. pub fn isNoncharacterCodePoint(self: NoncharacterCodePoint, cp: u21) bool { if (cp < self.lo or cp > self.hi) return false; const index = cp - self.lo; return if (index >= self.array.len) false else self.array[index]; }
src/components/autogen/PropList/NoncharacterCodePoint.zig
const std = @import("std"); pub const AudioFormat = enum { signed8, signed16_lsb, }; pub fn mixDown( dst: []u8, mix_buffer: []const f32, audio_format: AudioFormat, num_channels: usize, channel_index: usize, vol: f32, ) void { switch (audio_format) { .signed8 => { mixDownS8(dst, mix_buffer, num_channels, channel_index, vol); }, .signed16_lsb => { mixDownS16LSB(dst, mix_buffer, num_channels, channel_index, vol); }, } } // convert from float to 16-bit, applying clamping // `vol` should be set to something lower than 1.0 to avoid clipping fn mixDownS16LSB( dst: []u8, mix_buffer: []const f32, num_channels: usize, channel_index: usize, vol: f32, ) void { std.debug.assert(dst.len == mix_buffer.len * 2 * num_channels); const mul = vol * 32767.0; var i: usize = 0; while (i < mix_buffer.len) : (i += 1) { const value = mix_buffer[i] * mul; const clamped_value = if (value <= -32767.0) @as(i16, -32767) else if (value >= 32766.0) @as(i16, 32766) else if (value != value) // NaN @as(i16, 0) else @floatToInt(i16, value); const index = (i * num_channels + channel_index) * 2; dst[index + 0] = @intCast(u8, clamped_value & 0xFF); dst[index + 1] = @intCast(u8, (clamped_value >> 8) & 0xFF); } } fn mixDownS8( dst: []u8, mix_buffer: []const f32, num_channels: usize, channel_index: usize, vol: f32, ) void { std.debug.assert(dst.len == mix_buffer.len * num_channels); const mul = vol * 127.0; var i: usize = 0; while (i < mix_buffer.len) : (i += 1) { const value = mix_buffer[i] * mul; const clamped_value = if (value <= -127.0) @as(i8, -127) else if (value >= 126.0) @as(i8, 126) else if (value != value) // NaN @as(i8, 0) else @floatToInt(i8, value); dst[i * num_channels + channel_index] = @bitCast(u8, clamped_value); } }
src/zang/mixdown.zig
const std = @import("std"); const CaveList = [12]Node; const HashList = [24]u8; //-------------------------------------------------------------------------------------------------- const Node = struct { name: []const u8, hash: u8, connection_indices: [6]usize, connection_count: u8, is_small: bool, pub fn init(name: []const u8) Node { return Node{ .name = name, .hash = cave_hash(name), .connection_indices = undefined, .connection_count = 0, .is_small = is_small_string(name) }; } pub fn attach(self: *Node, index: usize) void { self.connection_indices[self.connection_count] = index; self.connection_count += 1; } }; //-------------------------------------------------------------------------------------------------- pub fn is_small_string(value: []const u8) bool { return (value[0] >= 'a'); } //-------------------------------------------------------------------------------------------------- pub fn cave_hash(string: []const u8) u8 { if (std.mem.eql(u8, string, "end")) { return 0; } var hash: u8 = string[0]; hash +%= string[1]; return hash; } //-------------------------------------------------------------------------------------------------- pub fn attempt_add_cave(cave_list: *CaveList, cave_count: *usize, new_cave: []const u8) void { const hash = cave_hash(new_cave); for (cave_list) |existing| { if (existing.hash == hash) { return; // already exists } } //std.log.info("adding cave {s} at pos {d}", .{ new_cave, cave_count.* }); cave_list[cave_count.*] = Node.init(new_cave); cave_count.* += 1; } //-------------------------------------------------------------------------------------------------- pub fn find_cave_idx(cave_list: CaveList, cave_count: usize, find: []const u8) usize { _ = cave_count; const hash = cave_hash(find); for (cave_list) |existing, idx| { if (existing.hash == hash) { return idx; } } unreachable; } //-------------------------------------------------------------------------------------------------- pub fn count_visits(hash: u8, visited: HashList, visited_count: usize) u8 { var count: u8 = 0; for (visited[0..visited_count]) |visited_hash| { if (visited_hash == hash) { count += 1; } } return count; } //-------------------------------------------------------------------------------------------------- pub fn attach_cave(cave_list: *CaveList, cave_count: usize, node: []const u8, attachee: []const u8) void { const a_idx = find_cave_idx(cave_list.*, cave_count, node); const b_idx = find_cave_idx(cave_list.*, cave_count, attachee); cave_list[a_idx].attach(b_idx); } //-------------------------------------------------------------------------------------------------- pub fn count_paths(node_idx: usize, cave_list: CaveList, cave_count: usize, visited: *HashList, visited_count: *usize, allow_double_visit: u8) u32 { const hash = cave_list[node_idx].hash; if (hash == 0) { // reached end // If double visits are allowed, then only return if double visits occurred. This prevents double counting of combinations without double visits if (allow_double_visit != 0) { const visit_count = count_visits(allow_double_visit, visited.*, visited_count.*); if (visit_count != 2) { return 0; // excluded as double visit didn't occur } } return 1; } visited[visited_count.*] = hash; visited_count.* += 1; const this_cave = cave_list[node_idx]; const connection_count = this_cave.connection_count; var total: u32 = 0; for (this_cave.connection_indices[0..connection_count]) |connection_idx| { const next_cave = cave_list[connection_idx]; const visit_count = count_visits(next_cave.hash, visited.*, visited_count.*); const can_visit = (next_cave.is_small == false or visit_count == 0 or (visit_count == 1 and next_cave.hash == allow_double_visit)); if (can_visit) { total += count_paths(connection_idx, cave_list, cave_count, visited, visited_count, allow_double_visit); } } visited_count.* -= 1; // pop visited return total; } //-------------------------------------------------------------------------------------------------- pub fn main() anyerror!void { var buf: [1024]u8 = undefined; var buf_size: usize = undefined; { const file = std.fs.cwd().openFile("data/day12_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 reader = std.io.bufferedReader(file.reader()); var istream = reader.reader(); buf_size = try istream.readAll(&buf); } var caves: CaveList = undefined; var cave_count: usize = 0; { var lines = std.mem.tokenize(u8, buf[0..buf_size], "\n"); var i: usize = 0; while (lines.next()) |line| : (i += 1) { var nodes = std.mem.tokenize(u8, line, "-"); var a = nodes.next().?; var b = nodes.next().?; attempt_add_cave(&caves, &cave_count, a); attempt_add_cave(&caves, &cave_count, b); attach_cave(&caves, cave_count, a, b); attach_cave(&caves, cave_count, b, a); } } const allow_double_visit: u8 = 0; // Magic value that means no cave is allowed to be visited twice var visited: HashList = undefined; var visited_count: usize = 0; const start_idx = find_cave_idx(caves, cave_count, "start"); const part1_count: u32 = count_paths(start_idx, caves, cave_count, &visited, &visited_count, allow_double_visit); std.log.info("Part 1 num_paths: {d}", .{part1_count}); const allowed_twice = [_]*const [2:0]u8{ "yw", "wn", "dc", "ah", "fi", "th" }; var part2_count: u32 = part1_count; for (allowed_twice) |allowed| { const allowed_hash = cave_hash(allowed); part2_count += count_paths(start_idx, caves, cave_count, &visited, &visited_count, allowed_hash); } std.log.info("Part 2 num_paths: {d}", .{part2_count}); } //--------------------------------------------------------------------------------------------------
src/day12.zig
const base = @import("base.zig"); const letter = @import("letter.zig"); const tables = @import("tables.zig"); const warn = @import("std").debug.warn; /// isUpper reports whether the rune is an upper case letter. pub fn isUpper(rune: u32) bool { if (rune <= base.max_latin1) { const p = tables.properties[@intCast(usize, rune)]; return (p & base.pLmask) == base.pLu; } return letter.isExcludingLatin(tables.Upper, rune); } // isLower reports whether the rune is a lower case letter. pub fn isLower(rune: u32) bool { if (rune <= base.max_latin1) { const p = tables.properties[@intCast(usize, rune)]; return (p & base.pLmask) == base.pLl; } return letter.isExcludingLatin(tables.Lower, rune); } // IsTitle reports whether the rune is a title case letter. pub fn isTitle(rune: u32) bool { if (rune <= base.max_latin1) { return false; } return letter.isExcludingLatin(tables.Title, rune); } const toResult = struct{ mapped: u32, found_mapping: bool, }; fn to_case(_case: base.Case, rune: u32, case_range: []base.CaseRange) toResult { if (_case.rune() < 0 or base.Case.Max.rune() <= _case.rune()) { return toResult{ .mapped = base.replacement_char, .found_mapping = false, }; } var lo: usize = 0; var hi = case_range.len; while (lo < hi) { const m = lo + (hi - lo) / 2; const cr = case_range[m]; if (cr.lo <= rune and rune <= cr.hi) { const delta = cr.delta[_case.rune()]; if (delta > @intCast(i32, base.max_rune)) { // In an Upper-Lower sequence, which always starts with // an UpperCase letter, the real deltas always look like: //{0, 1, 0} UpperCase (Lower is next) //{-1, 0, -1} LowerCase (Upper, Title are previous) // The characters at even offsets from the beginning of the // sequence are upper case; the ones at odd offsets are lower. // The correct mapping can be done by clearing or setting the low // bit in the sequence offset. // The constants UpperCase and TitleCase are even while LowerCase // is odd so we take the low bit from _case. var i: u32 = 1; return toResult{ .mapped = cr.lo + ((rune - cr.lo) & ~i | _case.rune() & 1), .found_mapping = true, }; } return toResult{ .mapped = @intCast(u32, @intCast(i32, rune) + delta), .found_mapping = true, }; } if (rune < cr.lo) { hi = m; } else { lo = m + 1; } } return toResult{ .mapped = rune, .found_mapping = false, }; } // to maps the rune to the specified case: UpperCase, LowerCase, or TitleCase. pub fn to(case: base.Case, rune: u32) u32 { const v = to_case(case, rune, tables.CaseRanges); return v.mapped; } pub fn toUpper(rune: u32) u32 { if (rune <= base.max_ascii) { if ('a' <= rune and rune <= 'z') { return rune - ('a' - 'A'); } return rune; } return to(base.Case.Upper, rune); } pub fn toLower(rune: u32) u32 { if (rune <= base.max_ascii) { if ('A' <= rune and rune <= 'Z') { return rune + ('a' - 'A'); } return rune; } return to(base.Case.Lower, rune); } pub fn toTitle(rune: u32) u32 { if (rune <= base.max_ascii) { if ('a' <= rune and rune <= 'z') { return rune - ('a' - 'A'); } return rune; } return to(base.Case.Title, rune); } // SimpleFold iterates over Unicode code points equivalent under // the Unicode-defined simple case folding. Among the code points // equivalent to rune (including rune itself), SimpleFold returns the // smallest rune > r if one exists, or else the smallest rune >= 0. // If r is not a valid Unicode code point, SimpleFold(r) returns r. // // For example: // SimpleFold('A') = 'a' // SimpleFold('a') = 'A' // // SimpleFold('K') = 'k' // SimpleFold('k') = '\u212A' (Kelvin symbol, K) // SimpleFold('\u212A') = 'K' // // SimpleFold('1') = '1' // // SimpleFold(-2) = -2 // pub fn simpleFold(r: u32) u32 { if (r < 0 or r > base.max_rune) { return r; } const idx = @intCast(usize, r); if (idx < tables.asciiFold.len) { return @intCast(u32, tables.asciiFold[idx]); } var lo: usize = 0; var hi = caseOrbit.len; while (lo < hi) { const m = lo + (hi - lo) / 2; if (@intCast(u32, tables.caseOrbit[m].from) < r) { lo = m + 1; } else { hi = m; } } if (lo < tables.caseOrbit.len and @intCast(tables.caseOrbit[lo].from) == r) { return @intCast(u32, tables.caseOrbit[lo].to); } // No folding specified. This is a one- or two-element // equivalence class containing rune and ToLower(rune) // and ToUpper(rune) if they are different from rune const l = toLower(r); if (l != r) { return l; } return toUpper(r); } pub const graphic_ranges = []*const base.RangeTable{ tables.L, tables.M, tables.N, tables.P, tables.S, tables.Zs, }; pub const print_ranges = []*const base.RangeTable{ tables.L, tables.M, tables.N, tables.P, tables.S, }; pub fn in(r: u32, ranges: []const *const base.RangeTable) bool { for (ranges) |inside| { if (letter.is(inside, r)) { return true; } } return false; } // IsGraphic reports whether the rune is defined as a Graphic by Unicode. // Such characters include letters, marks, numbers, punctuation, symbols, and // spaces, from categories L, M, N, P, S, Zs. pub fn isGraphic(r: u32) bool { if (r <= base.max_latin1) { return tables.properties[@intCast(usize, r)] & base.pg != 0; } return in(r, graphic_ranges[0..]); } // IsPrint reports whether the rune is defined as printable by Go. Such // characters include letters, marks, numbers, punctuation, symbols, and the // ASCII space character, from categories L, M, N, P, S and the ASCII space // character. This categorization is the same as IsGraphic except that the // only spacing character is ASCII space, U+0020 pub fn isPrint(r: u32) bool { if (r <= base.max_latin1) { return tables.properties[@intCast(usize, r)] & base.pp != 0; } return in(r, print_ranges[0..]); } pub fn isOneOf(ranges: []*base.RangeTable, r: u32) bool { return in(r, ranges); } // IsControl reports whether the rune is a control character. // The C (Other) Unicode category includes more code points // such as surrogates; use Is(C, r) to test for them. pub fn isControl(r: u32) bool { if (r <= base.max_latin1) { return tables.properties[@intCast(usize, r)] & base.pC != 0; } return false; } // IsLetter reports whether the rune is a letter (category L). pub fn isLetter(r: u32) bool { if (r <= base.max_latin1) { return tables.properties[@intCast(usize, r)] & base.pLmask != 0; } return letter.isExcludingLatin(tables.Letter, r); } // IsMark reports whether the rune is a mark character (category M). pub fn isMark(r: u32) bool { // There are no mark characters in Latin-1. return letter.isExcludingLatin(tables.Mark, r); } // IsNumber reports whether the rune is a number (category N). pub fn isNumber(r: u32) bool { if (r <= base.max_latin1) { return tables.properties[@intCast(usize, r)] & base.pN != 0; } return letter.isExcludingLatin(tables.Number, r); } // IsPunct reports whether the rune is a Unicode punctuation character // (category P). pub fn isPunct(r: u32) bool { if (r <= base.max_latin1) { return tables.properties[@intCast(usize, r)] & base.pP != 0; } return letter.is(tables.Punct, r); } // IsSpace reports whether the rune is a space character as defined // by Unicode's White Space property; in the Latin-1 space // this is // '\t', '\n', '\v', '\f', '\r', ' ', U+0085 (NEL), U+00A0 (NBSP). // Other definitions of spacing characters are set by category // Z and property Pattern_White_Space. pub fn isSpace(r: u32) bool { if (r <= base.max_latin1) { switch (r) { '\t', '\n', 0x0B, 0x0C, '\r', ' ', 0x85, 0xA0 => return true, else => return false, } } return letter.isExcludingLatin(tables.White_Space, r); } // IsSymbol reports whether the rune is a symbolic character. pub fn isSymbol(r: u32) bool { if (r <= base.max_latin1) { return tables.properties[@intCast(usize, r)] & base.pS != 0; } return letter.isExcludingLatin(tables.Symbol, r); } // isDigit reports whether the rune is a decimal digit. pub fn isDigit(r: u32) bool { if (r <= base.max_latin1) { return '0' <= r and r <= '9'; } return letter.isExcludingLatin(tables.Digit, r); }
src/unicode/index.zig
const std = @import("std"); const os = @import("root").os; const platform = os.platform; const range = os.lib.range.range; const scheduler = os.thread.scheduler; const idt = @import("idt.zig"); const gdt = @import("gdt.zig"); const pic = @import("pic.zig"); const thread = @import("thread.zig"); pub const num_handlers = 0x100; pub const InterruptHandler = fn(*InterruptFrame)void; pub const InterruptState = bool; export var handlers: [256]InterruptHandler = [_]InterruptHandler {unhandled_interrupt} ** num_handlers; var itable: *[256]idt.IdtEntry = undefined; var raw_callbacks: [256](fn() callconv(.Naked) void) = undefined; /// Use ist=2 for scheduler calls and ist=1 for interrupts pub fn add_handler(idx: u8, f: InterruptHandler, interrupt: bool, priv_level: u2, ist: u3) void { itable[idx] = idt.entry(raw_callbacks[idx], interrupt, priv_level, ist); handlers[idx] = f; } pub const boostrap_vector: u8 = 0x30; pub const wait_yield_vector: u8 = 0x31; pub const syscall_vector: u8 = 0x32; pub const spurious_vector: u8 = 0x3F; var last_vector: u8 = spurious_vector; pub fn allocate_vector() u8 { return @atomicRmw(u8, &last_vector, .Add, 1, .AcqRel) + 1; } pub fn init_interrupts() void { pic.disable(); itable = &idt.idt; inline for(range(num_handlers)) |intnum| { raw_callbacks[intnum] = make_handler(intnum); add_handler(intnum, unhandled_interrupt, true, 0, 0); } add_handler(0x0E, page_fault_handler, true, 3, 1); add_handler(boostrap_vector, os.thread.preemption.bootstrap, true, 0, 0); add_handler(wait_yield_vector, os.thread.preemption.wait_yield, true, 0, 2); add_handler(spurious_vector, spurious_handler, true, 0, 1); } fn spurious_handler(frame: *InterruptFrame) void { } fn type_page_fault(error_code: usize) platform.PageFaultAccess { if((error_code & 0x10) != 0) return .InstructionFetch; if((error_code & 0x2) != 0) return .Write; return .Read; } fn page_fault_handler(frame: *InterruptFrame) void { const page_fault_addr = asm( "mov %%cr2, %[addr]" :[addr] "=r" (-> usize) ); const page_fault_type = type_page_fault(frame.ec); platform.page_fault(page_fault_addr, (frame.ec & 1) != 0, page_fault_type, frame); } fn unhandled_interrupt(frame: *InterruptFrame) void { os.log("Interrupts: Unhandled interrupt: {}!\n", .{frame.intnum}); frame.dump(); frame.trace_stack(); os.platform.hang(); } fn is_exception(intnum: u64) bool { return switch(intnum) { 0x00 ... 0x1F => true, else => false, }; } fn name(intnum: u64) []const u8 { return switch(intnum) { 0x00 => "Divide by zero", 0x01 => "Debug", 0x02 => "Non-maskable interrupt", 0x03 => "Breakpoint", 0x04 => "Overflow", 0x05 => "Bound range exceeded", 0x06 => "Invalid opcode", 0x07 => "Device not available", 0x08 => "Double fault", 0x09 => "Coprocessor Segment Overrun", 0x0A => "Invalid TSS", 0x0B => "Segment Not Present", 0x0C => "Stack-Segment Fault", 0x0D => "General Protection Fault", 0x0E => "Page Fault", 0x0F => unreachable, 0x10 => "x87 Floating-Point Exception", 0x11 => "Alignment Check", 0x12 => "Machine Check", 0x13 => "SIMD Floating-Point Exception", 0x14 => "Virtualization Exception", 0x15 ... 0x1D => unreachable, 0x1E => "Security Exception", else => unreachable, }; } fn has_error_code(intnum: u64) bool { return switch(intnum) { // Exceptions 0x00 ... 0x07 => false, 0x08 => true, 0x09 => false, 0x0A ... 0x0E => true, 0x0F ... 0x10 => false, 0x11 => true, 0x12 ... 0x14 => false, //0x15 ... 0x1D => unreachable, 0x1E => true, //0x1F => unreachable, // Other interrupts else => false, }; } pub fn make_handler(comptime intnum: u8) idt.InterruptHandler { return struct { fn func() callconv(.Naked) void { const ec = if(comptime(!has_error_code(intnum))) "push $0\n" else ""; asm volatile( ec ++ "push %[intnum]\njmp interrupt_common\n" : : [intnum] "i" (@as(u8, intnum)) ); } }.func; } pub const InterruptFrame = packed struct { es: u64, ds: u64, r15: u64, r14: u64, r13: u64, r12: u64, r11: u64, r10: u64, r9: u64, r8: u64, rdi: u64, rsi: u64, rbp: u64, rdx: u64, rcx: u64, rbx: u64, rax: u64, intnum: u64, ec: u64, rip: u64, cs: u64, eflags: u64, rsp: u64, ss: u64, pub fn dump(self: *const @This()) void { os.log("FRAME DUMP:\n", .{}); os.log("RAX={x:0>16} RBX={x:0>16} RCX={x:0>16} RDX={x:0>16}\n", .{self.rax, self.rbx, self.rcx, self.rdx}); os.log("RSI={x:0>16} RDI={x:0>16} RBP={x:0>16} RSP={x:0>16}\n", .{self.rsi, self.rdi, self.rbp, self.rsp}); os.log("R8 ={x:0>16} R9 ={x:0>16} R10={x:0>16} R11={x:0>16}\n", .{self.r8, self.r9, self.r10, self.r11}); os.log("R12={x:0>16} R13={x:0>16} R14={x:0>16} R15={x:0>16}\n", .{self.r12, self.r13, self.r14, self.r15}); os.log("RIP={x:0>16} int={x:0>16} ec ={x:0>16}\n", .{self.rip, self.intnum, self.ec}); } pub fn trace_stack(self: *const @This()) void { os.lib.debug.dump_frame(self.rbp, self.rip); } }; export fn interrupt_common() callconv(.Naked) void { asm volatile( \\push %%rax \\push %%rbx \\push %%rcx \\push %%rdx \\push %%rbp \\push %%rsi \\push %%rdi \\push %%r8 \\push %%r9 \\push %%r10 \\push %%r11 \\push %%r12 \\push %%r13 \\push %%r14 \\push %%r15 \\mov %%ds, %%rax \\push %%rax \\mov %%es, %%rax \\push %%rax \\mov %%rsp, %%rdi \\mov %[dsel], %%ax \\mov %%ax, %%es \\mov %%ax, %%ds \\call interrupt_handler \\pop %%rax \\mov %%rax, %%es \\pop %%rax \\mov %%rax, %%ds \\pop %%r15 \\pop %%r14 \\pop %%r13 \\pop %%r12 \\pop %%r11 \\pop %%r10 \\pop %%r9 \\pop %%r8 \\pop %%rdi \\pop %%rsi \\pop %%rbp \\pop %%rdx \\pop %%rcx \\pop %%rbx \\pop %%rax \\add $16, %%rsp // Pop error code and interrupt number \\iretq : : [dsel] "i" (gdt.selector.data64) ); unreachable; } export fn interrupt_handler(frame: u64) void { const int_frame = @intToPtr(*InterruptFrame, frame); int_frame.intnum &= 0xFF; if(int_frame.intnum < num_handlers) { handlers[int_frame.intnum](int_frame); } } // Turns out GAS is so terrible we have to write a small assembler ourselves. const swapgs = [_]u8{0x0F, 0x01, 0xF8}; const sti = [_]u8{0xFB}; const rex = [_]u8{0x41}; fn pack_le(comptime T: type, comptime value: u32) [@sizeOf(T)]u8 { var result: [@sizeOf(T)]u8 = undefined; std.mem.writeIntLittle(T, &result, value); return result; } fn mov_gs_offset_rsp(comptime offset: u32) [9]u8 { return [_]u8{0x65, 0x48, 0x89, 0x24, 0x25} ++ pack_le(u32, offset); } fn mov_rsp_gs_offset(comptime offset: u32) [9]u8 { return [_]u8{0x65, 0x48, 0x8B, 0x24, 0x25} ++ pack_le(u32, offset); } fn mov_rsp_rsp_offset(comptime offset: u32) [8]u8 { return [_]u8{0x48, 0x8B, 0xA4, 0x24} ++ pack_le(u32, offset); } fn push_gs_offset(comptime offset: u32) [8]u8 { return [_]u8{0x65, 0xFF, 0x34, 0x25} ++ pack_le(u32, offset); } fn pushi32(comptime value: i32) [5]u8 { return [_]u8{0x68} ++ pack_le(i32, value); } fn pushi8(comptime value: i8) [2]u8 { return [_]u8{0x6A} ++ pack_le(i8, value); } fn push_reg(comptime regnum: u3) [1]u8 { return [_]u8{0x50 | @as(u8, regnum)}; } // Assumes IA32_FMASK (0xC0000084) disables interrupts const rsp_stash_offset = @byteOffsetOf(os.platform.smp.CoreData, "platform_data") + @byteOffsetOf(os.platform.thread.CoreData, "rsp_stash") ; const task_offset = @byteOffsetOf(os.platform.smp.CoreData, "current_task"); const kernel_stack_offset = @byteOffsetOf(os.thread.Task, "stack"); const syscall_handler_bytes = [0]u8{} // First make sure we get a proper stack pointer while // saving away all the userspace registers. ++ swapgs // swapgs ++ mov_gs_offset_rsp(rsp_stash_offset) // mov gs:[rsp_stash_offset], rsp ++ mov_rsp_gs_offset(task_offset) // mov rsp, gs:[task_offset] ++ mov_rsp_rsp_offset(kernel_stack_offset) // mov rsp, [rsp + kernel_stack_offset] // Now we have a kernel stack in rsp // Set up an iret frame ++ pushi8(gdt.selector.userdata64) // push user_data_sel // iret ss ++ push_gs_offset(rsp_stash_offset) // push gs:[rsp_stash_offset] // iret rsp ++ rex ++ push_reg(11 - 8) // push r11 // iret rflags ++ pushi8(gdt.selector.usercode64) // push user_code_sel // iret cs ++ push_reg(1) // push rcx // iret rip ++ swapgs ++ sti // Now let's set up the rest of the interrupt frame ++ pushi8(0) // push 0 // error code ++ pushi32(syscall_vector) // push 0x80 // interrupt vector ; fn hex_chr(comptime value: u4) u8 { return "0123456789ABCDEF"[value]; } fn hex_str(comptime value: u8) [2]u8 { var buf: [2]u8 = undefined; buf[0] = hex_chr(@truncate(u4, value >> 4)); buf[1] = hex_chr(@truncate(u4, value)); return buf; } pub fn syscall_handler() callconv(.Naked) void { // https://github.com/ziglang/zig/issues/8644 comptime var syscall_handler_asm: []const u8 = &[_]u8{}; inline for(syscall_handler_bytes) |b| syscall_handler_asm = syscall_handler_asm ++ [_]u8{'.', 'b', 'y', 't', 'e', ' ', '0', 'x'} ++ hex_str(b) ++ [_]u8{'\n'}; asm volatile( syscall_handler_asm ++ \\jmp interrupt_common \\ ); unreachable; }
src/platform/x86_64/interrupts.zig
const std = @import("std"); const ArrayList = std.ArrayList; pub const ShelfType = enum { top_result, song, video, artist, album, community_playlists, featured_playlists, pub fn from_str(str: []const u8) !ShelfType { std.log.warn("{s}", .{str}); if (std.mem.eql(u8, str, "Top result")) { return .top_result; } else if (std.mem.eql(u8, str, "Songs")) { return .song; } else if (std.mem.eql(u8, str, "Videos")) { return .video; } else if (std.mem.eql(u8, str, "Artists")) { return .artist; } else if (std.mem.eql(u8, str, "Albums")) { return .album; } else if (std.mem.eql(u8, str, "Community playlists")) { return .community_playlists; } else if (std.mem.eql(u8, str, "Featured playlists")) { return .featured_playlists; } return error.InvalidType; } }; pub const TopResult = union(enum) { song: Song, video: Video, artist, album, community_playlists, featured_playlists, }; pub const Song = struct { title: []u8, artist_name: []u8, artist_id: []u8, id: []u8, album_name: []u8, album_id: []u8, }; pub const Video = struct { title: []u8, artist_name: []u8, artist_id: []u8, id: []u8, }; pub const Artist = struct { name: []u8, id: []u8, }; // Responses pub const SearchResult = struct { top_result: TopResult = undefined, songs: ArrayList(Song), videos: ArrayList(Video), featured_playlists: u16 = 1, community_playlists: u16 = 1, albums: u16 = 1, artists: ArrayList(Artist), allocator: std.mem.Allocator, const Self = @This(); pub fn init(allocator: std.mem.Allocator) Self { return Self{ .songs = ArrayList(Song).init(allocator), .videos = ArrayList(Video).init(allocator), .artists = ArrayList(Artist).init(allocator), .allocator = allocator, }; } pub fn deinit(self: Self) void { for (self.songs.items) |song| { self.allocator.free(song.title); self.allocator.free(song.id); self.allocator.free(song.artist_name); self.allocator.free(song.artist_id); self.allocator.free(song.album_name); self.allocator.free(song.album_id); } for (self.videos.items) |video| { self.allocator.free(video.title); self.allocator.free(video.id); self.allocator.free(video.artist_name); self.allocator.free(video.artist_id); } for (self.artists.items) |artist| { self.allocator.free(artist.name); self.allocator.free(artist.id); } self.songs.deinit(); self.videos.deinit(); self.artists.deinit(); } };
src/model.zig
const std = @import("std"); const util = @import("util"); const input = @embedFile("17.txt"); const CubeState = enum(u1) { inactive = 0, active = 1, }; const World = struct { buf: [2]Buf = buf_init, const Buf = [30][30][30][30]CubeState; const buf_init = comptime blk: { var buf = [_][30][30][30]CubeState{ [_][30][30]CubeState{ [_][30]CubeState{ [_]CubeState{ .inactive, } ** 30, } ** 30, } ** 30, } ** 30; for (util.gridRows(input)) |row, x| { for (row) |state, y| { buf[x + 12][y + 12][15][15] = switch (state) { '.' => .inactive, '#' => .active, else => unreachable, }; } } break :blk [_]Buf{buf} ** 2; }; fn tick(self: *World, idx: u1, comptime @"4d": bool) void { const n_iter = [_]comptime_int{ -1, 0, 1 }; const w_iter = if (@"4d") n_iter else [_]comptime_int{0}; for (self.buf[idx]) |*x_axis, x| { if (x == 0 or x == 29) continue; for (x_axis) |*y_axis, y| { if (y == 0 or y == 29) continue; for (y_axis) |*z_axis_, z| { const z_axis = if (@"4d") z_axis_ else z_axis_[15..16]; if (z == 0 or z == 29) continue; for (z_axis) |state, w_| { if (@"4d") if (w_ == 0 or w_ == 29) continue; const w = if (@"4d") w_ else 15; var neighbors: u8 = 0; inline for (n_iter) |dx| { inline for (n_iter) |dy| { inline for (n_iter) |dz| { inline for (w_iter) |dw| { if (dx == 0 and dy == 0 and dz == 0 and dw == 0) continue; const x2 = if (dx == -1) x - 1 else x + dx; const y2 = if (dy == -1) y - 1 else y + dy; const z2 = if (dz == -1) z - 1 else z + dz; const w2 = if (dw == -1) w - 1 else w + dw; neighbors += @enumToInt(self.buf[idx][x2][y2][z2][w2]); } } } } self.buf[~idx][x][y][z][w] = switch (state) { .inactive => if (neighbors == 3) CubeState.active else CubeState.inactive, .active => if (neighbors == 2 or neighbors == 3) CubeState.active else CubeState.inactive, }; } } } } } fn count(self: World, idx: u1, comptime @"4d": bool) u32 { var accum: u32 = 0; for (self.buf[idx]) |*x_axis| { for (x_axis) |*y_axis| { for (y_axis) |*z_axis_| { const z_axis = if (@"4d") z_axis_ else z_axis_[15..16]; for (z_axis) |state| { accum += @enumToInt(state); } } } } return accum; } }; pub fn main(n: util.Utils) !void { var world = World{}; var results: [2]u32 = undefined; inline for ([_]bool{ false, true }) |@"4d"| { var idx: u1 = 0; for ([_]void{{}} ** 6) |_| { defer idx +%= 1; world.tick(idx, @"4d"); } results[@boolToInt(@"4d")] = world.count(idx, @"4d"); if (!@"4d") world = .{}; } try n.out.print("{}\n{}\n", .{ results[0], results[1] }); }
2020/17.zig
const std = @import("std"); const api = @import("./buzz_api.zig"); const utils = @import("../src/utils.zig"); const builtin = @import("builtin"); export fn time(vm: *api.VM) c_int { vm.bz_pushNum(@intToFloat(f64, std.time.milliTimestamp())); return 1; } export fn env(vm: *api.VM) c_int { const key = api.Value.bz_valueToString(vm.bz_peek(0)) orelse ""; if (std.os.getenvZ(key)) |value| { vm.bz_pushString(api.ObjString.bz_string(vm, utils.toCString(api.VM.allocator, value) orelse { vm.bz_throwString("Could not get environment variable"); return -1; }) orelse { vm.bz_throwString("Could not get environment variable"); return -1; }); return 1; } return 0; } fn sysTempDir() []const u8 { return switch (builtin.os.tag) { .windows => unreachable, // TODO: GetTempPath else => std.os.getenv("TMPDIR") orelse std.os.getenv("TMP") orelse std.os.getenv("TEMP") orelse std.os.getenv("TEMPDIR") orelse "/tmp", }; } export fn tmpDir(vm: *api.VM) c_int { const tmp_dir: []const u8 = sysTempDir(); vm.bz_pushString(api.ObjString.bz_string(vm, utils.toCString(api.VM.allocator, tmp_dir) orelse { vm.bz_throwString("Could not get tmp dir"); return -1; }) orelse { vm.bz_throwString("Could not get tmp dir"); return -1; }); return 1; } // TODO: what if file with same random name exists already? export fn tmpFilename(vm: *api.VM) c_int { const prefix: ?[*:0]const u8 = api.Value.bz_valueToString(vm.bz_peek(0)); var random_part = std.ArrayList(u8).init(api.VM.allocator); defer random_part.deinit(); random_part.writer().print("{x}", .{std.crypto.random.int(i64)}) catch { vm.bz_throwString("Could not get tmp file"); return -1; }; var random_part_b64 = std.ArrayList(u8).initCapacity(api.VM.allocator, std.base64.standard.Encoder.calcSize(random_part.items.len)) catch { vm.bz_throwString("Could not get tmp file"); return -1; }; random_part_b64.expandToCapacity(); defer random_part_b64.deinit(); _ = std.base64.standard.Encoder.encode(random_part_b64.items, random_part.items); var final = std.ArrayList(u8).init(api.VM.allocator); defer final.deinit(); // TODO: take into account system file separator (windows is \) if (prefix) |uprefix| { final.writer().print("{s}{s}-{s}", .{ sysTempDir(), uprefix, random_part_b64.items }) catch { vm.bz_throwString("Could not get tmp file"); return -1; }; } else { final.writer().print("{s}{s}", .{ sysTempDir(), random_part_b64.items }) catch { vm.bz_throwString("Could not get tmp file"); return -1; }; } vm.bz_pushString(api.ObjString.bz_string(vm, utils.toCString(api.VM.allocator, final.items) orelse { vm.bz_throwString("Could not get tmp file"); return -1; }) orelse { vm.bz_throwString("Could not get tmp file"); return -1; }); return 1; } // If it was named `exit` it would be considered by zig as a callback when std.os.exit is called export fn buzzExit(vm: *api.VM) c_int { const exitCode: u8 = @floatToInt(u8, api.Value.bz_valueToNumber(vm.bz_peek(0))); std.os.exit(exitCode); return 0; } export fn execute(vm: *api.VM) c_int { // const command: []const u8 = std.mem.sliceTo(api.Value.bz_valueToString(vm.bz_peek(0)) orelse "", 0); var command = std.ArrayList([]const u8).init(api.VM.allocator); defer command.deinit(); const argv = api.ObjList.bz_valueToList(vm.bz_peek(0)); const len = argv.bz_listLen(); var i: usize = 0; while (i < len) : (i += 1) { command.append(utils.toSlice(api.Value.bz_valueToString(argv.bz_listGet(i)) orelse "")) catch { vm.bz_throwString("Could not execute"); return -1; }; } const child_process = std.ChildProcess.init(command.items, api.VM.allocator) catch { vm.bz_throwString("Could not execute"); return -1; }; child_process.disable_aslr = true; child_process.spawn() catch { vm.bz_throwString("Could not execute"); return -1; }; vm.bz_pushNum(@intToFloat(f64, (child_process.wait() catch |err| { std.debug.print("err: {}\n", .{err}); vm.bz_throwString("Could not execute"); return -1; }).Exited)); return 1; }
lib/buzz_os.zig
const std = @import("std"); const Wat = @import("../wat.zig"); const Instance = @import("../instance.zig"); const Memory = @import("../Memory.zig"); test "import" { var fbs = std.io.fixedBufferStream( \\(module \\ (type (;0;) (func (param i32) (result i32))) \\ (import "env" "thing" (func (type 0))) \\ (export "run" (func 0))) ); var module = try Wat.parse(std.testing.allocator, fbs.reader()); defer module.deinit(); var instance = try module.instantiate(std.testing.allocator, null, struct { pub const env = struct { pub fn thing(mem: *Memory, arg: i32) i32 { return arg + 1; } }; }); defer instance.deinit(); { const result = try instance.call("run", .{@as(i32, 1)}); try std.testing.expectEqual(@as(i32, 2), result.?.I32); } { const result = try instance.call("run", .{@as(i32, 42)}); try std.testing.expectEqual(@as(i32, 43), result.?.I32); } } test "import multiple" { var fbs = std.io.fixedBufferStream( \\(module \\ (type (;0;) (func (param i32) (param i32) (result i32))) \\ (import "env" "add" (func (type 0))) \\ (import "env" "mul" (func (type 0))) \\ (export "add" (func 0)) \\ (export "mul" (func 1))) ); var module = try Wat.parse(std.testing.allocator, fbs.reader()); defer module.deinit(); var instance = try module.instantiate(std.testing.allocator, null, struct { pub const env = struct { pub fn add(mem: *Memory, arg0: i32, arg1: i32) i32 { return arg0 + arg1; } pub fn mul(mem: *Memory, arg0: i32, arg1: i32) i32 { return arg0 * arg1; } }; }); defer instance.deinit(); { const result = try instance.call("add", .{ @as(i32, 2), @as(i32, 3) }); try std.testing.expectEqual(@as(i32, 5), result.?.I32); } { const result = try instance.call("mul", .{ @as(i32, 2), @as(i32, 3) }); try std.testing.expectEqual(@as(i32, 6), result.?.I32); } }
src/func/imports.zig
const std = @import("std"); const input = @import("input.zig"); pub fn run(stdout: anytype) anyerror!void { { var input_ = try input.readFile("inputs/day2"); defer input_.deinit(); const result = try part1(&input_); try stdout.print("2a: {}\n", .{ result }); std.debug.assert(result == 1813801); } { var input_ = try input.readFile("inputs/day2"); defer input_.deinit(); const result = try part2(&input_); try stdout.print("2b: {}\n", .{ result }); std.debug.assert(result == 1960569556); } } fn part1(input_: anytype) !i64 { var horizontal: i64 = 0; var depth: i64 = 0; while (try input_.next()) |line| { const command = try parseCommand(line); switch (command.direction) { .forward => horizontal += command.distance, .down => depth += command.distance, .up => depth -= command.distance, } } return horizontal * depth; } fn part2(input_: anytype) !i64 { var horizontal: i64 = 0; var depth: i64 = 0; var aim: i64 = 0; while (try input_.next()) |line| { const command = try parseCommand(line); switch (command.direction) { .forward => { horizontal += command.distance; depth += aim * command.distance; }, .down => aim += command.distance, .up => aim -= command.distance, } } return horizontal * depth; } const Command = struct { direction: Direction, distance: i64, }; const Direction = enum { forward, down, up, }; fn parseCommand(line: []const u8) !Command { var parts = std.mem.split(u8, line, " "); const direction_s = parts.next() orelse return error.InvalidInput; const direction = std.meta.stringToEnum(Direction, direction_s) orelse return error.InvalidInput; const distance_s = parts.next() orelse return error.InvalidInput; const distance = try std.fmt.parseInt(i64, distance_s, 10); return Command { .direction = direction, .distance = distance, }; } test "day 2 example 1" { const input_ = \\forward 5 \\down 5 \\forward 8 \\up 3 \\down 8 \\forward 2 ; try std.testing.expectEqual(@as(i64, 15 * 10), try part1(&input.readString(input_))); try std.testing.expectEqual(@as(i64, 15 * 60), try part2(&input.readString(input_))); }
src/day2.zig
const std = @import("std"); fn getSrcPtrType(comptime T: type) ?type { return switch (@typeInfo(T)) { .Pointer => T, .Fn => T, .AnyFrame => T, .Optional => |o| switch (@typeInfo(o.child)) { .Pointer => |p| if (p.is_allowzero) null else o.child, .Fn => o.child, .AnyFrame => o.child, else => null, }, else => null, }; } fn isAllowZeroPtr(comptime T: type) bool { return switch (@typeInfo(T)) { .Pointer => |p| p.is_allowzero, .Optional => true, else => false, }; } fn genericArgCount(comptime fn_info: std.builtin.TypeInfo.Fn) comptime_int { for (fn_info.args) |arg, i| { if (arg.is_generic) return fn_info.args.len - i; } return 0; } fn sentinelEql(comptime left: anytype, comptime right: anytype) bool { if (@TypeOf(left) != @TypeOf(right)) { return false; } return std.meta.eql(left, right); } /// Translated from ir.cpp:types_match_const_cast_only fn typesMatchConstCastOnly(comptime wanted: type, comptime actual: type, comptime wanted_is_mutable: bool) bool { comptime { const wanted_info = @typeInfo(wanted); const actual_info = @typeInfo(actual); if (wanted == actual) return true; const wanted_ptr_type = getSrcPtrType(wanted); const actual_ptr_type = getSrcPtrType(actual); const wanted_allows_zero = isAllowZeroPtr(wanted); const actual_allows_zero = isAllowZeroPtr(actual); const wanted_is_c_ptr = wanted_info == .Pointer and wanted_info.Pointer.size == .C; const actual_is_c_ptr = actual_info == .Pointer and actual_info.Pointer.size == .C; const wanted_opt_or_ptr = wanted_ptr_type != null and @typeInfo(wanted_ptr_type.?) == .Pointer; const actual_opt_or_ptr = actual_ptr_type != null and @typeInfo(actual_ptr_type.?) == .Pointer; if (wanted_opt_or_ptr and actual_opt_or_ptr) { const wanted_ptr_info = @typeInfo(wanted_ptr_type.?).Pointer; const actual_ptr_info = @typeInfo(actual_ptr_type.?).Pointer; const ok_null_term_ptrs = wanted_ptr_info.sentinel == null or (actual_ptr_info.sentinel != null and sentinelEql(wanted_ptr_info.sentinel, actual_ptr_info.sentinel)); if (!ok_null_term_ptrs) { return false; } const ptr_sizes_eql = actual_ptr_info.size == wanted_ptr_info.size; if (!(ptr_sizes_eql or wanted_is_c_ptr or actual_is_c_ptr)) { return false; } const ok_cv_qualifiers = (!actual_ptr_info.is_const or wanted_ptr_info.is_const) and (!actual_ptr_info.is_volatile or wanted_ptr_info.is_volatile); if (!ok_cv_qualifiers) { return false; } if (!typesMatchConstCastOnly( wanted_ptr_info.child, actual_ptr_info.child, !wanted_ptr_info.is_const, )) { return false; } const ok_allows_zero = (wanted_allows_zero and (actual_allows_zero or !wanted_is_mutable)) or (!wanted_allows_zero and !actual_allows_zero); if (!ok_allows_zero) { return false; } if ((@sizeOf(wanted) > 0 and @sizeOf(actual) > 0) and actual_ptr_info.alignment >= wanted_ptr_info.alignment) { return true; } } // arrays if (wanted_info == .Array and actual_info == .Array and wanted_info.Array.len == actual_info.Array.len) { if (!typesMatchConstCastOnly( wanted_info.Array.child, actual_info.Array.child, wanted_is_mutable, )) { return false; } const ok_sentinels = wanted_info.Array.sentinel == null or (actual_info.Array.sentinel != null and sentinelEql(wanted_info.Array.sentinel, actual_info.Array.sentinel)); if (!ok_sentinels) { return false; } return true; } // const slice if (isSlice(wanted) and isSlice(actual)) { const wanted_slice_info = @typeInfo(wanted).Pointer; const actual_slice_info = @typeInfo(actual).Pointer; const ok_sentinels = wanted_slice_info.sentinel == null or (actual_slice_info.sentinel != null and sentinelEql(wanted_slice_info.sentinel, actual_slice_info.sentinel)); if (!ok_sentinels) { return false; } const ok_cv_qualifiers = (!actual_slice_info.is_const or wanted_slice_info.is_const) and (!actual_slice_info.is_volatile or wanted_slice_info.is_volatile); if (!ok_cv_qualifiers) { return false; } if (actual_slice_info.alignment < wanted_slice_info.alignment) { return false; } if (!typesMatchConstCastOnly( wanted_slice_info.child, actual_slice_info.child, !wanted_slice_info.is_const, )) { return false; } return true; } // optional types if (wanted_info == .Optional and actual_info == .Optional) { if ((wanted_ptr_type != null) != (actual_ptr_type != null)) { return false; } if (!typesMatchConstCastOnly( wanted_info.Optional.child, actual_info.Optional.child, wanted_is_mutable, )) { return false; } return true; } // error union if (wanted_info == .ErrorUnion and actual_info == .ErrorUnion) { if (!typesMatchConstCastOnly( wanted_info.ErrorUnion.payload, actual_info.ErrorUnion.payload, wanted_is_mutable, )) { return false; } if (!typesMatchConstCastOnly( wanted_info.ErrorUnion.error_set, actual_info.ErrorUnion.error_set, wanted_is_mutable, )) { return false; } return true; } // error set if (wanted_info == .ErrorSet and actual_info == .ErrorSet) { return isSuperset(wanted, actual); } // fn if (wanted_info == .Fn and actual_info == .Fn) { if (wanted_info.Fn.alignment > actual_info.Fn.alignment) { return false; } if (wanted_info.Fn.is_var_args != actual_info.Fn.is_var_args) { return false; } if (wanted_info.Fn.is_generic != actual_info.Fn.is_generic) { return false; } if (!wanted_info.Fn.is_generic and actual_info.Fn.return_type != null) { if (!typesMatchConstCastOnly( wanted_info.Fn.return_type.?, actual_info.Fn.return_type.?, false, )) { return false; } } if (wanted_info.Fn.args.len != actual_info.Fn.args.len) { return false; } if (genericArgCount(wanted_info.Fn) != genericArgCount(actual_info.Fn)) { return false; } if (wanted_info.Fn.calling_convention != actual_info.Fn.calling_convention) { return false; } var i = 0; while (i < wanted_info.Fn.args.len) : (i += 1) { const actual_arg_info = actual_info.Fn.args[i]; const wanted_arg_info = wanted_info.Fn.args[i]; if (actual_arg_info.is_generic != wanted_arg_info.is_generic) { return false; } if (actual_arg_info.is_noalias != wanted_arg_info.is_noalias) { return false; } if (actual_arg_info.is_generic) { continue; } if (!typesMatchConstCastOnly( actual_arg_info.arg_type.?, wanted_arg_info.arg_type.?, false, )) { return false; } } return true; } if (wanted_info == .Int and actual_info == .Int) { if (wanted_info.Int.signedness != actual_info.Int.signedness or wanted_info.Int.bits != actual_info.Int.bits) { return false; } return true; } if (wanted_info == .Vector and actual_info == .Vector) { if (wanted_info.Vector.len != actual_info.Vector.len) { return false; } if (!typesMatchConstCastOnly( wanted_info.Vector.child, actual_info.Vector.child, false, )) { return false; } return true; } return false; } } fn isSuperset(comptime A: type, comptime B: type) bool { const a_info = @typeInfo(A).ErrorSet.?; const b_info = @typeInfo(B).ErrorSet.?; for (b_info) |b_err| { var found = false; for (a_info) |a_err| { if (std.mem.eql(u8, a_err.name, b_err.name)) { found = true; break; } } if (!found) { return false; } } return true; } fn errSetEql(comptime A: type, comptime B: type) bool { if (A == B) return true; const a_info = @typeInfo(A).ErrorSet.?; const b_info = @typeInfo(B).ErrorSet.?; if (a_info.len != b_info.len) return false; return isSuperset(A, B); } /// Translated from ir.cpp:ir_resolve_peer_types pub fn PeerType(comptime types: anytype) ?type { var prev_type: type = undefined; var prev_info: std.builtin.TypeInfo = undefined; var i = 0; while (true) { prev_type = types[i]; prev_info = @typeInfo(prev_type); if (prev_info == .NoReturn) { i += 1; if (i == types.len) { return prev_type; } continue; } break; } // Differences with stage1 implementation: // we need only keep the type and use || // to update it, no need to separately keep // an error entry table. var err_set_type: ?type = null; if (prev_info == .ErrorSet) { err_set_type = prev_type; } var any_are_null = prev_info == .Null; var convert_to_const_slice = false; var make_the_slice_const = false; var make_the_pointer_const = false; while (i < types.len) : (i += 1) { const cur_type = types[i]; const cur_info = @typeInfo(cur_type); prev_info = @typeInfo(prev_type); if (prev_type == cur_type) continue; if (prev_info == .NoReturn) { prev_type = cur_type; continue; } if (cur_info == .NoReturn) { continue; } if (prev_info == .ErrorSet) { switch (cur_info) { .ErrorSet => { if (err_set_type == anyerror) { continue; } if (cur_type == anyerror) { prev_type = cur_type; err_set_type = anyerror; continue; } if (isSuperset(err_set_type.?, cur_type)) { continue; } if (isSuperset(cur_type, err_set_type.?)) { err_set_type = cur_type; prev_type = cur_type; continue; } err_set_type = err_set_type.? || cur_type; continue; }, .ErrorUnion => |cur_err_union| { if (err_set_type == anyerror) { prev_type = cur_type; continue; } const cur_err_set_type = cur_err_union.error_set; if (cur_err_set_type == anyerror) { err_set_type = anyerror; prev_type = cur_type; continue; } if (isSuperset(cur_err_set_type, err_set_type.?)) { err_set_type = cur_err_set_type; prev_type = cur_type; errors = cur_errors; continue; } err_set_type = err_set_type.? || cur_err_set_type; prev_type = cur_type; continue; }, else => { prev_type = cur_type; continue; }, } } if (cur_info == .ErrorSet) { if (cur_type == anyerror) { err_set_type = anyerror; continue; } if (err_set_type == anyerror) { continue; } if (err_set_type == null) { err_set_type = cur_type; continue; } if (isSuperset(err_set_type.?, cur_type)) { continue; } err_set_type = err_set_type.? || cur_type; continue; } if (prev_info == .ErrorUnion and cur_info == .ErrorUnion) { const prev_payload_type = prev_info.ErrorUnion.payload; const cur_payload_type = cur_info.ErrorUnion.payload; const const_cast_prev = typesMatchConstCastOnly(prev_payload_type, cur_payload_type, false); const const_cast_cur = typesMatchConstCastOnly(cur_payload_type, prev_payload_type, false); if (const_cast_cur or const_cast_prev) { if (const_cast_cur) { prev_type = cur_type; } const prev_err_set_type = if (err_set_type) |s| s else prev_info.ErrorUnion.error_set; const cur_err_set_type = cur_info.ErrorUnion.error_set; if (errSetEql(prev_err_set_type, cur_err_set_type)) { continue; } if (prev_err_set_type == anyerror or cur_err_set_type == anyerror) { err_set_type = anyerror; continue; } if (err_set_type == null) { err_set_type = prev_err_set_type; } if (isSuperset(err_set_type, cur_err_set_type)) { continue; } if (isSuperset(cur_err_set_type, err_set_type)) { err_set_type = cur_err_set_type; continue; } err_set_type = err_set_type.? || cur_err_set_type; continue; } } if (prev_info == .Null) { prev_type = cur_type; any_are_null = true; continue; } if (cur_info == .Null) { any_are_null = true; continue; } if (prev_info == .Enum and cur_info == .EnumLiteral) { // We assume the enum literal is coercible to any enum type continue; } if (prev_info == .Union and prev_info.Union.tag_type != null and cur_info == .EnumLiteral) { // Same as above continue; } if (cur_info == .Enum and prev_info == .EnumLiteral) { // Same as above prev_type = cur_type; continue; } if (cur_info == .Union and cur_info.Union.tag_type != null and prev_info == .EnumLiteral) { // Same as above prev_type = cur_type; continue; } if (prev_info == .Pointer and prev_info.Pointer.size == .C and (cur_info == .ComptimeInt or cur_info == .Int)) { continue; } if (cur_info == .Pointer and cur_info.Pointer.size == .C and (prev_info == .ComptimeInt or prev_info == .Int)) { prev_type = cur_type; continue; } if (prev_info == .Pointer and cur_info == .Pointer) { if (prev_info.Pointer.size == .C and typesMatchConstCastOnly( prev_info.Pointer.child, cur_info.Pointer.child, !prev_info.Pointer.is_const, )) { continue; } if (cur_info.Pointer.size == .C and typesMatchConstCastOnly( cur_info.Pointer.child, prev_info.Pointer.child, !cur_info.Pointer.is_const, )) { prev_type = cur_type; continue; } } if (typesMatchConstCastOnly(prev_type, cur_type, false)) continue; if (typesMatchConstCastOnly(cur_type, prev_type, false)) { prev_type = cur_type; continue; } if (prev_info == .Int and cur_info == .Int and prev_info.Int.signedness == cur_info.Int.signedness) { if (cur_info.Int.bits > prev_info.Int.bits) { prev_type = cur_type; } continue; } if (prev_info == .Float and cur_info == .Float) { if (cur_info.Float.bits > prev_info.Float.bits) { prev_type = cur_type; } continue; } if (prev_info == .ErrorUnion and typesMatchConstCastOnly(prev_info.ErrorUnion.payload, cur_type, false)) { continue; } if (cur_info == .ErrorUnion and typesMatchConstCastOnly(cur_info.ErrorUnion.payload, prev_type, false)) { if (err_set_type) |err_set| { const cur_err_set_type = cur_info.ErrorUnion.error_set; if (err_set_type == anyerror or cur_err_set_type == anyerror) { err_set_type = anyerror; prev_type = cur_type; continue; } err_set_type = err_set_type.? || cur_err_set_type; } prev_type = cur_type; continue; } if (prev_info == .Optional and typesMatchConstCastOnly(prev_info.Optional.child, cur_type, false)) { continue; } if (cur_info == .Optional and typesMatchConstCastOnly(cur_info.Optional.child, prev_type, false)) { prev_type = cur_type; continue; } if (prev_info == .Optional and typesMatchConstCastOnly(cur_type, prev_info.Optional.child, false)) { prev_type = cur_type; any_are_null = true; continue; } if (cur_info == .Optional and typesMatchConstCastOnly(prev_type, cur_info.Optional.child, false)) { any_are_null = true; continue; } if (cur_info == .Undefined) continue; if (prev_info == .Undefined) { prev_type = cur_type; continue; } if (prev_info == .ComptimeInt and (cur_info == .Int or cur_info == .ComptimeInt)) { prev_type = cur_type; continue; } if (prev_info == .ComptimeFloat and (cur_info == .Float or cur_info == .ComptimeFloat)) { prev_type = cur_type; continue; } if (cur_info == .ComptimeInt and (prev_info == .Int or prev_info == .ComptimeInt)) { continue; } if (cur_info == .ComptimeFloat and (prev_info == .Float or prev_info == .ComptimeFloat)) { continue; } // *[N]T to [*]T if (prev_info == .Pointer and prev_info.Pointer.size == .One and @typeInfo(prev_info.Pointer.child) == .Array and (cur_info == .Pointer and cur_info.Pointer.size == .Many)) { convert_to_const_slice = false; prev_type = cur_type; if (prev_info.Pointer.is_const and !cur_info.Pointer.is_const) { make_the_pointer_const = true; } continue; } // *[N]T to [*]T if (cur_info == .Pointer and cur_info.Pointer.size == .One and @typeInfo(cur_info.Pointer.child) == .Array and (prev_info == .Pointer and prev_info.Pointer.size == .Many)) { if (cur_info.Pointer.is_const and !prev_info.Pointer.is_const) { make_the_pointer_const = true; } continue; } // *[N]T to []T // *[N]T to E![]T if (cur_info == .Pointer and cur_info.Pointer.size == .One and @typeInfo(cur_info.Pointer.child) == .Array and ((prev_info == .ErrorUnion and isSlice(prev_info.ErrorUnion.payload)) or isSlice(prev_type))) { const array_type = cur_info.Pointer.child; const slice_type = if (prev_info == .ErrorUnion) prev_info.ErrorUnion.payload else prev_type; const array_info = @typeInfo(array_type).Array; const slice_ptr_type = slicePtrType(slice_type); const slice_ptr_info = @typeInfo(slice_ptr_type); if (typesMatchConstCastOnly( slice_ptr_info.Pointer.child, array_info.child, false, )) { const const_ok = slice_ptr_info.Pointer.is_const or array_info.size == 0 or !cur_info.Pointer.is_const; if (!const_ok) make_the_slice_const = true; convert_to_const_slice = false; continue; } } // *[N]T to []T // *[N]T to E![]T if (prev_info == .Pointer and prev_info.Pointer.size == .One and @typeInfo(prev_info.Pointer.child) == .Array and ((cur_info == .ErrorUnion and isSlice(cur_info.ErrorUnion.payload)) or (cur_info == .Optional and isSlice(cur_info.Optional.child)) or isSlice(cur_type))) { const array_type = prev_info.Pointer.child; const slice_type = switch (cur_info) { .ErrorUnion => |error_union_info| error_union_info.payload, .Optional => |optional_info| optional_info.child, else => cur_type, }; const array_info = @typeInfo(array_type).Array; const slice_ptr_type = slicePtrType(slice_type); const slice_ptr_info = @typeInfo(slice_ptr_type); if (typesMatchConstCastOnly( slice_ptr_info.Pointer.child, array_info.child, false, )) { const const_ok = slice_ptr_info.Pointer.is_const or array_info.size == 0 or !prev_info.Pointer.is_const; if (!const_ok) make_the_slice_const = true; prev_type = cur_type; convert_to_const_slice = false; continue; } } // *[N]T and *[M]T const both_ptr_to_arr = (cur_info == .Pointer and cur_info.Pointer.size == .One and @typeInfo(cur_info.Pointer.child) == .Array and prev_info == .Pointer and prev_info.Pointer.size == .One and @typeInfo(prev_info.Pointer.child) == .Array); if (both_ptr_to_arr) { const cur_array_info = @typeInfo(cur_info.Pointer.child).Array; const prev_array_info = @typeInfo(prev_info.Pointer.child).Array; if (prev_array_info.sentinel == null or (cur_array_info.sentinel != null and sentinelEql(prev_array_info.sentinel, cur_array_info.sentinel)) and typesMatchConstCastOnly( cur_array_info.child, prev_array_info.child, !cur_info.Pointer.is_const, )) { const const_ok = cur_info.Pointer.is_const or !prev_info.Pointer.is_const or prev_array_info.len == 0; if (!const_ok) make_the_slice_const = true; prev_type = cur_type; convert_to_const_slice = true; continue; } if (cur_array_info.sentinel == null or (prev_array_info.sentinel != null and sentinelEql(cur_array_info.sentinel, prev_array_info.sentinel)) and typesMatchConstCastOnly( prev_array_info.child, cur_array_info.child, !prev_info.Pointer.is_const, )) { const const_ok = prev_indo.Pointer.is_const or !cur_info.Pointer.is_const or cur_array_info.len == 0; if (!const_ok) make_the_slice_const = true; convert_to_const_slice = true; continue; } } if (prev_info == .Enum and cur_info == .Union and cur_info.Union.tag_type != null) { if (cur_info.Union.tag_type.? == prev_type) { continue; } } if (cur_info == .Enum and prev_info == .Union and prev_info.Union.tag_type != null) { if (prev_info.Union.tag_type.? == cur_type) { prev_type = cur_type; continue; } } return null; } if (convert_to_const_slice) { if (prev_info == .Pointer) { const array_type = prev_info.Pointer.child; const array_info = @typeInfo(array_type).Array; const slice_type = @Type(.{ .Pointer = .{ .child = array_info.child, .is_const = prev_info.Pointer.is_const or make_the_slice_const, .is_volatile = false, .size = .Slice, .alignment = if (@sizeOf(array_info.child) > 0) @alignOf(array_info.child) else 0, .is_allowzero = false, .sentinel = array_info.sentinel, }, }); if (err_set_type) |err_type| { return err_type!slice_type; } return slice_type; } } else if (err_set_type) |err_type| { return switch (prev_info) { .ErrorSet => err_type, .ErrorUnion => |u| err_type!u.payload, else => null, }; } else if (any_are_null and prev_info != .Null) { if (prev_info == .Optional) { return prev_type; } return ?prev_type; } else if (make_the_slice_const) { const slice_type = switch (prev_info) { .ErrorUnion => |u| u.payload, .Pointer => |p| if (p.size == .Slice) prev_type else unreachable, else => unreachable, }; const adjusted_slice_type = blk: { var ptr_info = @typeInfo(slice_type); ptr_info.Pointer.is_const = make_the_slice_const; break :blk @Type(ptr_info); }; return switch (prev_info) { .ErrorUnion => |u| u.error_set!adjusted_slice_type, .Pointer => |p| if (p.size == .Slice) adjusted_slice_type else unreachable, else => unreachable, }; } else if (make_the_pointer_const) { return blk: { var ptr_info = @typeInfo(prev_type); ptr_info.Pointer.is_const = make_the_pointer_const; break :blk @Type(ptr_info); }; } return prev_type; } fn slicePtrType(comptime S: type) type { var info = @typeInfo(S); info.Pointer.size = .Many; return @Type(info); } const isSlice = std.meta.trait.isSlice; pub fn coercesTo(comptime dst: type, comptime src: type) bool { return (PeerType(.{ dst, src }) orelse return false) == dst; } const ContainsAnytype = struct { val: anytype }; const AnyType = std.meta.fieldInfo(ContainsAnytype, "val").field_type; pub fn requiresComptime(comptime T: type) bool { comptime { switch (T) { AnyType, comptime_int, comptime_float, type, @Type(.EnumLiteral), @Type(.Null), @Type(.Undefined), => return true, else => {}, } const info = @typeInfo(T); switch (info) { .BoundFn => return true, .Array => |a| return requiresComptime(a.child), .Struct => |s| { for (s.fields) |f| { if (requiresComptime(f.field_type)) return true; } return false; }, .Union => |u| { for (u.fields) |f| { if (requiresComptime(f.field_type)) return true; } return false; }, .Optional => |o| return requiresComptime(o.child), .ErrorUnion => |u| return requiresComptime(u.payload), .Pointer => |p| { if (@typeInfo(p.child) == .Opaque) return false; return requiresComptime(p.child); }, .Fn => |f| return f.is_generic, else => return false, } } } fn testPeerTypeIs(comptime types: anytype, comptime result: type) void { std.testing.expect((PeerType(types) orelse unreachable) == result); } fn testNoPeerType(comptime types: anytype) void { std.testing.expect(PeerType(types) == null); } test "PeerType" { testPeerTypeIs(.{ *const [3:0]u8, *const [15:0]u8 }, [:0]const u8); testPeerTypeIs(.{ usize, u8 }, usize); const E1 = error{OutOfMemory}; const E2 = error{}; const S = struct {}; testPeerTypeIs(.{ E1, E2 }, E1); testPeerTypeIs(.{ E1, anyerror!S, E2 }, anyerror!S); testPeerTypeIs(.{ *align(16) usize, *align(2) usize }, *align(2) usize); testNoPeerType(.{ usize, void }); testNoPeerType(.{ struct {}, struct {} }); } test "coercesTo" { std.testing.expect(coercesTo([]const u8, *const [123:0]u8)); std.testing.expect(coercesTo(usize, comptime_int)); } test "requiresComptime" { std.testing.expect(requiresComptime(comptime_int)); std.testing.expect(requiresComptime(struct { foo: anytype })); std.testing.expect(requiresComptime(struct { foo: struct { bar: comptime_float } })); std.testing.expect(!requiresComptime(struct { foo: void })); }
PeerType.zig
const std = @import("std"); const net = std.net; const os = std.os; const linux = os.linux; const io_uring_sqe = linux.io_uring_sqe; const io_uring_cqe = linux.io_uring_cqe; const assert = std.debug.assert; const Server = struct { ring: linux.IO_Uring, fn q_accept( self: *Server, user_data: u64, /// This argument is a socket that has been created with `socket`, bound to a local address /// with `bind`, and is listening for connections after a `listen`. sock: os.socket_t, /// This argument is a pointer to a sockaddr structure. This structure is filled in with the /// address of the peer socket, as known to the communications layer. The exact format of the /// address returned addr is determined by the socket's address family (see `socket` and the /// respective protocol man pages). addr: *os.sockaddr, /// This argument is a value-result argument: the caller must initialize it to contain the /// size (in bytes) of the structure pointed to by addr; on return it will contain the actual size /// of the peer address. /// /// The returned address is truncated if the buffer provided is too small; in this case, `addr_size` /// will return a value greater than was supplied to the call. addr_size: *os.socklen_t, /// The following values can be bitwise ORed in flags to obtain different behavior: /// * `SOCK.NONBLOCK` - Set the `O.NONBLOCK` file status flag on the open file description (see `open`) /// referred to by the new file descriptor. Using this flag saves extra calls to `fcntl` to achieve /// the same result. /// * `SOCK.CLOEXEC` - Set the close-on-exec (`FD_CLOEXEC`) flag on the new file descriptor. See the /// description of the `O.CLOEXEC` flag in `open` for reasons why this may be useful. flags: u32, ) !*io_uring_sqe { return try self.ring.accept(user_data, sock, addr, addr_size, flags); } fn q_tick(self: *Server) !*io_uring_sqe { const sqe_tick = try self.ring.nop(33); sqe_tick.flags |= linux.IOSQE_IO_LINK; const ts = os.linux.kernel_timespec{ .tv_sec = 0, .tv_nsec = 1000000 }; return try self.ring.link_timeout(66, &ts, 0); } }; const Op = union(enum) { accept: struct { sock: os.socket_t, flags: u32 = os.SOCK.CLOEXEC | os.SOCK.NONBLOCK, addr: os.sockaddr = undefined, addr_size: os.socklen_t = @sizeOf(os.sockaddr), }, fn prep(self: Op, ring: linux.IO_Uring, user_data: u64) !*io_uring_sqe { switch (self) { .accept => |*c| { return try ring.accept(user_data, c.sock, c.addr, c.addr_size, c.flags); }, } } }; pub fn main() !void { const LISTEN_BACKLOG = 1; const address = try net.Address.parseIp4("127.0.0.1", 3131); const listen_socket = try os.socket(address.any.family, os.SOCK.STREAM | os.SOCK.CLOEXEC, 0); defer os.closeSocket(listen_socket); // try os.setsockopt(listen_socket, os.SOL.SOCKET, os.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1))); try os.bind(listen_socket, &address.any, address.getOsSockLen()); try os.listen(listen_socket, LISTEN_BACKLOG); var ring = try std.os.linux.IO_Uring.init(256, 0); defer ring.deinit(); // // var cqes: [128]io_uring_cqe = undefined; // std.time.Timer // linux.timerfd_create(linux.CLOCK.MONOTONIC, flags: u32); var cqes: [16]io_uring_cqe = undefined; var pending = try std.BoundedArray(Op, 256).init(0); { const idx_accept = pending.len; try pending.append(Op{ .accept = .{ .sock = listen_socket } }); try pending.get(idx_accept).prep(ring, idx_accept); } // _ = try ring.accept(accept_competion_idx, listen_socket, &peer_addr.any, &peer_addr_size, os.SOCK.CLOEXEC | os.SOCK.NONBLOCK); // completions.addOne() while (true) { const nsubmit = try ring.submit(); const ncqe = try ring.copy_cqes(&cqes, 1); std.log.info("loop: nsubmit={} ncqe={}\n", .{ nsubmit, ncqe }); for (cqes[0..ncqe]) |cqe| { const op_idx = cqe.user_data; const op = pending.get(op_idx); switch (op) { .accept => |accept| { std.log.info("{}", .{accept}); try op.prep(ring, op_idx); }, } // switch (cqe.err()) { // .SUCCESS => {}, // else => |errno| std.debug.panic("unhandled errno: {}", .{errno}), // } std.log.info("cqe: {}", .{cqe}); } } // submit: non-blocking }
src/io_uring-tcp-hasher/main.zig
pub const MSSIP_FLAGS_PROHIBIT_RESIZE_ON_CREATE = @as(u32, 65536); pub const MSSIP_FLAGS_USE_CATALOG = @as(u32, 131072); pub const MSSIP_FLAGS_MULTI_HASH = @as(u32, 262144); pub const SPC_INC_PE_RESOURCES_FLAG = @as(u32, 128); pub const SPC_INC_PE_DEBUG_INFO_FLAG = @as(u32, 64); pub const SPC_INC_PE_IMPORT_ADDR_TABLE_FLAG = @as(u32, 32); pub const SPC_EXC_PE_PAGE_HASHES_FLAG = @as(u32, 16); pub const SPC_INC_PE_PAGE_HASHES_FLAG = @as(u32, 256); pub const SPC_DIGEST_GENERATE_FLAG = @as(u32, 512); pub const SPC_DIGEST_SIGN_FLAG = @as(u32, 1024); pub const SPC_DIGEST_SIGN_EX_FLAG = @as(u32, 16384); pub const SPC_RELAXED_PE_MARKER_CHECK = @as(u32, 2048); pub const SPC_MARKER_CHECK_SKIP_SIP_INDIRECT_DATA_FLAG = @as(u32, 1); pub const SPC_MARKER_CHECK_CURRENTLY_SUPPORTED_FLAGS = @as(u32, 1); pub const SIP_CAP_SET_VERSION_2 = @as(u32, 2); pub const SIP_CAP_SET_VERSION_3 = @as(u32, 3); pub const SIP_CAP_SET_CUR_VER = @as(u32, 3); pub const SIP_CAP_FLAG_SEALING = @as(u32, 1); pub const SIP_MAX_MAGIC_NUMBER = @as(u32, 4); //-------------------------------------------------------------------------------- // Section: Types (18) //-------------------------------------------------------------------------------- pub const SIP_SUBJECTINFO = extern struct { cbSize: u32, pgSubjectType: ?*Guid, hFile: ?HANDLE, pwsFileName: ?[*:0]const u16, pwsDisplayName: ?[*:0]const u16, dwReserved1: u32, dwIntVersion: u32, hProv: usize, DigestAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, dwFlags: u32, dwEncodingType: u32, dwReserved2: u32, fdwCAPISettings: u32, fdwSecuritySettings: u32, dwIndex: u32, dwUnionChoice: u32, Anonymous: extern union { psFlat: ?*MS_ADDINFO_FLAT, psCatMember: ?*MS_ADDINFO_CATALOGMEMBER, psBlob: ?*MS_ADDINFO_BLOB, }, pClientData: ?*anyopaque, }; pub const MS_ADDINFO_FLAT = extern struct { cbStruct: u32, pIndirectData: ?*SIP_INDIRECT_DATA, }; pub const MS_ADDINFO_CATALOGMEMBER = extern struct { cbStruct: u32, pStore: ?*CRYPTCATSTORE, pMember: ?*CRYPTCATMEMBER, }; pub const MS_ADDINFO_BLOB = extern struct { cbStruct: u32, cbMemObject: u32, pbMemObject: ?*u8, cbMemSignedMsg: u32, pbMemSignedMsg: ?*u8, }; pub const SIP_CAP_SET_V2 = extern struct { cbSize: u32, dwVersion: u32, isMultiSign: BOOL, dwReserved: u32, }; pub const SIP_CAP_SET_V3 = extern struct { cbSize: u32, dwVersion: u32, isMultiSign: BOOL, Anonymous: extern union { dwFlags: u32, dwReserved: u32, }, }; pub const SIP_INDIRECT_DATA = extern struct { Data: CRYPT_ATTRIBUTE_TYPE_VALUE, DigestAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, Digest: CRYPTOAPI_BLOB, }; pub const pCryptSIPGetSignedDataMsg = fn( pSubjectInfo: ?*SIP_SUBJECTINFO, pdwEncodingType: ?*u32, dwIndex: u32, pcbSignedDataMsg: ?*u32, pbSignedDataMsg: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const pCryptSIPPutSignedDataMsg = fn( pSubjectInfo: ?*SIP_SUBJECTINFO, dwEncodingType: u32, pdwIndex: ?*u32, cbSignedDataMsg: u32, pbSignedDataMsg: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const pCryptSIPCreateIndirectData = fn( pSubjectInfo: ?*SIP_SUBJECTINFO, pcbIndirectData: ?*u32, pIndirectData: ?*SIP_INDIRECT_DATA, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const pCryptSIPVerifyIndirectData = fn( pSubjectInfo: ?*SIP_SUBJECTINFO, pIndirectData: ?*SIP_INDIRECT_DATA, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const pCryptSIPRemoveSignedDataMsg = fn( pSubjectInfo: ?*SIP_SUBJECTINFO, dwIndex: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const SIP_DISPATCH_INFO = extern struct { cbSize: u32, hSIP: ?HANDLE, pfGet: ?pCryptSIPGetSignedDataMsg, pfPut: ?pCryptSIPPutSignedDataMsg, pfCreate: ?pCryptSIPCreateIndirectData, pfVerify: ?pCryptSIPVerifyIndirectData, pfRemove: ?pCryptSIPRemoveSignedDataMsg, }; pub const pfnIsFileSupported = fn( hFile: ?HANDLE, pgSubject: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const pfnIsFileSupportedName = fn( pwszFileName: ?PWSTR, pgSubject: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const SIP_ADD_NEWPROVIDER = extern struct { cbStruct: u32, pgSubject: ?*Guid, pwszDLLFileName: ?PWSTR, pwszMagicNumber: ?PWSTR, pwszIsFunctionName: ?PWSTR, pwszGetFuncName: ?PWSTR, pwszPutFuncName: ?PWSTR, pwszCreateFuncName: ?PWSTR, pwszVerifyFuncName: ?PWSTR, pwszRemoveFuncName: ?PWSTR, pwszIsFunctionNameFmt2: ?PWSTR, pwszGetCapFuncName: ?PWSTR, }; pub const pCryptSIPGetCaps = fn( pSubjInfo: ?*SIP_SUBJECTINFO, pCaps: ?*SIP_CAP_SET_V3, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const pCryptSIPGetSealedDigest = fn( pSubjectInfo: ?*SIP_SUBJECTINFO, pSig: ?[*:0]const u8, dwSig: u32, pbDigest: ?[*:0]u8, pcbDigest: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; //-------------------------------------------------------------------------------- // Section: Functions (12) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn CryptSIPGetSignedDataMsg( pSubjectInfo: ?*SIP_SUBJECTINFO, pdwEncodingType: ?*CERT_QUERY_ENCODING_TYPE, dwIndex: u32, pcbSignedDataMsg: ?*u32, pbSignedDataMsg: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn CryptSIPPutSignedDataMsg( pSubjectInfo: ?*SIP_SUBJECTINFO, dwEncodingType: CERT_QUERY_ENCODING_TYPE, pdwIndex: ?*u32, cbSignedDataMsg: u32, pbSignedDataMsg: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn CryptSIPCreateIndirectData( pSubjectInfo: ?*SIP_SUBJECTINFO, pcbIndirectData: ?*u32, pIndirectData: ?*SIP_INDIRECT_DATA, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn CryptSIPVerifyIndirectData( pSubjectInfo: ?*SIP_SUBJECTINFO, pIndirectData: ?*SIP_INDIRECT_DATA, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WINTRUST" fn CryptSIPRemoveSignedDataMsg( pSubjectInfo: ?*SIP_SUBJECTINFO, dwIndex: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "CRYPT32" fn CryptSIPLoad( pgSubject: ?*const Guid, dwFlags: u32, pSipDispatch: ?*SIP_DISPATCH_INFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "CRYPT32" fn CryptSIPRetrieveSubjectGuid( FileName: ?[*:0]const u16, hFileIn: ?HANDLE, pgSubject: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "CRYPT32" fn CryptSIPRetrieveSubjectGuidForCatalogFile( FileName: ?[*:0]const u16, hFileIn: ?HANDLE, pgSubject: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "CRYPT32" fn CryptSIPAddProvider( psNewProv: ?*SIP_ADD_NEWPROVIDER, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "CRYPT32" fn CryptSIPRemoveProvider( pgProv: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "WINTRUST" fn CryptSIPGetCaps( pSubjInfo: ?*SIP_SUBJECTINFO, pCaps: ?*SIP_CAP_SET_V3, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINTRUST" fn CryptSIPGetSealedDigest( pSubjectInfo: ?*SIP_SUBJECTINFO, pSig: ?[*:0]const u8, dwSig: u32, pbDigest: ?[*:0]u8, pcbDigest: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (10) //-------------------------------------------------------------------------------- const Guid = @import("../../zig.zig").Guid; const BOOL = @import("../../foundation.zig").BOOL; const CERT_QUERY_ENCODING_TYPE = @import("../../security/cryptography.zig").CERT_QUERY_ENCODING_TYPE; const CRYPT_ALGORITHM_IDENTIFIER = @import("../../security/cryptography.zig").CRYPT_ALGORITHM_IDENTIFIER; const CRYPT_ATTRIBUTE_TYPE_VALUE = @import("../../security/cryptography.zig").CRYPT_ATTRIBUTE_TYPE_VALUE; const CRYPTCATMEMBER = @import("../../security/cryptography/catalog.zig").CRYPTCATMEMBER; const CRYPTCATSTORE = @import("../../security/cryptography/catalog.zig").CRYPTCATSTORE; const CRYPTOAPI_BLOB = @import("../../security/cryptography.zig").CRYPTOAPI_BLOB; const HANDLE = @import("../../foundation.zig").HANDLE; const PWSTR = @import("../../foundation.zig").PWSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "pCryptSIPGetSignedDataMsg")) { _ = pCryptSIPGetSignedDataMsg; } if (@hasDecl(@This(), "pCryptSIPPutSignedDataMsg")) { _ = pCryptSIPPutSignedDataMsg; } if (@hasDecl(@This(), "pCryptSIPCreateIndirectData")) { _ = pCryptSIPCreateIndirectData; } if (@hasDecl(@This(), "pCryptSIPVerifyIndirectData")) { _ = pCryptSIPVerifyIndirectData; } if (@hasDecl(@This(), "pCryptSIPRemoveSignedDataMsg")) { _ = pCryptSIPRemoveSignedDataMsg; } if (@hasDecl(@This(), "pfnIsFileSupported")) { _ = pfnIsFileSupported; } if (@hasDecl(@This(), "pfnIsFileSupportedName")) { _ = pfnIsFileSupportedName; } if (@hasDecl(@This(), "pCryptSIPGetCaps")) { _ = pCryptSIPGetCaps; } if (@hasDecl(@This(), "pCryptSIPGetSealedDigest")) { _ = pCryptSIPGetSealedDigest; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/security/cryptography/sip.zig
pub const DIALENG_OperationComplete = @as(u32, 65536); pub const DIALENG_RedialAttempt = @as(u32, 65537); pub const DIALENG_RedialWait = @as(u32, 65538); pub const INTERNET_INVALID_PORT_NUMBER = @as(u32, 0); pub const INTERNET_DEFAULT_FTP_PORT = @as(u32, 21); pub const INTERNET_DEFAULT_GOPHER_PORT = @as(u32, 70); pub const INTERNET_DEFAULT_SOCKS_PORT = @as(u32, 1080); pub const INTERNET_MAX_HOST_NAME_LENGTH = @as(u32, 256); pub const INTERNET_MAX_USER_NAME_LENGTH = @as(u32, 128); pub const INTERNET_MAX_PASSWORD_LENGTH = @as(u32, 128); pub const INTERNET_MAX_PORT_NUMBER_LENGTH = @as(u32, 5); pub const INTERNET_MAX_PORT_NUMBER_VALUE = @as(u32, 65535); pub const INTERNET_KEEP_ALIVE_UNKNOWN = @as(u32, 4294967295); pub const INTERNET_KEEP_ALIVE_ENABLED = @as(u32, 1); pub const INTERNET_KEEP_ALIVE_DISABLED = @as(u32, 0); pub const INTERNET_REQFLAG_FROM_CACHE = @as(u32, 1); pub const INTERNET_REQFLAG_ASYNC = @as(u32, 2); pub const INTERNET_REQFLAG_VIA_PROXY = @as(u32, 4); pub const INTERNET_REQFLAG_NO_HEADERS = @as(u32, 8); pub const INTERNET_REQFLAG_PASSIVE = @as(u32, 16); pub const INTERNET_REQFLAG_CACHE_WRITE_DISABLED = @as(u32, 64); pub const INTERNET_REQFLAG_NET_TIMEOUT = @as(u32, 128); pub const INTERNET_FLAG_IDN_DIRECT = @as(u32, 1); pub const INTERNET_FLAG_IDN_PROXY = @as(u32, 2); pub const INTERNET_FLAG_RELOAD = @as(u32, 2147483648); pub const INTERNET_FLAG_RAW_DATA = @as(u32, 1073741824); pub const INTERNET_FLAG_EXISTING_CONNECT = @as(u32, 536870912); pub const INTERNET_FLAG_ASYNC = @as(u32, 268435456); pub const INTERNET_FLAG_PASSIVE = @as(u32, 134217728); pub const INTERNET_FLAG_NO_CACHE_WRITE = @as(u32, 67108864); pub const INTERNET_FLAG_DONT_CACHE = @as(u32, 67108864); pub const INTERNET_FLAG_MAKE_PERSISTENT = @as(u32, 33554432); pub const INTERNET_FLAG_FROM_CACHE = @as(u32, 16777216); pub const INTERNET_FLAG_OFFLINE = @as(u32, 16777216); pub const INTERNET_FLAG_SECURE = @as(u32, 8388608); pub const INTERNET_FLAG_KEEP_CONNECTION = @as(u32, 4194304); pub const INTERNET_FLAG_NO_AUTO_REDIRECT = @as(u32, 2097152); pub const INTERNET_FLAG_READ_PREFETCH = @as(u32, 1048576); pub const INTERNET_FLAG_NO_COOKIES = @as(u32, 524288); pub const INTERNET_FLAG_NO_AUTH = @as(u32, 262144); pub const INTERNET_FLAG_CACHE_IF_NET_FAIL = @as(u32, 65536); pub const INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP = @as(u32, 32768); pub const INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS = @as(u32, 16384); pub const INTERNET_FLAG_IGNORE_CERT_DATE_INVALID = @as(u32, 8192); pub const INTERNET_FLAG_IGNORE_CERT_CN_INVALID = @as(u32, 4096); pub const INTERNET_FLAG_RESYNCHRONIZE = @as(u32, 2048); pub const INTERNET_FLAG_HYPERLINK = @as(u32, 1024); pub const INTERNET_FLAG_NO_UI = @as(u32, 512); pub const INTERNET_FLAG_PRAGMA_NOCACHE = @as(u32, 256); pub const INTERNET_FLAG_CACHE_ASYNC = @as(u32, 128); pub const INTERNET_FLAG_FORMS_SUBMIT = @as(u32, 64); pub const INTERNET_FLAG_FWD_BACK = @as(u32, 32); pub const INTERNET_FLAG_NEED_FILE = @as(u32, 16); pub const INTERNET_FLAG_MUST_CACHE_REQUEST = @as(u32, 16); pub const INTERNET_ERROR_MASK_INSERT_CDROM = @as(u32, 1); pub const INTERNET_ERROR_MASK_COMBINED_SEC_CERT = @as(u32, 2); pub const INTERNET_ERROR_MASK_NEED_MSN_SSPI_PKG = @as(u32, 4); pub const INTERNET_ERROR_MASK_LOGIN_FAILURE_DISPLAY_ENTITY_BODY = @as(u32, 8); pub const WININET_API_FLAG_ASYNC = @as(u32, 1); pub const WININET_API_FLAG_SYNC = @as(u32, 4); pub const WININET_API_FLAG_USE_CONTEXT = @as(u32, 8); pub const INTERNET_NO_CALLBACK = @as(u32, 0); pub const IDSI_FLAG_KEEP_ALIVE = @as(u32, 1); pub const IDSI_FLAG_SECURE = @as(u32, 2); pub const IDSI_FLAG_PROXY = @as(u32, 4); pub const IDSI_FLAG_TUNNEL = @as(u32, 8); pub const INTERNET_PER_CONN_FLAGS_UI = @as(u32, 10); pub const PROXY_TYPE_DIRECT = @as(u32, 1); pub const PROXY_TYPE_PROXY = @as(u32, 2); pub const PROXY_TYPE_AUTO_PROXY_URL = @as(u32, 4); pub const PROXY_TYPE_AUTO_DETECT = @as(u32, 8); pub const AUTO_PROXY_FLAG_USER_SET = @as(u32, 1); pub const AUTO_PROXY_FLAG_ALWAYS_DETECT = @as(u32, 2); pub const AUTO_PROXY_FLAG_DETECTION_RUN = @as(u32, 4); pub const AUTO_PROXY_FLAG_MIGRATED = @as(u32, 8); pub const AUTO_PROXY_FLAG_DONT_CACHE_PROXY_RESULT = @as(u32, 16); pub const AUTO_PROXY_FLAG_CACHE_INIT_RUN = @as(u32, 32); pub const AUTO_PROXY_FLAG_DETECTION_SUSPECT = @as(u32, 64); pub const ISO_FORCE_DISCONNECTED = @as(u32, 1); pub const INTERNET_RFC1123_FORMAT = @as(u32, 0); pub const INTERNET_RFC1123_BUFSIZE = @as(u32, 30); pub const ICU_USERNAME = @as(u32, 1073741824); pub const INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY = @as(u32, 4); pub const INTERNET_SERVICE_FTP = @as(u32, 1); pub const INTERNET_SERVICE_GOPHER = @as(u32, 2); pub const INTERNET_SERVICE_HTTP = @as(u32, 3); pub const IRF_ASYNC = @as(u32, 1); pub const IRF_SYNC = @as(u32, 4); pub const IRF_USE_CONTEXT = @as(u32, 8); pub const IRF_NO_WAIT = @as(u32, 8); pub const ISO_GLOBAL = @as(u32, 1); pub const ISO_REGISTRY = @as(u32, 2); pub const INTERNET_OPTION_CALLBACK = @as(u32, 1); pub const INTERNET_OPTION_CONNECT_TIMEOUT = @as(u32, 2); pub const INTERNET_OPTION_CONNECT_RETRIES = @as(u32, 3); pub const INTERNET_OPTION_CONNECT_BACKOFF = @as(u32, 4); pub const INTERNET_OPTION_SEND_TIMEOUT = @as(u32, 5); pub const INTERNET_OPTION_CONTROL_SEND_TIMEOUT = @as(u32, 5); pub const INTERNET_OPTION_RECEIVE_TIMEOUT = @as(u32, 6); pub const INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT = @as(u32, 6); pub const INTERNET_OPTION_DATA_SEND_TIMEOUT = @as(u32, 7); pub const INTERNET_OPTION_DATA_RECEIVE_TIMEOUT = @as(u32, 8); pub const INTERNET_OPTION_HANDLE_TYPE = @as(u32, 9); pub const INTERNET_OPTION_LISTEN_TIMEOUT = @as(u32, 11); pub const INTERNET_OPTION_READ_BUFFER_SIZE = @as(u32, 12); pub const INTERNET_OPTION_WRITE_BUFFER_SIZE = @as(u32, 13); pub const INTERNET_OPTION_ASYNC_ID = @as(u32, 15); pub const INTERNET_OPTION_ASYNC_PRIORITY = @as(u32, 16); pub const INTERNET_OPTION_PARENT_HANDLE = @as(u32, 21); pub const INTERNET_OPTION_KEEP_CONNECTION = @as(u32, 22); pub const INTERNET_OPTION_REQUEST_FLAGS = @as(u32, 23); pub const INTERNET_OPTION_EXTENDED_ERROR = @as(u32, 24); pub const INTERNET_OPTION_OFFLINE_MODE = @as(u32, 26); pub const INTERNET_OPTION_CACHE_STREAM_HANDLE = @as(u32, 27); pub const INTERNET_OPTION_USERNAME = @as(u32, 28); pub const INTERNET_OPTION_PASSWORD = @as(u32, 29); pub const INTERNET_OPTION_ASYNC = @as(u32, 30); pub const INTERNET_OPTION_SECURITY_FLAGS = @as(u32, 31); pub const INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT = @as(u32, 32); pub const INTERNET_OPTION_DATAFILE_NAME = @as(u32, 33); pub const INTERNET_OPTION_URL = @as(u32, 34); pub const INTERNET_OPTION_SECURITY_CERTIFICATE = @as(u32, 35); pub const INTERNET_OPTION_SECURITY_KEY_BITNESS = @as(u32, 36); pub const INTERNET_OPTION_REFRESH = @as(u32, 37); pub const INTERNET_OPTION_PROXY = @as(u32, 38); pub const INTERNET_OPTION_SETTINGS_CHANGED = @as(u32, 39); pub const INTERNET_OPTION_VERSION = @as(u32, 40); pub const INTERNET_OPTION_USER_AGENT = @as(u32, 41); pub const INTERNET_OPTION_END_BROWSER_SESSION = @as(u32, 42); pub const INTERNET_OPTION_PROXY_USERNAME = @as(u32, 43); pub const INTERNET_OPTION_PROXY_PASSWORD = @as(u32, 44); pub const INTERNET_OPTION_CONTEXT_VALUE = @as(u32, 45); pub const INTERNET_OPTION_CONNECT_LIMIT = @as(u32, 46); pub const INTERNET_OPTION_SECURITY_SELECT_CLIENT_CERT = @as(u32, 47); pub const INTERNET_OPTION_POLICY = @as(u32, 48); pub const INTERNET_OPTION_DISCONNECTED_TIMEOUT = @as(u32, 49); pub const INTERNET_OPTION_CONNECTED_STATE = @as(u32, 50); pub const INTERNET_OPTION_IDLE_STATE = @as(u32, 51); pub const INTERNET_OPTION_OFFLINE_SEMANTICS = @as(u32, 52); pub const INTERNET_OPTION_SECONDARY_CACHE_KEY = @as(u32, 53); pub const INTERNET_OPTION_CALLBACK_FILTER = @as(u32, 54); pub const INTERNET_OPTION_CONNECT_TIME = @as(u32, 55); pub const INTERNET_OPTION_SEND_THROUGHPUT = @as(u32, 56); pub const INTERNET_OPTION_RECEIVE_THROUGHPUT = @as(u32, 57); pub const INTERNET_OPTION_REQUEST_PRIORITY = @as(u32, 58); pub const INTERNET_OPTION_HTTP_VERSION = @as(u32, 59); pub const INTERNET_OPTION_RESET_URLCACHE_SESSION = @as(u32, 60); pub const INTERNET_OPTION_ERROR_MASK = @as(u32, 62); pub const INTERNET_OPTION_FROM_CACHE_TIMEOUT = @as(u32, 63); pub const INTERNET_OPTION_BYPASS_EDITED_ENTRY = @as(u32, 64); pub const INTERNET_OPTION_HTTP_DECODING = @as(u32, 65); pub const INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO = @as(u32, 67); pub const INTERNET_OPTION_CODEPAGE = @as(u32, 68); pub const INTERNET_OPTION_CACHE_TIMESTAMPS = @as(u32, 69); pub const INTERNET_OPTION_DISABLE_AUTODIAL = @as(u32, 70); pub const INTERNET_OPTION_MAX_CONNS_PER_SERVER = @as(u32, 73); pub const INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER = @as(u32, 74); pub const INTERNET_OPTION_PER_CONNECTION_OPTION = @as(u32, 75); pub const INTERNET_OPTION_DIGEST_AUTH_UNLOAD = @as(u32, 76); pub const INTERNET_OPTION_IGNORE_OFFLINE = @as(u32, 77); pub const INTERNET_OPTION_IDENTITY = @as(u32, 78); pub const INTERNET_OPTION_REMOVE_IDENTITY = @as(u32, 79); pub const INTERNET_OPTION_ALTER_IDENTITY = @as(u32, 80); pub const INTERNET_OPTION_SUPPRESS_BEHAVIOR = @as(u32, 81); pub const INTERNET_OPTION_AUTODIAL_MODE = @as(u32, 82); pub const INTERNET_OPTION_AUTODIAL_CONNECTION = @as(u32, 83); pub const INTERNET_OPTION_CLIENT_CERT_CONTEXT = @as(u32, 84); pub const INTERNET_OPTION_AUTH_FLAGS = @as(u32, 85); pub const INTERNET_OPTION_COOKIES_3RD_PARTY = @as(u32, 86); pub const INTERNET_OPTION_DISABLE_PASSPORT_AUTH = @as(u32, 87); pub const INTERNET_OPTION_SEND_UTF8_SERVERNAME_TO_PROXY = @as(u32, 88); pub const INTERNET_OPTION_EXEMPT_CONNECTION_LIMIT = @as(u32, 89); pub const INTERNET_OPTION_ENABLE_PASSPORT_AUTH = @as(u32, 90); pub const INTERNET_OPTION_HIBERNATE_INACTIVE_WORKER_THREADS = @as(u32, 91); pub const INTERNET_OPTION_ACTIVATE_WORKER_THREADS = @as(u32, 92); pub const INTERNET_OPTION_RESTORE_WORKER_THREAD_DEFAULTS = @as(u32, 93); pub const INTERNET_OPTION_SOCKET_SEND_BUFFER_LENGTH = @as(u32, 94); pub const INTERNET_OPTION_PROXY_SETTINGS_CHANGED = @as(u32, 95); pub const INTERNET_OPTION_DATAFILE_EXT = @as(u32, 96); pub const INTERNET_OPTION_CODEPAGE_PATH = @as(u32, 100); pub const INTERNET_OPTION_CODEPAGE_EXTRA = @as(u32, 101); pub const INTERNET_OPTION_IDN = @as(u32, 102); pub const INTERNET_OPTION_MAX_CONNS_PER_PROXY = @as(u32, 103); pub const INTERNET_OPTION_SUPPRESS_SERVER_AUTH = @as(u32, 104); pub const INTERNET_OPTION_SERVER_CERT_CHAIN_CONTEXT = @as(u32, 105); pub const INTERNET_OPTION_ENABLE_REDIRECT_CACHE_READ = @as(u32, 122); pub const INTERNET_OPTION_COMPRESSED_CONTENT_LENGTH = @as(u32, 147); pub const INTERNET_OPTION_ENABLE_HTTP_PROTOCOL = @as(u32, 148); pub const INTERNET_OPTION_HTTP_PROTOCOL_USED = @as(u32, 149); pub const INTERNET_OPTION_ENCODE_EXTRA = @as(u32, 155); pub const INTERNET_OPTION_HSTS = @as(u32, 157); pub const INTERNET_OPTION_ENTERPRISE_CONTEXT = @as(u32, 159); pub const INTERNET_OPTION_CONNECTION_FILTER = @as(u32, 162); pub const INTERNET_OPTION_REFERER_TOKEN_BINDING_HOSTNAME = @as(u32, 163); pub const INTERNET_OPTION_TOKEN_BINDING_PUBLIC_KEY = @as(u32, 181); pub const INTERNET_OPTION_COOKIES_SAME_SITE_LEVEL = @as(u32, 187); pub const INTERNET_FIRST_OPTION = @as(u32, 1); pub const INTERNET_LAST_OPTION = @as(u32, 187); pub const INTERNET_PRIORITY_FOREGROUND = @as(u32, 1000); pub const HTTP_COOKIES_SAME_SITE_LEVEL_UNKNOWN = @as(u32, 0); pub const HTTP_COOKIES_SAME_SITE_LEVEL_SAME_SITE = @as(u32, 1); pub const HTTP_COOKIES_SAME_SITE_LEVEL_CROSS_SITE_LAX = @as(u32, 2); pub const HTTP_COOKIES_SAME_SITE_LEVEL_CROSS_SITE = @as(u32, 3); pub const HTTP_COOKIES_SAME_SITE_LEVEL_MAX = @as(u32, 3); pub const HTTP_PROTOCOL_FLAG_HTTP2 = @as(u32, 2); pub const HTTP_PROTOCOL_MASK = @as(u32, 2); pub const INTERNET_HANDLE_TYPE_INTERNET = @as(u32, 1); pub const INTERNET_HANDLE_TYPE_CONNECT_FTP = @as(u32, 2); pub const INTERNET_HANDLE_TYPE_CONNECT_GOPHER = @as(u32, 3); pub const INTERNET_HANDLE_TYPE_CONNECT_HTTP = @as(u32, 4); pub const INTERNET_HANDLE_TYPE_FTP_FIND = @as(u32, 5); pub const INTERNET_HANDLE_TYPE_FTP_FIND_HTML = @as(u32, 6); pub const INTERNET_HANDLE_TYPE_FTP_FILE = @as(u32, 7); pub const INTERNET_HANDLE_TYPE_FTP_FILE_HTML = @as(u32, 8); pub const INTERNET_HANDLE_TYPE_GOPHER_FIND = @as(u32, 9); pub const INTERNET_HANDLE_TYPE_GOPHER_FIND_HTML = @as(u32, 10); pub const INTERNET_HANDLE_TYPE_GOPHER_FILE = @as(u32, 11); pub const INTERNET_HANDLE_TYPE_GOPHER_FILE_HTML = @as(u32, 12); pub const INTERNET_HANDLE_TYPE_HTTP_REQUEST = @as(u32, 13); pub const INTERNET_HANDLE_TYPE_FILE_REQUEST = @as(u32, 14); pub const AUTH_FLAG_DISABLE_NEGOTIATE = @as(u32, 1); pub const AUTH_FLAG_ENABLE_NEGOTIATE = @as(u32, 2); pub const AUTH_FLAG_DISABLE_BASIC_CLEARCHANNEL = @as(u32, 4); pub const AUTH_FLAG_DISABLE_SERVER_AUTH = @as(u32, 8); pub const SECURITY_FLAG_UNKNOWNBIT = @as(u32, 2147483648); pub const SECURITY_FLAG_FORTEZZA = @as(u32, 134217728); pub const SECURITY_FLAG_NORMALBITNESS = @as(u32, 268435456); pub const SECURITY_FLAG_SSL = @as(u32, 2); pub const SECURITY_FLAG_SSL3 = @as(u32, 4); pub const SECURITY_FLAG_PCT = @as(u32, 8); pub const SECURITY_FLAG_PCT4 = @as(u32, 16); pub const SECURITY_FLAG_IETFSSL4 = @as(u32, 32); pub const SECURITY_FLAG_40BIT = @as(u32, 268435456); pub const SECURITY_FLAG_128BIT = @as(u32, 536870912); pub const SECURITY_FLAG_56BIT = @as(u32, 1073741824); pub const SECURITY_FLAG_IGNORE_REVOCATION = @as(u32, 128); pub const SECURITY_FLAG_IGNORE_WRONG_USAGE = @as(u32, 512); pub const SECURITY_FLAG_IGNORE_WEAK_SIGNATURE = @as(u32, 65536); pub const SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS = @as(u32, 16384); pub const SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP = @as(u32, 32768); pub const SECURITY_FLAG_OPT_IN_WEAK_SIGNATURE = @as(u32, 131072); pub const AUTODIAL_MODE_NEVER = @as(u32, 1); pub const AUTODIAL_MODE_ALWAYS = @as(u32, 2); pub const AUTODIAL_MODE_NO_NETWORK_PRESENT = @as(u32, 4); pub const INTERNET_STATUS_RESOLVING_NAME = @as(u32, 10); pub const INTERNET_STATUS_NAME_RESOLVED = @as(u32, 11); pub const INTERNET_STATUS_CONNECTING_TO_SERVER = @as(u32, 20); pub const INTERNET_STATUS_CONNECTED_TO_SERVER = @as(u32, 21); pub const INTERNET_STATUS_SENDING_REQUEST = @as(u32, 30); pub const INTERNET_STATUS_REQUEST_SENT = @as(u32, 31); pub const INTERNET_STATUS_RECEIVING_RESPONSE = @as(u32, 40); pub const INTERNET_STATUS_RESPONSE_RECEIVED = @as(u32, 41); pub const INTERNET_STATUS_CTL_RESPONSE_RECEIVED = @as(u32, 42); pub const INTERNET_STATUS_PREFETCH = @as(u32, 43); pub const INTERNET_STATUS_CLOSING_CONNECTION = @as(u32, 50); pub const INTERNET_STATUS_CONNECTION_CLOSED = @as(u32, 51); pub const INTERNET_STATUS_HANDLE_CREATED = @as(u32, 60); pub const INTERNET_STATUS_HANDLE_CLOSING = @as(u32, 70); pub const INTERNET_STATUS_DETECTING_PROXY = @as(u32, 80); pub const INTERNET_STATUS_REQUEST_COMPLETE = @as(u32, 100); pub const INTERNET_STATUS_REDIRECT = @as(u32, 110); pub const INTERNET_STATUS_INTERMEDIATE_RESPONSE = @as(u32, 120); pub const INTERNET_STATUS_USER_INPUT_REQUIRED = @as(u32, 140); pub const INTERNET_STATUS_STATE_CHANGE = @as(u32, 200); pub const INTERNET_STATUS_COOKIE_SENT = @as(u32, 320); pub const INTERNET_STATUS_COOKIE_RECEIVED = @as(u32, 321); pub const INTERNET_STATUS_PRIVACY_IMPACTED = @as(u32, 324); pub const INTERNET_STATUS_P3P_HEADER = @as(u32, 325); pub const INTERNET_STATUS_P3P_POLICYREF = @as(u32, 326); pub const INTERNET_STATUS_COOKIE_HISTORY = @as(u32, 327); pub const MAX_GOPHER_DISPLAY_TEXT = @as(u32, 128); pub const MAX_GOPHER_SELECTOR_TEXT = @as(u32, 256); pub const MAX_GOPHER_HOST_NAME = @as(u32, 256); pub const MAX_GOPHER_CATEGORY_NAME = @as(u32, 128); pub const MAX_GOPHER_ATTRIBUTE_NAME = @as(u32, 128); pub const MIN_GOPHER_ATTRIBUTE_LENGTH = @as(u32, 256); pub const GOPHER_ATTRIBUTE_ID_BASE = @as(u32, 2882325504); pub const GOPHER_CATEGORY_ID_ALL = @as(u32, 2882325505); pub const GOPHER_CATEGORY_ID_INFO = @as(u32, 2882325506); pub const GOPHER_CATEGORY_ID_ADMIN = @as(u32, 2882325507); pub const GOPHER_CATEGORY_ID_VIEWS = @as(u32, 2882325508); pub const GOPHER_CATEGORY_ID_ABSTRACT = @as(u32, 2882325509); pub const GOPHER_CATEGORY_ID_VERONICA = @as(u32, 2882325510); pub const GOPHER_CATEGORY_ID_ASK = @as(u32, 2882325511); pub const GOPHER_CATEGORY_ID_UNKNOWN = @as(u32, 2882325512); pub const GOPHER_ATTRIBUTE_ID_ALL = @as(u32, 2882325513); pub const GOPHER_ATTRIBUTE_ID_ADMIN = @as(u32, 2882325514); pub const GOPHER_ATTRIBUTE_ID_MOD_DATE = @as(u32, 2882325515); pub const GOPHER_ATTRIBUTE_ID_TTL = @as(u32, 2882325516); pub const GOPHER_ATTRIBUTE_ID_SCORE = @as(u32, 2882325517); pub const GOPHER_ATTRIBUTE_ID_RANGE = @as(u32, 2882325518); pub const GOPHER_ATTRIBUTE_ID_SITE = @as(u32, 2882325519); pub const GOPHER_ATTRIBUTE_ID_ORG = @as(u32, 2882325520); pub const GOPHER_ATTRIBUTE_ID_LOCATION = @as(u32, 2882325521); pub const GOPHER_ATTRIBUTE_ID_GEOG = @as(u32, 2882325522); pub const GOPHER_ATTRIBUTE_ID_TIMEZONE = @as(u32, 2882325523); pub const GOPHER_ATTRIBUTE_ID_PROVIDER = @as(u32, 2882325524); pub const GOPHER_ATTRIBUTE_ID_VERSION = @as(u32, 2882325525); pub const GOPHER_ATTRIBUTE_ID_ABSTRACT = @as(u32, 2882325526); pub const GOPHER_ATTRIBUTE_ID_VIEW = @as(u32, 2882325527); pub const GOPHER_ATTRIBUTE_ID_TREEWALK = @as(u32, 2882325528); pub const GOPHER_ATTRIBUTE_ID_UNKNOWN = @as(u32, 2882325529); pub const HTTP_MAJOR_VERSION = @as(u32, 1); pub const HTTP_MINOR_VERSION = @as(u32, 0); pub const HTTP_QUERY_MIME_VERSION = @as(u32, 0); pub const HTTP_QUERY_CONTENT_TYPE = @as(u32, 1); pub const HTTP_QUERY_CONTENT_TRANSFER_ENCODING = @as(u32, 2); pub const HTTP_QUERY_CONTENT_ID = @as(u32, 3); pub const HTTP_QUERY_CONTENT_DESCRIPTION = @as(u32, 4); pub const HTTP_QUERY_CONTENT_LENGTH = @as(u32, 5); pub const HTTP_QUERY_CONTENT_LANGUAGE = @as(u32, 6); pub const HTTP_QUERY_ALLOW = @as(u32, 7); pub const HTTP_QUERY_PUBLIC = @as(u32, 8); pub const HTTP_QUERY_DATE = @as(u32, 9); pub const HTTP_QUERY_EXPIRES = @as(u32, 10); pub const HTTP_QUERY_LAST_MODIFIED = @as(u32, 11); pub const HTTP_QUERY_MESSAGE_ID = @as(u32, 12); pub const HTTP_QUERY_URI = @as(u32, 13); pub const HTTP_QUERY_DERIVED_FROM = @as(u32, 14); pub const HTTP_QUERY_COST = @as(u32, 15); pub const HTTP_QUERY_LINK = @as(u32, 16); pub const HTTP_QUERY_PRAGMA = @as(u32, 17); pub const HTTP_QUERY_VERSION = @as(u32, 18); pub const HTTP_QUERY_STATUS_CODE = @as(u32, 19); pub const HTTP_QUERY_STATUS_TEXT = @as(u32, 20); pub const HTTP_QUERY_RAW_HEADERS = @as(u32, 21); pub const HTTP_QUERY_RAW_HEADERS_CRLF = @as(u32, 22); pub const HTTP_QUERY_CONNECTION = @as(u32, 23); pub const HTTP_QUERY_ACCEPT = @as(u32, 24); pub const HTTP_QUERY_ACCEPT_CHARSET = @as(u32, 25); pub const HTTP_QUERY_ACCEPT_ENCODING = @as(u32, 26); pub const HTTP_QUERY_ACCEPT_LANGUAGE = @as(u32, 27); pub const HTTP_QUERY_AUTHORIZATION = @as(u32, 28); pub const HTTP_QUERY_CONTENT_ENCODING = @as(u32, 29); pub const HTTP_QUERY_FORWARDED = @as(u32, 30); pub const HTTP_QUERY_FROM = @as(u32, 31); pub const HTTP_QUERY_IF_MODIFIED_SINCE = @as(u32, 32); pub const HTTP_QUERY_LOCATION = @as(u32, 33); pub const HTTP_QUERY_ORIG_URI = @as(u32, 34); pub const HTTP_QUERY_REFERER = @as(u32, 35); pub const HTTP_QUERY_RETRY_AFTER = @as(u32, 36); pub const HTTP_QUERY_SERVER = @as(u32, 37); pub const HTTP_QUERY_TITLE = @as(u32, 38); pub const HTTP_QUERY_USER_AGENT = @as(u32, 39); pub const HTTP_QUERY_WWW_AUTHENTICATE = @as(u32, 40); pub const HTTP_QUERY_PROXY_AUTHENTICATE = @as(u32, 41); pub const HTTP_QUERY_ACCEPT_RANGES = @as(u32, 42); pub const HTTP_QUERY_SET_COOKIE = @as(u32, 43); pub const HTTP_QUERY_COOKIE = @as(u32, 44); pub const HTTP_QUERY_REQUEST_METHOD = @as(u32, 45); pub const HTTP_QUERY_REFRESH = @as(u32, 46); pub const HTTP_QUERY_CONTENT_DISPOSITION = @as(u32, 47); pub const HTTP_QUERY_AGE = @as(u32, 48); pub const HTTP_QUERY_CACHE_CONTROL = @as(u32, 49); pub const HTTP_QUERY_CONTENT_BASE = @as(u32, 50); pub const HTTP_QUERY_CONTENT_LOCATION = @as(u32, 51); pub const HTTP_QUERY_CONTENT_MD5 = @as(u32, 52); pub const HTTP_QUERY_CONTENT_RANGE = @as(u32, 53); pub const HTTP_QUERY_ETAG = @as(u32, 54); pub const HTTP_QUERY_HOST = @as(u32, 55); pub const HTTP_QUERY_IF_MATCH = @as(u32, 56); pub const HTTP_QUERY_IF_NONE_MATCH = @as(u32, 57); pub const HTTP_QUERY_IF_RANGE = @as(u32, 58); pub const HTTP_QUERY_IF_UNMODIFIED_SINCE = @as(u32, 59); pub const HTTP_QUERY_MAX_FORWARDS = @as(u32, 60); pub const HTTP_QUERY_PROXY_AUTHORIZATION = @as(u32, 61); pub const HTTP_QUERY_RANGE = @as(u32, 62); pub const HTTP_QUERY_TRANSFER_ENCODING = @as(u32, 63); pub const HTTP_QUERY_UPGRADE = @as(u32, 64); pub const HTTP_QUERY_VARY = @as(u32, 65); pub const HTTP_QUERY_VIA = @as(u32, 66); pub const HTTP_QUERY_WARNING = @as(u32, 67); pub const HTTP_QUERY_EXPECT = @as(u32, 68); pub const HTTP_QUERY_PROXY_CONNECTION = @as(u32, 69); pub const HTTP_QUERY_UNLESS_MODIFIED_SINCE = @as(u32, 70); pub const HTTP_QUERY_ECHO_REQUEST = @as(u32, 71); pub const HTTP_QUERY_ECHO_REPLY = @as(u32, 72); pub const HTTP_QUERY_ECHO_HEADERS = @as(u32, 73); pub const HTTP_QUERY_ECHO_HEADERS_CRLF = @as(u32, 74); pub const HTTP_QUERY_PROXY_SUPPORT = @as(u32, 75); pub const HTTP_QUERY_AUTHENTICATION_INFO = @as(u32, 76); pub const HTTP_QUERY_PASSPORT_URLS = @as(u32, 77); pub const HTTP_QUERY_PASSPORT_CONFIG = @as(u32, 78); pub const HTTP_QUERY_X_CONTENT_TYPE_OPTIONS = @as(u32, 79); pub const HTTP_QUERY_P3P = @as(u32, 80); pub const HTTP_QUERY_X_P2P_PEERDIST = @as(u32, 81); pub const HTTP_QUERY_TRANSLATE = @as(u32, 82); pub const HTTP_QUERY_X_UA_COMPATIBLE = @as(u32, 83); pub const HTTP_QUERY_DEFAULT_STYLE = @as(u32, 84); pub const HTTP_QUERY_X_FRAME_OPTIONS = @as(u32, 85); pub const HTTP_QUERY_X_XSS_PROTECTION = @as(u32, 86); pub const HTTP_QUERY_SET_COOKIE2 = @as(u32, 87); pub const HTTP_QUERY_DO_NOT_TRACK = @as(u32, 88); pub const HTTP_QUERY_KEEP_ALIVE = @as(u32, 89); pub const HTTP_QUERY_HTTP2_SETTINGS = @as(u32, 90); pub const HTTP_QUERY_STRICT_TRANSPORT_SECURITY = @as(u32, 91); pub const HTTP_QUERY_TOKEN_BINDING = @as(u32, 92); pub const HTTP_QUERY_INCLUDE_REFERRED_TOKEN_BINDING_ID = @as(u32, 93); pub const HTTP_QUERY_INCLUDE_REFERER_TOKEN_BINDING_ID = @as(u32, 93); pub const HTTP_QUERY_PUBLIC_KEY_PINS = @as(u32, 94); pub const HTTP_QUERY_PUBLIC_KEY_PINS_REPORT_ONLY = @as(u32, 95); pub const HTTP_QUERY_MAX = @as(u32, 95); pub const HTTP_QUERY_CUSTOM = @as(u32, 65535); pub const HTTP_QUERY_FLAG_REQUEST_HEADERS = @as(u32, 2147483648); pub const HTTP_QUERY_FLAG_SYSTEMTIME = @as(u32, 1073741824); pub const HTTP_QUERY_FLAG_NUMBER = @as(u32, 536870912); pub const HTTP_QUERY_FLAG_COALESCE = @as(u32, 268435456); pub const HTTP_QUERY_FLAG_NUMBER64 = @as(u32, 134217728); pub const HTTP_QUERY_FLAG_COALESCE_WITH_COMMA = @as(u32, 67108864); pub const HTTP_STATUS_MISDIRECTED_REQUEST = @as(u32, 421); pub const HTTP_ADDREQ_INDEX_MASK = @as(u32, 65535); pub const HTTP_ADDREQ_FLAGS_MASK = @as(u32, 4294901760); pub const HSR_ASYNC = @as(u32, 1); pub const HSR_SYNC = @as(u32, 4); pub const HSR_USE_CONTEXT = @as(u32, 8); pub const HSR_INITIATE = @as(u32, 8); pub const HSR_DOWNLOAD = @as(u32, 16); pub const HSR_CHUNKED = @as(u32, 32); pub const INTERNET_COOKIE_IS_SECURE = @as(u32, 1); pub const INTERNET_COOKIE_IS_SESSION = @as(u32, 2); pub const INTERNET_COOKIE_PROMPT_REQUIRED = @as(u32, 32); pub const INTERNET_COOKIE_EVALUATE_P3P = @as(u32, 64); pub const INTERNET_COOKIE_APPLY_P3P = @as(u32, 128); pub const INTERNET_COOKIE_P3P_ENABLED = @as(u32, 256); pub const INTERNET_COOKIE_IS_RESTRICTED = @as(u32, 512); pub const INTERNET_COOKIE_IE6 = @as(u32, 1024); pub const INTERNET_COOKIE_IS_LEGACY = @as(u32, 2048); pub const INTERNET_COOKIE_NON_SCRIPT = @as(u32, 4096); pub const INTERNET_COOKIE_HOST_ONLY = @as(u32, 16384); pub const INTERNET_COOKIE_APPLY_HOST_ONLY = @as(u32, 32768); pub const INTERNET_COOKIE_HOST_ONLY_APPLIED = @as(u32, 524288); pub const INTERNET_COOKIE_SAME_SITE_STRICT = @as(u32, 1048576); pub const INTERNET_COOKIE_SAME_SITE_LAX = @as(u32, 2097152); pub const INTERNET_COOKIE_SAME_SITE_LEVEL_CROSS_SITE = @as(u32, 4194304); pub const FLAG_ICC_FORCE_CONNECTION = @as(u32, 1); pub const FLAGS_ERROR_UI_FILTER_FOR_ERRORS = @as(u32, 1); pub const FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS = @as(u32, 2); pub const FLAGS_ERROR_UI_FLAGS_GENERATE_DATA = @as(u32, 4); pub const FLAGS_ERROR_UI_FLAGS_NO_UI = @as(u32, 8); pub const FLAGS_ERROR_UI_SERIALIZE_DIALOGS = @as(u32, 16); pub const INTERNET_ERROR_BASE = @as(u32, 12000); pub const ERROR_INTERNET_OUT_OF_HANDLES = @as(u32, 12001); pub const ERROR_INTERNET_TIMEOUT = @as(u32, 12002); pub const ERROR_INTERNET_EXTENDED_ERROR = @as(u32, 12003); pub const ERROR_INTERNET_INTERNAL_ERROR = @as(u32, 12004); pub const ERROR_INTERNET_INVALID_URL = @as(u32, 12005); pub const ERROR_INTERNET_UNRECOGNIZED_SCHEME = @as(u32, 12006); pub const ERROR_INTERNET_NAME_NOT_RESOLVED = @as(u32, 12007); pub const ERROR_INTERNET_PROTOCOL_NOT_FOUND = @as(u32, 12008); pub const ERROR_INTERNET_INVALID_OPTION = @as(u32, 12009); pub const ERROR_INTERNET_BAD_OPTION_LENGTH = @as(u32, 12010); pub const ERROR_INTERNET_OPTION_NOT_SETTABLE = @as(u32, 12011); pub const ERROR_INTERNET_SHUTDOWN = @as(u32, 12012); pub const ERROR_INTERNET_INCORRECT_USER_NAME = @as(u32, 12013); pub const ERROR_INTERNET_INCORRECT_PASSWORD = @as(u32, 12014); pub const ERROR_INTERNET_LOGIN_FAILURE = @as(u32, 12015); pub const ERROR_INTERNET_INVALID_OPERATION = @as(u32, 12016); pub const ERROR_INTERNET_OPERATION_CANCELLED = @as(u32, 12017); pub const ERROR_INTERNET_INCORRECT_HANDLE_TYPE = @as(u32, 12018); pub const ERROR_INTERNET_INCORRECT_HANDLE_STATE = @as(u32, 12019); pub const ERROR_INTERNET_NOT_PROXY_REQUEST = @as(u32, 12020); pub const ERROR_INTERNET_REGISTRY_VALUE_NOT_FOUND = @as(u32, 12021); pub const ERROR_INTERNET_BAD_REGISTRY_PARAMETER = @as(u32, 12022); pub const ERROR_INTERNET_NO_DIRECT_ACCESS = @as(u32, 12023); pub const ERROR_INTERNET_NO_CONTEXT = @as(u32, 12024); pub const ERROR_INTERNET_NO_CALLBACK = @as(u32, 12025); pub const ERROR_INTERNET_REQUEST_PENDING = @as(u32, 12026); pub const ERROR_INTERNET_INCORRECT_FORMAT = @as(u32, 12027); pub const ERROR_INTERNET_ITEM_NOT_FOUND = @as(u32, 12028); pub const ERROR_INTERNET_CANNOT_CONNECT = @as(u32, 12029); pub const ERROR_INTERNET_CONNECTION_ABORTED = @as(u32, 12030); pub const ERROR_INTERNET_CONNECTION_RESET = @as(u32, 12031); pub const ERROR_INTERNET_FORCE_RETRY = @as(u32, 12032); pub const ERROR_INTERNET_INVALID_PROXY_REQUEST = @as(u32, 12033); pub const ERROR_INTERNET_NEED_UI = @as(u32, 12034); pub const ERROR_INTERNET_HANDLE_EXISTS = @as(u32, 12036); pub const ERROR_INTERNET_SEC_CERT_DATE_INVALID = @as(u32, 12037); pub const ERROR_INTERNET_SEC_CERT_CN_INVALID = @as(u32, 12038); pub const ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR = @as(u32, 12039); pub const ERROR_INTERNET_HTTPS_TO_HTTP_ON_REDIR = @as(u32, 12040); pub const ERROR_INTERNET_MIXED_SECURITY = @as(u32, 12041); pub const ERROR_INTERNET_CHG_POST_IS_NON_SECURE = @as(u32, 12042); pub const ERROR_INTERNET_POST_IS_NON_SECURE = @as(u32, 12043); pub const ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED = @as(u32, 12044); pub const ERROR_INTERNET_INVALID_CA = @as(u32, 12045); pub const ERROR_INTERNET_CLIENT_AUTH_NOT_SETUP = @as(u32, 12046); pub const ERROR_INTERNET_ASYNC_THREAD_FAILED = @as(u32, 12047); pub const ERROR_INTERNET_REDIRECT_SCHEME_CHANGE = @as(u32, 12048); pub const ERROR_INTERNET_DIALOG_PENDING = @as(u32, 12049); pub const ERROR_INTERNET_RETRY_DIALOG = @as(u32, 12050); pub const ERROR_INTERNET_HTTPS_HTTP_SUBMIT_REDIR = @as(u32, 12052); pub const ERROR_INTERNET_INSERT_CDROM = @as(u32, 12053); pub const ERROR_INTERNET_FORTEZZA_LOGIN_NEEDED = @as(u32, 12054); pub const ERROR_INTERNET_SEC_CERT_ERRORS = @as(u32, 12055); pub const ERROR_INTERNET_SEC_CERT_NO_REV = @as(u32, 12056); pub const ERROR_INTERNET_SEC_CERT_REV_FAILED = @as(u32, 12057); pub const ERROR_HTTP_HSTS_REDIRECT_REQUIRED = @as(u32, 12060); pub const ERROR_INTERNET_SEC_CERT_WEAK_SIGNATURE = @as(u32, 12062); pub const ERROR_FTP_TRANSFER_IN_PROGRESS = @as(u32, 12110); pub const ERROR_FTP_DROPPED = @as(u32, 12111); pub const ERROR_FTP_NO_PASSIVE_MODE = @as(u32, 12112); pub const ERROR_GOPHER_PROTOCOL_ERROR = @as(u32, 12130); pub const ERROR_GOPHER_NOT_FILE = @as(u32, 12131); pub const ERROR_GOPHER_DATA_ERROR = @as(u32, 12132); pub const ERROR_GOPHER_END_OF_DATA = @as(u32, 12133); pub const ERROR_GOPHER_INVALID_LOCATOR = @as(u32, 12134); pub const ERROR_GOPHER_INCORRECT_LOCATOR_TYPE = @as(u32, 12135); pub const ERROR_GOPHER_NOT_GOPHER_PLUS = @as(u32, 12136); pub const ERROR_GOPHER_ATTRIBUTE_NOT_FOUND = @as(u32, 12137); pub const ERROR_GOPHER_UNKNOWN_LOCATOR = @as(u32, 12138); pub const ERROR_HTTP_HEADER_NOT_FOUND = @as(u32, 12150); pub const ERROR_HTTP_DOWNLEVEL_SERVER = @as(u32, 12151); pub const ERROR_HTTP_INVALID_SERVER_RESPONSE = @as(u32, 12152); pub const ERROR_HTTP_INVALID_HEADER = @as(u32, 12153); pub const ERROR_HTTP_INVALID_QUERY_REQUEST = @as(u32, 12154); pub const ERROR_HTTP_HEADER_ALREADY_EXISTS = @as(u32, 12155); pub const ERROR_HTTP_REDIRECT_FAILED = @as(u32, 12156); pub const ERROR_HTTP_NOT_REDIRECTED = @as(u32, 12160); pub const ERROR_HTTP_COOKIE_NEEDS_CONFIRMATION = @as(u32, 12161); pub const ERROR_HTTP_COOKIE_DECLINED = @as(u32, 12162); pub const ERROR_HTTP_REDIRECT_NEEDS_CONFIRMATION = @as(u32, 12168); pub const ERROR_INTERNET_SECURITY_CHANNEL_ERROR = @as(u32, 12157); pub const ERROR_INTERNET_UNABLE_TO_CACHE_FILE = @as(u32, 12158); pub const ERROR_INTERNET_TCPIP_NOT_INSTALLED = @as(u32, 12159); pub const ERROR_INTERNET_DISCONNECTED = @as(u32, 12163); pub const ERROR_INTERNET_SERVER_UNREACHABLE = @as(u32, 12164); pub const ERROR_INTERNET_PROXY_SERVER_UNREACHABLE = @as(u32, 12165); pub const ERROR_INTERNET_BAD_AUTO_PROXY_SCRIPT = @as(u32, 12166); pub const ERROR_INTERNET_UNABLE_TO_DOWNLOAD_SCRIPT = @as(u32, 12167); pub const ERROR_INTERNET_SEC_INVALID_CERT = @as(u32, 12169); pub const ERROR_INTERNET_SEC_CERT_REVOKED = @as(u32, 12170); pub const ERROR_INTERNET_FAILED_DUETOSECURITYCHECK = @as(u32, 12171); pub const ERROR_INTERNET_NOT_INITIALIZED = @as(u32, 12172); pub const ERROR_INTERNET_NEED_MSN_SSPI_PKG = @as(u32, 12173); pub const ERROR_INTERNET_LOGIN_FAILURE_DISPLAY_ENTITY_BODY = @as(u32, 12174); pub const ERROR_INTERNET_DECODING_FAILED = @as(u32, 12175); pub const ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED_PROXY = @as(u32, 12187); pub const ERROR_INTERNET_SECURE_FAILURE_PROXY = @as(u32, 12188); pub const ERROR_INTERNET_HTTP_PROTOCOL_MISMATCH = @as(u32, 12190); pub const ERROR_INTERNET_GLOBAL_CALLBACK_FAILED = @as(u32, 12191); pub const ERROR_INTERNET_FEATURE_DISABLED = @as(u32, 12192); pub const INTERNET_ERROR_LAST = @as(u32, 12192); pub const NORMAL_CACHE_ENTRY = @as(u32, 1); pub const STICKY_CACHE_ENTRY = @as(u32, 4); pub const EDITED_CACHE_ENTRY = @as(u32, 8); pub const TRACK_OFFLINE_CACHE_ENTRY = @as(u32, 16); pub const TRACK_ONLINE_CACHE_ENTRY = @as(u32, 32); pub const SPARSE_CACHE_ENTRY = @as(u32, 65536); pub const COOKIE_CACHE_ENTRY = @as(u32, 1048576); pub const URLHISTORY_CACHE_ENTRY = @as(u32, 2097152); pub const CACHEGROUP_ATTRIBUTE_GET_ALL = @as(u32, 4294967295); pub const CACHEGROUP_ATTRIBUTE_BASIC = @as(u32, 1); pub const CACHEGROUP_ATTRIBUTE_FLAG = @as(u32, 2); pub const CACHEGROUP_ATTRIBUTE_TYPE = @as(u32, 4); pub const CACHEGROUP_ATTRIBUTE_QUOTA = @as(u32, 8); pub const CACHEGROUP_ATTRIBUTE_GROUPNAME = @as(u32, 16); pub const CACHEGROUP_ATTRIBUTE_STORAGE = @as(u32, 32); pub const CACHEGROUP_FLAG_NONPURGEABLE = @as(u32, 1); pub const CACHEGROUP_FLAG_GIDONLY = @as(u32, 4); pub const CACHEGROUP_FLAG_FLUSHURL_ONDELETE = @as(u32, 2); pub const CACHEGROUP_SEARCH_ALL = @as(u32, 0); pub const CACHEGROUP_SEARCH_BYURL = @as(u32, 1); pub const CACHEGROUP_TYPE_INVALID = @as(u32, 1); pub const GROUPNAME_MAX_LENGTH = @as(u32, 120); pub const GROUP_OWNER_STORAGE_SIZE = @as(u32, 4); pub const CACHE_ENTRY_ATTRIBUTE_FC = @as(u32, 4); pub const CACHE_ENTRY_HITRATE_FC = @as(u32, 16); pub const CACHE_ENTRY_MODTIME_FC = @as(u32, 64); pub const CACHE_ENTRY_EXPTIME_FC = @as(u32, 128); pub const CACHE_ENTRY_ACCTIME_FC = @as(u32, 256); pub const CACHE_ENTRY_SYNCTIME_FC = @as(u32, 512); pub const CACHE_ENTRY_HEADERINFO_FC = @as(u32, 1024); pub const CACHE_ENTRY_EXEMPT_DELTA_FC = @as(u32, 2048); pub const INTERNET_CACHE_GROUP_ADD = @as(u32, 0); pub const INTERNET_CACHE_GROUP_REMOVE = @as(u32, 1); pub const INTERNET_DIAL_FORCE_PROMPT = @as(u32, 8192); pub const INTERNET_DIAL_SHOW_OFFLINE = @as(u32, 16384); pub const INTERNET_DIAL_UNATTENDED = @as(u32, 32768); pub const INTERENT_GOONLINE_REFRESH = @as(u32, 1); pub const INTERENT_GOONLINE_NOPROMPT = @as(u32, 2); pub const INTERENT_GOONLINE_MASK = @as(u32, 3); pub const INTERNET_CONNECTION_LAN = @as(u32, 2); pub const INTERNET_CONNECTION_OFFLINE = @as(u32, 32); pub const INTERNET_CUSTOMDIAL_CONNECT = @as(u32, 0); pub const INTERNET_CUSTOMDIAL_UNATTENDED = @as(u32, 1); pub const INTERNET_CUSTOMDIAL_DISCONNECT = @as(u32, 2); pub const INTERNET_CUSTOMDIAL_SHOWOFFLINE = @as(u32, 4); pub const INTERNET_CUSTOMDIAL_SAFE_FOR_UNATTENDED = @as(u32, 1); pub const INTERNET_CUSTOMDIAL_WILL_SUPPLY_STATE = @as(u32, 2); pub const INTERNET_CUSTOMDIAL_CAN_HANGUP = @as(u32, 4); pub const INTERNET_DIALSTATE_DISCONNECTED = @as(u32, 1); pub const INTERNET_IDENTITY_FLAG_PRIVATE_CACHE = @as(u32, 1); pub const INTERNET_IDENTITY_FLAG_SHARED_CACHE = @as(u32, 2); pub const INTERNET_IDENTITY_FLAG_CLEAR_DATA = @as(u32, 4); pub const INTERNET_IDENTITY_FLAG_CLEAR_COOKIES = @as(u32, 8); pub const INTERNET_IDENTITY_FLAG_CLEAR_HISTORY = @as(u32, 16); pub const INTERNET_IDENTITY_FLAG_CLEAR_CONTENT = @as(u32, 32); pub const INTERNET_SUPPRESS_RESET_ALL = @as(u32, 0); pub const INTERNET_SUPPRESS_COOKIE_POLICY = @as(u32, 1); pub const INTERNET_SUPPRESS_COOKIE_POLICY_RESET = @as(u32, 2); pub const PRIVACY_TEMPLATE_NO_COOKIES = @as(u32, 0); pub const PRIVACY_TEMPLATE_HIGH = @as(u32, 1); pub const PRIVACY_TEMPLATE_MEDIUM_HIGH = @as(u32, 2); pub const PRIVACY_TEMPLATE_MEDIUM = @as(u32, 3); pub const PRIVACY_TEMPLATE_MEDIUM_LOW = @as(u32, 4); pub const PRIVACY_TEMPLATE_LOW = @as(u32, 5); pub const PRIVACY_TEMPLATE_CUSTOM = @as(u32, 100); pub const PRIVACY_TEMPLATE_ADVANCED = @as(u32, 101); pub const PRIVACY_TEMPLATE_MAX = @as(u32, 5); pub const PRIVACY_TYPE_FIRST_PARTY = @as(u32, 0); pub const PRIVACY_TYPE_THIRD_PARTY = @as(u32, 1); pub const MAX_CACHE_ENTRY_INFO_SIZE = @as(u32, 4096); pub const INTERNET_REQFLAG_FROM_APP_CACHE = @as(u32, 256); pub const INTERNET_FLAG_BGUPDATE = @as(u32, 8); pub const INTERNET_FLAG_FTP_FOLDER_VIEW = @as(u32, 4); pub const INTERNET_PREFETCH_PROGRESS = @as(u32, 0); pub const INTERNET_PREFETCH_COMPLETE = @as(u32, 1); pub const INTERNET_PREFETCH_ABORTED = @as(u32, 2); pub const ISO_FORCE_OFFLINE = @as(u32, 1); pub const DLG_FLAGS_INVALID_CA = @as(u32, 16777216); pub const DLG_FLAGS_SEC_CERT_CN_INVALID = @as(u32, 33554432); pub const DLG_FLAGS_SEC_CERT_DATE_INVALID = @as(u32, 67108864); pub const DLG_FLAGS_WEAK_SIGNATURE = @as(u32, 2097152); pub const DLG_FLAGS_INSECURE_FALLBACK = @as(u32, 4194304); pub const DLG_FLAGS_SEC_CERT_REV_FAILED = @as(u32, 8388608); pub const INTERNET_SERVICE_URL = @as(u32, 0); pub const INTERNET_OPTION_CONTEXT_VALUE_OLD = @as(u32, 10); pub const INTERNET_OPTION_NET_SPEED = @as(u32, 61); pub const INTERNET_OPTION_SECURITY_CONNECTION_INFO = @as(u32, 66); pub const INTERNET_OPTION_DETECT_POST_SEND = @as(u32, 71); pub const INTERNET_OPTION_DISABLE_NTLM_PREAUTH = @as(u32, 72); pub const INTERNET_OPTION_ORIGINAL_CONNECT_FLAGS = @as(u32, 97); pub const INTERNET_OPTION_CERT_ERROR_FLAGS = @as(u32, 98); pub const INTERNET_OPTION_IGNORE_CERT_ERROR_FLAGS = @as(u32, 99); pub const INTERNET_OPTION_SESSION_START_TIME = @as(u32, 106); pub const INTERNET_OPTION_PROXY_CREDENTIALS = @as(u32, 107); pub const INTERNET_OPTION_EXTENDED_CALLBACKS = @as(u32, 108); pub const INTERNET_OPTION_PROXY_FROM_REQUEST = @as(u32, 109); pub const INTERNET_OPTION_ALLOW_FAILED_CONNECT_CONTENT = @as(u32, 110); pub const INTERNET_OPTION_CACHE_PARTITION = @as(u32, 111); pub const INTERNET_OPTION_AUTODIAL_HWND = @as(u32, 112); pub const INTERNET_OPTION_SERVER_CREDENTIALS = @as(u32, 113); pub const INTERNET_OPTION_WPAD_SLEEP = @as(u32, 114); pub const INTERNET_OPTION_FAIL_ON_CACHE_WRITE_ERROR = @as(u32, 115); pub const INTERNET_OPTION_DOWNLOAD_MODE = @as(u32, 116); pub const INTERNET_OPTION_RESPONSE_RESUMABLE = @as(u32, 117); pub const INTERNET_OPTION_CM_HANDLE_COPY_REF = @as(u32, 118); pub const INTERNET_OPTION_CONNECTION_INFO = @as(u32, 120); pub const INTERNET_OPTION_BACKGROUND_CONNECTIONS = @as(u32, 121); pub const INTERNET_OPTION_DO_NOT_TRACK = @as(u32, 123); pub const INTERNET_OPTION_USE_MODIFIED_HEADER_FILTER = @as(u32, 124); pub const INTERNET_OPTION_WWA_MODE = @as(u32, 125); pub const INTERNET_OPTION_UPGRADE_TO_WEB_SOCKET = @as(u32, 126); pub const INTERNET_OPTION_WEB_SOCKET_KEEPALIVE_INTERVAL = @as(u32, 127); pub const INTERNET_OPTION_UNLOAD_NOTIFY_EVENT = @as(u32, 128); pub const INTERNET_OPTION_SOCKET_NODELAY = @as(u32, 129); pub const INTERNET_OPTION_APP_CACHE = @as(u32, 130); pub const INTERNET_OPTION_DEPENDENCY_HANDLE = @as(u32, 131); pub const INTERNET_OPTION_USE_FIRST_AVAILABLE_CONNECTION = @as(u32, 132); pub const INTERNET_OPTION_TIMED_CONNECTION_LIMIT_BYPASS = @as(u32, 133); pub const INTERNET_OPTION_WEB_SOCKET_CLOSE_TIMEOUT = @as(u32, 134); pub const INTERNET_OPTION_FLUSH_STATE = @as(u32, 135); pub const INTERNET_OPTION_DISALLOW_PREMATURE_EOF = @as(u32, 137); pub const INTERNET_OPTION_SOCKET_NOTIFICATION_IOCTL = @as(u32, 138); pub const INTERNET_OPTION_CACHE_ENTRY_EXTRA_DATA = @as(u32, 139); pub const INTERNET_OPTION_MAX_QUERY_BUFFER_SIZE = @as(u32, 140); pub const INTERNET_OPTION_FALSE_START = @as(u32, 141); pub const INTERNET_OPTION_USER_PASS_SERVER_ONLY = @as(u32, 142); pub const INTERNET_OPTION_SERVER_AUTH_SCHEME = @as(u32, 143); pub const INTERNET_OPTION_PROXY_AUTH_SCHEME = @as(u32, 144); pub const INTERNET_OPTION_TUNNEL_ONLY = @as(u32, 145); pub const INTERNET_OPTION_SOURCE_PORT = @as(u32, 146); pub const INTERNET_OPTION_ENABLE_DUO = @as(u32, 148); pub const INTERNET_OPTION_DUO_USED = @as(u32, 149); pub const INTERNET_OPTION_CHUNK_ENCODE_REQUEST = @as(u32, 150); pub const INTERNET_OPTION_SECURE_FAILURE = @as(u32, 151); pub const INTERNET_OPTION_NOTIFY_SENDING_COOKIE = @as(u32, 152); pub const INTERNET_OPTION_CLIENT_CERT_ISSUER_LIST = @as(u32, 153); pub const INTERNET_OPTION_RESET = @as(u32, 154); pub const INTERNET_OPTION_SERVER_ADDRESS_INFO = @as(u32, 156); pub const INTERNET_OPTION_ENABLE_WBOEXT = @as(u32, 158); pub const INTERNET_OPTION_DISABLE_INSECURE_FALLBACK = @as(u32, 160); pub const INTERNET_OPTION_ALLOW_INSECURE_FALLBACK = @as(u32, 161); pub const INTERNET_OPTION_SET_IN_PRIVATE = @as(u32, 164); pub const INTERNET_OPTION_DOWNLOAD_MODE_HANDLE = @as(u32, 165); pub const INTERNET_OPTION_EDGE_COOKIES = @as(u32, 166); pub const INTERNET_OPTION_NO_HTTP_SERVER_AUTH = @as(u32, 167); pub const INTERNET_OPTION_ENABLE_HEADER_CALLBACKS = @as(u32, 168); pub const INTERNET_OPTION_PRESERVE_REQUEST_SERVER_CREDENTIALS_ON_REDIRECT = @as(u32, 169); pub const INTERNET_OPTION_PRESERVE_REFERER_ON_HTTPS_TO_HTTP_REDIRECT = @as(u32, 170); pub const INTERNET_OPTION_TCP_FAST_OPEN = @as(u32, 171); pub const INTERNET_OPTION_SYNC_MODE_AUTOMATIC_SESSION_DISABLED = @as(u32, 172); pub const INTERNET_OPTION_ENABLE_ZLIB_DEFLATE = @as(u32, 173); pub const INTERNET_OPTION_ENCODE_FALLBACK_FOR_REDIRECT_URI = @as(u32, 174); pub const INTERNET_OPTION_EDGE_COOKIES_TEMP = @as(u32, 175); pub const INTERNET_OPTION_OPT_IN_WEAK_SIGNATURE = @as(u32, 176); pub const INTERNET_OPTION_PARSE_LINE_FOLDING = @as(u32, 177); pub const INTERNET_OPTION_FORCE_DECODE = @as(u32, 178); pub const INTERNET_OPTION_COOKIES_APPLY_HOST_ONLY = @as(u32, 179); pub const INTERNET_OPTION_EDGE_MODE = @as(u32, 180); pub const INTERNET_OPTION_CANCEL_CACHE_WRITE = @as(u32, 182); pub const INTERNET_OPTION_AUTH_SCHEME_SELECTED = @as(u32, 183); pub const INTERNET_OPTION_NOCACHE_WRITE_IN_PRIVATE = @as(u32, 184); pub const INTERNET_OPTION_ACTIVITY_ID = @as(u32, 185); pub const INTERNET_OPTION_REQUEST_TIMES = @as(u32, 186); pub const INTERNET_OPTION_GLOBAL_CALLBACK = @as(u32, 188); pub const INTERNET_OPTION_ENABLE_TEST_SIGNING = @as(u32, 189); pub const INTERNET_OPTION_DISABLE_PROXY_LINK_LOCAL_NAME_RESOLUTION = @as(u32, 190); pub const INTERNET_OPTION_HTTP_09 = @as(u32, 191); pub const INTERNET_LAST_OPTION_INTERNAL = @as(u32, 191); pub const INTERNET_OPTION_OFFLINE_TIMEOUT = @as(u32, 49); pub const INTERNET_OPTION_LINE_STATE = @as(u32, 50); pub const DUO_PROTOCOL_FLAG_SPDY3 = @as(u32, 1); pub const DUO_PROTOCOL_MASK = @as(u32, 1); pub const AUTH_FLAG_RESET = @as(u32, 0); pub const INTERNET_AUTH_SCHEME_BASIC = @as(u32, 0); pub const INTERNET_AUTH_SCHEME_DIGEST = @as(u32, 1); pub const INTERNET_AUTH_SCHEME_NTLM = @as(u32, 2); pub const INTERNET_AUTH_SCHEME_KERBEROS = @as(u32, 3); pub const INTERNET_AUTH_SCHEME_NEGOTIATE = @as(u32, 4); pub const INTERNET_AUTH_SCHEME_PASSPORT = @as(u32, 5); pub const INTERNET_AUTH_SCHEME_UNKNOWN = @as(u32, 6); pub const INTERNET_STATUS_SENDING_COOKIE = @as(u32, 328); pub const INTERNET_STATUS_REQUEST_HEADERS_SET = @as(u32, 329); pub const INTERNET_STATUS_RESPONSE_HEADERS_SET = @as(u32, 330); pub const INTERNET_STATUS_PROXY_CREDENTIALS = @as(u32, 400); pub const INTERNET_STATUS_SERVER_CREDENTIALS = @as(u32, 401); pub const INTERNET_STATUS_SERVER_CONNECTION_STATE = @as(u32, 410); pub const INTERNET_STATUS_END_BROWSER_SESSION = @as(u32, 420); pub const INTERNET_STATUS_COOKIE = @as(u32, 430); pub const COOKIE_STATE_LB = @as(u32, 0); pub const COOKIE_STATE_UB = @as(u32, 5); pub const MaxPrivacySettings = @as(u32, 16384); pub const INTERNET_STATUS_FILTER_RESOLVING = @as(u32, 1); pub const INTERNET_STATUS_FILTER_RESOLVED = @as(u32, 2); pub const INTERNET_STATUS_FILTER_CONNECTING = @as(u32, 4); pub const INTERNET_STATUS_FILTER_CONNECTED = @as(u32, 8); pub const INTERNET_STATUS_FILTER_SENDING = @as(u32, 16); pub const INTERNET_STATUS_FILTER_SENT = @as(u32, 32); pub const INTERNET_STATUS_FILTER_RECEIVING = @as(u32, 64); pub const INTERNET_STATUS_FILTER_RECEIVED = @as(u32, 128); pub const INTERNET_STATUS_FILTER_CLOSING = @as(u32, 256); pub const INTERNET_STATUS_FILTER_CLOSED = @as(u32, 512); pub const INTERNET_STATUS_FILTER_HANDLE_CREATED = @as(u32, 1024); pub const INTERNET_STATUS_FILTER_HANDLE_CLOSING = @as(u32, 2048); pub const INTERNET_STATUS_FILTER_PREFETCH = @as(u32, 4096); pub const INTERNET_STATUS_FILTER_REDIRECT = @as(u32, 8192); pub const INTERNET_STATUS_FILTER_STATE_CHANGE = @as(u32, 16384); pub const HTTP_ADDREQ_FLAG_RESPONSE_HEADERS = @as(u32, 33554432); pub const HTTP_ADDREQ_FLAG_ALLOW_EMPTY_VALUES = @as(u32, 67108864); pub const COOKIE_DONT_ALLOW = @as(u32, 1); pub const COOKIE_ALLOW = @as(u32, 2); pub const COOKIE_ALLOW_ALL = @as(u32, 4); pub const COOKIE_DONT_ALLOW_ALL = @as(u32, 8); pub const COOKIE_OP_SET = @as(u32, 1); pub const COOKIE_OP_MODIFY = @as(u32, 2); pub const COOKIE_OP_GET = @as(u32, 4); pub const COOKIE_OP_SESSION = @as(u32, 8); pub const COOKIE_OP_PERSISTENT = @as(u32, 16); pub const COOKIE_OP_3RD_PARTY = @as(u32, 32); pub const INTERNET_COOKIE_PERSISTENT_HOST_ONLY = @as(u32, 65536); pub const INTERNET_COOKIE_RESTRICTED_ZONE = @as(u32, 131072); pub const INTERNET_COOKIE_EDGE_COOKIES = @as(u32, 262144); pub const INTERNET_COOKIE_ALL_COOKIES = @as(u32, 536870912); pub const INTERNET_COOKIE_NO_CALLBACK = @as(u32, 1073741824); pub const INTERNET_COOKIE_ECTX_3RDPARTY = @as(u32, 2147483648); pub const FLAGS_ERROR_UI_SHOW_IDN_HOSTNAME = @as(u32, 32); pub const ERROR_INTERNET_NO_NEW_CONTAINERS = @as(u32, 12051); pub const ERROR_INTERNET_SOURCE_PORT_IN_USE = @as(u32, 12058); pub const ERROR_INTERNET_INSECURE_FALLBACK_REQUIRED = @as(u32, 12059); pub const ERROR_INTERNET_PROXY_ALERT = @as(u32, 12061); pub const ERROR_INTERNET_NO_CM_CONNECTION = @as(u32, 12080); pub const ERROR_HTTP_PUSH_STATUS_CODE_NOT_SUPPORTED = @as(u32, 12147); pub const ERROR_HTTP_PUSH_RETRY_NOT_SUPPORTED = @as(u32, 12148); pub const ERROR_HTTP_PUSH_ENABLE_FAILED = @as(u32, 12149); pub const ERROR_INTERNET_DISALLOW_INPRIVATE = @as(u32, 12189); pub const ERROR_INTERNET_OFFLINE = @as(u32, 12163); pub const INTERNET_INTERNAL_ERROR_BASE = @as(u32, 12900); pub const ERROR_INTERNET_INTERNAL_SOCKET_ERROR = @as(u32, 12901); pub const ERROR_INTERNET_CONNECTION_AVAILABLE = @as(u32, 12902); pub const ERROR_INTERNET_NO_KNOWN_SERVERS = @as(u32, 12903); pub const ERROR_INTERNET_PING_FAILED = @as(u32, 12904); pub const ERROR_INTERNET_NO_PING_SUPPORT = @as(u32, 12905); pub const ERROR_INTERNET_CACHE_SUCCESS = @as(u32, 12906); pub const ERROR_HTTP_COOKIE_NEEDS_CONFIRMATION_EX = @as(u32, 12907); pub const HTTP_1_1_CACHE_ENTRY = @as(u32, 64); pub const STATIC_CACHE_ENTRY = @as(u32, 128); pub const MUST_REVALIDATE_CACHE_ENTRY = @as(u32, 256); pub const SHORTPATH_CACHE_ENTRY = @as(u32, 512); pub const DOWNLOAD_CACHE_ENTRY = @as(u32, 1024); pub const REDIRECT_CACHE_ENTRY = @as(u32, 2048); pub const COOKIE_ACCEPTED_CACHE_ENTRY = @as(u32, 4096); pub const COOKIE_LEASHED_CACHE_ENTRY = @as(u32, 8192); pub const COOKIE_DOWNGRADED_CACHE_ENTRY = @as(u32, 16384); pub const COOKIE_REJECTED_CACHE_ENTRY = @as(u32, 32768); pub const PRIVACY_MODE_CACHE_ENTRY = @as(u32, 131072); pub const XDR_CACHE_ENTRY = @as(u32, 262144); pub const IMMUTABLE_CACHE_ENTRY = @as(u32, 524288); pub const PENDING_DELETE_CACHE_ENTRY = @as(u32, 4194304); pub const OTHER_USER_CACHE_ENTRY = @as(u32, 8388608); pub const PRIVACY_IMPACTED_CACHE_ENTRY = @as(u32, 33554432); pub const POST_RESPONSE_CACHE_ENTRY = @as(u32, 67108864); pub const INSTALLED_CACHE_ENTRY = @as(u32, 268435456); pub const POST_CHECK_CACHE_ENTRY = @as(u32, 536870912); pub const IDENTITY_CACHE_ENTRY = @as(u32, 2147483648); pub const ANY_CACHE_ENTRY = @as(u32, 4294967295); pub const CACHEGROUP_FLAG_VALID = @as(u32, 7); pub const CACHEGROUP_ID_BUILTIN_STICKY = @as(u64, 1152921504606846983); pub const INTERNET_CACHE_FLAG_ALLOW_COLLISIONS = @as(u32, 256); pub const INTERNET_CACHE_FLAG_INSTALLED_ENTRY = @as(u32, 512); pub const INTERNET_CACHE_FLAG_ENTRY_OR_MAPPING = @as(u32, 1024); pub const INTERNET_CACHE_FLAG_ADD_FILENAME_ONLY = @as(u32, 2048); pub const INTERNET_CACHE_FLAG_GET_STRUCT_ONLY = @as(u32, 4096); pub const CACHE_ENTRY_TYPE_FC = @as(u32, 4096); pub const CACHE_ENTRY_MODIFY_DATA_FC = @as(u32, 2147483648); pub const INTERNET_CACHE_CONTAINER_NOSUBDIRS = @as(u32, 1); pub const INTERNET_CACHE_CONTAINER_AUTODELETE = @as(u32, 2); pub const INTERNET_CACHE_CONTAINER_RESERVED1 = @as(u32, 4); pub const INTERNET_CACHE_CONTAINER_NODESKTOPINIT = @as(u32, 8); pub const INTERNET_CACHE_CONTAINER_MAP_ENABLED = @as(u32, 16); pub const INTERNET_CACHE_CONTAINER_BLOOM_FILTER = @as(u32, 32); pub const INTERNET_CACHE_CONTAINER_SHARE_READ = @as(u32, 256); pub const INTERNET_CACHE_CONTAINER_SHARE_READ_WRITE = @as(u32, 768); pub const CACHE_FIND_CONTAINER_RETURN_NOCHANGE = @as(u32, 1); pub const CACHE_HEADER_DATA_CURRENT_SETTINGS_VERSION = @as(u32, 0); pub const CACHE_HEADER_DATA_CONLIST_CHANGE_COUNT = @as(u32, 1); pub const CACHE_HEADER_DATA_COOKIE_CHANGE_COUNT = @as(u32, 2); pub const CACHE_HEADER_DATA_NOTIFICATION_HWND = @as(u32, 3); pub const CACHE_HEADER_DATA_NOTIFICATION_MESG = @as(u32, 4); pub const CACHE_HEADER_DATA_ROOTGROUP_OFFSET = @as(u32, 5); pub const CACHE_HEADER_DATA_GID_LOW = @as(u32, 6); pub const CACHE_HEADER_DATA_GID_HIGH = @as(u32, 7); pub const CACHE_HEADER_DATA_LAST_SCAVENGE_TIMESTAMP = @as(u32, 8); pub const CACHE_HEADER_DATA_CACHE_READ_COUNT_SINCE_LAST_SCAVENGE = @as(u32, 9); pub const CACHE_HEADER_DATA_CACHE_WRITE_COUNT_SINCE_LAST_SCAVENGE = @as(u32, 10); pub const CACHE_HEADER_DATA_HSTS_CHANGE_COUNT = @as(u32, 11); pub const CACHE_HEADER_DATA_CACHE_RESERVED_12 = @as(u32, 12); pub const CACHE_HEADER_DATA_CACHE_RESERVED_13 = @as(u32, 13); pub const CACHE_HEADER_DATA_SSL_STATE_COUNT = @as(u32, 14); pub const CACHE_HEADER_DATA_DOWNLOAD_PARTIAL = @as(u32, 14); pub const CACHE_HEADER_DATA_CACHE_RESERVED_15 = @as(u32, 15); pub const CACHE_HEADER_DATA_CACHE_RESERVED_16 = @as(u32, 16); pub const CACHE_HEADER_DATA_CACHE_RESERVED_17 = @as(u32, 17); pub const CACHE_HEADER_DATA_CACHE_RESERVED_18 = @as(u32, 18); pub const CACHE_HEADER_DATA_CACHE_RESERVED_19 = @as(u32, 19); pub const CACHE_HEADER_DATA_CACHE_RESERVED_20 = @as(u32, 20); pub const CACHE_HEADER_DATA_NOTIFICATION_FILTER = @as(u32, 21); pub const CACHE_HEADER_DATA_ROOT_LEAK_OFFSET = @as(u32, 22); pub const CACHE_HEADER_DATA_CACHE_RESERVED_23 = @as(u32, 23); pub const CACHE_HEADER_DATA_CACHE_RESERVED_24 = @as(u32, 24); pub const CACHE_HEADER_DATA_CACHE_RESERVED_25 = @as(u32, 25); pub const CACHE_HEADER_DATA_CACHE_RESERVED_26 = @as(u32, 26); pub const CACHE_HEADER_DATA_ROOT_GROUPLIST_OFFSET = @as(u32, 27); pub const CACHE_HEADER_DATA_CACHE_RESERVED_28 = @as(u32, 28); pub const CACHE_HEADER_DATA_CACHE_RESERVED_29 = @as(u32, 29); pub const CACHE_HEADER_DATA_CACHE_RESERVED_30 = @as(u32, 30); pub const CACHE_HEADER_DATA_CACHE_RESERVED_31 = @as(u32, 31); pub const CACHE_HEADER_DATA_LAST = @as(u32, 31); pub const CACHE_NOTIFY_ADD_URL = @as(u32, 1); pub const CACHE_NOTIFY_DELETE_URL = @as(u32, 2); pub const CACHE_NOTIFY_UPDATE_URL = @as(u32, 4); pub const CACHE_NOTIFY_DELETE_ALL = @as(u32, 8); pub const CACHE_NOTIFY_URL_SET_STICKY = @as(u32, 16); pub const CACHE_NOTIFY_URL_UNSET_STICKY = @as(u32, 32); pub const CACHE_NOTIFY_SET_ONLINE = @as(u32, 256); pub const CACHE_NOTIFY_SET_OFFLINE = @as(u32, 512); pub const CACHE_NOTIFY_FILTER_CHANGED = @as(u32, 268435456); pub const APP_CACHE_LOOKUP_NO_MASTER_ONLY = @as(u32, 1); pub const APP_CACHE_ENTRY_TYPE_MASTER = @as(u32, 1); pub const APP_CACHE_ENTRY_TYPE_EXPLICIT = @as(u32, 2); pub const APP_CACHE_ENTRY_TYPE_FALLBACK = @as(u32, 4); pub const APP_CACHE_ENTRY_TYPE_FOREIGN = @as(u32, 8); pub const APP_CACHE_ENTRY_TYPE_MANIFEST = @as(u32, 16); pub const CACHE_CONFIG_CONTENT_QUOTA_FC = @as(u32, 32768); pub const CACHE_CONFIG_TOTAL_CONTENT_QUOTA_FC = @as(u32, 65536); pub const CACHE_CONFIG_APPCONTAINER_CONTENT_QUOTA_FC = @as(u32, 131072); pub const CACHE_CONFIG_APPCONTAINER_TOTAL_CONTENT_QUOTA_FC = @as(u32, 262144); pub const INTERNET_AUTOPROXY_INIT_DEFAULT = @as(u32, 1); pub const INTERNET_AUTOPROXY_INIT_DOWNLOADSYNC = @as(u32, 2); pub const INTERNET_AUTOPROXY_INIT_QUERYSTATE = @as(u32, 4); pub const INTERNET_AUTOPROXY_INIT_ONLYQUERY = @as(u32, 8); pub const INTERNET_SUPPRESS_COOKIE_PERSIST = @as(u32, 3); pub const INTERNET_SUPPRESS_COOKIE_PERSIST_RESET = @as(u32, 4); pub const HTTP_WEB_SOCKET_MAX_CLOSE_REASON_LENGTH = @as(u32, 123); pub const HTTP_WEB_SOCKET_MIN_KEEPALIVE_VALUE = @as(u32, 10000); pub const INTERNET_GLOBAL_CALLBACK_SENDING_HTTP_HEADERS = @as(u32, 1); //-------------------------------------------------------------------------------- // Section: Types (120) //-------------------------------------------------------------------------------- pub const CACHE_CONFIG = enum(u32) { FORCE_CLEANUP_FC = 32, DISK_CACHE_PATHS_FC = 64, SYNC_MODE_FC = 128, CONTENT_PATHS_FC = 256, HISTORY_PATHS_FC = 1024, COOKIES_PATHS_FC = 512, QUOTA_FC = 2048, USER_MODE_FC = 4096, CONTENT_USAGE_FC = 8192, STICKY_CONTENT_USAGE_FC = 16384, }; pub const CACHE_CONFIG_FORCE_CLEANUP_FC = CACHE_CONFIG.FORCE_CLEANUP_FC; pub const CACHE_CONFIG_DISK_CACHE_PATHS_FC = CACHE_CONFIG.DISK_CACHE_PATHS_FC; pub const CACHE_CONFIG_SYNC_MODE_FC = CACHE_CONFIG.SYNC_MODE_FC; pub const CACHE_CONFIG_CONTENT_PATHS_FC = CACHE_CONFIG.CONTENT_PATHS_FC; pub const CACHE_CONFIG_HISTORY_PATHS_FC = CACHE_CONFIG.HISTORY_PATHS_FC; pub const CACHE_CONFIG_COOKIES_PATHS_FC = CACHE_CONFIG.COOKIES_PATHS_FC; pub const CACHE_CONFIG_QUOTA_FC = CACHE_CONFIG.QUOTA_FC; pub const CACHE_CONFIG_USER_MODE_FC = CACHE_CONFIG.USER_MODE_FC; pub const CACHE_CONFIG_CONTENT_USAGE_FC = CACHE_CONFIG.CONTENT_USAGE_FC; pub const CACHE_CONFIG_STICKY_CONTENT_USAGE_FC = CACHE_CONFIG.STICKY_CONTENT_USAGE_FC; pub const FTP_FLAGS = enum(u32) { FTP_TRANSFER_TYPE_ASCII = 1, FTP_TRANSFER_TYPE_BINARY = 2, FTP_TRANSFER_TYPE_UNKNOWN = 0, // INTERNET_FLAG_TRANSFER_ASCII = 1, this enum value conflicts with FTP_TRANSFER_TYPE_ASCII // INTERNET_FLAG_TRANSFER_BINARY = 2, this enum value conflicts with FTP_TRANSFER_TYPE_BINARY }; pub const FTP_TRANSFER_TYPE_ASCII = FTP_FLAGS.FTP_TRANSFER_TYPE_ASCII; pub const FTP_TRANSFER_TYPE_BINARY = FTP_FLAGS.FTP_TRANSFER_TYPE_BINARY; pub const FTP_TRANSFER_TYPE_UNKNOWN = FTP_FLAGS.FTP_TRANSFER_TYPE_UNKNOWN; pub const INTERNET_FLAG_TRANSFER_ASCII = FTP_FLAGS.FTP_TRANSFER_TYPE_ASCII; pub const INTERNET_FLAG_TRANSFER_BINARY = FTP_FLAGS.FTP_TRANSFER_TYPE_BINARY; pub const INTERNET_CONNECTION = enum(u32) { CONNECTION_CONFIGURED = 64, CONNECTION_LAN_ = 2, CONNECTION_MODEM = 1, CONNECTION_MODEM_BUSY = 8, CONNECTION_OFFLINE_ = 32, CONNECTION_PROXY = 4, RAS_INSTALLED = 16, _, pub fn initFlags(o: struct { CONNECTION_CONFIGURED: u1 = 0, CONNECTION_LAN_: u1 = 0, CONNECTION_MODEM: u1 = 0, CONNECTION_MODEM_BUSY: u1 = 0, CONNECTION_OFFLINE_: u1 = 0, CONNECTION_PROXY: u1 = 0, RAS_INSTALLED: u1 = 0, }) INTERNET_CONNECTION { return @intToEnum(INTERNET_CONNECTION, (if (o.CONNECTION_CONFIGURED == 1) @enumToInt(INTERNET_CONNECTION.CONNECTION_CONFIGURED) else 0) | (if (o.CONNECTION_LAN_ == 1) @enumToInt(INTERNET_CONNECTION.CONNECTION_LAN_) else 0) | (if (o.CONNECTION_MODEM == 1) @enumToInt(INTERNET_CONNECTION.CONNECTION_MODEM) else 0) | (if (o.CONNECTION_MODEM_BUSY == 1) @enumToInt(INTERNET_CONNECTION.CONNECTION_MODEM_BUSY) else 0) | (if (o.CONNECTION_OFFLINE_ == 1) @enumToInt(INTERNET_CONNECTION.CONNECTION_OFFLINE_) else 0) | (if (o.CONNECTION_PROXY == 1) @enumToInt(INTERNET_CONNECTION.CONNECTION_PROXY) else 0) | (if (o.RAS_INSTALLED == 1) @enumToInt(INTERNET_CONNECTION.RAS_INSTALLED) else 0) ); } }; pub const INTERNET_CONNECTION_CONFIGURED = INTERNET_CONNECTION.CONNECTION_CONFIGURED; pub const INTERNET_CONNECTION_LAN_ = INTERNET_CONNECTION.CONNECTION_LAN_; pub const INTERNET_CONNECTION_MODEM = INTERNET_CONNECTION.CONNECTION_MODEM; pub const INTERNET_CONNECTION_MODEM_BUSY = INTERNET_CONNECTION.CONNECTION_MODEM_BUSY; pub const INTERNET_CONNECTION_OFFLINE_ = INTERNET_CONNECTION.CONNECTION_OFFLINE_; pub const INTERNET_CONNECTION_PROXY = INTERNET_CONNECTION.CONNECTION_PROXY; pub const INTERNET_RAS_INSTALLED = INTERNET_CONNECTION.RAS_INSTALLED; pub const HTTP_ADDREQ_FLAG = enum(u32) { ADD = 536870912, ADD_IF_NEW = 268435456, COALESCE = 1073741824, // COALESCE_WITH_COMMA = 1073741824, this enum value conflicts with COALESCE COALESCE_WITH_SEMICOLON = 16777216, REPLACE = 2147483648, _, pub fn initFlags(o: struct { ADD: u1 = 0, ADD_IF_NEW: u1 = 0, COALESCE: u1 = 0, COALESCE_WITH_SEMICOLON: u1 = 0, REPLACE: u1 = 0, }) HTTP_ADDREQ_FLAG { return @intToEnum(HTTP_ADDREQ_FLAG, (if (o.ADD == 1) @enumToInt(HTTP_ADDREQ_FLAG.ADD) else 0) | (if (o.ADD_IF_NEW == 1) @enumToInt(HTTP_ADDREQ_FLAG.ADD_IF_NEW) else 0) | (if (o.COALESCE == 1) @enumToInt(HTTP_ADDREQ_FLAG.COALESCE) else 0) | (if (o.COALESCE_WITH_SEMICOLON == 1) @enumToInt(HTTP_ADDREQ_FLAG.COALESCE_WITH_SEMICOLON) else 0) | (if (o.REPLACE == 1) @enumToInt(HTTP_ADDREQ_FLAG.REPLACE) else 0) ); } }; pub const HTTP_ADDREQ_FLAG_ADD = HTTP_ADDREQ_FLAG.ADD; pub const HTTP_ADDREQ_FLAG_ADD_IF_NEW = HTTP_ADDREQ_FLAG.ADD_IF_NEW; pub const HTTP_ADDREQ_FLAG_COALESCE = HTTP_ADDREQ_FLAG.COALESCE; pub const HTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA = HTTP_ADDREQ_FLAG.COALESCE; pub const HTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON = HTTP_ADDREQ_FLAG.COALESCE_WITH_SEMICOLON; pub const HTTP_ADDREQ_FLAG_REPLACE = HTTP_ADDREQ_FLAG.REPLACE; pub const INTERNET_COOKIE_FLAGS = enum(u32) { COOKIE_HTTPONLY = 8192, COOKIE_THIRD_PARTY = 16, FLAG_RESTRICTED_ZONE = 131072, }; pub const INTERNET_COOKIE_HTTPONLY = INTERNET_COOKIE_FLAGS.COOKIE_HTTPONLY; pub const INTERNET_COOKIE_THIRD_PARTY = INTERNET_COOKIE_FLAGS.COOKIE_THIRD_PARTY; pub const INTERNET_FLAG_RESTRICTED_ZONE = INTERNET_COOKIE_FLAGS.FLAG_RESTRICTED_ZONE; pub const PROXY_AUTO_DETECT_TYPE = enum(u32) { HCP = 1, NS_A = 2, _, pub fn initFlags(o: struct { HCP: u1 = 0, NS_A: u1 = 0, }) PROXY_AUTO_DETECT_TYPE { return @intToEnum(PROXY_AUTO_DETECT_TYPE, (if (o.HCP == 1) @enumToInt(PROXY_AUTO_DETECT_TYPE.HCP) else 0) | (if (o.NS_A == 1) @enumToInt(PROXY_AUTO_DETECT_TYPE.NS_A) else 0) ); } }; pub const PROXY_AUTO_DETECT_TYPE_DHCP = PROXY_AUTO_DETECT_TYPE.HCP; pub const PROXY_AUTO_DETECT_TYPE_DNS_A = PROXY_AUTO_DETECT_TYPE.NS_A; pub const INTERNET_AUTODIAL = enum(u32) { FAILIFSECURITYCHECK = 4, FORCE_ONLINE = 1, FORCE_UNATTENDED = 2, OVERRIDE_NET_PRESENT = 8, }; pub const INTERNET_AUTODIAL_FAILIFSECURITYCHECK = INTERNET_AUTODIAL.FAILIFSECURITYCHECK; pub const INTERNET_AUTODIAL_FORCE_ONLINE = INTERNET_AUTODIAL.FORCE_ONLINE; pub const INTERNET_AUTODIAL_FORCE_UNATTENDED = INTERNET_AUTODIAL.FORCE_UNATTENDED; pub const INTERNET_AUTODIAL_OVERRIDE_NET_PRESENT = INTERNET_AUTODIAL.OVERRIDE_NET_PRESENT; pub const GOPHER_TYPE = enum(u32) { ASK = 1073741824, BINARY = 512, BITMAP = 16384, CALENDAR = 524288, CSO = 4, DIRECTORY = 2, DOS_ARCHIVE = 32, ERROR = 8, GIF = 4096, GOPHER_PLUS = 2147483648, HTML = 131072, IMAGE = 8192, INDEX_SERVER = 128, INLINE = 1048576, MAC_BINHEX = 16, MOVIE = 32768, PDF = 262144, REDUNDANT = 1024, SOUND = 65536, TELNET = 256, TEXT_FILE = 1, TN3270 = 2048, UNIX_UUENCODED = 64, UNKNOWN = 536870912, }; pub const GOPHER_TYPE_ASK = GOPHER_TYPE.ASK; pub const GOPHER_TYPE_BINARY = GOPHER_TYPE.BINARY; pub const GOPHER_TYPE_BITMAP = GOPHER_TYPE.BITMAP; pub const GOPHER_TYPE_CALENDAR = GOPHER_TYPE.CALENDAR; pub const GOPHER_TYPE_CSO = GOPHER_TYPE.CSO; pub const GOPHER_TYPE_DIRECTORY = GOPHER_TYPE.DIRECTORY; pub const GOPHER_TYPE_DOS_ARCHIVE = GOPHER_TYPE.DOS_ARCHIVE; pub const GOPHER_TYPE_ERROR = GOPHER_TYPE.ERROR; pub const GOPHER_TYPE_GIF = GOPHER_TYPE.GIF; pub const GOPHER_TYPE_GOPHER_PLUS = GOPHER_TYPE.GOPHER_PLUS; pub const GOPHER_TYPE_HTML = GOPHER_TYPE.HTML; pub const GOPHER_TYPE_IMAGE = GOPHER_TYPE.IMAGE; pub const GOPHER_TYPE_INDEX_SERVER = GOPHER_TYPE.INDEX_SERVER; pub const GOPHER_TYPE_INLINE = GOPHER_TYPE.INLINE; pub const GOPHER_TYPE_MAC_BINHEX = GOPHER_TYPE.MAC_BINHEX; pub const GOPHER_TYPE_MOVIE = GOPHER_TYPE.MOVIE; pub const GOPHER_TYPE_PDF = GOPHER_TYPE.PDF; pub const GOPHER_TYPE_REDUNDANT = GOPHER_TYPE.REDUNDANT; pub const GOPHER_TYPE_SOUND = GOPHER_TYPE.SOUND; pub const GOPHER_TYPE_TELNET = GOPHER_TYPE.TELNET; pub const GOPHER_TYPE_TEXT_FILE = GOPHER_TYPE.TEXT_FILE; pub const GOPHER_TYPE_TN3270 = GOPHER_TYPE.TN3270; pub const GOPHER_TYPE_UNIX_UUENCODED = GOPHER_TYPE.UNIX_UUENCODED; pub const GOPHER_TYPE_UNKNOWN = GOPHER_TYPE.UNKNOWN; pub const INTERNET_PER_CONN = enum(u32) { AUTOCONFIG_URL = 4, AUTODISCOVERY_FLAGS = 5, FLAGS = 1, PROXY_BYPASS = 3, PROXY_SERVER = 2, AUTOCONFIG_SECONDARY_URL = 6, AUTOCONFIG_RELOAD_DELAY_MINS = 7, AUTOCONFIG_LAST_DETECT_TIME = 8, AUTOCONFIG_LAST_DETECT_URL = 9, }; pub const INTERNET_PER_CONN_AUTOCONFIG_URL = INTERNET_PER_CONN.AUTOCONFIG_URL; pub const INTERNET_PER_CONN_AUTODISCOVERY_FLAGS = INTERNET_PER_CONN.AUTODISCOVERY_FLAGS; pub const INTERNET_PER_CONN_FLAGS = INTERNET_PER_CONN.FLAGS; pub const INTERNET_PER_CONN_PROXY_BYPASS = INTERNET_PER_CONN.PROXY_BYPASS; pub const INTERNET_PER_CONN_PROXY_SERVER = INTERNET_PER_CONN.PROXY_SERVER; pub const INTERNET_PER_CONN_AUTOCONFIG_SECONDARY_URL = INTERNET_PER_CONN.AUTOCONFIG_SECONDARY_URL; pub const INTERNET_PER_CONN_AUTOCONFIG_RELOAD_DELAY_MINS = INTERNET_PER_CONN.AUTOCONFIG_RELOAD_DELAY_MINS; pub const INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_TIME = INTERNET_PER_CONN.AUTOCONFIG_LAST_DETECT_TIME; pub const INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_URL = INTERNET_PER_CONN.AUTOCONFIG_LAST_DETECT_URL; pub const INTERNET_ACCESS_TYPE = enum(u32) { DIRECT = 1, PRECONFIG = 0, PROXY = 3, }; pub const INTERNET_OPEN_TYPE_DIRECT = INTERNET_ACCESS_TYPE.DIRECT; pub const INTERNET_OPEN_TYPE_PRECONFIG = INTERNET_ACCESS_TYPE.PRECONFIG; pub const INTERNET_OPEN_TYPE_PROXY = INTERNET_ACCESS_TYPE.PROXY; pub const INTERNET_STATE = enum(u32) { CONNECTED = 1, DISCONNECTED = 2, DISCONNECTED_BY_USER = 16, IDLE = 256, BUSY = 512, }; pub const INTERNET_STATE_CONNECTED = INTERNET_STATE.CONNECTED; pub const INTERNET_STATE_DISCONNECTED = INTERNET_STATE.DISCONNECTED; pub const INTERNET_STATE_DISCONNECTED_BY_USER = INTERNET_STATE.DISCONNECTED_BY_USER; pub const INTERNET_STATE_IDLE = INTERNET_STATE.IDLE; pub const INTERNET_STATE_BUSY = INTERNET_STATE.BUSY; pub const HTTP_PUSH_WAIT_HANDLE = isize; pub const INTERNET_SCHEME = enum(i32) { PARTIAL = -2, UNKNOWN = -1, DEFAULT = 0, FTP = 1, GOPHER = 2, HTTP = 3, HTTPS = 4, FILE = 5, NEWS = 6, MAILTO = 7, SOCKS = 8, JAVASCRIPT = 9, VBSCRIPT = 10, RES = 11, // FIRST = 1, this enum value conflicts with FTP // LAST = 11, this enum value conflicts with RES }; pub const INTERNET_SCHEME_PARTIAL = INTERNET_SCHEME.PARTIAL; pub const INTERNET_SCHEME_UNKNOWN = INTERNET_SCHEME.UNKNOWN; pub const INTERNET_SCHEME_DEFAULT = INTERNET_SCHEME.DEFAULT; pub const INTERNET_SCHEME_FTP = INTERNET_SCHEME.FTP; pub const INTERNET_SCHEME_GOPHER = INTERNET_SCHEME.GOPHER; pub const INTERNET_SCHEME_HTTP = INTERNET_SCHEME.HTTP; pub const INTERNET_SCHEME_HTTPS = INTERNET_SCHEME.HTTPS; pub const INTERNET_SCHEME_FILE = INTERNET_SCHEME.FILE; pub const INTERNET_SCHEME_NEWS = INTERNET_SCHEME.NEWS; pub const INTERNET_SCHEME_MAILTO = INTERNET_SCHEME.MAILTO; pub const INTERNET_SCHEME_SOCKS = INTERNET_SCHEME.SOCKS; pub const INTERNET_SCHEME_JAVASCRIPT = INTERNET_SCHEME.JAVASCRIPT; pub const INTERNET_SCHEME_VBSCRIPT = INTERNET_SCHEME.VBSCRIPT; pub const INTERNET_SCHEME_RES = INTERNET_SCHEME.RES; pub const INTERNET_SCHEME_FIRST = INTERNET_SCHEME.FTP; pub const INTERNET_SCHEME_LAST = INTERNET_SCHEME.RES; pub const INTERNET_ASYNC_RESULT = extern struct { dwResult: usize, dwError: u32, }; pub const INTERNET_DIAGNOSTIC_SOCKET_INFO = extern struct { Socket: usize, SourcePort: u32, DestPort: u32, Flags: u32, }; pub const INTERNET_PROXY_INFO = extern struct { dwAccessType: INTERNET_ACCESS_TYPE, lpszProxy: ?*i8, lpszProxyBypass: ?*i8, }; pub const INTERNET_PER_CONN_OPTIONA = extern struct { dwOption: INTERNET_PER_CONN, Value: extern union { dwValue: u32, pszValue: ?PSTR, ftValue: FILETIME, }, }; pub const INTERNET_PER_CONN_OPTIONW = extern struct { dwOption: INTERNET_PER_CONN, Value: extern union { dwValue: u32, pszValue: ?PWSTR, ftValue: FILETIME, }, }; pub const INTERNET_PER_CONN_OPTION_LISTA = extern struct { dwSize: u32, pszConnection: ?PSTR, dwOptionCount: u32, dwOptionError: u32, pOptions: ?*INTERNET_PER_CONN_OPTIONA, }; pub const INTERNET_PER_CONN_OPTION_LISTW = extern struct { dwSize: u32, pszConnection: ?PWSTR, dwOptionCount: u32, dwOptionError: u32, pOptions: ?*INTERNET_PER_CONN_OPTIONW, }; pub const INTERNET_VERSION_INFO = extern struct { dwMajorVersion: u32, dwMinorVersion: u32, }; pub const INTERNET_CONNECTED_INFO = extern struct { dwConnectedState: INTERNET_STATE, dwFlags: u32, }; pub const URL_COMPONENTSA = extern struct { dwStructSize: u32, lpszScheme: ?PSTR, dwSchemeLength: u32, nScheme: INTERNET_SCHEME, lpszHostName: ?PSTR, dwHostNameLength: u32, nPort: u16, lpszUserName: ?PSTR, dwUserNameLength: u32, lpszPassword: ?PSTR, dwPasswordLength: u32, lpszUrlPath: ?PSTR, dwUrlPathLength: u32, lpszExtraInfo: ?PSTR, dwExtraInfoLength: u32, }; pub const URL_COMPONENTSW = extern struct { dwStructSize: u32, lpszScheme: ?PWSTR, dwSchemeLength: u32, nScheme: INTERNET_SCHEME, lpszHostName: ?PWSTR, dwHostNameLength: u32, nPort: u16, lpszUserName: ?PWSTR, dwUserNameLength: u32, lpszPassword: ?PWSTR, dwPasswordLength: u32, lpszUrlPath: ?PWSTR, dwUrlPathLength: u32, lpszExtraInfo: ?PWSTR, dwExtraInfoLength: u32, }; pub const INTERNET_CERTIFICATE_INFO = extern struct { ftExpiry: FILETIME, ftStart: FILETIME, lpszSubjectInfo: ?*i8, lpszIssuerInfo: ?*i8, lpszProtocolName: ?*i8, lpszSignatureAlgName: ?*i8, lpszEncryptionAlgName: ?*i8, dwKeySize: u32, }; pub const INTERNET_BUFFERSA = extern struct { dwStructSize: u32, Next: ?*INTERNET_BUFFERSA, lpcszHeader: ?[*:0]const u8, dwHeadersLength: u32, dwHeadersTotal: u32, lpvBuffer: ?*anyopaque, dwBufferLength: u32, dwBufferTotal: u32, dwOffsetLow: u32, dwOffsetHigh: u32, }; pub const INTERNET_BUFFERSW = extern struct { dwStructSize: u32, Next: ?*INTERNET_BUFFERSW, lpcszHeader: ?[*:0]const u16, dwHeadersLength: u32, dwHeadersTotal: u32, lpvBuffer: ?*anyopaque, dwBufferLength: u32, dwBufferTotal: u32, dwOffsetLow: u32, dwOffsetHigh: u32, }; pub const LPINTERNET_STATUS_CALLBACK = fn( hInternet: ?*anyopaque, dwContext: usize, dwInternetStatus: u32, lpvStatusInformation: ?*anyopaque, dwStatusInformationLength: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const InternetCookieState = enum(i32) { UNKNOWN = 0, ACCEPT = 1, PROMPT = 2, LEASH = 3, DOWNGRADE = 4, REJECT = 5, // MAX = 5, this enum value conflicts with REJECT }; pub const COOKIE_STATE_UNKNOWN = InternetCookieState.UNKNOWN; pub const COOKIE_STATE_ACCEPT = InternetCookieState.ACCEPT; pub const COOKIE_STATE_PROMPT = InternetCookieState.PROMPT; pub const COOKIE_STATE_LEASH = InternetCookieState.LEASH; pub const COOKIE_STATE_DOWNGRADE = InternetCookieState.DOWNGRADE; pub const COOKIE_STATE_REJECT = InternetCookieState.REJECT; pub const COOKIE_STATE_MAX = InternetCookieState.REJECT; pub const IncomingCookieState = extern struct { cSession: i32, cPersistent: i32, cAccepted: i32, cLeashed: i32, cDowngraded: i32, cBlocked: i32, pszLocation: ?[*:0]const u8, }; pub const OutgoingCookieState = extern struct { cSent: i32, cSuppressed: i32, pszLocation: ?[*:0]const u8, }; pub const InternetCookieHistory = extern struct { fAccepted: BOOL, fLeashed: BOOL, fDowngraded: BOOL, fRejected: BOOL, }; pub const CookieDecision = extern struct { dwCookieState: u32, fAllowSession: BOOL, }; pub const GOPHER_FIND_DATAA = extern struct { DisplayString: [129]CHAR, GopherType: GOPHER_TYPE, SizeLow: u32, SizeHigh: u32, LastModificationTime: FILETIME, Locator: [654]CHAR, }; pub const GOPHER_FIND_DATAW = extern struct { DisplayString: [129]u16, GopherType: GOPHER_TYPE, SizeLow: u32, SizeHigh: u32, LastModificationTime: FILETIME, Locator: [654]u16, }; pub const GOPHER_ADMIN_ATTRIBUTE_TYPE = extern struct { Comment: ?*i8, EmailAddress: ?*i8, }; pub const GOPHER_MOD_DATE_ATTRIBUTE_TYPE = extern struct { DateAndTime: FILETIME, }; pub const GOPHER_TTL_ATTRIBUTE_TYPE = extern struct { Ttl: u32, }; pub const GOPHER_SCORE_ATTRIBUTE_TYPE = extern struct { Score: i32, }; pub const GOPHER_SCORE_RANGE_ATTRIBUTE_TYPE = extern struct { LowerBound: i32, UpperBound: i32, }; pub const GOPHER_SITE_ATTRIBUTE_TYPE = extern struct { Site: ?*i8, }; pub const GOPHER_ORGANIZATION_ATTRIBUTE_TYPE = extern struct { Organization: ?*i8, }; pub const GOPHER_LOCATION_ATTRIBUTE_TYPE = extern struct { Location: ?*i8, }; pub const GOPHER_GEOGRAPHICAL_LOCATION_ATTRIBUTE_TYPE = extern struct { DegreesNorth: i32, MinutesNorth: i32, SecondsNorth: i32, DegreesEast: i32, MinutesEast: i32, SecondsEast: i32, }; pub const GOPHER_TIMEZONE_ATTRIBUTE_TYPE = extern struct { Zone: i32, }; pub const GOPHER_PROVIDER_ATTRIBUTE_TYPE = extern struct { Provider: ?*i8, }; pub const GOPHER_VERSION_ATTRIBUTE_TYPE = extern struct { Version: ?*i8, }; pub const GOPHER_ABSTRACT_ATTRIBUTE_TYPE = extern struct { ShortAbstract: ?*i8, AbstractFile: ?*i8, }; pub const GOPHER_VIEW_ATTRIBUTE_TYPE = extern struct { ContentType: ?*i8, Language: ?*i8, Size: u32, }; pub const GOPHER_VERONICA_ATTRIBUTE_TYPE = extern struct { TreeWalk: BOOL, }; pub const GOPHER_ASK_ATTRIBUTE_TYPE = extern struct { QuestionType: ?*i8, QuestionText: ?*i8, }; pub const GOPHER_UNKNOWN_ATTRIBUTE_TYPE = extern struct { Text: ?*i8, }; pub const GOPHER_ATTRIBUTE_TYPE = extern struct { CategoryId: u32, AttributeId: u32, AttributeType: extern union { Admin: GOPHER_ADMIN_ATTRIBUTE_TYPE, ModDate: GOPHER_MOD_DATE_ATTRIBUTE_TYPE, Ttl: GOPHER_TTL_ATTRIBUTE_TYPE, Score: GOPHER_SCORE_ATTRIBUTE_TYPE, ScoreRange: GOPHER_SCORE_RANGE_ATTRIBUTE_TYPE, Site: GOPHER_SITE_ATTRIBUTE_TYPE, Organization: GOPHER_ORGANIZATION_ATTRIBUTE_TYPE, Location: GOPHER_LOCATION_ATTRIBUTE_TYPE, GeographicalLocation: GOPHER_GEOGRAPHICAL_LOCATION_ATTRIBUTE_TYPE, TimeZone: GOPHER_TIMEZONE_ATTRIBUTE_TYPE, Provider: GOPHER_PROVIDER_ATTRIBUTE_TYPE, Version: GOPHER_VERSION_ATTRIBUTE_TYPE, Abstract: GOPHER_ABSTRACT_ATTRIBUTE_TYPE, View: GOPHER_VIEW_ATTRIBUTE_TYPE, Veronica: GOPHER_VERONICA_ATTRIBUTE_TYPE, Ask: GOPHER_ASK_ATTRIBUTE_TYPE, Unknown: GOPHER_UNKNOWN_ATTRIBUTE_TYPE, }, }; pub const GOPHER_ATTRIBUTE_ENUMERATOR = fn( lpAttributeInfo: ?*GOPHER_ATTRIBUTE_TYPE, dwError: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const INTERNET_COOKIE2 = extern struct { pwszName: ?PWSTR, pwszValue: ?PWSTR, pwszDomain: ?PWSTR, pwszPath: ?PWSTR, dwFlags: u32, ftExpires: FILETIME, fExpiresSet: BOOL, }; pub const PFN_AUTH_NOTIFY = fn( param0: usize, param1: u32, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const INTERNET_AUTH_NOTIFY_DATA = extern struct { cbStruct: u32, dwOptions: u32, pfnNotify: ?PFN_AUTH_NOTIFY, dwContext: usize, }; pub const INTERNET_CACHE_ENTRY_INFOA = extern struct { dwStructSize: u32, lpszSourceUrlName: ?PSTR, lpszLocalFileName: ?PSTR, CacheEntryType: u32, dwUseCount: u32, dwHitRate: u32, dwSizeLow: u32, dwSizeHigh: u32, LastModifiedTime: FILETIME, ExpireTime: FILETIME, LastAccessTime: FILETIME, LastSyncTime: FILETIME, lpHeaderInfo: ?PSTR, dwHeaderInfoSize: u32, lpszFileExtension: ?PSTR, Anonymous: extern union { dwReserved: u32, dwExemptDelta: u32, }, }; pub const INTERNET_CACHE_ENTRY_INFOW = extern struct { dwStructSize: u32, lpszSourceUrlName: ?PWSTR, lpszLocalFileName: ?PWSTR, CacheEntryType: u32, dwUseCount: u32, dwHitRate: u32, dwSizeLow: u32, dwSizeHigh: u32, LastModifiedTime: FILETIME, ExpireTime: FILETIME, LastAccessTime: FILETIME, LastSyncTime: FILETIME, lpHeaderInfo: ?PWSTR, dwHeaderInfoSize: u32, lpszFileExtension: ?PWSTR, Anonymous: extern union { dwReserved: u32, dwExemptDelta: u32, }, }; pub const INTERNET_CACHE_TIMESTAMPS = extern struct { ftExpires: FILETIME, ftLastModified: FILETIME, }; pub const INTERNET_CACHE_GROUP_INFOA = extern struct { dwGroupSize: u32, dwGroupFlags: u32, dwGroupType: u32, dwDiskUsage: u32, dwDiskQuota: u32, dwOwnerStorage: [4]u32, szGroupName: [120]CHAR, }; pub const INTERNET_CACHE_GROUP_INFOW = extern struct { dwGroupSize: u32, dwGroupFlags: u32, dwGroupType: u32, dwDiskUsage: u32, dwDiskQuota: u32, dwOwnerStorage: [4]u32, szGroupName: [120]u16, }; pub const AutoProxyHelperVtbl = extern struct { IsResolvable: isize, GetIPAddress: isize, ResolveHostName: isize, IsInNet: isize, IsResolvableEx: isize, GetIPAddressEx: isize, ResolveHostNameEx: isize, IsInNetEx: isize, SortIpList: isize, }; pub const AUTO_PROXY_SCRIPT_BUFFER = extern struct { dwStructSize: u32, lpszScriptBuffer: ?PSTR, dwScriptBufferSize: u32, }; pub const AutoProxyHelperFunctions = extern struct { lpVtbl: ?*const AutoProxyHelperVtbl, }; pub const pfnInternetInitializeAutoProxyDll = fn( dwVersion: u32, lpszDownloadedTempFile: ?PSTR, lpszMime: ?PSTR, lpAutoProxyCallbacks: ?*AutoProxyHelperFunctions, lpAutoProxyScriptBuffer: ?*AUTO_PROXY_SCRIPT_BUFFER, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const pfnInternetDeInitializeAutoProxyDll = fn( lpszMime: ?PSTR, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const pfnInternetGetProxyInfo = fn( lpszUrl: ?[*:0]const u8, dwUrlLength: u32, lpszUrlHostName: ?PSTR, dwUrlHostNameLength: u32, lplpszProxyHostName: ?*?PSTR, lpdwProxyHostNameLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const WPAD_CACHE_DELETE = enum(i32) { CURRENT = 0, ALL = 1, }; pub const WPAD_CACHE_DELETE_CURRENT = WPAD_CACHE_DELETE.CURRENT; pub const WPAD_CACHE_DELETE_ALL = WPAD_CACHE_DELETE.ALL; pub const PFN_DIAL_HANDLER = fn( param0: ?HWND, param1: ?[*:0]const u8, param2: u32, param3: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; const IID_IDialEventSink_Value = Guid.initString("2d86f4ff-6e2d-4488-b2e9-6934afd41bea"); pub const IID_IDialEventSink = &IID_IDialEventSink_Value; pub const IDialEventSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnEvent: fn( self: *const IDialEventSink, dwEvent: u32, dwStatus: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDialEventSink_OnEvent(self: *const T, dwEvent: u32, dwStatus: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDialEventSink.VTable, self.vtable).OnEvent(@ptrCast(*const IDialEventSink, self), dwEvent, dwStatus); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDialEngine_Value = Guid.initString("39fd782b-7905-40d5-9148-3c9b190423d5"); pub const IID_IDialEngine = &IID_IDialEngine_Value; pub const IDialEngine = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IDialEngine, pwzConnectoid: ?[*:0]const u16, pIDES: ?*IDialEventSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProperty: fn( self: *const IDialEngine, pwzProperty: ?[*:0]const u16, pwzValue: ?PWSTR, dwBufSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProperty: fn( self: *const IDialEngine, pwzProperty: ?[*:0]const u16, pwzValue: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Dial: fn( self: *const IDialEngine, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HangUp: fn( self: *const IDialEngine, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetConnectedState: fn( self: *const IDialEngine, pdwState: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetConnectHandle: fn( self: *const IDialEngine, pdwHandle: ?*usize, ) 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 IDialEngine_Initialize(self: *const T, pwzConnectoid: ?[*:0]const u16, pIDES: ?*IDialEventSink) callconv(.Inline) HRESULT { return @ptrCast(*const IDialEngine.VTable, self.vtable).Initialize(@ptrCast(*const IDialEngine, self), pwzConnectoid, pIDES); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDialEngine_GetProperty(self: *const T, pwzProperty: ?[*:0]const u16, pwzValue: ?PWSTR, dwBufSize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDialEngine.VTable, self.vtable).GetProperty(@ptrCast(*const IDialEngine, self), pwzProperty, pwzValue, dwBufSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDialEngine_SetProperty(self: *const T, pwzProperty: ?[*:0]const u16, pwzValue: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IDialEngine.VTable, self.vtable).SetProperty(@ptrCast(*const IDialEngine, self), pwzProperty, pwzValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDialEngine_Dial(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDialEngine.VTable, self.vtable).Dial(@ptrCast(*const IDialEngine, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDialEngine_HangUp(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDialEngine.VTable, self.vtable).HangUp(@ptrCast(*const IDialEngine, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDialEngine_GetConnectedState(self: *const T, pdwState: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDialEngine.VTable, self.vtable).GetConnectedState(@ptrCast(*const IDialEngine, self), pdwState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDialEngine_GetConnectHandle(self: *const T, pdwHandle: ?*usize) callconv(.Inline) HRESULT { return @ptrCast(*const IDialEngine.VTable, self.vtable).GetConnectHandle(@ptrCast(*const IDialEngine, self), pdwHandle); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDialBranding_Value = Guid.initString("8aecafa9-4306-43cc-8c5a-765f2979cc16"); pub const IID_IDialBranding = &IID_IDialBranding_Value; pub const IDialBranding = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IDialBranding, pwzConnectoid: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBitmap: fn( self: *const IDialBranding, dwIndex: u32, phBitmap: ?*?HBITMAP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDialBranding_Initialize(self: *const T, pwzConnectoid: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IDialBranding.VTable, self.vtable).Initialize(@ptrCast(*const IDialBranding, self), pwzConnectoid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDialBranding_GetBitmap(self: *const T, dwIndex: u32, phBitmap: ?*?HBITMAP) callconv(.Inline) HRESULT { return @ptrCast(*const IDialBranding.VTable, self.vtable).GetBitmap(@ptrCast(*const IDialBranding, self), dwIndex, phBitmap); } };} pub usingnamespace MethodMixin(@This()); }; pub const INTERNET_PREFETCH_STATUS = extern struct { dwStatus: u32, dwSize: u32, }; pub const INTERNET_SECURITY_INFO = extern struct { dwSize: u32, pCertificate: ?*const CERT_CONTEXT, pcCertChain: ?*CERT_CHAIN_CONTEXT, connectionInfo: SecPkgContext_ConnectionInfo, cipherInfo: SecPkgContext_CipherInfo, pcUnverifiedCertChain: ?*CERT_CHAIN_CONTEXT, channelBindingToken: SecPkgContext_Bindings, }; pub const INTERNET_SECURITY_CONNECTION_INFO = extern struct { dwSize: u32, fSecure: BOOL, connectionInfo: SecPkgContext_ConnectionInfo, cipherInfo: SecPkgContext_CipherInfo, }; pub const FORTCMD = enum(i32) { LOGON = 1, LOGOFF = 2, CHG_PERSONALITY = 3, }; pub const FORTCMD_LOGON = FORTCMD.LOGON; pub const FORTCMD_LOGOFF = FORTCMD.LOGOFF; pub const FORTCMD_CHG_PERSONALITY = FORTCMD.CHG_PERSONALITY; pub const FORTSTAT = enum(i32) { INSTALLED = 1, LOGGEDON = 2, }; pub const FORTSTAT_INSTALLED = FORTSTAT.INSTALLED; pub const FORTSTAT_LOGGEDON = FORTSTAT.LOGGEDON; pub const INTERNET_DOWNLOAD_MODE_HANDLE = extern struct { pcwszFileName: ?[*:0]const u16, phFile: ?*?HANDLE, }; pub const REQUEST_TIMES = enum(i32) { NameResolutionStart = 0, NameResolutionEnd = 1, ConnectionEstablishmentStart = 2, ConnectionEstablishmentEnd = 3, TLSHandshakeStart = 4, TLSHandshakeEnd = 5, HttpRequestTimeMax = 32, }; pub const NameResolutionStart = REQUEST_TIMES.NameResolutionStart; pub const NameResolutionEnd = REQUEST_TIMES.NameResolutionEnd; pub const ConnectionEstablishmentStart = REQUEST_TIMES.ConnectionEstablishmentStart; pub const ConnectionEstablishmentEnd = REQUEST_TIMES.ConnectionEstablishmentEnd; pub const TLSHandshakeStart = REQUEST_TIMES.TLSHandshakeStart; pub const TLSHandshakeEnd = REQUEST_TIMES.TLSHandshakeEnd; pub const HttpRequestTimeMax = REQUEST_TIMES.HttpRequestTimeMax; pub const HTTP_REQUEST_TIMES = extern struct { cTimes: u32, rgTimes: [32]u64, }; pub const INTERNET_SERVER_CONNECTION_STATE = extern struct { lpcwszHostName: ?[*:0]const u16, fProxy: BOOL, dwCounter: u32, dwConnectionLimit: u32, dwAvailableCreates: u32, dwAvailableKeepAlives: u32, dwActiveConnections: u32, dwWaiters: u32, }; pub const INTERNET_END_BROWSER_SESSION_DATA = extern struct { lpBuffer: ?*anyopaque, dwBufferLength: u32, }; pub const INTERNET_CALLBACK_COOKIE = extern struct { pcwszName: ?[*:0]const u16, pcwszValue: ?[*:0]const u16, pcwszDomain: ?[*:0]const u16, pcwszPath: ?[*:0]const u16, ftExpires: FILETIME, dwFlags: u32, }; pub const INTERNET_CREDENTIALS = extern struct { lpcwszHostName: ?[*:0]const u16, dwPort: u32, dwScheme: u32, lpcwszUrl: ?[*:0]const u16, lpcwszRealm: ?[*:0]const u16, fAuthIdentity: BOOL, Anonymous: extern union { Anonymous: extern struct { lpcwszUserName: ?[*:0]const u16, lpcwszPassword: ?[*:0]const u16, }, pAuthIdentityOpaque: ?*anyopaque, }, }; pub const HTTP_PUSH_TRANSPORT_SETTING = extern struct { TransportSettingId: Guid, BrokerEventId: Guid, }; pub const HTTP_PUSH_NOTIFICATION_STATUS = extern struct { ChannelStatusValid: BOOL, ChannelStatus: u32, }; pub const HTTP_PUSH_WAIT_TYPE = enum(i32) { EnableComplete = 0, ReceiveComplete = 1, SendComplete = 2, }; pub const HttpPushWaitEnableComplete = HTTP_PUSH_WAIT_TYPE.EnableComplete; pub const HttpPushWaitReceiveComplete = HTTP_PUSH_WAIT_TYPE.ReceiveComplete; pub const HttpPushWaitSendComplete = HTTP_PUSH_WAIT_TYPE.SendComplete; pub const INTERNET_COOKIE = extern struct { cbSize: u32, pszName: ?PSTR, pszData: ?PSTR, pszDomain: ?PSTR, pszPath: ?PSTR, pftExpires: ?*FILETIME, dwFlags: u32, pszUrl: ?PSTR, pszP3PPolicy: ?PSTR, }; pub const COOKIE_DLG_INFO = extern struct { pszServer: ?PWSTR, pic: ?*INTERNET_COOKIE, dwStopWarning: u32, cx: i32, cy: i32, pszHeader: ?PWSTR, dwOperation: u32, }; pub const INTERNET_CACHE_CONFIG_PATH_ENTRYA = extern struct { CachePath: [260]CHAR, dwCacheSize: u32, }; pub const INTERNET_CACHE_CONFIG_PATH_ENTRYW = extern struct { CachePath: [260]u16, dwCacheSize: u32, }; pub const INTERNET_CACHE_CONFIG_INFOA = extern struct { dwStructSize: u32, dwContainer: u32, dwQuota: u32, dwReserved4: u32, fPerUser: BOOL, dwSyncMode: u32, dwNumCachePaths: u32, Anonymous: extern union { Anonymous: extern struct { CachePath: [260]CHAR, dwCacheSize: u32, }, CachePaths: [1]INTERNET_CACHE_CONFIG_PATH_ENTRYA, }, dwNormalUsage: u32, dwExemptUsage: u32, }; pub const INTERNET_CACHE_CONFIG_INFOW = extern struct { dwStructSize: u32, dwContainer: u32, dwQuota: u32, dwReserved4: u32, fPerUser: BOOL, dwSyncMode: u32, dwNumCachePaths: u32, Anonymous: extern union { Anonymous: extern struct { CachePath: [260]u16, dwCacheSize: u32, }, CachePaths: [1]INTERNET_CACHE_CONFIG_PATH_ENTRYW, }, dwNormalUsage: u32, dwExemptUsage: u32, }; pub const INTERNET_CACHE_CONTAINER_INFOA = extern struct { dwCacheVersion: u32, lpszName: ?PSTR, lpszCachePrefix: ?PSTR, lpszVolumeLabel: ?PSTR, lpszVolumeTitle: ?PSTR, }; pub const INTERNET_CACHE_CONTAINER_INFOW = extern struct { dwCacheVersion: u32, lpszName: ?PWSTR, lpszCachePrefix: ?PWSTR, lpszVolumeLabel: ?PWSTR, lpszVolumeTitle: ?PWSTR, }; pub const WININET_SYNC_MODE = enum(i32) { NEVER = 0, ON_EXPIRY = 1, ONCE_PER_SESSION = 2, ALWAYS = 3, AUTOMATIC = 4, // DEFAULT = 4, this enum value conflicts with AUTOMATIC }; pub const WININET_SYNC_MODE_NEVER = WININET_SYNC_MODE.NEVER; pub const WININET_SYNC_MODE_ON_EXPIRY = WININET_SYNC_MODE.ON_EXPIRY; pub const WININET_SYNC_MODE_ONCE_PER_SESSION = WININET_SYNC_MODE.ONCE_PER_SESSION; pub const WININET_SYNC_MODE_ALWAYS = WININET_SYNC_MODE.ALWAYS; pub const WININET_SYNC_MODE_AUTOMATIC = WININET_SYNC_MODE.AUTOMATIC; pub const WININET_SYNC_MODE_DEFAULT = WININET_SYNC_MODE.AUTOMATIC; pub const APP_CACHE_STATE = enum(i32) { NoUpdateNeeded = 0, UpdateNeeded = 1, UpdateNeededNew = 2, UpdateNeededMasterOnly = 3, }; pub const AppCacheStateNoUpdateNeeded = APP_CACHE_STATE.NoUpdateNeeded; pub const AppCacheStateUpdateNeeded = APP_CACHE_STATE.UpdateNeeded; pub const AppCacheStateUpdateNeededNew = APP_CACHE_STATE.UpdateNeededNew; pub const AppCacheStateUpdateNeededMasterOnly = APP_CACHE_STATE.UpdateNeededMasterOnly; pub const APP_CACHE_DOWNLOAD_ENTRY = extern struct { pwszUrl: ?PWSTR, dwEntryType: u32, }; pub const APP_CACHE_DOWNLOAD_LIST = extern struct { dwEntryCount: u32, pEntries: ?*APP_CACHE_DOWNLOAD_ENTRY, }; pub const APP_CACHE_FINALIZE_STATE = enum(i32) { Incomplete = 0, ManifestChange = 1, Complete = 2, }; pub const AppCacheFinalizeStateIncomplete = APP_CACHE_FINALIZE_STATE.Incomplete; pub const AppCacheFinalizeStateManifestChange = APP_CACHE_FINALIZE_STATE.ManifestChange; pub const AppCacheFinalizeStateComplete = APP_CACHE_FINALIZE_STATE.Complete; pub const APP_CACHE_GROUP_INFO = extern struct { pwszManifestUrl: ?PWSTR, ftLastAccessTime: FILETIME, ullSize: u64, }; pub const APP_CACHE_GROUP_LIST = extern struct { dwAppCacheGroupCount: u32, pAppCacheGroups: ?*APP_CACHE_GROUP_INFO, }; pub const URLCACHE_ENTRY_INFO = extern struct { pwszSourceUrlName: ?PWSTR, pwszLocalFileName: ?PWSTR, dwCacheEntryType: u32, dwUseCount: u32, dwHitRate: u32, dwSizeLow: u32, dwSizeHigh: u32, ftLastModifiedTime: FILETIME, ftExpireTime: FILETIME, ftLastAccessTime: FILETIME, ftLastSyncTime: FILETIME, pbHeaderInfo: ?*u8, cbHeaderInfoSize: u32, pbExtraData: ?*u8, cbExtraDataSize: u32, }; pub const URL_CACHE_LIMIT_TYPE = enum(i32) { IE = 0, IETotal = 1, AppContainer = 2, AppContainerTotal = 3, Num = 4, }; pub const UrlCacheLimitTypeIE = URL_CACHE_LIMIT_TYPE.IE; pub const UrlCacheLimitTypeIETotal = URL_CACHE_LIMIT_TYPE.IETotal; pub const UrlCacheLimitTypeAppContainer = URL_CACHE_LIMIT_TYPE.AppContainer; pub const UrlCacheLimitTypeAppContainerTotal = URL_CACHE_LIMIT_TYPE.AppContainerTotal; pub const UrlCacheLimitTypeNum = URL_CACHE_LIMIT_TYPE.Num; pub const WININET_PROXY_INFO = extern struct { fProxy: BOOL, fBypass: BOOL, ProxyScheme: INTERNET_SCHEME, pwszProxy: ?PWSTR, ProxyPort: u16, }; pub const WININET_PROXY_INFO_LIST = extern struct { dwProxyInfoCount: u32, pProxyInfo: ?*WININET_PROXY_INFO, }; pub const CACHE_OPERATOR = fn( pcei: ?*INTERNET_CACHE_ENTRY_INFOA, pcbcei: ?*u32, pOpData: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const HTTP_WEB_SOCKET_OPERATION = enum(i32) { SEND_OPERATION = 0, RECEIVE_OPERATION = 1, CLOSE_OPERATION = 2, SHUTDOWN_OPERATION = 3, }; pub const HTTP_WEB_SOCKET_SEND_OPERATION = HTTP_WEB_SOCKET_OPERATION.SEND_OPERATION; pub const HTTP_WEB_SOCKET_RECEIVE_OPERATION = HTTP_WEB_SOCKET_OPERATION.RECEIVE_OPERATION; pub const HTTP_WEB_SOCKET_CLOSE_OPERATION = HTTP_WEB_SOCKET_OPERATION.CLOSE_OPERATION; pub const HTTP_WEB_SOCKET_SHUTDOWN_OPERATION = HTTP_WEB_SOCKET_OPERATION.SHUTDOWN_OPERATION; pub const HTTP_WEB_SOCKET_BUFFER_TYPE = enum(i32) { BINARY_MESSAGE_TYPE = 0, BINARY_FRAGMENT_TYPE = 1, UTF8_MESSAGE_TYPE = 2, UTF8_FRAGMENT_TYPE = 3, CLOSE_TYPE = 4, PING_TYPE = 5, }; pub const HTTP_WEB_SOCKET_BINARY_MESSAGE_TYPE = HTTP_WEB_SOCKET_BUFFER_TYPE.BINARY_MESSAGE_TYPE; pub const HTTP_WEB_SOCKET_BINARY_FRAGMENT_TYPE = HTTP_WEB_SOCKET_BUFFER_TYPE.BINARY_FRAGMENT_TYPE; pub const HTTP_WEB_SOCKET_UTF8_MESSAGE_TYPE = HTTP_WEB_SOCKET_BUFFER_TYPE.UTF8_MESSAGE_TYPE; pub const HTTP_WEB_SOCKET_UTF8_FRAGMENT_TYPE = HTTP_WEB_SOCKET_BUFFER_TYPE.UTF8_FRAGMENT_TYPE; pub const HTTP_WEB_SOCKET_CLOSE_TYPE = HTTP_WEB_SOCKET_BUFFER_TYPE.CLOSE_TYPE; pub const HTTP_WEB_SOCKET_PING_TYPE = HTTP_WEB_SOCKET_BUFFER_TYPE.PING_TYPE; pub const HTTP_WEB_SOCKET_CLOSE_STATUS = enum(i32) { SUCCESS_CLOSE_STATUS = 1000, ENDPOINT_TERMINATED_CLOSE_STATUS = 1001, PROTOCOL_ERROR_CLOSE_STATUS = 1002, INVALID_DATA_TYPE_CLOSE_STATUS = 1003, EMPTY_CLOSE_STATUS = 1005, ABORTED_CLOSE_STATUS = 1006, INVALID_PAYLOAD_CLOSE_STATUS = 1007, POLICY_VIOLATION_CLOSE_STATUS = 1008, MESSAGE_TOO_BIG_CLOSE_STATUS = 1009, UNSUPPORTED_EXTENSIONS_CLOSE_STATUS = 1010, SERVER_ERROR_CLOSE_STATUS = 1011, SECURE_HANDSHAKE_ERROR_CLOSE_STATUS = 1015, }; pub const HTTP_WEB_SOCKET_SUCCESS_CLOSE_STATUS = HTTP_WEB_SOCKET_CLOSE_STATUS.SUCCESS_CLOSE_STATUS; pub const HTTP_WEB_SOCKET_ENDPOINT_TERMINATED_CLOSE_STATUS = HTTP_WEB_SOCKET_CLOSE_STATUS.ENDPOINT_TERMINATED_CLOSE_STATUS; pub const HTTP_WEB_SOCKET_PROTOCOL_ERROR_CLOSE_STATUS = HTTP_WEB_SOCKET_CLOSE_STATUS.PROTOCOL_ERROR_CLOSE_STATUS; pub const HTTP_WEB_SOCKET_INVALID_DATA_TYPE_CLOSE_STATUS = HTTP_WEB_SOCKET_CLOSE_STATUS.INVALID_DATA_TYPE_CLOSE_STATUS; pub const HTTP_WEB_SOCKET_EMPTY_CLOSE_STATUS = HTTP_WEB_SOCKET_CLOSE_STATUS.EMPTY_CLOSE_STATUS; pub const HTTP_WEB_SOCKET_ABORTED_CLOSE_STATUS = HTTP_WEB_SOCKET_CLOSE_STATUS.ABORTED_CLOSE_STATUS; pub const HTTP_WEB_SOCKET_INVALID_PAYLOAD_CLOSE_STATUS = HTTP_WEB_SOCKET_CLOSE_STATUS.INVALID_PAYLOAD_CLOSE_STATUS; pub const HTTP_WEB_SOCKET_POLICY_VIOLATION_CLOSE_STATUS = HTTP_WEB_SOCKET_CLOSE_STATUS.POLICY_VIOLATION_CLOSE_STATUS; pub const HTTP_WEB_SOCKET_MESSAGE_TOO_BIG_CLOSE_STATUS = HTTP_WEB_SOCKET_CLOSE_STATUS.MESSAGE_TOO_BIG_CLOSE_STATUS; pub const HTTP_WEB_SOCKET_UNSUPPORTED_EXTENSIONS_CLOSE_STATUS = HTTP_WEB_SOCKET_CLOSE_STATUS.UNSUPPORTED_EXTENSIONS_CLOSE_STATUS; pub const HTTP_WEB_SOCKET_SERVER_ERROR_CLOSE_STATUS = HTTP_WEB_SOCKET_CLOSE_STATUS.SERVER_ERROR_CLOSE_STATUS; pub const HTTP_WEB_SOCKET_SECURE_HANDSHAKE_ERROR_CLOSE_STATUS = HTTP_WEB_SOCKET_CLOSE_STATUS.SECURE_HANDSHAKE_ERROR_CLOSE_STATUS; pub const HTTP_WEB_SOCKET_ASYNC_RESULT = extern struct { AsyncResult: INTERNET_ASYNC_RESULT, Operation: HTTP_WEB_SOCKET_OPERATION, BufferType: HTTP_WEB_SOCKET_BUFFER_TYPE, dwBytesTransferred: u32, }; pub const HTTP_POLICY_EXTENSION_TYPE = enum(i32) { NONE = 0, WINHTTP = 1, WININET = 2, }; pub const POLICY_EXTENSION_TYPE_NONE = HTTP_POLICY_EXTENSION_TYPE.NONE; pub const POLICY_EXTENSION_TYPE_WINHTTP = HTTP_POLICY_EXTENSION_TYPE.WINHTTP; pub const POLICY_EXTENSION_TYPE_WININET = HTTP_POLICY_EXTENSION_TYPE.WININET; pub const HTTP_POLICY_EXTENSION_VERSION = enum(i32) { @"1" = 1, }; pub const POLICY_EXTENSION_VERSION1 = HTTP_POLICY_EXTENSION_VERSION.@"1"; pub const HTTP_POLICY_EXTENSION_INIT = fn( Version: HTTP_POLICY_EXTENSION_VERSION, Type: HTTP_POLICY_EXTENSION_TYPE, pvData: ?*anyopaque, cbData: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const HTTP_POLICY_EXTENSION_SHUTDOWN = fn( Type: HTTP_POLICY_EXTENSION_TYPE, ) callconv(@import("std").os.windows.WINAPI) u32; const CLSID_ProofOfPossessionCookieInfoManager_Value = Guid.initString("a9927f85-a304-4390-8b23-a75f1c668600"); pub const CLSID_ProofOfPossessionCookieInfoManager = &CLSID_ProofOfPossessionCookieInfoManager_Value; pub const ProofOfPossessionCookieInfo = extern struct { name: ?PWSTR, data: ?PWSTR, flags: u32, p3pHeader: ?PWSTR, }; const IID_IProofOfPossessionCookieInfoManager_Value = Guid.initString("cdaece56-4edf-43df-b113-88e4556fa1bb"); pub const IID_IProofOfPossessionCookieInfoManager = &IID_IProofOfPossessionCookieInfoManager_Value; pub const IProofOfPossessionCookieInfoManager = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCookieInfoForUri: fn( self: *const IProofOfPossessionCookieInfoManager, uri: ?[*:0]const u16, cookieInfoCount: ?*u32, cookieInfo: [*]?*ProofOfPossessionCookieInfo, ) 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 IProofOfPossessionCookieInfoManager_GetCookieInfoForUri(self: *const T, uri: ?[*:0]const u16, cookieInfoCount: ?*u32, cookieInfo: [*]?*ProofOfPossessionCookieInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IProofOfPossessionCookieInfoManager.VTable, self.vtable).GetCookieInfoForUri(@ptrCast(*const IProofOfPossessionCookieInfoManager, self), uri, cookieInfoCount, cookieInfo); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IProofOfPossessionCookieInfoManager2_Value = Guid.initString("15e41407-b42f-4ae7-9966-34a087b2d713"); pub const IID_IProofOfPossessionCookieInfoManager2 = &IID_IProofOfPossessionCookieInfoManager2_Value; pub const IProofOfPossessionCookieInfoManager2 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCookieInfoWithUriForAccount: fn( self: *const IProofOfPossessionCookieInfoManager2, webAccount: ?*IInspectable, uri: ?[*:0]const u16, cookieInfoCount: ?*u32, cookieInfo: [*]?*ProofOfPossessionCookieInfo, ) 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 IProofOfPossessionCookieInfoManager2_GetCookieInfoWithUriForAccount(self: *const T, webAccount: ?*IInspectable, uri: ?[*:0]const u16, cookieInfoCount: ?*u32, cookieInfo: [*]?*ProofOfPossessionCookieInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IProofOfPossessionCookieInfoManager2.VTable, self.vtable).GetCookieInfoWithUriForAccount(@ptrCast(*const IProofOfPossessionCookieInfoManager2, self), webAccount, uri, cookieInfoCount, cookieInfo); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (296) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetTimeFromSystemTimeA( pst: ?*const SYSTEMTIME, dwRFC: u32, // TODO: what to do with BytesParamIndex 3? lpszTime: ?PSTR, cbTime: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetTimeFromSystemTimeW( pst: ?*const SYSTEMTIME, dwRFC: u32, // TODO: what to do with BytesParamIndex 3? lpszTime: ?PWSTR, cbTime: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetTimeFromSystemTime( pst: ?*const SYSTEMTIME, dwRFC: u32, // TODO: what to do with BytesParamIndex 3? lpszTime: ?PSTR, cbTime: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetTimeToSystemTimeA( lpszTime: ?[*:0]const u8, pst: ?*SYSTEMTIME, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetTimeToSystemTimeW( lpszTime: ?[*:0]const u16, pst: ?*SYSTEMTIME, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetTimeToSystemTime( lpszTime: ?[*:0]const u8, pst: ?*SYSTEMTIME, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetCrackUrlA( lpszUrl: [*:0]const u8, dwUrlLength: u32, dwFlags: WIN_HTTP_CREATE_URL_FLAGS, lpUrlComponents: ?*URL_COMPONENTSA, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetCrackUrlW( lpszUrl: [*:0]const u16, dwUrlLength: u32, dwFlags: WIN_HTTP_CREATE_URL_FLAGS, lpUrlComponents: ?*URL_COMPONENTSW, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetCreateUrlA( lpUrlComponents: ?*URL_COMPONENTSA, dwFlags: u32, lpszUrl: ?[*:0]u8, lpdwUrlLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetCreateUrlW( lpUrlComponents: ?*URL_COMPONENTSW, dwFlags: u32, lpszUrl: ?[*:0]u16, lpdwUrlLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetCanonicalizeUrlA( lpszUrl: ?[*:0]const u8, lpszBuffer: [*:0]u8, lpdwBufferLength: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetCanonicalizeUrlW( lpszUrl: ?[*:0]const u16, lpszBuffer: [*:0]u16, lpdwBufferLength: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetCombineUrlA( lpszBaseUrl: ?[*:0]const u8, lpszRelativeUrl: ?[*:0]const u8, lpszBuffer: [*:0]u8, lpdwBufferLength: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetCombineUrlW( lpszBaseUrl: ?[*:0]const u16, lpszRelativeUrl: ?[*:0]const u16, lpszBuffer: [*:0]u16, lpdwBufferLength: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetOpenA( lpszAgent: ?[*:0]const u8, dwAccessType: u32, lpszProxy: ?[*:0]const u8, lpszProxyBypass: ?[*:0]const u8, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetOpenW( lpszAgent: ?[*:0]const u16, dwAccessType: u32, lpszProxy: ?[*:0]const u16, lpszProxyBypass: ?[*:0]const u16, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetCloseHandle( hInternet: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetConnectA( hInternet: ?*anyopaque, lpszServerName: ?[*:0]const u8, nServerPort: u16, lpszUserName: ?[*:0]const u8, lpszPassword: ?[*:0]const u8, dwService: u32, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetConnectW( hInternet: ?*anyopaque, lpszServerName: ?[*:0]const u16, nServerPort: u16, lpszUserName: ?[*:0]const u16, lpszPassword: ?[*:0]const u16, dwService: u32, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetOpenUrlA( hInternet: ?*anyopaque, lpszUrl: ?[*:0]const u8, lpszHeaders: ?[*:0]const u8, dwHeadersLength: u32, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetOpenUrlW( hInternet: ?*anyopaque, lpszUrl: ?[*:0]const u16, lpszHeaders: ?[*:0]const u16, dwHeadersLength: u32, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetReadFile( hFile: ?*anyopaque, // TODO: what to do with BytesParamIndex 2? lpBuffer: ?*anyopaque, dwNumberOfBytesToRead: u32, lpdwNumberOfBytesRead: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetReadFileExA( hFile: ?*anyopaque, lpBuffersOut: ?*INTERNET_BUFFERSA, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetReadFileExW( hFile: ?*anyopaque, lpBuffersOut: ?*INTERNET_BUFFERSW, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetSetFilePointer( hFile: ?*anyopaque, lDistanceToMove: i32, lpDistanceToMoveHigh: ?*i32, dwMoveMethod: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetWriteFile( hFile: ?*anyopaque, // TODO: what to do with BytesParamIndex 2? lpBuffer: ?*const anyopaque, dwNumberOfBytesToWrite: u32, lpdwNumberOfBytesWritten: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetQueryDataAvailable( hFile: ?*anyopaque, lpdwNumberOfBytesAvailable: ?*u32, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetFindNextFileA( hFind: ?*anyopaque, lpvFindData: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetFindNextFileW( hFind: ?*anyopaque, lpvFindData: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetQueryOptionA( hInternet: ?*anyopaque, dwOption: u32, // TODO: what to do with BytesParamIndex 3? lpBuffer: ?*anyopaque, lpdwBufferLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetQueryOptionW( hInternet: ?*anyopaque, dwOption: u32, // TODO: what to do with BytesParamIndex 3? lpBuffer: ?*anyopaque, lpdwBufferLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetSetOptionA( hInternet: ?*anyopaque, dwOption: u32, lpBuffer: ?*anyopaque, dwBufferLength: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetSetOptionW( hInternet: ?*anyopaque, dwOption: u32, lpBuffer: ?*anyopaque, dwBufferLength: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetSetOptionExA( hInternet: ?*anyopaque, dwOption: u32, lpBuffer: ?*anyopaque, dwBufferLength: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetSetOptionExW( hInternet: ?*anyopaque, dwOption: u32, lpBuffer: ?*anyopaque, dwBufferLength: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetLockRequestFile( hInternet: ?*anyopaque, lphLockRequestInfo: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetUnlockRequestFile( hLockRequestInfo: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetGetLastResponseInfoA( lpdwError: ?*u32, lpszBuffer: ?[*:0]u8, lpdwBufferLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetGetLastResponseInfoW( lpdwError: ?*u32, lpszBuffer: ?[*:0]u16, lpdwBufferLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetSetStatusCallbackA( hInternet: ?*anyopaque, lpfnInternetCallback: ?LPINTERNET_STATUS_CALLBACK, ) callconv(@import("std").os.windows.WINAPI) ?LPINTERNET_STATUS_CALLBACK; pub extern "WININET" fn InternetSetStatusCallbackW( hInternet: ?*anyopaque, lpfnInternetCallback: ?LPINTERNET_STATUS_CALLBACK, ) callconv(@import("std").os.windows.WINAPI) ?LPINTERNET_STATUS_CALLBACK; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetSetStatusCallback( hInternet: ?*anyopaque, lpfnInternetCallback: ?LPINTERNET_STATUS_CALLBACK, ) callconv(@import("std").os.windows.WINAPI) ?LPINTERNET_STATUS_CALLBACK; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpFindFirstFileA( hConnect: ?*anyopaque, lpszSearchFile: ?[*:0]const u8, lpFindFileData: ?*WIN32_FIND_DATAA, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpFindFirstFileW( hConnect: ?*anyopaque, lpszSearchFile: ?[*:0]const u16, lpFindFileData: ?*WIN32_FIND_DATAW, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpGetFileA( hConnect: ?*anyopaque, lpszRemoteFile: ?[*:0]const u8, lpszNewFile: ?[*:0]const u8, fFailIfExists: BOOL, dwFlagsAndAttributes: u32, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpGetFileW( hConnect: ?*anyopaque, lpszRemoteFile: ?[*:0]const u16, lpszNewFile: ?[*:0]const u16, fFailIfExists: BOOL, dwFlagsAndAttributes: u32, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpPutFileA( hConnect: ?*anyopaque, lpszLocalFile: ?[*:0]const u8, lpszNewRemoteFile: ?[*:0]const u8, dwFlags: FTP_FLAGS, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpPutFileW( hConnect: ?*anyopaque, lpszLocalFile: ?[*:0]const u16, lpszNewRemoteFile: ?[*:0]const u16, dwFlags: FTP_FLAGS, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn FtpGetFileEx( hFtpSession: ?*anyopaque, lpszRemoteFile: ?[*:0]const u8, lpszNewFile: ?[*:0]const u16, fFailIfExists: BOOL, dwFlagsAndAttributes: u32, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn FtpPutFileEx( hFtpSession: ?*anyopaque, lpszLocalFile: ?[*:0]const u16, lpszNewRemoteFile: ?[*:0]const u8, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpDeleteFileA( hConnect: ?*anyopaque, lpszFileName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpDeleteFileW( hConnect: ?*anyopaque, lpszFileName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpRenameFileA( hConnect: ?*anyopaque, lpszExisting: ?[*:0]const u8, lpszNew: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpRenameFileW( hConnect: ?*anyopaque, lpszExisting: ?[*:0]const u16, lpszNew: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpOpenFileA( hConnect: ?*anyopaque, lpszFileName: ?[*:0]const u8, dwAccess: u32, dwFlags: FTP_FLAGS, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpOpenFileW( hConnect: ?*anyopaque, lpszFileName: ?[*:0]const u16, dwAccess: u32, dwFlags: FTP_FLAGS, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpCreateDirectoryA( hConnect: ?*anyopaque, lpszDirectory: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpCreateDirectoryW( hConnect: ?*anyopaque, lpszDirectory: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpRemoveDirectoryA( hConnect: ?*anyopaque, lpszDirectory: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpRemoveDirectoryW( hConnect: ?*anyopaque, lpszDirectory: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpSetCurrentDirectoryA( hConnect: ?*anyopaque, lpszDirectory: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpSetCurrentDirectoryW( hConnect: ?*anyopaque, lpszDirectory: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpGetCurrentDirectoryA( hConnect: ?*anyopaque, lpszCurrentDirectory: [*:0]u8, lpdwCurrentDirectory: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpGetCurrentDirectoryW( hConnect: ?*anyopaque, lpszCurrentDirectory: [*:0]u16, lpdwCurrentDirectory: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpCommandA( hConnect: ?*anyopaque, fExpectResponse: BOOL, dwFlags: FTP_FLAGS, lpszCommand: ?[*:0]const u8, dwContext: usize, phFtpCommand: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpCommandW( hConnect: ?*anyopaque, fExpectResponse: BOOL, dwFlags: FTP_FLAGS, lpszCommand: ?[*:0]const u16, dwContext: usize, phFtpCommand: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FtpGetFileSize( hFile: ?*anyopaque, lpdwFileSizeHigh: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GopherCreateLocatorA( lpszHost: ?[*:0]const u8, nServerPort: u16, lpszDisplayString: ?[*:0]const u8, lpszSelectorString: ?[*:0]const u8, dwGopherType: u32, lpszLocator: ?[*:0]u8, lpdwBufferLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GopherCreateLocatorW( lpszHost: ?[*:0]const u16, nServerPort: u16, lpszDisplayString: ?[*:0]const u16, lpszSelectorString: ?[*:0]const u16, dwGopherType: u32, lpszLocator: ?[*:0]u16, lpdwBufferLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GopherGetLocatorTypeA( lpszLocator: ?[*:0]const u8, lpdwGopherType: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GopherGetLocatorTypeW( lpszLocator: ?[*:0]const u16, lpdwGopherType: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GopherFindFirstFileA( hConnect: ?*anyopaque, lpszLocator: ?[*:0]const u8, lpszSearchString: ?[*:0]const u8, lpFindData: ?*GOPHER_FIND_DATAA, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GopherFindFirstFileW( hConnect: ?*anyopaque, lpszLocator: ?[*:0]const u16, lpszSearchString: ?[*:0]const u16, lpFindData: ?*GOPHER_FIND_DATAW, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GopherOpenFileA( hConnect: ?*anyopaque, lpszLocator: ?[*:0]const u8, lpszView: ?[*:0]const u8, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GopherOpenFileW( hConnect: ?*anyopaque, lpszLocator: ?[*:0]const u16, lpszView: ?[*:0]const u16, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GopherGetAttributeA( hConnect: ?*anyopaque, lpszLocator: ?[*:0]const u8, lpszAttributeName: ?[*:0]const u8, lpBuffer: [*:0]u8, dwBufferLength: u32, lpdwCharactersReturned: ?*u32, lpfnEnumerator: ?GOPHER_ATTRIBUTE_ENUMERATOR, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GopherGetAttributeW( hConnect: ?*anyopaque, lpszLocator: ?[*:0]const u16, lpszAttributeName: ?[*:0]const u16, lpBuffer: [*:0]u8, dwBufferLength: u32, lpdwCharactersReturned: ?*u32, lpfnEnumerator: ?GOPHER_ATTRIBUTE_ENUMERATOR, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn HttpOpenRequestA( hConnect: ?*anyopaque, lpszVerb: ?[*:0]const u8, lpszObjectName: ?[*:0]const u8, lpszVersion: ?[*:0]const u8, lpszReferrer: ?[*:0]const u8, lplpszAcceptTypes: ?*?PSTR, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn HttpOpenRequestW( hConnect: ?*anyopaque, lpszVerb: ?[*:0]const u16, lpszObjectName: ?[*:0]const u16, lpszVersion: ?[*:0]const u16, lpszReferrer: ?[*:0]const u16, lplpszAcceptTypes: ?*?PWSTR, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn HttpAddRequestHeadersA( hRequest: ?*anyopaque, lpszHeaders: [*:0]const u8, dwHeadersLength: u32, dwModifiers: HTTP_ADDREQ_FLAG, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn HttpAddRequestHeadersW( hRequest: ?*anyopaque, lpszHeaders: [*:0]const u16, dwHeadersLength: u32, dwModifiers: HTTP_ADDREQ_FLAG, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn HttpSendRequestA( hRequest: ?*anyopaque, lpszHeaders: ?[*:0]const u8, dwHeadersLength: u32, // TODO: what to do with BytesParamIndex 4? lpOptional: ?*anyopaque, dwOptionalLength: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn HttpSendRequestW( hRequest: ?*anyopaque, lpszHeaders: ?[*:0]const u16, dwHeadersLength: u32, // TODO: what to do with BytesParamIndex 4? lpOptional: ?*anyopaque, dwOptionalLength: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn HttpSendRequestExA( hRequest: ?*anyopaque, lpBuffersIn: ?*INTERNET_BUFFERSA, lpBuffersOut: ?*INTERNET_BUFFERSA, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn HttpSendRequestExW( hRequest: ?*anyopaque, lpBuffersIn: ?*INTERNET_BUFFERSW, lpBuffersOut: ?*INTERNET_BUFFERSW, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn HttpEndRequestA( hRequest: ?*anyopaque, lpBuffersOut: ?*INTERNET_BUFFERSA, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn HttpEndRequestW( hRequest: ?*anyopaque, lpBuffersOut: ?*INTERNET_BUFFERSW, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn HttpQueryInfoA( hRequest: ?*anyopaque, dwInfoLevel: u32, // TODO: what to do with BytesParamIndex 3? lpBuffer: ?*anyopaque, lpdwBufferLength: ?*u32, lpdwIndex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn HttpQueryInfoW( hRequest: ?*anyopaque, dwInfoLevel: u32, // TODO: what to do with BytesParamIndex 3? lpBuffer: ?*anyopaque, lpdwBufferLength: ?*u32, lpdwIndex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetSetCookieA( lpszUrl: ?[*:0]const u8, lpszCookieName: ?[*:0]const u8, lpszCookieData: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetSetCookieW( lpszUrl: ?[*:0]const u16, lpszCookieName: ?[*:0]const u16, lpszCookieData: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetGetCookieA( lpszUrl: ?[*:0]const u8, lpszCookieName: ?[*:0]const u8, lpszCookieData: ?[*:0]u8, lpdwSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetGetCookieW( lpszUrl: ?[*:0]const u16, lpszCookieName: ?[*:0]const u16, lpszCookieData: ?[*:0]u16, lpdwSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WININET" fn InternetSetCookieExA( lpszUrl: ?[*:0]const u8, lpszCookieName: ?[*:0]const u8, lpszCookieData: ?[*:0]const u8, dwFlags: u32, dwReserved: usize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WININET" fn InternetSetCookieExW( lpszUrl: ?[*:0]const u16, lpszCookieName: ?[*:0]const u16, lpszCookieData: ?[*:0]const u16, dwFlags: u32, dwReserved: usize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WININET" fn InternetGetCookieExA( lpszUrl: ?[*:0]const u8, lpszCookieName: ?[*:0]const u8, lpszCookieData: ?[*:0]u8, lpdwSize: ?*u32, dwFlags: INTERNET_COOKIE_FLAGS, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WININET" fn InternetGetCookieExW( lpszUrl: ?[*:0]const u16, lpszCookieName: ?[*:0]const u16, lpszCookieData: ?[*:0]u16, lpdwSize: ?*u32, dwFlags: INTERNET_COOKIE_FLAGS, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetFreeCookies( pCookies: ?*INTERNET_COOKIE2, dwCookieCount: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "WININET" fn InternetGetCookieEx2( pcwszUrl: ?[*:0]const u16, pcwszCookieName: ?[*:0]const u16, dwFlags: u32, ppCookies: ?*?*INTERNET_COOKIE2, pdwCookieCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn InternetSetCookieEx2( pcwszUrl: ?[*:0]const u16, pCookie: ?*const INTERNET_COOKIE2, pcwszP3PPolicy: ?[*:0]const u16, dwFlags: u32, pdwCookieState: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetAttemptConnect( dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetCheckConnectionA( lpszUrl: ?[*:0]const u8, dwFlags: u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetCheckConnectionW( lpszUrl: ?[*:0]const u16, dwFlags: u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn ResumeSuspendedDownload( hRequest: ?*anyopaque, dwResultCode: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetErrorDlg( hWnd: ?HWND, hRequest: ?*anyopaque, dwError: u32, dwFlags: u32, lppvData: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetConfirmZoneCrossingA( hWnd: ?HWND, szUrlPrev: ?PSTR, szUrlNew: ?PSTR, bPost: BOOL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetConfirmZoneCrossingW( hWnd: ?HWND, szUrlPrev: ?PWSTR, szUrlNew: ?PWSTR, bPost: BOOL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetConfirmZoneCrossing( hWnd: ?HWND, szUrlPrev: ?PSTR, szUrlNew: ?PSTR, bPost: BOOL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn CreateUrlCacheEntryA( lpszUrlName: ?[*:0]const u8, dwExpectedFileSize: u32, lpszFileExtension: ?[*:0]const u8, lpszFileName: *[260]u8, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn CreateUrlCacheEntryW( lpszUrlName: ?[*:0]const u16, dwExpectedFileSize: u32, lpszFileExtension: ?[*:0]const u16, lpszFileName: *[260]u16, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn CommitUrlCacheEntryA( lpszUrlName: ?[*:0]const u8, lpszLocalFileName: ?[*:0]const u8, ExpireTime: FILETIME, LastModifiedTime: FILETIME, CacheEntryType: u32, lpHeaderInfo: ?[*:0]u8, cchHeaderInfo: u32, lpszFileExtension: ?[*:0]const u8, lpszOriginalUrl: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn CommitUrlCacheEntryW( lpszUrlName: ?[*:0]const u16, lpszLocalFileName: ?[*:0]const u16, ExpireTime: FILETIME, LastModifiedTime: FILETIME, CacheEntryType: u32, lpszHeaderInfo: ?[*:0]u16, cchHeaderInfo: u32, lpszFileExtension: ?[*:0]const u16, lpszOriginalUrl: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn RetrieveUrlCacheEntryFileA( lpszUrlName: ?[*:0]const u8, // TODO: what to do with BytesParamIndex 2? lpCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOA, lpcbCacheEntryInfo: ?*u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn RetrieveUrlCacheEntryFileW( lpszUrlName: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 2? lpCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOW, lpcbCacheEntryInfo: ?*u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn UnlockUrlCacheEntryFileA( lpszUrlName: ?[*:0]const u8, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn UnlockUrlCacheEntryFileW( lpszUrlName: ?[*:0]const u16, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn UnlockUrlCacheEntryFile( lpszUrlName: ?[*:0]const u8, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn RetrieveUrlCacheEntryStreamA( lpszUrlName: ?[*:0]const u8, // TODO: what to do with BytesParamIndex 2? lpCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOA, lpcbCacheEntryInfo: ?*u32, fRandomRead: BOOL, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn RetrieveUrlCacheEntryStreamW( lpszUrlName: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 2? lpCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOW, lpcbCacheEntryInfo: ?*u32, fRandomRead: BOOL, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn ReadUrlCacheEntryStream( hUrlCacheStream: ?HANDLE, dwLocation: u32, // TODO: what to do with BytesParamIndex 3? lpBuffer: ?*anyopaque, lpdwLen: ?*u32, Reserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn ReadUrlCacheEntryStreamEx( hUrlCacheStream: ?HANDLE, qwLocation: u64, // TODO: what to do with BytesParamIndex 3? lpBuffer: ?*anyopaque, lpdwLen: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn UnlockUrlCacheEntryStream( hUrlCacheStream: ?HANDLE, Reserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GetUrlCacheEntryInfoA( lpszUrlName: ?[*:0]const u8, // TODO: what to do with BytesParamIndex 2? lpCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOA, lpcbCacheEntryInfo: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GetUrlCacheEntryInfoW( lpszUrlName: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 2? lpCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOW, lpcbCacheEntryInfo: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FindFirstUrlCacheGroup( dwFlags: u32, dwFilter: u32, lpSearchCondition: ?*anyopaque, dwSearchCondition: u32, lpGroupId: ?*i64, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FindNextUrlCacheGroup( hFind: ?HANDLE, lpGroupId: ?*i64, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GetUrlCacheGroupAttributeA( gid: i64, dwFlags: u32, dwAttributes: u32, // TODO: what to do with BytesParamIndex 4? lpGroupInfo: ?*INTERNET_CACHE_GROUP_INFOA, lpcbGroupInfo: ?*u32, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GetUrlCacheGroupAttributeW( gid: i64, dwFlags: u32, dwAttributes: u32, // TODO: what to do with BytesParamIndex 4? lpGroupInfo: ?*INTERNET_CACHE_GROUP_INFOW, lpcbGroupInfo: ?*u32, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn SetUrlCacheGroupAttributeA( gid: i64, dwFlags: u32, dwAttributes: u32, lpGroupInfo: ?*INTERNET_CACHE_GROUP_INFOA, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn SetUrlCacheGroupAttributeW( gid: i64, dwFlags: u32, dwAttributes: u32, lpGroupInfo: ?*INTERNET_CACHE_GROUP_INFOW, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GetUrlCacheEntryInfoExA( lpszUrl: ?[*:0]const u8, // TODO: what to do with BytesParamIndex 2? lpCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOA, lpcbCacheEntryInfo: ?*u32, lpszRedirectUrl: ?PSTR, lpcbRedirectUrl: ?*u32, lpReserved: ?*anyopaque, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn GetUrlCacheEntryInfoExW( lpszUrl: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 2? lpCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOW, lpcbCacheEntryInfo: ?*u32, lpszRedirectUrl: ?PWSTR, lpcbRedirectUrl: ?*u32, lpReserved: ?*anyopaque, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn SetUrlCacheEntryInfoA( lpszUrlName: ?[*:0]const u8, lpCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOA, dwFieldControl: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn SetUrlCacheEntryInfoW( lpszUrlName: ?[*:0]const u16, lpCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOW, dwFieldControl: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn CreateUrlCacheGroup( dwFlags: u32, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i64; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn DeleteUrlCacheGroup( GroupId: i64, dwFlags: u32, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn SetUrlCacheEntryGroupA( lpszUrlName: ?[*:0]const u8, dwFlags: u32, GroupId: i64, pbGroupAttributes: ?*u8, cbGroupAttributes: u32, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn SetUrlCacheEntryGroupW( lpszUrlName: ?[*:0]const u16, dwFlags: u32, GroupId: i64, pbGroupAttributes: ?*u8, cbGroupAttributes: u32, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn SetUrlCacheEntryGroup( lpszUrlName: ?[*:0]const u8, dwFlags: u32, GroupId: i64, pbGroupAttributes: ?*u8, cbGroupAttributes: u32, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FindFirstUrlCacheEntryExA( lpszUrlSearchPattern: ?[*:0]const u8, dwFlags: u32, dwFilter: u32, GroupId: i64, // TODO: what to do with BytesParamIndex 5? lpFirstCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOA, lpcbCacheEntryInfo: ?*u32, lpGroupAttributes: ?*anyopaque, lpcbGroupAttributes: ?*u32, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FindFirstUrlCacheEntryExW( lpszUrlSearchPattern: ?[*:0]const u16, dwFlags: u32, dwFilter: u32, GroupId: i64, // TODO: what to do with BytesParamIndex 5? lpFirstCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOW, lpcbCacheEntryInfo: ?*u32, lpGroupAttributes: ?*anyopaque, lpcbGroupAttributes: ?*u32, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FindNextUrlCacheEntryExA( hEnumHandle: ?HANDLE, // TODO: what to do with BytesParamIndex 2? lpNextCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOA, lpcbCacheEntryInfo: ?*u32, lpGroupAttributes: ?*anyopaque, lpcbGroupAttributes: ?*u32, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FindNextUrlCacheEntryExW( hEnumHandle: ?HANDLE, // TODO: what to do with BytesParamIndex 2? lpNextCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOW, lpcbCacheEntryInfo: ?*u32, lpGroupAttributes: ?*anyopaque, lpcbGroupAttributes: ?*u32, lpReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FindFirstUrlCacheEntryA( lpszUrlSearchPattern: ?[*:0]const u8, // TODO: what to do with BytesParamIndex 2? lpFirstCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOA, lpcbCacheEntryInfo: ?*u32, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FindFirstUrlCacheEntryW( lpszUrlSearchPattern: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 2? lpFirstCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOW, lpcbCacheEntryInfo: ?*u32, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FindNextUrlCacheEntryA( hEnumHandle: ?HANDLE, // TODO: what to do with BytesParamIndex 2? lpNextCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOA, lpcbCacheEntryInfo: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FindNextUrlCacheEntryW( hEnumHandle: ?HANDLE, // TODO: what to do with BytesParamIndex 2? lpNextCacheEntryInfo: ?*INTERNET_CACHE_ENTRY_INFOW, lpcbCacheEntryInfo: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FindCloseUrlCache( hEnumHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn DeleteUrlCacheEntryA( lpszUrlName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn DeleteUrlCacheEntryW( lpszUrlName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn DeleteUrlCacheEntry( lpszUrlName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetDialA( hwndParent: ?HWND, lpszConnectoid: ?PSTR, dwFlags: u32, lpdwConnection: ?*usize, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetDialW( hwndParent: ?HWND, lpszConnectoid: ?PWSTR, dwFlags: u32, lpdwConnection: ?*usize, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetDial( hwndParent: ?HWND, lpszConnectoid: ?PSTR, dwFlags: u32, lpdwConnection: ?*u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetHangUp( dwConnection: usize, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetGoOnlineA( lpszURL: ?[*:0]const u8, hwndParent: ?HWND, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetGoOnlineW( lpszURL: ?[*:0]const u16, hwndParent: ?HWND, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetGoOnline( lpszURL: ?PSTR, hwndParent: ?HWND, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetAutodial( dwFlags: INTERNET_AUTODIAL, hwndParent: ?HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetAutodialHangup( dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetGetConnectedState( lpdwFlags: ?*INTERNET_CONNECTION, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetGetConnectedStateExA( lpdwFlags: ?*INTERNET_CONNECTION, lpszConnectionName: ?[*:0]u8, cchNameLen: u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetGetConnectedStateExW( lpdwFlags: ?*INTERNET_CONNECTION, lpszConnectionName: ?[*:0]u16, cchNameLen: u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn DeleteWpadCacheForNetworks( param0: WPAD_CACHE_DELETE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetInitializeAutoProxyDll( dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn DetectAutoProxyUrl( pszAutoProxyUrl: [*:0]u8, cchAutoProxyUrl: u32, dwDetectFlags: PROXY_AUTO_DETECT_TYPE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn CreateMD5SSOHash( pszChallengeInfo: ?PWSTR, pwszRealm: ?PWSTR, pwszTarget: ?PWSTR, pbHexHash: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetGetConnectedStateEx( lpdwFlags: ?*INTERNET_CONNECTION, lpszConnectionName: ?[*:0]u8, dwNameLen: u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetSetDialStateA( lpszConnectoid: ?[*:0]const u8, dwState: u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetSetDialStateW( lpszConnectoid: ?[*:0]const u16, dwState: u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetSetDialState( lpszConnectoid: ?[*:0]const u8, dwState: u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetSetPerSiteCookieDecisionA( pchHostName: ?[*:0]const u8, dwDecision: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetSetPerSiteCookieDecisionW( pchHostName: ?[*:0]const u16, dwDecision: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetGetPerSiteCookieDecisionA( pchHostName: ?[*:0]const u8, pResult: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetGetPerSiteCookieDecisionW( pchHostName: ?[*:0]const u16, pResult: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetClearAllPerSiteCookieDecisions( ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetEnumPerSiteCookieDecisionA( pszSiteName: [*:0]u8, pcSiteNameSize: ?*u32, pdwDecision: ?*u32, dwIndex: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn InternetEnumPerSiteCookieDecisionW( pszSiteName: [*:0]u16, pcSiteNameSize: ?*u32, pdwDecision: ?*u32, dwIndex: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn PrivacySetZonePreferenceW( dwZone: u32, dwType: u32, dwTemplate: u32, pszPreference: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn PrivacyGetZonePreferenceW( dwZone: u32, dwType: u32, pdwTemplate: ?*u32, pszBuffer: ?[*:0]u16, pdwBufferLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn HttpIsHostHstsEnabled( pcwszUrl: ?[*:0]const u16, pfIsHsts: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn InternetAlgIdToStringA( ai: u32, lpstr: [*:0]u8, lpdwstrLength: ?*u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetAlgIdToStringW( ai: u32, lpstr: [*:0]u16, lpdwstrLength: ?*u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetSecurityProtocolToStringA( dwProtocol: u32, lpstr: ?[*:0]u8, lpdwstrLength: ?*u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetSecurityProtocolToStringW( dwProtocol: u32, lpstr: ?[*:0]u16, lpdwstrLength: ?*u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetGetSecurityInfoByURLA( lpszURL: ?PSTR, ppCertChain: ?*?*CERT_CHAIN_CONTEXT, pdwSecureFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetGetSecurityInfoByURLW( lpszURL: ?[*:0]const u16, ppCertChain: ?*?*CERT_CHAIN_CONTEXT, pdwSecureFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetGetSecurityInfoByURL( lpszURL: ?PSTR, ppCertChain: ?*?*CERT_CHAIN_CONTEXT, pdwSecureFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn ShowSecurityInfo( hWndParent: ?HWND, pSecurityInfo: ?*INTERNET_SECURITY_INFO, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn ShowX509EncodedCertificate( hWndParent: ?HWND, // TODO: what to do with BytesParamIndex 2? lpCert: ?*u8, cbCert: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn ShowClientAuthCerts( hWndParent: ?HWND, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn ParseX509EncodedCertificateForListBoxEntry( // TODO: what to do with BytesParamIndex 1? lpCert: ?*u8, cbCert: u32, lpszListBoxEntry: ?[*:0]u8, lpdwListBoxEntry: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn InternetShowSecurityInfoByURLA( lpszURL: ?PSTR, hwndParent: ?HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetShowSecurityInfoByURLW( lpszURL: ?[*:0]const u16, hwndParent: ?HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetShowSecurityInfoByURL( lpszURL: ?PSTR, hwndParent: ?HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetFortezzaCommand( dwCommand: u32, hwnd: ?HWND, dwReserved: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetQueryFortezzaStatus( pdwStatus: ?*u32, dwReserved: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetWriteFileExA( hFile: ?*anyopaque, lpBuffersIn: ?*INTERNET_BUFFERSA, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetWriteFileExW( hFile: ?*anyopaque, lpBuffersIn: ?*INTERNET_BUFFERSW, dwFlags: u32, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn FindP3PPolicySymbol( pszSymbol: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "WININET" fn HttpGetServerCredentials( pwszUrl: ?PWSTR, ppwszUserName: ?*?PWSTR, ppwszPassword: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn HttpPushEnable( hRequest: ?*anyopaque, pTransportSetting: ?*HTTP_PUSH_TRANSPORT_SETTING, phWait: ?*HTTP_PUSH_WAIT_HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn HttpPushWait( hWait: HTTP_PUSH_WAIT_HANDLE, eType: HTTP_PUSH_WAIT_TYPE, pNotificationStatus: ?*HTTP_PUSH_NOTIFICATION_STATUS, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn HttpPushClose( hWait: HTTP_PUSH_WAIT_HANDLE, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "WININET" fn HttpCheckDavComplianceA( lpszUrl: ?[*:0]const u8, lpszComplianceToken: ?[*:0]const u8, lpfFound: ?*i32, hWnd: ?HWND, lpvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn HttpCheckDavComplianceW( lpszUrl: ?[*:0]const u16, lpszComplianceToken: ?[*:0]const u16, lpfFound: ?*i32, hWnd: ?HWND, lpvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn IsUrlCacheEntryExpiredA( lpszUrlName: ?[*:0]const u8, dwFlags: u32, pftLastModified: ?*FILETIME, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn IsUrlCacheEntryExpiredW( lpszUrlName: ?[*:0]const u16, dwFlags: u32, pftLastModified: ?*FILETIME, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn CreateUrlCacheEntryExW( lpszUrlName: ?[*:0]const u16, dwExpectedFileSize: u32, lpszFileExtension: ?[*:0]const u16, lpszFileName: *[260]u16, dwReserved: u32, fPreserveIncomingFileName: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn GetUrlCacheEntryBinaryBlob( pwszUrlName: ?[*:0]const u16, dwType: ?*u32, pftExpireTime: ?*FILETIME, pftAccessTime: ?*FILETIME, pftModifiedTime: ?*FILETIME, ppbBlob: ?[*]?*u8, pcbBlob: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn CommitUrlCacheEntryBinaryBlob( pwszUrlName: ?[*:0]const u16, dwType: u32, ftExpireTime: FILETIME, ftModifiedTime: FILETIME, pbBlob: ?[*:0]const u8, cbBlob: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn CreateUrlCacheContainerA( Name: ?[*:0]const u8, lpCachePrefix: ?[*:0]const u8, lpszCachePath: ?[*:0]const u8, KBCacheLimit: u32, dwContainerType: u32, dwOptions: u32, pvBuffer: ?*anyopaque, cbBuffer: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn CreateUrlCacheContainerW( Name: ?[*:0]const u16, lpCachePrefix: ?[*:0]const u16, lpszCachePath: ?[*:0]const u16, KBCacheLimit: u32, dwContainerType: u32, dwOptions: u32, pvBuffer: ?*anyopaque, cbBuffer: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn DeleteUrlCacheContainerA( Name: ?[*:0]const u8, dwOptions: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn DeleteUrlCacheContainerW( Name: ?[*:0]const u16, dwOptions: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn FindFirstUrlCacheContainerA( pdwModified: ?*u32, // TODO: what to do with BytesParamIndex 2? lpContainerInfo: ?*INTERNET_CACHE_CONTAINER_INFOA, lpcbContainerInfo: ?*u32, dwOptions: u32, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub extern "WININET" fn FindFirstUrlCacheContainerW( pdwModified: ?*u32, // TODO: what to do with BytesParamIndex 2? lpContainerInfo: ?*INTERNET_CACHE_CONTAINER_INFOW, lpcbContainerInfo: ?*u32, dwOptions: u32, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub extern "WININET" fn FindNextUrlCacheContainerA( hEnumHandle: ?HANDLE, // TODO: what to do with BytesParamIndex 2? lpContainerInfo: ?*INTERNET_CACHE_CONTAINER_INFOA, lpcbContainerInfo: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn FindNextUrlCacheContainerW( hEnumHandle: ?HANDLE, // TODO: what to do with BytesParamIndex 2? lpContainerInfo: ?*INTERNET_CACHE_CONTAINER_INFOW, lpcbContainerInfo: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FreeUrlCacheSpaceA( lpszCachePath: ?[*:0]const u8, dwSize: u32, dwFilter: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "WININET" fn FreeUrlCacheSpaceW( lpszCachePath: ?[*:0]const u16, dwSize: u32, dwFilter: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn UrlCacheFreeGlobalSpace( ullTargetSize: u64, dwFilter: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheGetGlobalCacheSize( dwFilter: u32, pullSize: ?*u64, pullLimit: ?*u64, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WININET" fn GetUrlCacheConfigInfoA( lpCacheConfigInfo: ?*INTERNET_CACHE_CONFIG_INFOA, lpcbCacheConfigInfo: ?*u32, dwFieldControl: CACHE_CONFIG, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WININET" fn GetUrlCacheConfigInfoW( lpCacheConfigInfo: ?*INTERNET_CACHE_CONFIG_INFOW, lpcbCacheConfigInfo: ?*u32, dwFieldControl: CACHE_CONFIG, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn SetUrlCacheConfigInfoA( lpCacheConfigInfo: ?*INTERNET_CACHE_CONFIG_INFOA, dwFieldControl: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn SetUrlCacheConfigInfoW( lpCacheConfigInfo: ?*INTERNET_CACHE_CONFIG_INFOW, dwFieldControl: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn RunOnceUrlCache( hwnd: ?HWND, hinst: ?HINSTANCE, lpszCmd: ?PSTR, nCmdShow: i32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn DeleteIE3Cache( hwnd: ?HWND, hinst: ?HINSTANCE, lpszCmd: ?PSTR, nCmdShow: i32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UpdateUrlCacheContentPath( szNewPath: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn RegisterUrlCacheNotification( hWnd: ?HWND, uMsg: u32, gid: i64, dwOpsFilter: u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn GetUrlCacheHeaderData( nIdx: u32, lpdwData: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn SetUrlCacheHeaderData( nIdx: u32, dwData: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn IncrementUrlCacheHeaderData( nIdx: u32, lpdwData: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn LoadUrlCacheContent( ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn AppCacheLookup( pwszUrl: ?[*:0]const u16, dwFlags: u32, phAppCache: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn AppCacheCheckManifest( pwszMasterUrl: ?[*:0]const u16, pwszManifestUrl: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 3? pbManifestData: ?*const u8, dwManifestDataSize: u32, // TODO: what to do with BytesParamIndex 5? pbManifestResponseHeaders: ?*const u8, dwManifestResponseHeadersSize: u32, peState: ?*APP_CACHE_STATE, phNewAppCache: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn AppCacheGetDownloadList( hAppCache: ?*anyopaque, pDownloadList: ?*APP_CACHE_DOWNLOAD_LIST, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn AppCacheFreeDownloadList( pDownloadList: ?*APP_CACHE_DOWNLOAD_LIST, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "WININET" fn AppCacheFinalize( hAppCache: ?*anyopaque, // TODO: what to do with BytesParamIndex 2? pbManifestData: ?*const u8, dwManifestDataSize: u32, peState: ?*APP_CACHE_FINALIZE_STATE, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn AppCacheGetFallbackUrl( hAppCache: ?*anyopaque, pwszUrl: ?[*:0]const u16, ppwszFallbackUrl: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn AppCacheGetManifestUrl( hAppCache: ?*anyopaque, ppwszManifestUrl: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn AppCacheDuplicateHandle( hAppCache: ?*anyopaque, phDuplicatedAppCache: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn AppCacheCloseHandle( hAppCache: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "WININET" fn AppCacheFreeGroupList( pAppCacheGroupList: ?*APP_CACHE_GROUP_LIST, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "WININET" fn AppCacheGetGroupList( pAppCacheGroupList: ?*APP_CACHE_GROUP_LIST, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn AppCacheGetInfo( hAppCache: ?*anyopaque, pAppCacheInfo: ?*APP_CACHE_GROUP_INFO, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn AppCacheDeleteGroup( pwszManifestUrl: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn AppCacheFreeSpace( ftCutOff: FILETIME, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn AppCacheGetIEGroupList( pAppCacheGroupList: ?*APP_CACHE_GROUP_LIST, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn AppCacheDeleteIEGroup( pwszManifestUrl: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn AppCacheFreeIESpace( ftCutOff: FILETIME, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn AppCacheCreateAndCommitFile( hAppCache: ?*anyopaque, pwszSourceFilePath: ?[*:0]const u16, pwszUrl: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 4? pbResponseHeaders: ?*const u8, dwResponseHeadersSize: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn HttpOpenDependencyHandle( hRequestHandle: ?*anyopaque, fBackground: BOOL, phDependencyHandle: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn HttpCloseDependencyHandle( hDependencyHandle: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "WININET" fn HttpDuplicateDependencyHandle( hDependencyHandle: ?*anyopaque, phDuplicatedDependencyHandle: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn HttpIndicatePageLoadComplete( hDependencyHandle: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheFreeEntryInfo( pCacheEntryInfo: ?*URLCACHE_ENTRY_INFO, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "WININET" fn UrlCacheGetEntryInfo( hAppCache: ?*anyopaque, pcwszUrl: ?[*:0]const u16, pCacheEntryInfo: ?*URLCACHE_ENTRY_INFO, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheCloseEntryHandle( hEntryFile: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "WININET" fn UrlCacheRetrieveEntryFile( hAppCache: ?*anyopaque, pcwszUrl: ?[*:0]const u16, pCacheEntryInfo: ?*URLCACHE_ENTRY_INFO, phEntryFile: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheReadEntryStream( hUrlCacheStream: ?*anyopaque, ullLocation: u64, pBuffer: ?*anyopaque, dwBufferLen: u32, pdwBufferLen: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheRetrieveEntryStream( hAppCache: ?*anyopaque, pcwszUrl: ?[*:0]const u16, fRandomRead: BOOL, pCacheEntryInfo: ?*URLCACHE_ENTRY_INFO, phEntryStream: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheUpdateEntryExtraData( hAppCache: ?*anyopaque, pcwszUrl: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 3? pbExtraData: ?*const u8, cbExtraData: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheCreateContainer( pwszName: ?[*:0]const u16, pwszPrefix: ?[*:0]const u16, pwszDirectory: ?[*:0]const u16, ullLimit: u64, dwOptions: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheCheckEntriesExist( rgpwszUrls: [*]?PWSTR, cEntries: u32, rgfExist: [*]BOOL, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheGetContentPaths( pppwszDirectories: ?*?*?PWSTR, pcDirectories: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheGetGlobalLimit( limitType: URL_CACHE_LIMIT_TYPE, pullLimit: ?*u64, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheSetGlobalLimit( limitType: URL_CACHE_LIMIT_TYPE, ullLimit: u64, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheReloadSettings( ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheContainerSetEntryMaximumAge( pwszPrefix: ?[*:0]const u16, dwEntryMaxAge: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheFindFirstEntry( pwszPrefix: ?[*:0]const u16, dwFlags: u32, dwFilter: u32, GroupId: i64, pCacheEntryInfo: ?*URLCACHE_ENTRY_INFO, phFind: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheFindNextEntry( hFind: ?HANDLE, pCacheEntryInfo: ?*URLCACHE_ENTRY_INFO, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn UrlCacheServer( ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn ReadGuidsForConnectedNetworks( pcNetworks: ?*u32, pppwszNetworkGuids: ?*?*?PWSTR, pppbstrNetworkNames: ?*?*?BSTR, pppwszGWMacs: ?*?*?PWSTR, pcGatewayMacs: ?*u32, pdwFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn IsHostInProxyBypassList( tScheme: INTERNET_SCHEME, lpszHost: [*:0]const u8, cchHost: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetFreeProxyInfoList( pProxyInfoList: ?*WININET_PROXY_INFO_LIST, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "WININET" fn InternetGetProxyForUrl( hInternet: ?*anyopaque, pcwszUrl: ?[*:0]const u16, pProxyInfoList: ?*WININET_PROXY_INFO_LIST, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn DoConnectoidsExist( ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn GetDiskInfoA( pszPath: ?[*:0]const u8, pdwClusterSize: ?*u32, pdlAvail: ?*u64, pdlTotal: ?*u64, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn PerformOperationOverUrlCacheA( pszUrlSearchPattern: ?[*:0]const u8, dwFlags: u32, dwFilter: u32, GroupId: i64, pReserved1: ?*anyopaque, pdwReserved2: ?*u32, pReserved3: ?*anyopaque, op: ?CACHE_OPERATOR, pOperatorData: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn IsProfilesEnabled( ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternalInternetGetCookie( lpszUrl: ?[*:0]const u8, lpszCookieData: [*:0]u8, lpdwDataSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WININET" fn ImportCookieFileA( szFilename: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn ImportCookieFileW( szFilename: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn ExportCookieFileA( szFilename: ?[*:0]const u8, fAppend: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn ExportCookieFileW( szFilename: ?[*:0]const u16, fAppend: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn IsDomainLegalCookieDomainA( pchDomain: ?[*:0]const u8, pchFullDomain: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn IsDomainLegalCookieDomainW( pchDomain: ?[*:0]const u16, pchFullDomain: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn HttpWebSocketCompleteUpgrade( hRequest: ?*anyopaque, dwContext: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "WININET" fn HttpWebSocketSend( hWebSocket: ?*anyopaque, BufferType: HTTP_WEB_SOCKET_BUFFER_TYPE, // TODO: what to do with BytesParamIndex 3? pvBuffer: ?*anyopaque, dwBufferLength: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn HttpWebSocketReceive( hWebSocket: ?*anyopaque, // TODO: what to do with BytesParamIndex 2? pvBuffer: ?*anyopaque, dwBufferLength: u32, pdwBytesRead: ?*u32, pBufferType: ?*HTTP_WEB_SOCKET_BUFFER_TYPE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn HttpWebSocketClose( hWebSocket: ?*anyopaque, usStatus: u16, // TODO: what to do with BytesParamIndex 3? pvReason: ?*anyopaque, dwReasonLength: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn HttpWebSocketShutdown( hWebSocket: ?*anyopaque, usStatus: u16, // TODO: what to do with BytesParamIndex 3? pvReason: ?*anyopaque, dwReasonLength: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn HttpWebSocketQueryCloseStatus( hWebSocket: ?*anyopaque, pusStatus: ?*u16, // TODO: what to do with BytesParamIndex 3? pvReason: ?*anyopaque, dwReasonLength: u32, pdwReasonLengthConsumed: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WININET" fn InternetConvertUrlFromWireToWideChar( pcszUrl: [*:0]const u8, cchUrl: u32, pcwszBaseUrl: ?[*:0]const u16, dwCodePageHost: u32, dwCodePagePath: u32, fEncodePathExtra: BOOL, dwCodePageExtra: u32, ppwszConvertedUrl: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (81) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const INTERNET_PER_CONN_OPTION = thismodule.INTERNET_PER_CONN_OPTIONA; pub const INTERNET_PER_CONN_OPTION_LIST = thismodule.INTERNET_PER_CONN_OPTION_LISTA; pub const URL_COMPONENTS = thismodule.URL_COMPONENTSA; pub const INTERNET_BUFFERS = thismodule.INTERNET_BUFFERSA; pub const GOPHER_FIND_DATA = thismodule.GOPHER_FIND_DATAA; pub const INTERNET_CACHE_ENTRY_INFO = thismodule.INTERNET_CACHE_ENTRY_INFOA; pub const INTERNET_CACHE_GROUP_INFO = thismodule.INTERNET_CACHE_GROUP_INFOA; pub const INTERNET_CACHE_CONFIG_PATH_ENTRY = thismodule.INTERNET_CACHE_CONFIG_PATH_ENTRYA; pub const INTERNET_CACHE_CONFIG_INFO = thismodule.INTERNET_CACHE_CONFIG_INFOA; pub const INTERNET_CACHE_CONTAINER_INFO = thismodule.INTERNET_CACHE_CONTAINER_INFOA; pub const InternetCrackUrl = thismodule.InternetCrackUrlA; pub const InternetCreateUrl = thismodule.InternetCreateUrlA; pub const InternetCanonicalizeUrl = thismodule.InternetCanonicalizeUrlA; pub const InternetCombineUrl = thismodule.InternetCombineUrlA; pub const InternetOpen = thismodule.InternetOpenA; pub const InternetConnect = thismodule.InternetConnectA; pub const InternetOpenUrl = thismodule.InternetOpenUrlA; pub const InternetReadFileEx = thismodule.InternetReadFileExA; pub const InternetFindNextFile = thismodule.InternetFindNextFileA; pub const InternetQueryOption = thismodule.InternetQueryOptionA; pub const InternetSetOption = thismodule.InternetSetOptionA; pub const InternetSetOptionEx = thismodule.InternetSetOptionExA; pub const InternetGetLastResponseInfo = thismodule.InternetGetLastResponseInfoA; pub const FtpFindFirstFile = thismodule.FtpFindFirstFileA; pub const FtpGetFile = thismodule.FtpGetFileA; pub const FtpPutFile = thismodule.FtpPutFileA; pub const FtpDeleteFile = thismodule.FtpDeleteFileA; pub const FtpRenameFile = thismodule.FtpRenameFileA; pub const FtpOpenFile = thismodule.FtpOpenFileA; pub const FtpCreateDirectory = thismodule.FtpCreateDirectoryA; pub const FtpRemoveDirectory = thismodule.FtpRemoveDirectoryA; pub const FtpSetCurrentDirectory = thismodule.FtpSetCurrentDirectoryA; pub const FtpGetCurrentDirectory = thismodule.FtpGetCurrentDirectoryA; pub const FtpCommand = thismodule.FtpCommandA; pub const GopherCreateLocator = thismodule.GopherCreateLocatorA; pub const GopherGetLocatorType = thismodule.GopherGetLocatorTypeA; pub const GopherFindFirstFile = thismodule.GopherFindFirstFileA; pub const GopherOpenFile = thismodule.GopherOpenFileA; pub const GopherGetAttribute = thismodule.GopherGetAttributeA; pub const HttpOpenRequest = thismodule.HttpOpenRequestA; pub const HttpAddRequestHeaders = thismodule.HttpAddRequestHeadersA; pub const HttpSendRequest = thismodule.HttpSendRequestA; pub const HttpSendRequestEx = thismodule.HttpSendRequestExA; pub const HttpEndRequest = thismodule.HttpEndRequestA; pub const HttpQueryInfo = thismodule.HttpQueryInfoA; pub const InternetSetCookie = thismodule.InternetSetCookieA; pub const InternetGetCookie = thismodule.InternetGetCookieA; pub const InternetSetCookieEx = thismodule.InternetSetCookieExA; pub const InternetGetCookieEx = thismodule.InternetGetCookieExA; pub const InternetCheckConnection = thismodule.InternetCheckConnectionA; pub const CreateUrlCacheEntry = thismodule.CreateUrlCacheEntryA; pub const CommitUrlCacheEntry = thismodule.CommitUrlCacheEntryA; pub const RetrieveUrlCacheEntryFile = thismodule.RetrieveUrlCacheEntryFileA; pub const RetrieveUrlCacheEntryStream = thismodule.RetrieveUrlCacheEntryStreamA; pub const GetUrlCacheEntryInfo = thismodule.GetUrlCacheEntryInfoA; pub const GetUrlCacheGroupAttribute = thismodule.GetUrlCacheGroupAttributeA; pub const SetUrlCacheGroupAttribute = thismodule.SetUrlCacheGroupAttributeA; pub const GetUrlCacheEntryInfoEx = thismodule.GetUrlCacheEntryInfoExA; pub const SetUrlCacheEntryInfo = thismodule.SetUrlCacheEntryInfoA; pub const FindFirstUrlCacheEntryEx = thismodule.FindFirstUrlCacheEntryExA; pub const FindNextUrlCacheEntryEx = thismodule.FindNextUrlCacheEntryExA; pub const FindFirstUrlCacheEntry = thismodule.FindFirstUrlCacheEntryA; pub const FindNextUrlCacheEntry = thismodule.FindNextUrlCacheEntryA; pub const InternetSetPerSiteCookieDecision = thismodule.InternetSetPerSiteCookieDecisionA; pub const InternetGetPerSiteCookieDecision = thismodule.InternetGetPerSiteCookieDecisionA; pub const InternetEnumPerSiteCookieDecision = thismodule.InternetEnumPerSiteCookieDecisionA; pub const InternetAlgIdToString = thismodule.InternetAlgIdToStringA; pub const InternetSecurityProtocolToString = thismodule.InternetSecurityProtocolToStringA; pub const InternetWriteFileEx = thismodule.InternetWriteFileExA; pub const HttpCheckDavCompliance = thismodule.HttpCheckDavComplianceA; pub const IsUrlCacheEntryExpired = thismodule.IsUrlCacheEntryExpiredA; pub const CreateUrlCacheContainer = thismodule.CreateUrlCacheContainerA; pub const DeleteUrlCacheContainer = thismodule.DeleteUrlCacheContainerA; pub const FindFirstUrlCacheContainer = thismodule.FindFirstUrlCacheContainerA; pub const FindNextUrlCacheContainer = thismodule.FindNextUrlCacheContainerA; pub const FreeUrlCacheSpace = thismodule.FreeUrlCacheSpaceA; pub const GetUrlCacheConfigInfo = thismodule.GetUrlCacheConfigInfoA; pub const SetUrlCacheConfigInfo = thismodule.SetUrlCacheConfigInfoA; pub const ImportCookieFile = thismodule.ImportCookieFileA; pub const ExportCookieFile = thismodule.ExportCookieFileA; pub const IsDomainLegalCookieDomain = thismodule.IsDomainLegalCookieDomainA; }, .wide => struct { pub const INTERNET_PER_CONN_OPTION = thismodule.INTERNET_PER_CONN_OPTIONW; pub const INTERNET_PER_CONN_OPTION_LIST = thismodule.INTERNET_PER_CONN_OPTION_LISTW; pub const URL_COMPONENTS = thismodule.URL_COMPONENTSW; pub const INTERNET_BUFFERS = thismodule.INTERNET_BUFFERSW; pub const GOPHER_FIND_DATA = thismodule.GOPHER_FIND_DATAW; pub const INTERNET_CACHE_ENTRY_INFO = thismodule.INTERNET_CACHE_ENTRY_INFOW; pub const INTERNET_CACHE_GROUP_INFO = thismodule.INTERNET_CACHE_GROUP_INFOW; pub const INTERNET_CACHE_CONFIG_PATH_ENTRY = thismodule.INTERNET_CACHE_CONFIG_PATH_ENTRYW; pub const INTERNET_CACHE_CONFIG_INFO = thismodule.INTERNET_CACHE_CONFIG_INFOW; pub const INTERNET_CACHE_CONTAINER_INFO = thismodule.INTERNET_CACHE_CONTAINER_INFOW; pub const InternetCrackUrl = thismodule.InternetCrackUrlW; pub const InternetCreateUrl = thismodule.InternetCreateUrlW; pub const InternetCanonicalizeUrl = thismodule.InternetCanonicalizeUrlW; pub const InternetCombineUrl = thismodule.InternetCombineUrlW; pub const InternetOpen = thismodule.InternetOpenW; pub const InternetConnect = thismodule.InternetConnectW; pub const InternetOpenUrl = thismodule.InternetOpenUrlW; pub const InternetReadFileEx = thismodule.InternetReadFileExW; pub const InternetFindNextFile = thismodule.InternetFindNextFileW; pub const InternetQueryOption = thismodule.InternetQueryOptionW; pub const InternetSetOption = thismodule.InternetSetOptionW; pub const InternetSetOptionEx = thismodule.InternetSetOptionExW; pub const InternetGetLastResponseInfo = thismodule.InternetGetLastResponseInfoW; pub const FtpFindFirstFile = thismodule.FtpFindFirstFileW; pub const FtpGetFile = thismodule.FtpGetFileW; pub const FtpPutFile = thismodule.FtpPutFileW; pub const FtpDeleteFile = thismodule.FtpDeleteFileW; pub const FtpRenameFile = thismodule.FtpRenameFileW; pub const FtpOpenFile = thismodule.FtpOpenFileW; pub const FtpCreateDirectory = thismodule.FtpCreateDirectoryW; pub const FtpRemoveDirectory = thismodule.FtpRemoveDirectoryW; pub const FtpSetCurrentDirectory = thismodule.FtpSetCurrentDirectoryW; pub const FtpGetCurrentDirectory = thismodule.FtpGetCurrentDirectoryW; pub const FtpCommand = thismodule.FtpCommandW; pub const GopherCreateLocator = thismodule.GopherCreateLocatorW; pub const GopherGetLocatorType = thismodule.GopherGetLocatorTypeW; pub const GopherFindFirstFile = thismodule.GopherFindFirstFileW; pub const GopherOpenFile = thismodule.GopherOpenFileW; pub const GopherGetAttribute = thismodule.GopherGetAttributeW; pub const HttpOpenRequest = thismodule.HttpOpenRequestW; pub const HttpAddRequestHeaders = thismodule.HttpAddRequestHeadersW; pub const HttpSendRequest = thismodule.HttpSendRequestW; pub const HttpSendRequestEx = thismodule.HttpSendRequestExW; pub const HttpEndRequest = thismodule.HttpEndRequestW; pub const HttpQueryInfo = thismodule.HttpQueryInfoW; pub const InternetSetCookie = thismodule.InternetSetCookieW; pub const InternetGetCookie = thismodule.InternetGetCookieW; pub const InternetSetCookieEx = thismodule.InternetSetCookieExW; pub const InternetGetCookieEx = thismodule.InternetGetCookieExW; pub const InternetCheckConnection = thismodule.InternetCheckConnectionW; pub const CreateUrlCacheEntry = thismodule.CreateUrlCacheEntryW; pub const CommitUrlCacheEntry = thismodule.CommitUrlCacheEntryW; pub const RetrieveUrlCacheEntryFile = thismodule.RetrieveUrlCacheEntryFileW; pub const RetrieveUrlCacheEntryStream = thismodule.RetrieveUrlCacheEntryStreamW; pub const GetUrlCacheEntryInfo = thismodule.GetUrlCacheEntryInfoW; pub const GetUrlCacheGroupAttribute = thismodule.GetUrlCacheGroupAttributeW; pub const SetUrlCacheGroupAttribute = thismodule.SetUrlCacheGroupAttributeW; pub const GetUrlCacheEntryInfoEx = thismodule.GetUrlCacheEntryInfoExW; pub const SetUrlCacheEntryInfo = thismodule.SetUrlCacheEntryInfoW; pub const FindFirstUrlCacheEntryEx = thismodule.FindFirstUrlCacheEntryExW; pub const FindNextUrlCacheEntryEx = thismodule.FindNextUrlCacheEntryExW; pub const FindFirstUrlCacheEntry = thismodule.FindFirstUrlCacheEntryW; pub const FindNextUrlCacheEntry = thismodule.FindNextUrlCacheEntryW; pub const InternetSetPerSiteCookieDecision = thismodule.InternetSetPerSiteCookieDecisionW; pub const InternetGetPerSiteCookieDecision = thismodule.InternetGetPerSiteCookieDecisionW; pub const InternetEnumPerSiteCookieDecision = thismodule.InternetEnumPerSiteCookieDecisionW; pub const InternetAlgIdToString = thismodule.InternetAlgIdToStringW; pub const InternetSecurityProtocolToString = thismodule.InternetSecurityProtocolToStringW; pub const InternetWriteFileEx = thismodule.InternetWriteFileExW; pub const HttpCheckDavCompliance = thismodule.HttpCheckDavComplianceW; pub const IsUrlCacheEntryExpired = thismodule.IsUrlCacheEntryExpiredW; pub const CreateUrlCacheContainer = thismodule.CreateUrlCacheContainerW; pub const DeleteUrlCacheContainer = thismodule.DeleteUrlCacheContainerW; pub const FindFirstUrlCacheContainer = thismodule.FindFirstUrlCacheContainerW; pub const FindNextUrlCacheContainer = thismodule.FindNextUrlCacheContainerW; pub const FreeUrlCacheSpace = thismodule.FreeUrlCacheSpaceW; pub const GetUrlCacheConfigInfo = thismodule.GetUrlCacheConfigInfoW; pub const SetUrlCacheConfigInfo = thismodule.SetUrlCacheConfigInfoW; pub const ImportCookieFile = thismodule.ImportCookieFileW; pub const ExportCookieFile = thismodule.ExportCookieFileW; pub const IsDomainLegalCookieDomain = thismodule.IsDomainLegalCookieDomainW; }, .unspecified => if (@import("builtin").is_test) struct { pub const INTERNET_PER_CONN_OPTION = *opaque{}; pub const INTERNET_PER_CONN_OPTION_LIST = *opaque{}; pub const URL_COMPONENTS = *opaque{}; pub const INTERNET_BUFFERS = *opaque{}; pub const GOPHER_FIND_DATA = *opaque{}; pub const INTERNET_CACHE_ENTRY_INFO = *opaque{}; pub const INTERNET_CACHE_GROUP_INFO = *opaque{}; pub const INTERNET_CACHE_CONFIG_PATH_ENTRY = *opaque{}; pub const INTERNET_CACHE_CONFIG_INFO = *opaque{}; pub const INTERNET_CACHE_CONTAINER_INFO = *opaque{}; pub const InternetCrackUrl = *opaque{}; pub const InternetCreateUrl = *opaque{}; pub const InternetCanonicalizeUrl = *opaque{}; pub const InternetCombineUrl = *opaque{}; pub const InternetOpen = *opaque{}; pub const InternetConnect = *opaque{}; pub const InternetOpenUrl = *opaque{}; pub const InternetReadFileEx = *opaque{}; pub const InternetFindNextFile = *opaque{}; pub const InternetQueryOption = *opaque{}; pub const InternetSetOption = *opaque{}; pub const InternetSetOptionEx = *opaque{}; pub const InternetGetLastResponseInfo = *opaque{}; pub const FtpFindFirstFile = *opaque{}; pub const FtpGetFile = *opaque{}; pub const FtpPutFile = *opaque{}; pub const FtpDeleteFile = *opaque{}; pub const FtpRenameFile = *opaque{}; pub const FtpOpenFile = *opaque{}; pub const FtpCreateDirectory = *opaque{}; pub const FtpRemoveDirectory = *opaque{}; pub const FtpSetCurrentDirectory = *opaque{}; pub const FtpGetCurrentDirectory = *opaque{}; pub const FtpCommand = *opaque{}; pub const GopherCreateLocator = *opaque{}; pub const GopherGetLocatorType = *opaque{}; pub const GopherFindFirstFile = *opaque{}; pub const GopherOpenFile = *opaque{}; pub const GopherGetAttribute = *opaque{}; pub const HttpOpenRequest = *opaque{}; pub const HttpAddRequestHeaders = *opaque{}; pub const HttpSendRequest = *opaque{}; pub const HttpSendRequestEx = *opaque{}; pub const HttpEndRequest = *opaque{}; pub const HttpQueryInfo = *opaque{}; pub const InternetSetCookie = *opaque{}; pub const InternetGetCookie = *opaque{}; pub const InternetSetCookieEx = *opaque{}; pub const InternetGetCookieEx = *opaque{}; pub const InternetCheckConnection = *opaque{}; pub const CreateUrlCacheEntry = *opaque{}; pub const CommitUrlCacheEntry = *opaque{}; pub const RetrieveUrlCacheEntryFile = *opaque{}; pub const RetrieveUrlCacheEntryStream = *opaque{}; pub const GetUrlCacheEntryInfo = *opaque{}; pub const GetUrlCacheGroupAttribute = *opaque{}; pub const SetUrlCacheGroupAttribute = *opaque{}; pub const GetUrlCacheEntryInfoEx = *opaque{}; pub const SetUrlCacheEntryInfo = *opaque{}; pub const FindFirstUrlCacheEntryEx = *opaque{}; pub const FindNextUrlCacheEntryEx = *opaque{}; pub const FindFirstUrlCacheEntry = *opaque{}; pub const FindNextUrlCacheEntry = *opaque{}; pub const InternetSetPerSiteCookieDecision = *opaque{}; pub const InternetGetPerSiteCookieDecision = *opaque{}; pub const InternetEnumPerSiteCookieDecision = *opaque{}; pub const InternetAlgIdToString = *opaque{}; pub const InternetSecurityProtocolToString = *opaque{}; pub const InternetWriteFileEx = *opaque{}; pub const HttpCheckDavCompliance = *opaque{}; pub const IsUrlCacheEntryExpired = *opaque{}; pub const CreateUrlCacheContainer = *opaque{}; pub const DeleteUrlCacheContainer = *opaque{}; pub const FindFirstUrlCacheContainer = *opaque{}; pub const FindNextUrlCacheContainer = *opaque{}; pub const FreeUrlCacheSpace = *opaque{}; pub const GetUrlCacheConfigInfo = *opaque{}; pub const SetUrlCacheConfigInfo = *opaque{}; pub const ImportCookieFile = *opaque{}; pub const ExportCookieFile = *opaque{}; pub const IsDomainLegalCookieDomain = *opaque{}; } else struct { pub const INTERNET_PER_CONN_OPTION = @compileError("'INTERNET_PER_CONN_OPTION' requires that UNICODE be set to true or false in the root module"); pub const INTERNET_PER_CONN_OPTION_LIST = @compileError("'INTERNET_PER_CONN_OPTION_LIST' requires that UNICODE be set to true or false in the root module"); pub const URL_COMPONENTS = @compileError("'URL_COMPONENTS' requires that UNICODE be set to true or false in the root module"); pub const INTERNET_BUFFERS = @compileError("'INTERNET_BUFFERS' requires that UNICODE be set to true or false in the root module"); pub const GOPHER_FIND_DATA = @compileError("'GOPHER_FIND_DATA' requires that UNICODE be set to true or false in the root module"); pub const INTERNET_CACHE_ENTRY_INFO = @compileError("'INTERNET_CACHE_ENTRY_INFO' requires that UNICODE be set to true or false in the root module"); pub const INTERNET_CACHE_GROUP_INFO = @compileError("'INTERNET_CACHE_GROUP_INFO' requires that UNICODE be set to true or false in the root module"); pub const INTERNET_CACHE_CONFIG_PATH_ENTRY = @compileError("'INTERNET_CACHE_CONFIG_PATH_ENTRY' requires that UNICODE be set to true or false in the root module"); pub const INTERNET_CACHE_CONFIG_INFO = @compileError("'INTERNET_CACHE_CONFIG_INFO' requires that UNICODE be set to true or false in the root module"); pub const INTERNET_CACHE_CONTAINER_INFO = @compileError("'INTERNET_CACHE_CONTAINER_INFO' requires that UNICODE be set to true or false in the root module"); pub const InternetCrackUrl = @compileError("'InternetCrackUrl' requires that UNICODE be set to true or false in the root module"); pub const InternetCreateUrl = @compileError("'InternetCreateUrl' requires that UNICODE be set to true or false in the root module"); pub const InternetCanonicalizeUrl = @compileError("'InternetCanonicalizeUrl' requires that UNICODE be set to true or false in the root module"); pub const InternetCombineUrl = @compileError("'InternetCombineUrl' requires that UNICODE be set to true or false in the root module"); pub const InternetOpen = @compileError("'InternetOpen' requires that UNICODE be set to true or false in the root module"); pub const InternetConnect = @compileError("'InternetConnect' requires that UNICODE be set to true or false in the root module"); pub const InternetOpenUrl = @compileError("'InternetOpenUrl' requires that UNICODE be set to true or false in the root module"); pub const InternetReadFileEx = @compileError("'InternetReadFileEx' requires that UNICODE be set to true or false in the root module"); pub const InternetFindNextFile = @compileError("'InternetFindNextFile' requires that UNICODE be set to true or false in the root module"); pub const InternetQueryOption = @compileError("'InternetQueryOption' requires that UNICODE be set to true or false in the root module"); pub const InternetSetOption = @compileError("'InternetSetOption' requires that UNICODE be set to true or false in the root module"); pub const InternetSetOptionEx = @compileError("'InternetSetOptionEx' requires that UNICODE be set to true or false in the root module"); pub const InternetGetLastResponseInfo = @compileError("'InternetGetLastResponseInfo' requires that UNICODE be set to true or false in the root module"); pub const FtpFindFirstFile = @compileError("'FtpFindFirstFile' requires that UNICODE be set to true or false in the root module"); pub const FtpGetFile = @compileError("'FtpGetFile' requires that UNICODE be set to true or false in the root module"); pub const FtpPutFile = @compileError("'FtpPutFile' requires that UNICODE be set to true or false in the root module"); pub const FtpDeleteFile = @compileError("'FtpDeleteFile' requires that UNICODE be set to true or false in the root module"); pub const FtpRenameFile = @compileError("'FtpRenameFile' requires that UNICODE be set to true or false in the root module"); pub const FtpOpenFile = @compileError("'FtpOpenFile' requires that UNICODE be set to true or false in the root module"); pub const FtpCreateDirectory = @compileError("'FtpCreateDirectory' requires that UNICODE be set to true or false in the root module"); pub const FtpRemoveDirectory = @compileError("'FtpRemoveDirectory' requires that UNICODE be set to true or false in the root module"); pub const FtpSetCurrentDirectory = @compileError("'FtpSetCurrentDirectory' requires that UNICODE be set to true or false in the root module"); pub const FtpGetCurrentDirectory = @compileError("'FtpGetCurrentDirectory' requires that UNICODE be set to true or false in the root module"); pub const FtpCommand = @compileError("'FtpCommand' requires that UNICODE be set to true or false in the root module"); pub const GopherCreateLocator = @compileError("'GopherCreateLocator' requires that UNICODE be set to true or false in the root module"); pub const GopherGetLocatorType = @compileError("'GopherGetLocatorType' requires that UNICODE be set to true or false in the root module"); pub const GopherFindFirstFile = @compileError("'GopherFindFirstFile' requires that UNICODE be set to true or false in the root module"); pub const GopherOpenFile = @compileError("'GopherOpenFile' requires that UNICODE be set to true or false in the root module"); pub const GopherGetAttribute = @compileError("'GopherGetAttribute' requires that UNICODE be set to true or false in the root module"); pub const HttpOpenRequest = @compileError("'HttpOpenRequest' requires that UNICODE be set to true or false in the root module"); pub const HttpAddRequestHeaders = @compileError("'HttpAddRequestHeaders' requires that UNICODE be set to true or false in the root module"); pub const HttpSendRequest = @compileError("'HttpSendRequest' requires that UNICODE be set to true or false in the root module"); pub const HttpSendRequestEx = @compileError("'HttpSendRequestEx' requires that UNICODE be set to true or false in the root module"); pub const HttpEndRequest = @compileError("'HttpEndRequest' requires that UNICODE be set to true or false in the root module"); pub const HttpQueryInfo = @compileError("'HttpQueryInfo' requires that UNICODE be set to true or false in the root module"); pub const InternetSetCookie = @compileError("'InternetSetCookie' requires that UNICODE be set to true or false in the root module"); pub const InternetGetCookie = @compileError("'InternetGetCookie' requires that UNICODE be set to true or false in the root module"); pub const InternetSetCookieEx = @compileError("'InternetSetCookieEx' requires that UNICODE be set to true or false in the root module"); pub const InternetGetCookieEx = @compileError("'InternetGetCookieEx' requires that UNICODE be set to true or false in the root module"); pub const InternetCheckConnection = @compileError("'InternetCheckConnection' requires that UNICODE be set to true or false in the root module"); pub const CreateUrlCacheEntry = @compileError("'CreateUrlCacheEntry' requires that UNICODE be set to true or false in the root module"); pub const CommitUrlCacheEntry = @compileError("'CommitUrlCacheEntry' requires that UNICODE be set to true or false in the root module"); pub const RetrieveUrlCacheEntryFile = @compileError("'RetrieveUrlCacheEntryFile' requires that UNICODE be set to true or false in the root module"); pub const RetrieveUrlCacheEntryStream = @compileError("'RetrieveUrlCacheEntryStream' requires that UNICODE be set to true or false in the root module"); pub const GetUrlCacheEntryInfo = @compileError("'GetUrlCacheEntryInfo' requires that UNICODE be set to true or false in the root module"); pub const GetUrlCacheGroupAttribute = @compileError("'GetUrlCacheGroupAttribute' requires that UNICODE be set to true or false in the root module"); pub const SetUrlCacheGroupAttribute = @compileError("'SetUrlCacheGroupAttribute' requires that UNICODE be set to true or false in the root module"); pub const GetUrlCacheEntryInfoEx = @compileError("'GetUrlCacheEntryInfoEx' requires that UNICODE be set to true or false in the root module"); pub const SetUrlCacheEntryInfo = @compileError("'SetUrlCacheEntryInfo' requires that UNICODE be set to true or false in the root module"); pub const FindFirstUrlCacheEntryEx = @compileError("'FindFirstUrlCacheEntryEx' requires that UNICODE be set to true or false in the root module"); pub const FindNextUrlCacheEntryEx = @compileError("'FindNextUrlCacheEntryEx' requires that UNICODE be set to true or false in the root module"); pub const FindFirstUrlCacheEntry = @compileError("'FindFirstUrlCacheEntry' requires that UNICODE be set to true or false in the root module"); pub const FindNextUrlCacheEntry = @compileError("'FindNextUrlCacheEntry' requires that UNICODE be set to true or false in the root module"); pub const InternetSetPerSiteCookieDecision = @compileError("'InternetSetPerSiteCookieDecision' requires that UNICODE be set to true or false in the root module"); pub const InternetGetPerSiteCookieDecision = @compileError("'InternetGetPerSiteCookieDecision' requires that UNICODE be set to true or false in the root module"); pub const InternetEnumPerSiteCookieDecision = @compileError("'InternetEnumPerSiteCookieDecision' requires that UNICODE be set to true or false in the root module"); pub const InternetAlgIdToString = @compileError("'InternetAlgIdToString' requires that UNICODE be set to true or false in the root module"); pub const InternetSecurityProtocolToString = @compileError("'InternetSecurityProtocolToString' requires that UNICODE be set to true or false in the root module"); pub const InternetWriteFileEx = @compileError("'InternetWriteFileEx' requires that UNICODE be set to true or false in the root module"); pub const HttpCheckDavCompliance = @compileError("'HttpCheckDavCompliance' requires that UNICODE be set to true or false in the root module"); pub const IsUrlCacheEntryExpired = @compileError("'IsUrlCacheEntryExpired' requires that UNICODE be set to true or false in the root module"); pub const CreateUrlCacheContainer = @compileError("'CreateUrlCacheContainer' requires that UNICODE be set to true or false in the root module"); pub const DeleteUrlCacheContainer = @compileError("'DeleteUrlCacheContainer' requires that UNICODE be set to true or false in the root module"); pub const FindFirstUrlCacheContainer = @compileError("'FindFirstUrlCacheContainer' requires that UNICODE be set to true or false in the root module"); pub const FindNextUrlCacheContainer = @compileError("'FindNextUrlCacheContainer' requires that UNICODE be set to true or false in the root module"); pub const FreeUrlCacheSpace = @compileError("'FreeUrlCacheSpace' requires that UNICODE be set to true or false in the root module"); pub const GetUrlCacheConfigInfo = @compileError("'GetUrlCacheConfigInfo' requires that UNICODE be set to true or false in the root module"); pub const SetUrlCacheConfigInfo = @compileError("'SetUrlCacheConfigInfo' requires that UNICODE be set to true or false in the root module"); pub const ImportCookieFile = @compileError("'ImportCookieFile' requires that UNICODE be set to true or false in the root module"); pub const ExportCookieFile = @compileError("'ExportCookieFile' requires that UNICODE be set to true or false in the root module"); pub const IsDomainLegalCookieDomain = @compileError("'IsDomainLegalCookieDomain' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (23) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BSTR = @import("../foundation.zig").BSTR; const CERT_CHAIN_CONTEXT = @import("../security/cryptography.zig").CERT_CHAIN_CONTEXT; const CERT_CONTEXT = @import("../security/cryptography.zig").CERT_CONTEXT; const CHAR = @import("../foundation.zig").CHAR; const FILETIME = @import("../foundation.zig").FILETIME; const HANDLE = @import("../foundation.zig").HANDLE; const HBITMAP = @import("../graphics/gdi.zig").HBITMAP; const HINSTANCE = @import("../foundation.zig").HINSTANCE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IInspectable = @import("../system/win_rt.zig").IInspectable; const IUnknown = @import("../system/com.zig").IUnknown; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const SecPkgContext_Bindings = @import("../security/authentication/identity.zig").SecPkgContext_Bindings; const SecPkgContext_CipherInfo = @import("../security/authentication/identity.zig").SecPkgContext_CipherInfo; const SecPkgContext_ConnectionInfo = @import("../security/authentication/identity.zig").SecPkgContext_ConnectionInfo; const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME; const WIN32_FIND_DATAA = @import("../storage/file_system.zig").WIN32_FIND_DATAA; const WIN32_FIND_DATAW = @import("../storage/file_system.zig").WIN32_FIND_DATAW; const WIN_HTTP_CREATE_URL_FLAGS = @import("../networking/win_http.zig").WIN_HTTP_CREATE_URL_FLAGS; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "LPINTERNET_STATUS_CALLBACK")) { _ = LPINTERNET_STATUS_CALLBACK; } if (@hasDecl(@This(), "GOPHER_ATTRIBUTE_ENUMERATOR")) { _ = GOPHER_ATTRIBUTE_ENUMERATOR; } if (@hasDecl(@This(), "PFN_AUTH_NOTIFY")) { _ = PFN_AUTH_NOTIFY; } if (@hasDecl(@This(), "pfnInternetInitializeAutoProxyDll")) { _ = pfnInternetInitializeAutoProxyDll; } if (@hasDecl(@This(), "pfnInternetDeInitializeAutoProxyDll")) { _ = pfnInternetDeInitializeAutoProxyDll; } if (@hasDecl(@This(), "pfnInternetGetProxyInfo")) { _ = pfnInternetGetProxyInfo; } if (@hasDecl(@This(), "PFN_DIAL_HANDLER")) { _ = PFN_DIAL_HANDLER; } if (@hasDecl(@This(), "CACHE_OPERATOR")) { _ = CACHE_OPERATOR; } if (@hasDecl(@This(), "HTTP_POLICY_EXTENSION_INIT")) { _ = HTTP_POLICY_EXTENSION_INIT; } if (@hasDecl(@This(), "HTTP_POLICY_EXTENSION_SHUTDOWN")) { _ = HTTP_POLICY_EXTENSION_SHUTDOWN; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/networking/win_inet.zig