code
stringlengths
38
801k
repo_path
stringlengths
6
263
usingnamespace @import("root").preamble; const log = lib.output.log.scoped(.{ .prefix = "VirtioNet", .filter = .info, }).write; const virtio_pci = os.drivers.misc.virtio_pci; const DevConfig = packed struct { mac: [6]u8, }; /// virtio-net driver instance const Driver = struct { transport: virtio_pci.Driver, mac: [6]u8 = undefined, // Initialize the virtio transport, but don't change modes pub fn init(pciaddr: os.platform.pci.Addr) !Driver { var v = try virtio_pci.Driver.init(pciaddr, VIRTIO_NET_F_MAC, 0); var d: Driver = .{ .transport = v }; const c = @ptrCast(*volatile DevConfig, d.transport.dev); log(.info, "MAC addr {0X}:{0X}:{0X}:{0X}:{0X}:{0X}", .{ c.mac[0], c.mac[1], c.mac[2], c.mac[3], c.mac[4], c.mac[5] }); var iter = d.transport.iter(1); { var hdr: NetHdr = .{}; iter.begin(); iter.put(&hdr, @sizeOf(NetHdr), virtio_pci.vring_desc_flag_next); const text = "testing"; iter.put(&text[0], text.len, 0); } d.transport.start(1); d.wait(1); return d; } /// Wait for request to finish. fn wait(self: *Driver, queue: u8) void { while (self.transport.queues[queue].num_unused != self.transport.queues[queue].size) { self.transport.process(queue); } } }; fn process(self: *Driver, i: u8, head: virtio_pci.Descriptor) void { self.transport.freeChain(i, head); self.inflight -= 1; } pub fn registerController(addr: os.platform.pci.Addr) void { const alloc = os.memory.pmm.phys_heap; const drv = alloc.create(Driver) catch { log(.crit, "Virtio Ethernet controller: Allocation failure", .{}); return; }; errdefer alloc.destroy(drv); drv.* = Driver.init(addr) catch { log(.crit, "Virtio Ethernet controller: Init has failed!", .{}); return; }; errdefer drv.deinit(); } pub fn interrupt(drv: *Driver) void {} const VIRTIO_NET_F_MAC = 1 << 5; const NetHdr = packed struct { flags: u8 = 0, gso_type: u8 = 0, hdr_len: u16 = 0, gso_size: u16 = 0, csum_start: u16 = 0, csum_offset: u16 = 0, num_buffers: u16 = 0, };
subprojects/flork/src/drivers/net/virtio.zig
const std = @import("std"); usingnamespace @import("kiragine").kira.log; const engine = @import("kiragine"); const maxparticle = 1500; const ParticleSystem = engine.ParticleSystemGeneric(maxparticle); const windowWidth = 1024; const windowHeight = 768; const title = "Particle system"; const targetfps = 60; var rand: std.rand.Xoroshiro128 = undefined; var particlesys = ParticleSystem{ .drawfn = particledraw, }; fn particledraw(self: engine.Particle) engine.Error!void { const rect = engine.Rectangle{ .x = self.position.x, .y = self.position.y, .width = self.size.x, .height = self.size.y, }; try engine.drawRectangle(rect, self.colour); } fn fixedUpdate(fixedtime: f32) !void { particlesys.update(fixedtime); var i: u32 = 0; while (i < 10) : (i += 1) { const rann = rand.random.intRangeLessThan(i32, -100, 100); const p = engine.Particle{ .position = .{ .x = 300 + @intToFloat(f32, i * i), .y = windowHeight - 100 }, .size = .{ .x = 5, .y = 5 }, .velocity = .{ .x = @intToFloat(f32, rann), .y = -100 }, .lifetime = 1.5, .colour = engine.Colour.rgba(200, 70, 120, 255), .fade = 200, .fade_colour = engine.Colour.rgba(30, 30, 100, 50), }; _ = particlesys.add(p); } } fn draw() !void { engine.clearScreen(0.1, 0.1, 0.1, 1.0); // Push the triangle batch, it can be mixed with quad batch try engine.pushBatch2D(engine.Renderer2DBatchTag.triangles); // Uses the draw call as we set(particleDraw) if it's not set // it'll fallback to draw as rectangles //try particlesys.draw(); // draws as rectangles //try particlesys.drawAsRectangles(); // draws as textures(Don't forget to enable texture batch!) // try particlesys.drawAsTextures(); // draws as triangles //try particlesys.drawAsTriangles(); // draws as circles try particlesys.drawAsCircles(); // Pops the current batch try engine.popBatch2D(); } pub fn main() !void { const callbacks = engine.Callbacks{ .draw = draw, .fixed = fixedUpdate, }; try engine.init(callbacks, windowWidth, windowHeight, title, targetfps, std.heap.page_allocator); var buf: [8]u8 = undefined; try std.crypto.randomBytes(buf[0..]); const seed = std.mem.readIntLittle(u64, buf[0..8]); rand = std.rand.DefaultPrng.init(seed); try engine.open(); try engine.update(); try engine.deinit(); }
examples/particlesystem.zig
const std = @import("std"); const Builder = @import("std").build.Builder; const Build = @import("std").build; const Builtin = @import("std").builtin; const Zig = @import("std").zig; const globalflags = [_][]const u8{"-std=c99"}; pub var strip = false; fn setup(exe: *Build.LibExeObjStep, target: Zig.CrossTarget) void { const target_os = target.getOsTag(); switch (target_os) { .windows => { exe.setTarget(target); exe.linkSystemLibrary("gdi32"); exe.linkSystemLibrary("opengl32"); exe.subsystem = Builtin.SubSystem.Console; }, .linux => { exe.setTarget(target); exe.linkSystemLibrary("X11"); }, else => {}, } } fn compileGLFWWin32(exe: *Build.LibExeObjStep, comptime enginepath: []const u8) void { const flags = [_][]const u8{"-O2"} ++ globalflags; exe.linkSystemLibrary("gdi32"); exe.linkSystemLibrary("opengl32"); exe.defineCMacro("_GLFW_WIN32"); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/wgl_context.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/win32_init.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/win32_joystick.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/win32_monitor.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/win32_thread.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/win32_time.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/win32_window.c", &flags); } fn compileGLFWLinux(exe: *Build.LibExeObjStep, comptime enginepath: []const u8) void { const flags = [_][]const u8{"-O2"} ++ globalflags; exe.linkSystemLibrary("X11"); exe.defineCMacro("_GLFW_X11"); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/glx_context.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/posix_thread.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/posix_time.c", &flags); //exe.addCSourceFile("include/glfw-3.3.2/src/wl_init.c", &flags); //exe.addCSourceFile("include/glfw-3.3.2/src/wl_window.c", &flags); //exe.addCSourceFile("include/glfw-3.3.2/src/wl_monitor.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/x11_init.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/x11_window.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/x11_monitor.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/xkb_unicode.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/linux_joystick.c", &flags); } fn compileGLFWShared(exe: *Build.LibExeObjStep, comptime enginepath: []const u8) void { const flags = [_][]const u8{"-O2"} ++ globalflags; exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/init.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/context.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/input.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/monitor.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/window.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/vulkan.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/osmesa_context.c", &flags); exe.addCSourceFile(enginepath ++ "include/glfw-3.3.2/src/egl_context.c", &flags); //exe.addCSourceFile("include/glfw-3.3.2/src/null_init.c", &flags); //exe.addCSourceFile("include/glfw-3.3.2/src/null_joystick.c", &flags); //exe.addCSourceFile("include/glfw-3.3.2/src/null_monitor.c", &flags); //exe.addCSourceFile("include/glfw-3.3.2/src/null_window.c", &flags); } fn compileFreetypeWin32(exe: *Build.LibExeObjStep, comptime enginepath: []const u8) void { const flags = [_][]const u8{ "-O2", "-DFT2_BUILD_LIBRARY" } ++ globalflags; const p = enginepath ++ "include/freetype-2.10.2/"; exe.addCSourceFile(p ++ "builds/windows/ftdebug.c", &flags); exe.addCSourceFile(p ++ "src/base/ftsystem.c", &flags); } fn compileFreetypePosix(exe: *Build.LibExeObjStep, comptime enginepath: []const u8) void { const flags = [_][]const u8{ "-O2", "-DFT2_BUILD_LIBRARY" } ++ globalflags; const p = enginepath ++ "include/freetype-2.10.2/"; //exe.addCSourceFile(p ++ "builds/unix/ftsystem.c", &flags); exe.addCSourceFile(p ++ "src/base/ftdebug.c", &flags); exe.addCSourceFile(p ++ "src/base/ftsystem.c", &flags); } fn compileFreetypeShared(exe: *Build.LibExeObjStep, comptime enginepath: []const u8) void { const flags = [_][]const u8{ "-O2", "-DFT2_BUILD_LIBRARY" } ++ globalflags; const p = enginepath ++ "include/freetype-2.10.2/"; const ftpsharedsrc = comptime [_][]const u8{ p ++ "src/autofit/autofit.c", p ++ "src/base/ftbase.c", p ++ "src/base/ftbbox.c", p ++ "src/base/ftbdf.c", p ++ "src/base/ftbitmap.c", p ++ "src/base/ftcid.c", p ++ "src/base/ftfstype.c", p ++ "src/base/ftgasp.c", p ++ "src/base/ftglyph.c", p ++ "src/base/ftgxval.c", p ++ "src/base/ftinit.c", p ++ "src/base/ftmm.c", p ++ "src/base/ftotval.c", p ++ "src/base/ftpatent.c", p ++ "src/base/ftpfr.c", p ++ "src/base/ftstroke.c", p ++ "src/base/ftsynth.c", p ++ "src/base/fttype1.c", p ++ "src/base/ftwinfnt.c", p ++ "src/bdf/bdf.c", p ++ "src/bzip2/ftbzip2.c", p ++ "src/cache/ftcache.c", p ++ "src/cff/cff.c", p ++ "src/cid/type1cid.c", p ++ "src/gzip/ftgzip.c", p ++ "src/lzw/ftlzw.c", p ++ "src/pcf/pcf.c", p ++ "src/pfr/pfr.c", p ++ "src/psaux/psaux.c", p ++ "src/pshinter/pshinter.c", p ++ "src/psnames/psnames.c", p ++ "src/raster/raster.c", p ++ "src/sfnt/sfnt.c", p ++ "src/smooth/smooth.c", p ++ "src/truetype/truetype.c", p ++ "src/type1/type1.c", p ++ "src/type42/type42.c", p ++ "src/winfonts/winfnt.c", }; var i: u32 = 0; while (i < ftpsharedsrc.len) : (i += 1) { exe.addCSourceFile(ftpsharedsrc[i], &flags); } } fn addSourceFiles(exe: *Build.LibExeObjStep, target: Zig.CrossTarget, comptime enginepath: []const u8) void { exe.linkSystemLibrary("c"); const target_os = target.getOsTag(); switch (target_os) { .windows => { exe.setTarget(target); exe.subsystem = Builtin.SubSystem.Console; compileGLFWWin32(exe, enginepath); compileFreetypeWin32(exe, enginepath); }, .linux => { exe.setTarget(target); compileGLFWLinux(exe, enginepath); compileFreetypePosix(exe, enginepath); }, else => {}, } compileGLFWShared(exe, enginepath); compileFreetypeShared(exe, enginepath); const flags = [_][]const u8{"-O3"} ++ globalflags; exe.addCSourceFile(enginepath ++ "include/onefile/GLAD/gl.c", &flags); exe.addCSourceFile(enginepath ++ "include/onefile/stb/image.c", &flags); exe.addCSourceFile(enginepath ++ "include/onefile/stb/truetype.c", &flags); } fn addIncludeDirs(exe: *Build.LibExeObjStep, comptime enginepath: []const u8) void { exe.addIncludeDir(enginepath ++ "include/freetype-2.10.2/include/"); exe.addIncludeDir(enginepath ++ "include/freetype-2.10.2/include/freetype/config"); exe.addIncludeDir(enginepath ++ "include/glfw-3.3.2/include/"); exe.addIncludeDir(enginepath ++ "include/onefile/"); } pub fn buildExe(b: *Builder, target: Zig.CrossTarget, mode: Builtin.Mode, path: []const u8, name: []const u8, lib: *Build.LibExeObjStep, comptime enginepath: []const u8) *Build.LibExeObjStep { const exe = b.addExecutable(name, path); exe.strip = strip; exe.setOutputDir("build"); exe.linkSystemLibrary("c"); setup(exe, target); addIncludeDirs(exe, enginepath); exe.addLibPath("build/"); exe.linkSystemLibrary("kiragine"); exe.addPackagePath("kiragine", enginepath ++ "src/kiragine/kiragine.zig"); exe.setBuildMode(mode); exe.install(); return exe; } pub fn buildExePrimitive(b: *Builder, target: Zig.CrossTarget, mode: Builtin.Mode, path: []const u8, name: []const u8, lib: *Build.LibExeObjStep, comptime enginepath: []const u8) *Build.LibExeObjStep { const exe = b.addExecutable(name, path); exe.strip = strip; exe.setOutputDir("build"); exe.linkSystemLibrary("c"); setup(exe, target); addIncludeDirs(exe, enginepath); exe.addLibPath("build/"); exe.linkSystemLibrary("kiragine"); exe.addPackagePath("kira", enginepath ++ "src/kiragine/kira/kira.zig"); exe.setBuildMode(mode); exe.install(); return exe; } pub fn buildEngineStatic(b: *Builder, target: Zig.CrossTarget, mode: Builtin.Mode, comptime enginepath: []const u8) *Build.LibExeObjStep { var exe: *Build.LibExeObjStep = undefined; exe = b.addStaticLibrary("kiragine", enginepath ++ "src/kiragine/kiragine.zig"); exe.setOutputDir("build"); addIncludeDirs(exe, enginepath); addSourceFiles(exe, target, enginepath); exe.setBuildMode(mode); exe.install(); return exe; } pub fn buildEngine(b: *Builder, target: Zig.CrossTarget, mode: Builtin.Mode, comptime enginepath: []const u8) *Build.LibExeObjStep { var exe: *Build.LibExeObjStep = undefined; // WARN: Building a shared library does not work on windows // There is a problem while linking windows dll's with Builder.addSharedLibrary //const shared = comptime if (std.Target.current.os.tag == .linux) true else false; // Building as dll is problematic, when the windows problem solved, i'll reconsider building as dll return buildEngineStatic(b, target, mode, enginepath); //exe = b.addSharedLibrary("kiragine", enginepath ++ "src/kiragine/kiragine.zig", .{ .versioned = .{ .major = 1, .minor = 0, .patch = 0 }}); //exe.setOutputDir("build"); //exe.addIncludeDir(enginepath ++ "include/glfw-3.3.2/include/"); //exe.addIncludeDir(enginepath ++ "include/onefile/"); //addSourceFiles(exe, target, enginepath); //exe.setBuildMode(mode); //exe.install(); //return exe; }
libbuild.zig
const std = @import("std"); const math = std.math; const mem = std.mem; const Allocator = mem.Allocator; const assert = std.debug.assert; const trait = std.meta.trait; const builtin = @import("builtin"); /// ECS Schema with the IdType and all component types pub fn Schema(comptime IdType: type, comptime CompTypes: anytype) type { if (comptime !trait.isUnsignedInt(IdType)) { @compileError("Id type '" ++ @typeName(IdType) ++ "' must be an unsigned int."); } if (comptime @mod(@typeInfo(IdType).Int.bits, 2) != 0) { @compileError("Id type must be divisible by two"); } return struct { fn componentId(comptime T: type) IdType { comptime { for (CompTypes) |Type, i| { if (T == Type) { return i; } } } } pub const Entity = struct { id: IdType, internal: IdType, }; pub const World = struct { const Self = @This(); allocator: *Allocator, //----- Entities entities: []?Entity, current_entityid: IdType = 0, entities_deleted: IdType = 0, next_recycleid: ?IdType = null, //----- Components component_storages: MultiVecStore, component_storage_ptrs: std.ArrayList(usize), //----- Systems systems: std.AutoHashMap(*System, void), current_systemid: IdType = 0, //----- Resources /// Initialize a world in this ECS /// Generates the required storages pub fn init(allocator: *Allocator) !Self { var entities = try allocator.alloc(?Entity, math.maxInt(IdType)); errdefer allocator.free(entities); var component_storages = MultiVecStore.init(allocator); var component_storage_ptrs = std.ArrayList(usize).init(allocator); inline for (CompTypes) |T, i| { var storage = try ComponentStorage(T).init(allocator, @intCast(IdType, i)); try component_storages.append(ComponentStorage(T), storage); } inline for (CompTypes) |T, i| { try component_storage_ptrs.append(@ptrToInt(component_storages.getIndexPtr(ComponentStorage(T), i))); } var systems = std.AutoHashMap(*System, void).init(allocator); return Self{ .allocator = allocator, .entities = entities, .component_storages = component_storages, .component_storage_ptrs = component_storage_ptrs, .systems = systems, }; } /// Cleans up the world /// Deinits all the storages pub fn deinit(self: *Self) void { self.allocator.free(self.entities); var i: usize = 0; while (i < self.component_storage_ptrs.items.len) : (i += 1) { @intToPtr(*ComponentStorage(u1), self.component_storage_ptrs.items[i]).deinit(); } self.component_storages.deinit(); self.component_storage_ptrs.deinit(); self.systems.deinit(); } //----- Entities /// Create a single entity with components /// Components are passed as a tuple /// Ex: /// .{ /// @as(HealthComponent, health), /// @as(PositionComponent, position), ///} pub fn createEntity(self: *Self, components: anytype) !Entity { const T = @TypeOf(components); var entity: Entity = undefined; if (self.entities_deleted == 0) { entity = Entity{ .id = self.current_entityid, .internal = self.current_entityid, }; self.entities[self.current_entityid] = entity; self.current_entityid += 1; } else { if (self.entities[self.next_recycleid.?] == null) { entity = Entity{ .id = self.next_recycleid.?, .internal = self.next_recycleid.?, }; self.next_recycleid = null; self.entities[entity.id] = entity; self.entities_deleted -= 1; } else { entity = Entity{ .id = self.next_recycleid.?, .internal = self.next_recycleid.?, }; self.next_recycleid = self.entities[entity.id].?.id; self.entities[entity.id] = entity; self.entities_deleted -= 1; } } inline for (@typeInfo(T).Struct.fields) |field| { const FieldT = field.field_type; _ = try @intToPtr(*ComponentStorage(FieldT), self.component_storage_ptrs.items[componentId(FieldT)]).add(entity.id, @field(components, field.name)); } return entity; } /// Create multiple entities with components /// Components are passed as a tuple of slices /// Ex: /// .{ /// @as([]HealthComponent, &healths), /// @as([]PositionComponent, &positions), ///} pub fn createEntities(self: *Self, components: anytype) !void { const T = @TypeOf(components); var i: IdType = 0; while (i < @field(components, @typeInfo(T).Struct.fields[0].name).len) : (i += 1) { self.entities[self.current_entityid + i] = Entity{ .id = self.current_entityid + i, .internal = self.current_entityid + i, }; } // Checks to make sure that all component slices are the same length var components_len = components[0].len; inline for (@typeInfo(T).Struct.fields) |_, j| { if (@field(components, @typeInfo(T).Struct.fields[j].name).len != components_len) return error.InvalidComponents; } inline for (@typeInfo(T).Struct.fields) |field| { const FieldT = @typeInfo(field.field_type).Pointer.child; _ = try @intToPtr(*ComponentStorage(FieldT), self.component_storage_ptrs.items[componentId(FieldT)]).addSlice(self.current_entityid, @field(components, field.name)); } self.current_entityid += @intCast(IdType, @field(components, @typeInfo(T).Struct.fields[0].name).len); } /// Recycles an entity, said entity will no longer be valid pub fn deleteEntity(self: *Self, entity: Entity) !void { if (self.next_recycleid == null) { self.entities[entity.id] = null; self.next_recycleid = entity.id; } else { self.entities[entity.id] = Entity{ .id = self.next_recycleid.?, .internal = entity.id, }; self.next_recycleid = entity.id; } self.entities_deleted += 1; inline for (CompTypes) |T, i| { _ = self.component_storages.getIndexPtr(ComponentStorage(T), i).remove(entity.id) catch null; } } /// Checks if the entity exists in the world /// Not to be confused with if the entity is alive pub fn doesEntityExist(self: *Self, entity: *Entity) bool { if (entity.id <= self.entities.len) return true else return false; } /// Checks if the entity is alive /// An alive entity is an entity that still contains components pub fn isEntityAlive(self: *Self, entity: *Entity) bool { if (self.doesEntityExist(entity) and entity.id == entity.internal) return true else return false; } /// Adds a single component to an entity /// Invalidates pointers to the storage that you are adding to pub fn addComponentToEntity(self: *Self, entity: *Entity, comptime T: type, component: T) !void { var index = self.component_map.getValue(@typeName(T)) orelse return error.ComponentDoesNotExist; _ = try self.component_storages.getIndexPtr(ComponentStorage(T), index).add(entity.id, component); } /// Adds multiple components to an entity /// Components are declared with a struct /// Ex: /// struct { /// health: HealthComponent, /// position: PositionComponent, ///} /// Invalidates pointers to the storages that you are adding to pub fn addComponentsToEntity(self: *Self, entity: *Entity, comptime T: type, components: T) !void { inline for (@typeInfo(T).Struct.fields) |field| { const FieldT = field.field_type; var index = self.component_map.getValue(@typeName(FieldT)) orelse return error.ComponentDoesNotExist; _ = try self.component_storages.getIndexPtr(ComponentStorage(FieldT), index).add(entity.id, @field(components, field.name)); } } /// Removes one component from an entity pub fn removeComponentFromEntity(self: *Self, entity: *Entity, comptime T: type) !void { var index = self.component_map.getValue(@typeName(T)) orelse return error.ComponentDoesNotExist; _ = try self.component_storages.getIndexPtr(ComponentStorage(T), index).remove(entity.id); } //----- Components pub fn registerComponent(self: *Self, comptime Component: type) !void { @panic("TODO"); } /// Queries the world for entities that match the query /// Returns the entities in a AOS fashion /// The returned ArrayList must be user deinitialized /// Example Query: /// struct { /// health: *HealthComponent, /// position: *PositionComponent, /// } pub fn queryAOS(self: *Self, comptime Query: type) !std.ArrayList(Query) { var queries = std.ArrayList(Query).init(self.allocator); outer: for (self.entities) |_, i| { if (self.entities[i] != null) { var entity = self.entities[i].?; if (!self.isEntityAlive(&entity)) continue; var query: Query = undefined; inline for (@typeInfo(Query).Struct.fields) |field| { const FieldT = @typeInfo(field.field_type).Pointer.child; var storage = @intToPtr(*ComponentStorage(FieldT), self.component_storage_ptrs.items[componentId(FieldT)]); if (!storage.has(entity.id)) continue :outer; var comp = try storage.getByEntity(entity.id); @field(query, field.name) = comp; } try queries.append(query); } } return queries; } /// Queries the world for entities that match the query /// Returns the entities in a SOA fashion /// The returned Query must be user freed /// Example Query: /// struct { /// healths: []*HealthComponent, /// positions: []*PositionComponent, /// } pub fn querySOA(self: *Self, comptime Query: type) *Query {} //----- Systems /// Registers a system pub fn registerSystem(self: *Self, system: *System) !void { _ = try self.systems.put(system, {}); } /// Start up the scheduler pub fn run(self: *Self) !void { for (self.systems.items()) |system| { try system.key.run(self); } } //----- Resources. }; fn ComponentStorage(comptime CompType: type) type { return struct { const Self = @This(); allocator: *Allocator, component_id: IdType, dense: std.ArrayList(IdType), dense_len: IdType = 0, sparse: std.ArrayList(IdType), components: std.ArrayList(CompType), pub fn init(allocator: *Allocator, component_id: IdType) !Self { var dense = std.ArrayList(IdType).init(allocator); var sparse = std.ArrayList(IdType).init(allocator); var components = std.ArrayList(CompType).init(allocator); return Self{ .allocator = allocator, .component_id = component_id, .dense = dense, .sparse = sparse, .components = components, }; } pub fn deinit(self: *Self) void { self.components.deinit(); self.dense.deinit(); self.sparse.deinit(); } pub fn len(self: *Self) IdType { return self.dense_len; } pub fn add(self: *Self, entity: IdType, component: CompType) !IdType { if (self.has(entity)) { return error.AlreadyRegistered; } try self.dense.append(entity); try self.components.append(component); try self.sparse.resize(entity + 1); self.sparse.items[entity] = self.dense_len; self.dense_len += 1; return self.dense_len - 1; } pub fn addSlice(self: *Self, entity: IdType, components: []CompType) !void { if (self.has(entity)) { return error.AlreadyRegistered; } try self.sparse.resize(entity + components.len + 1); try self.dense.resize(self.dense_len + components.len); try self.components.resize(self.dense_len + components.len); var i: IdType = 0; while (i < components.len) : (i += 1) { var dense = self.dense_len + i; self.dense.items[dense] = entity + i; self.sparse.items[entity + i] = dense; self.components.items[dense] = components[i]; } self.dense_len += @intCast(IdType, components.len); } pub fn remove(self: *Self, entity: IdType) !CompType { if (!self.has(entity)) { return error.NotRegistered; } self.dense_len -= 1; const last_sparse = self.dense.items[self.dense_len]; const dense = self.sparse.items[entity]; _ = self.dense.swapRemove(dense); self.sparse.items[last_sparse] = dense; return self.components.swapRemove(dense); } pub fn has(self: *Self, entity: IdType) bool { if (entity >= self.sparse.items.len) { return false; } const dense = self.sparse.items[entity]; return dense < self.dense_len and self.dense.items[dense] == entity; } pub fn getByEntity(self: *Self, entity: IdType) !*CompType { if (!self.has(entity)) { return error.NotRegistered; } const dense = self.sparse.items[entity]; return &self.components.items[dense]; } pub fn getByDense(self: *Self, dense: IdType) !*CompType { if (dense >= self.dense_len) { return error.OutOfBounds; } return &self.components.items[dense]; } fn swapIndicesDense(self: *Self, dense1: IdType, dense2: IdType) !void { var tempSparse = elf.sparse.items[self.dense.items[dense1]]; self.sparse.items[self.dense.items[dense1]] = self.sparse.items[self.dense.items[dense2]]; self.sparse.items[self.dense.items[dense2]] = tempSparse; var tempComponent = self.components.items[dense1]; self.components.items[dense1] = self.components.items[dense2]; self.components.items[dense2] = tempComponent; var tempDense = self.dense.items[dense1]; self.dense.items[dense1] = self.dense.items[dense2]; self.dense.items[dense2] = tempDense; } }; } pub const System = struct { runFn: fn (self: *System, world: *World) anyerror!void, pub fn run(self: *System, world: *World) !void { try self.runFn(self, world); } }; }; } /// A Vector Storage that stores any type in a generic non comptime manner /// Stores all entries as their raw bytes /// Uses a hash map as an offset table pub const MultiVecStore = struct { const Self = @This(); allocator: *Allocator, data: []u8, data_len: usize, offset_map: std.AutoHashMap(usize, usize), len: usize, /// Initialize the MultiVecStore pub fn init(allocator: *Allocator) Self { return Self{ .allocator = allocator, .data = &[_]u8{}, .data_len = 0, .offset_map = std.AutoHashMap(usize, usize).init(allocator), .len = 0, }; } /// Initialize the MultiVecStore with a capacity /// The capacity is all types * the capacity pub fn initCapacity(comptime Types: anytype, capacity: usize, allocator: *Allocator) !Self { var len: usize = 0; inline for (Types) |T| { len += @sizeOf(T) * capacity; } return Self{ .allocator = allocator, .data = try allocator.alloc(u8, len), .data_len = len, .offset_map = std.AutoHashMap(usize, usize).init(allocator), .len = capacity * Types.len, }; } pub fn deinit(self: *Self) void { self.allocator.free(self.data); self.offset_map.deinit(); } pub fn append(self: *Self, comptime T: type, data: T) !void { const sizeT = @sizeOf(T); const offset = self.data_len; self.data = try self.allocator.realloc(self.data, offset + sizeT); const dataBytes = mem.toBytes(data); for (dataBytes[0..dataBytes.len]) |b, i| self.data[self.data_len + i] = b; try self.offset_map.putNoClobber(self.len, offset); self.data_len += sizeT; self.len += 1; } pub fn getIndex(self: *const Self, comptime T: type, index: usize) T { assert(index < self.len); const sizeT = @sizeOf(T); const offset = self.offset_map.get(index).?; var dataBytes = self.data[offset .. offset + sizeT]; return mem.bytesToValue(T, @ptrCast(*[sizeT]u8, dataBytes)); } pub fn getIndexPtr(self: *Self, comptime T: type, index: usize) *T { assert(index < self.len); const sizeT = @sizeOf(T); const offset = self.offset_map.get(index).?; var dataBytes = self.data[offset .. offset + sizeT]; return @ptrCast(*T, @alignCast(@alignOf(T), dataBytes)); } pub fn setIndex(self: *Self, comptime T: type, index: usize, data: T) void { assert(index < self.len); const sizeT = @sizeOf(T); const offset = self.offset_map.get(index).?; if (self.offset_map.get(index + 1) != null) { assert(self.offset_map.get(index + 1).? - offset == sizeT); } const dataBytes = mem.toBytes(data); for (dataBytes[0..dataBytes.len]) |b, i| self.data[offset + i] = b; } };
core/src/lib.zig
const std = @import("std"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; const Vm = @import("./vm.zig").Vm; // Zig's allocators operate on slices, the wrapped C library just passes a // length-less pointer into memory. The code in this file prepends a small // metadata block before each allocated chunk of memory to store information // for zig. const MemoryMetadata = struct { slice: []u8, }; // Don't fuss with alignment on this. const MemoryMetadataPtr = *align(1) MemoryMetadata; fn calcAllocSize(requested: usize) usize { return requested + @sizeOf(MemoryMetadata); } fn metadataFromPtr(memory: ?*c_void) MemoryMetadataPtr { return @intToPtr(MemoryMetadataPtr, @ptrToInt(memory) - @sizeOf(MemoryMetadata)); } fn ptrFromMetadataPtr(metadata: MemoryMetadataPtr) [*]u8 { return @intToPtr([*]u8, @ptrToInt(metadata) + @sizeOf(MemoryMetadata)); } /// There are a few possible combinations of parameters. /// • memory = null -> allocation /// • new_size = 0 -> deallocation /// • both != null/0 -> reallocation /// • both = null/0 -> no-op fn wrenReallocate(allocator: *Allocator, memory: ?*c_void, new_size: usize) ?*c_void { // This is apparently valid and described in more detail here: // https://github.com/wren-lang/wren/pull/279 if (memory == null and new_size == 0) { return null; } if (memory == null) { assert(new_size != 0); const begin = allocator.alloc(u8, calcAllocSize(new_size)) catch |e| { return null; }; var meta: MemoryMetadataPtr = @ptrCast(MemoryMetadataPtr, begin); var ptr = ptrFromMetadataPtr(meta); meta.slice.ptr = ptr; meta.slice.len = new_size; return ptr; } var old_meta = metadataFromPtr(memory); var slice: []u8 = undefined; slice.len = calcAllocSize(old_meta.slice.len); slice.ptr = @ptrCast([*]u8, old_meta); const allocSize = if (new_size == 0) 0 else calcAllocSize(new_size); const begin = allocator.realloc(slice, allocSize) catch |e| { return null; }; if (new_size != 0) { var new_meta = @ptrCast(MemoryMetadataPtr, begin); var ptr = ptrFromMetadataPtr(new_meta); new_meta.slice.ptr = ptr; new_meta.slice.len = new_size; return ptr; } return null; } pub fn allocatorWrapper(memory: ?*c_void, new_size: usize, user_data: ?*c_void) callconv(.C) ?*c_void { assert(user_data != null); const zvm = @ptrCast(*Vm, @alignCast(@alignOf(*Vm), user_data)); var allocator = zvm.allocator orelse std.debug.panic("allocatorWrapper must only be installed when an allocator is set", .{}); return wrenReallocate(allocator, memory, new_size); } const test_allocator = std.testing.allocator; test "allocating metadata" { const ptr = wrenReallocate(test_allocator, null, 32); const meta = metadataFromPtr(ptr); std.testing.expect(@ptrToInt(meta.slice.ptr) == @ptrToInt(ptr)); std.testing.expect(meta.slice.len == 32); _ = wrenReallocate(test_allocator, ptr, 0); } test "reallocating with metadata" { const ptr1 = wrenReallocate(test_allocator, null, 32); const ptr2 = wrenReallocate(test_allocator, ptr1, 128); const meta = metadataFromPtr(ptr2); std.testing.expect(@ptrToInt(meta.slice.ptr) == @ptrToInt(ptr2)); std.testing.expect(meta.slice.len == 128); _ = wrenReallocate(test_allocator, ptr2, 0); }
src/zapata/allocator_wrapper.zig
const std = @import("std"); const slf = @import("slf.zig"); const args_parser = @import("args"); pub fn printUsage(stream: anytype) !void { try stream.writeAll( \\slf-objdump [-h] [-i] [-e] [-s] [-r] [-d] [-x] [--raw] <file> \\ \\Prints information about a SLF file. If no option is given, the return code \\will tell if the given <file> is a valid SLF file. \\ \\The tables will always be print in the order imports, exports, relocations, strings, data. \\ \\Options: \\ -h, --help Prints this text. \\ -x, --all Prints all tables. \\ -i, --imports Prints the import table. \\ -e, --exports Prints the export table. \\ -s, --strings Prints the string table with all entries. \\ -r, --relocs Prints the table of relocations. \\ -d, --data Prints the data in "canonical" hex format. \\ --raw Dumps the raw section data to stdout. This option is mutual exclusive to all others. \\ ); } const CliOptions = struct { help: bool = false, imports: bool = false, exports: bool = false, strings: bool = false, relocs: bool = false, data: bool = false, raw: bool = false, all: bool = false, pub const shorthands = .{ .@"h" = "help", .@"i" = "imports", .@"e" = "exports", .@"s" = "strings", .@"r" = "relocs", .@"d" = "data", .@"x" = "all", }; }; pub fn main() !u8 { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var stderr = std.io.getStdErr().writer(); var stdout = std.io.getStdOut().writer(); var cli = args_parser.parseForCurrentProcess(CliOptions, gpa.allocator(), .print) catch return 1; defer cli.deinit(); if (cli.options.help) { try printUsage(stdout); return 0; } if (cli.options.all) { cli.options.data = true; cli.options.imports = true; cli.options.exports = true; cli.options.strings = true; cli.options.relocs = true; } const invalid_combo = cli.options.raw and (cli.options.data or cli.options.imports or cli.options.exports or cli.options.strings or cli.options.relocs); if (invalid_combo) { try stderr.writeAll("--raw and other options are mutually exclusive.\n"); return 1; } if (cli.positionals.len == 0) { try printUsage(stderr); return 1; } var any_previous = false; for (cli.positionals) |file_name| { var arena = std.heap.ArenaAllocator.init(gpa.allocator()); defer arena.deinit(); if (cli.positionals.len > 1) { if (any_previous) try stdout.writeAll("\n"); try stdout.writeAll(file_name); try stdout.writeAll(":\n"); any_previous = true; } const file_data = std.fs.cwd().readFileAlloc(arena.allocator(), file_name, 1 << 30) catch |err| { // 1 GB max. switch (err) { error.FileNotFound => try stderr.print("The file {s} does not exist.\n", .{file_name}), else => |e| return e, } return 1; }; errdefer arena.allocator().free(file_data); const view = slf.View.init(file_data, .{}) catch { try stderr.print("The file {s} does not seem to be a valid SLF file.\n", .{file_name}); return 1; }; if (cli.options.raw) { try stdout.writeAll(view.data()); return 0; } const string_table = view.strings(); if (cli.options.imports) { if (any_previous) try stdout.writeAll("\n"); if (view.imports()) |imports| { if (imports.count > 0) { try stdout.writeAll("Imports:\n"); try printSymbolTable(stdout, string_table, imports); } else { try stdout.writeAll("Empty import table.\n"); } } else { try stdout.writeAll("No import table.\n"); } any_previous = true; } if (cli.options.exports) { if (any_previous) try stdout.writeAll("\n"); if (view.exports()) |exports| { if (exports.count > 0) { try stdout.writeAll("Exports:\n"); try printSymbolTable(stdout, string_table, exports); } else { try stdout.writeAll("Empty export table.\n"); } } else { try stdout.writeAll("No export table.\n"); } any_previous = true; } if (cli.options.relocs) { if (any_previous) try stdout.writeAll("\n"); if (view.relocations()) |relocs| { if (relocs.count > 0) { try stdout.writeAll("Relocations:\n"); var iter = relocs.iterator(); while (iter.next()) |offset| { try stdout.print("- {X:0>8}\n", .{offset}); } } else { try stdout.writeAll("Empty relocation table.\n"); } } else { try stdout.writeAll("No relocation table.\n"); } any_previous = true; } if (cli.options.strings) { if (any_previous) try stdout.writeAll("\n"); if (string_table) |strings| { if (strings.limit > 4) { try stdout.writeAll("Strings:\n"); var iter = strings.iterator(); while (iter.next()) |string| { try stdout.print("- @{X:0>8} => \"{}\"\n", .{ string.offset, std.fmt.fmtSliceEscapeUpper(string.text), }); } } else { try stdout.writeAll("Empty string table.\n"); } } else { try stdout.writeAll("No string table.\n"); } any_previous = true; } if (cli.options.data) { if (any_previous) try stdout.writeAll("\n"); const dataset = view.data(); if (dataset.len > 0) { try stdout.writeAll("Data:\n"); var i: usize = 0; while (i < dataset.len) { const limit = std.math.min(16, dataset.len - i); try stdout.print("{X:0>8} {}\n", .{ i, std.fmt.fmtSliceHexLower(dataset[i..][0..limit]) }); i += limit; } } else { try stdout.writeAll("Empty data set.\n"); } any_previous = true; } } return 0; } fn printSymbolTable(stream: anytype, strings: ?slf.StringTable, table: slf.SymbolTable) !void { var lpad: usize = 0; { var iter = table.iterator(); while (iter.next()) |item| { const len = if (strings) |str| str.get(item.symbol_name).text.len else std.fmt.count("@{X:0>8}", .{item.symbol_name}); lpad = std.math.max(lpad, len); } } { var iter = table.iterator(); while (iter.next()) |item| { var buffer: [64]u8 = undefined; const name = if (strings) |str| @as([]const u8, str.get(item.symbol_name).text) else try std.fmt.bufPrint(&buffer, "@{X:0>8}", .{item.symbol_name}); try stream.writeAll("- "); try stream.writeAll(name); try stream.writeByteNTimes(' ', lpad - name.len); try stream.print(" => {X:0>8}\n", .{item.offset}); } } }
src/objdump.zig
use @import("multiboot.zig"); const tty = @import("tty.zig"); const x86 = @import("x86.zig"); const assert = @import("std").debug.assert; const Color = tty.Color; var stack: [*]usize = undefined; // Stack of free physical page. var stack_index: usize = 0; // Index into the stack. // Boundaries of the frame stack. pub var stack_size: usize = undefined; pub var stack_end: usize = undefined; //// // Return the amount of variable elements (in bytes). // pub fn available() usize { return stack_index * x86.PAGE_SIZE; } //// // Request a free physical page and return its address. // pub fn allocate() usize { if (available() == 0) tty.panic("out of memory"); stack_index -= 1; return stack[stack_index]; } //// // Free a previously allocated physical page. // // Arguments: // address: Address of the page to be freed. // pub fn free(address: usize) void { stack[stack_index] = x86.pageBase(address); stack_index += 1; } //// // Scan the memory map to index all available memory. // // Arguments: // info: Information structure from bootloader. // pub fn initialize(info: *const MultibootInfo) void { tty.step("Indexing Physical Memory"); // Ensure the bootloader has given us the memory map. assert ((info.flags & MULTIBOOT_INFO_MEMORY) != 0); assert ((info.flags & MULTIBOOT_INFO_MEM_MAP) != 0); // Place the stack of free pages after the last Multiboot module. stack = @intToPtr([*]usize, x86.pageAlign(info.lastModuleEnd())); // Calculate the approximate size of the stack based on the amount of total upper memory. stack_size = ((info.mem_upper * 1024) / x86.PAGE_SIZE) * @sizeOf(usize); stack_end = x86.pageAlign(@ptrToInt(stack) + stack_size); var map: usize = info.mmap_addr; while (map < info.mmap_addr + info.mmap_length) { var entry = @intToPtr(*MultibootMMapEntry, map); // Calculate the start and end of this memory area. var start = @truncate(usize, entry.addr); var end = @truncate(usize, start + entry.len); // Anything that comes before the end of the stack of free pages is reserved. start = if (start >= stack_end) start else stack_end; // Flag all the pages in this memory area as free. if (entry.type == MULTIBOOT_MEMORY_AVAILABLE) while (start < end) : (start += x86.PAGE_SIZE) free(start); // Go to the next entry in the memory map. map += entry.size + @sizeOf(@typeOf(entry.size)); } tty.colorPrint(Color.White, " {d} MB", available() / (1024 * 1024)); tty.stepOK(); }
kernel/pmem.zig
const std = @import("std"); const Wasm = @import("Wasm.zig"); const mem = std.mem; const io = std.io; var gpa_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const gpa = gpa_allocator.allocator(); pub fn log( comptime level: std.log.Level, comptime scope: @TypeOf(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { if (@import("build_flags").enable_logging) { std.log.defaultLog(level, scope, format, args); } } const usage = \\Usage: zwld [options] [files...] -o [path] \\ \\Options: \\-h, --help Print this help and exit \\-o [path] Output path of the binary \\--entry <entry> Name of entry point symbol \\--global-base=<value> Value from where the global data will start \\--import-memory Import memory from the host environment \\--import-table Import function table from the host environment \\--initial-memory=<value> Initial size of the linear memory \\--max-memory=<value> Maximum size of the linear memory \\--merge-data-segments[=false] Enable merging data segments (default=true) \\--no-entry Do not output any entry point \\--stack-first Place stack at start of linear memory instead of after data \\--stack-size=<value> Specifies the stack size in bytes ; pub fn main() !void { defer if (@import("builtin").mode == .Debug) { _ = gpa_allocator.deinit(); }; // we use arena for the arguments and its parsing var arena_allocator = std.heap.ArenaAllocator.init(gpa); defer arena_allocator.deinit(); const arena = arena_allocator.allocator(); const process_args = try std.process.argsAlloc(arena); defer std.process.argsFree(arena, process_args); const args = process_args[1..]; // exclude 'zwld' binary if (args.len == 0) { printHelpAndExit(); } var positionals = std.ArrayList([]const u8).init(arena); var entry_name: ?[]const u8 = null; var global_base: ?u32 = 1024; var import_memory: bool = false; var import_table: bool = false; var initial_memory: ?u32 = null; var max_memory: ?u32 = null; var merge_data_segments = true; var no_entry = false; var output_path: ?[]const u8 = null; var stack_first = false; var stack_size: ?u32 = null; var i: usize = 0; while (i < args.len) : (i += 1) { const arg = args[i]; if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) { printHelpAndExit(); } if (mem.eql(u8, arg, "--entry")) { if (i + 1 >= args.len) printErrorAndExit("Missing entry name argument", .{}); entry_name = args[i + 1]; i += 1; continue; } if (mem.startsWith(u8, arg, "--global-base")) { const index = mem.indexOfScalar(u8, arg, '=') orelse printErrorAndExit("Missing '=' symbol and value for global base", .{}); global_base = std.fmt.parseInt(u32, arg[index + 1 ..], 10) catch printErrorAndExit( "Could not parse value '{s}' into integer", .{arg[index + 1 ..]}, ); continue; } if (mem.eql(u8, arg, "--import-memory")) { import_memory = true; continue; } if (mem.eql(u8, arg, "--import-table")) { import_table = true; continue; } if (mem.startsWith(u8, arg, "--initial-memory")) { const index = mem.indexOfScalar(u8, arg, '=') orelse printErrorAndExit("Missing '=' symbol and value for initial memory", .{}); initial_memory = std.fmt.parseInt(u32, arg[index + 1 ..], 10) catch printErrorAndExit( "Could not parse value '{s}' into integer", .{arg[index + 1 ..]}, ); continue; } if (mem.startsWith(u8, arg, "--max-memory")) { const index = mem.indexOfScalar(u8, arg, '=') orelse printErrorAndExit("Missing '=' symbol and value for max memory", .{}); max_memory = std.fmt.parseInt(u32, arg[index + 1 ..], 10) catch printErrorAndExit( "Could not parse value '{s}' into integer", .{arg[index + 1 ..]}, ); continue; } if (mem.startsWith(u8, arg, "--merge-data-segments")) { merge_data_segments = true; if (mem.indexOfScalar(u8, arg, '=')) |index| { if (mem.eql(u8, arg[index + 1 ..], "false")) { merge_data_segments = false; } } continue; } if (mem.eql(u8, arg, "--no-entry")) { no_entry = true; continue; } if (mem.eql(u8, arg, "--stack-first")) { stack_first = true; continue; } if (mem.startsWith(u8, arg, "--stack-size")) { const index = mem.indexOfScalar(u8, arg, '=') orelse printErrorAndExit("Missing '=' symbol and value for stack size", .{}); stack_size = std.fmt.parseInt(u32, arg[index + 1 ..], 10) catch printErrorAndExit( "Could not parse value '{s}' into integer", .{arg[index + 1 ..]}, ); continue; } if (mem.eql(u8, arg, "-o")) { if (i + 1 >= args.len) printErrorAndExit("Missing output file argument", .{}); output_path = args[i + 1]; i += 1; continue; } if (mem.startsWith(u8, arg, "--")) { printErrorAndExit("Unknown argument '{s}'", .{arg}); } try positionals.append(arg); } if (positionals.items.len == 0) { printErrorAndExit("Expected one or more object files, none were given", .{}); } if (output_path == null) { printErrorAndExit("Missing output path", .{}); } var wasm_bin = try Wasm.openPath(output_path.?, .{ .entry_name = entry_name, .global_base = global_base, .import_memory = import_memory, .import_table = import_table, .initial_memory = initial_memory, .max_memory = max_memory, .merge_data_segments = merge_data_segments, .no_entry = no_entry, .stack_first = stack_first, .stack_size = stack_size, }); defer wasm_bin.deinit(gpa); try wasm_bin.addObjects(gpa, positionals.items); try wasm_bin.flush(gpa); } fn printHelpAndExit() noreturn { io.getStdOut().writer().print("{s}\n", .{usage}) catch {}; std.process.exit(0); } fn printErrorAndExit(comptime fmt: []const u8, args: anytype) noreturn { const writer = io.getStdErr().writer(); writer.print(fmt, args) catch {}; writer.writeByte('\n') catch {}; std.process.exit(1); }
src/main.zig
const std = @import("std"); const builtin = @import("builtin"); const stdx = @import("stdx"); const t = stdx.testing; const log = stdx.log.scoped(.platform); const sdl = @import("sdl"); const input_sdl = @import("input_sdl.zig"); pub const initSdlKeyDownEvent = input_sdl.initKeyDownEvent; pub const initSdlKeyUpEvent = input_sdl.initKeyUpEvent; pub const initSdlMouseDownEvent = input_sdl.initMouseDownEvent; pub const initSdlMouseUpEvent = input_sdl.initMouseUpEvent; pub const initSdlMouseMoveEvent = input_sdl.initMouseMoveEvent; pub const initSdlMouseScrollEvent = input_sdl.initMouseScrollEvent; const input_web = @import("input_web.zig"); pub const webToCanonicalKeyCode = input_web.toCanonicalKeyCode; const mouse = @import("mouse.zig"); pub const MouseButton = mouse.MouseButton; pub const MouseUpEvent = mouse.MouseUpEvent; pub const MouseDownEvent = mouse.MouseDownEvent; pub const MouseMoveEvent = mouse.MouseMoveEvent; pub const MouseScrollEvent = mouse.MouseScrollEvent; const keyboard = @import("keyboard.zig"); pub const KeyDownEvent = keyboard.KeyDownEvent; pub const KeyUpEvent = keyboard.KeyUpEvent; pub const KeyCode = keyboard.KeyCode; const event_dispatcher = @import("event_dispatcher.zig"); pub const EventDispatcher = event_dispatcher.EventDispatcher; pub const EventResult = event_dispatcher.EventResult; pub fn delay(us: u64) void { if (!builtin.target.isWasm()) { // TODO: How does this compare to std.time.sleep ? // std.time.sleep(us * 1000); sdl.SDL_Delay(@intCast(u32, us / 1000)); } else { // There isn't a good sleep mechanism in js since it's run on event loop. // stdx.time.sleep(self.target_ms_per_frame - render_time_ms); } } pub fn captureMouse(capture: bool) void { if (!builtin.target.isWasm()) { _ = sdl.SDL_CaptureMouse(@boolToInt(capture)); } else { } } pub const window_sdl = @import("window_sdl.zig"); const window = @import("window.zig"); pub const Window = window.Window; pub const quit = window.quit; pub const WindowResizeEvent = struct { const Self = @This(); width: u16, height: u16, pub fn init(width: u16, height: u16) Self { return .{ .width = width, .height = height, }; } }; pub const FetchResultEvent = struct { fetch_id: u32, buf: []const u8, };
platform/platform.zig
const std = @import("std"); const builtin = @import("builtin"); const IsWasm = builtin.target.isWasm(); const stdx = @import("stdx"); const platform = @import("platform"); const MouseUpEvent = platform.MouseUpEvent; const graphics = @import("graphics"); const Color = graphics.Color; const ui = @import("ui"); const Row = ui.widgets.Row; const Column = ui.widgets.Column; const Text = ui.widgets.Text; const TextButton = ui.widgets.TextButton; const TextField = ui.widgets.TextField; const Flex = ui.widgets.Flex; const Padding = ui.widgets.Padding; const Center = ui.widgets.Center; const Sized = ui.widgets.Sized; const ScrollList = ui.widgets.ScrollList; const helper = @import("helper.zig"); const log = stdx.log.scoped(.main); pub const App = struct { buf: std.ArrayList([]const u8), alloc: std.mem.Allocator, filter: []const u8, list: ui.WidgetRef(ScrollList), first_tf: ui.WidgetRef(TextField), last_tf: ui.WidgetRef(TextField), const Self = @This(); pub fn init(self: *Self, c: *ui.InitContext) void { self.buf = std.ArrayList([]const u8).init(c.alloc); self.alloc = c.alloc; self.filter = ""; } pub fn deinit(node: *ui.Node, _: std.mem.Allocator) void { const self = node.getWidget(Self); for (self.buf.items) |str| { self.alloc.free(str); } self.alloc.free(self.filter); self.buf.deinit(); } pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId { const S = struct { fn onClickCreate(self_: *Self, _: MouseUpEvent) void { const first_w = self_.first_tf.getWidget(); const last_w = self_.last_tf.getWidget(); const first = if (first_w.getValue().len == 0) "Foo" else first_w.getValue(); const last = if (last_w.getValue().len == 0) "Bar" else last_w.getValue(); const new_name = std.fmt.allocPrint(self_.alloc, "{s}, {s}", .{ first, last }) catch unreachable; self_.buf.append(new_name) catch unreachable; } fn onClickDelete(self_: *Self, _: MouseUpEvent) void { const selected_idx = self_.list.getWidget().getSelectedIdx(); if (selected_idx != ui.NullId) { self_.alloc.free(self_.buf.items[selected_idx]); _ = self_.buf.orderedRemove(selected_idx); } } fn onClickUpdate(self_: *Self, _: MouseUpEvent) void { const first_w = self_.first_tf.getWidget(); const last_w = self_.last_tf.getWidget(); const selected_idx = self_.list.getWidget().getSelectedIdx(); if (selected_idx != ui.NullId) { const first = if (first_w.getValue().len == 0) "Foo" else first_w.getValue(); const last = if (last_w.getValue().len == 0) "Bar" else last_w.getValue(); const new_name = std.fmt.allocPrint(self_.alloc, "{s}, {s}", .{ first, last }) catch unreachable; self_.alloc.free(self_.buf.items[selected_idx]); self_.buf.items[selected_idx] = new_name; } } fn onChangeSearch(self_: *Self, val: []const u8) void { self_.alloc.free(self_.filter); self_.filter = self_.alloc.dupe(u8, val) catch unreachable; } fn buildItem(self_: *Self, c_: *ui.BuildContext, i: u32) ui.FrameId { if (std.mem.startsWith(u8, self_.buf.items[i], self_.filter)) { return c_.decl(Text, .{ .text = self_.buf.items[i] }); } else { return ui.NullFrameId; } } }; const d = c.decl; const left_side = d(Column, .{ .children = c.list(.{ d(Flex, .{ .child = d(Sized, .{ .width = 300, .child = d(ScrollList, .{ .bind = &self.list, .children = c.range(self.buf.items.len, self, S.buildItem), }), }), }), }), }); const right_side = d(Column, .{ .spacing = 20, .children = c.list(.{ d(Row, .{ .children = c.list(.{ d(Padding, .{ .child = d(Text, .{ .text = "First: ", .color = Color.White }), }), d(Flex, .{ .child = d(TextField, .{ .bind = &self.first_tf, }), }), }), }), d(Row, .{ .children = c.list(.{ d(Padding, .{ .child = d(Text, .{ .text = "Last: ", .color = Color.White }), }), d(Flex, .{ .child = d(TextField, .{ .bind = &self.last_tf, }), }), }), }), d(Row, .{ .spacing = 10, .children = c.list(.{ d(Flex, .{ .child = d(TextButton, .{ .text = "Create", .corner_radius = 10, .onClick = c.funcExt(self, S.onClickCreate), }), }), d(Flex, .{ .child = d(TextButton, .{ .text = "Update", .corner_radius = 10, .onClick = c.funcExt(self, S.onClickUpdate), }), }), d(Flex, .{ .child = d(TextButton, .{ .text = "Delete", .corner_radius = 10, .onClick = c.funcExt(self, S.onClickDelete), }), }), }), }), }) }); return d(Center, .{ .child = d(Sized, .{ .width = 600, .height = 500, .child = d(Column, .{ .expand = false, .children = c.list(.{ d(Padding, .{ .padding = 0, .pad_bottom = 20, .child = d(Row, .{ .children = c.list(.{ d(Padding, .{ .padding = 10, .child = d(Text, .{ .text = c.fmt("Search: ({} Entries)", .{self.buf.items.len}), .color = Color.White, }), }), d(Flex, .{ .child = d(TextField, .{ .onChangeEnd = c.funcExt(self, S.onChangeSearch), }), }) }), }), }), d(Row, .{ .spacing = 10, .children = c.list(.{ left_side, right_side, }), }), }), }), }), }); } }; var app: helper.App = undefined; pub fn main() !void { // This is the app loop for desktop. For web/wasm see wasm exports below. app.init("CRUD"); defer app.deinit(); app.runEventLoop(update); } fn update(delta_ms: f32) void { const S = struct { fn buildRoot(_: void, c: *ui.BuildContext) ui.FrameId { return c.decl(App, .{}); } }; const ui_width = @intToFloat(f32, app.win.getWidth()); const ui_height = @intToFloat(f32, app.win.getHeight()); app.ui_mod.updateAndRender(delta_ms, {}, S.buildRoot, ui_width, ui_height) catch unreachable; } pub usingnamespace if (IsWasm) struct { export fn wasmInit() *const u8 { return helper.wasmInit(&app, "CRUD"); } export fn wasmUpdate(cur_time_ms: f64, input_buffer_len: u32) *const u8 { return helper.wasmUpdate(cur_time_ms, input_buffer_len, &app, update); } /// Not that useful since it's a long lived process in the browser. export fn wasmDeinit() void { app.deinit(); stdx.wasm.deinit(); } } else struct {};
ui/examples/crud.zig
const root = @import("root"); const BIOS = @import("bios.zig").BIOS; pub const GBA = struct { pub const VRAM = @intToPtr([*]align(2) volatile u16, 0x06000000); pub const SPRITE_VRAM = @intToPtr([*]align(2) volatile u16, 0x06010000); pub const BG_PALETTE_RAM = @intToPtr([*]align(2) volatile u16, 0x05000000); pub const OBJ_PALETTE_RAM = @intToPtr([*]align(2) volatile u16, 0x05000200); pub const EWRAM = @intToPtr([*]volatile u8, 0x02000000); pub const IWRAM = @intToPtr([*]volatile u8, 0x03000000); pub const OAM = @intToPtr([*]volatile u16, 0x07000000); pub const MEM_IO = @intToPtr(*volatile u32, 0x04000000); pub const REG_DISPCNT = @intToPtr(*volatile u16, @ptrToInt(MEM_IO) + 0x0000); pub const REG_DISPSTAT = @intToPtr(*volatile u16, @ptrToInt(MEM_IO) + 0x0004); pub const REG_VCOUNT = @intToPtr(*volatile u16, @ptrToInt(MEM_IO) + 0x0006); pub const REG_KEYINPUT = @intToPtr(*volatile u16, @ptrToInt(MEM_IO) + 0x0130); pub const REG_IE = @intToPtr(*volatile u16, @ptrToInt(MEM_IO) + 0x0200); pub const REG_IF = @intToPtr(*volatile u16, @ptrToInt(MEM_IO) + 0x0202); pub const REG_IME = @intToPtr(*volatile u16, @ptrToInt(MEM_IO) + 0x0208); pub const REG_ISR_MAIN = @intToPtr(*volatile fn() callconv(.Naked) void, 0x03007FFC); pub const REG_IF_BIOS = @intToPtr(*volatile u16, 0x3007FF8); pub const DSTAT_VBL_IRQ = 0x0008; pub const INT_VBLANK = 0x0001; pub const MODE4_FRONT_VRAM = VRAM; pub const MODE4_BACK_VRAM = @intToPtr([*]align(2) volatile u16, 0x0600A000); pub const SCREEN_WIDTH = 240; pub const SCREEN_HEIGHT = 160; pub const MODE3_SCREEN_SIZE = 75 * 1024; pub const MODE4_SCREEN_SIZE = 0x9600; pub const MODE5_SCREEN_SIZE = 40 * 1024; pub const PaletteBank = [16]u16; pub const PaletteMode = enum(u1) { Color16, Color256, }; pub const InterruptFlags = packed struct { vblank: bool = false, hblank: bool = false, vcounter: bool = false, timer0: bool = false, timer1: bool = false, timer2: bool = false, timer3: bool = false, serial: bool = false, dma0: bool = false, dma1: bool = false, dma2: bool = false, dma3: bool = false, keypad: bool = false, gamepak: bool = false, }; pub const Header = packed struct { romEntryPoint: u32, nintendoLogo: [156]u8, gameName: [12]u8, gameCode: [4]u8, makerCode: [2]u8, fixedValue: u8, mainUnitCode: u8, deviceType: u8, reservedArea: [7]u8, softwareVersion: u8, complementCheck: u8, reservedArea2: [2]u8, pub fn setup(comptime gameName: []const u8, comptime gameCode: []const u8, comptime makerCode: ?[]const u8, comptime softwareVersion: ?u8) Header { var header = Header{ .romEntryPoint = 0xEA00002E, .nintendoLogo = .{ 0x24, 0xFF, 0xAE, 0x51, 0x69, 0x9A, 0xA2, 0x21, 0x3D, 0x84, 0x82, 0x0A, 0x84, 0xE4, 0x09, 0xAD, 0x11, 0x24, 0x8B, 0x98, 0xC0, 0x81, 0x7F, 0x21, 0xA3, 0x52, 0xBE, 0x19, 0x93, 0x09, 0xCE, 0x20, 0x10, 0x46, 0x4A, 0x4A, 0xF8, 0x27, 0x31, 0xEC, 0x58, 0xC7, 0xE8, 0x33, 0x82, 0xE3, 0xCE, 0xBF, 0x85, 0xF4, 0xDF, 0x94, 0xCE, 0x4B, 0x09, 0xC1, 0x94, 0x56, 0x8A, 0xC0, 0x13, 0x72, 0xA7, 0xFC, 0x9F, 0x84, 0x4D, 0x73, 0xA3, 0xCA, 0x9A, 0x61, 0x58, 0x97, 0xA3, 0x27, 0xFC, 0x03, 0x98, 0x76, 0x23, 0x1D, 0xC7, 0x61, 0x03, 0x04, 0xAE, 0x56, 0xBF, 0x38, 0x84, 0x00, 0x40, 0xA7, 0x0E, 0xFD, 0xFF, 0x52, 0xFE, 0x03, 0x6F, 0x95, 0x30, 0xF1, 0x97, 0xFB, 0xC0, 0x85, 0x60, 0xD6, 0x80, 0x25, 0xA9, 0x63, 0xBE, 0x03, 0x01, 0x4E, 0x38, 0xE2, 0xF9, 0xA2, 0x34, 0xFF, 0xBB, 0x3E, 0x03, 0x44, 0x78, 0x00, 0x90, 0xCB, 0x88, 0x11, 0x3A, 0x94, 0x65, 0xC0, 0x7C, 0x63, 0x87, 0xF0, 0x3C, 0xAF, 0xD6, 0x25, 0xE4, 0x8B, 0x38, 0x0A, 0xAC, 0x72, 0x21, 0xD4, 0xF8, 0x07, }, .gameName = [_]u8{0} ** 12, .gameCode = [_]u8{0} ** 4, .makerCode = [_]u8{0} ** 2, .fixedValue = 0x96, .mainUnitCode = 0x00, .deviceType = 0x00, .reservedArea = [_]u8{0} ** 7, .softwareVersion = 0x00, .complementCheck = 0x00, .reservedArea2 = [_]u8{0} ** 2, }; comptime { const isUpper = @import("std").ascii.isUpper; const isDigit = @import("std").ascii.isDigit; for (gameName) |value, index| { var validChar = isUpper(value) or isDigit(value); if (validChar and index < 12) { header.gameName[index] = value; } else { if (index >= 12) { @compileError("Game name is too long, it needs to be no longer than 12 characters."); } else if (!validChar) { @compileError("Game name needs to be in uppercase, it can use digits."); } } } for (gameCode) |value, index| { var validChar = isUpper(value); if (validChar and index < 4) { header.gameCode[index] = value; } else { if (index >= 4) { @compileError("Game code is too long, it needs to be no longer than 4 characters."); } else if (!validChar) { @compileError("Game code needs to be in uppercase."); } } } if (makerCode) |mCode| { for (mCode) |value, index| { var validChar = isDigit(value); if (validChar and index < 2) { header.makerCode[index] = value; } else { if (index >= 2) { @compileError("Maker code is too long, it needs to be no longer than 2 characters."); } else if (!validChar) { @compileError("Maker code needs to be digits."); } } } } header.softwareVersion = softwareVersion orelse 0; var complementCheck: u8 = 0; var index: usize = 0xA0; var computeCheckData = @bitCast([192]u8, header); while (index < 0xA0 + (0xBD - 0xA0)) : (index += 1) { complementCheck +%= computeCheckData[index]; } var tempCheck = -(0x19 + @intCast(i32, complementCheck)); header.complementCheck = @intCast(u8, tempCheck & 0xFF); } return header; } }; pub fn toNativeColor(red: u8, green: u8, blue: u8) callconv(.Inline) u16 { return @as(u16, red & 0x1f) | (@as(u16, green & 0x1f) << 5) | (@as(u16, blue & 0x1f) << 10); } // TODO: maybe put this in IWRAM ? pub fn memcpy32(noalias destination: anytype, noalias source: anytype, count: usize) void { if (count < 4) { genericMemcpy(@ptrCast([*]u8, destination), @ptrCast([*]const u8, source), count); } else { if ((@ptrToInt(@ptrCast(*u8, destination)) % 4) == 0 and (@ptrToInt(@ptrCast(*const u8, source)) % 4) == 0) { alignedMemcpy(u32, @ptrCast([*]align(4) volatile u8, @alignCast(4, destination)), @ptrCast([*]align(4) const u8, @alignCast(4, source)), count); } else if ((@ptrToInt(@ptrCast(*u8, destination)) % 2) == 0 and (@ptrToInt(@ptrCast(*const u8, source)) % 2) == 0) { alignedMemcpy(u16, @ptrCast([*]align(2) volatile u8, @alignCast(2, destination)), @ptrCast([*]align(2) const u8, @alignCast(2, source)), count); } else { genericMemcpy(@ptrCast([*]volatile u8, destination), @ptrCast([*]const u8, source), count); } } } pub fn memcpy16(noalias destination: anytype, noalias source: anytype, count: usize) void { if (count < 2) { genericMemcpy(@ptrCast([*]u8, destination), @ptrCast([*]const u8, source), count); } else { if ((@ptrToInt(@ptrCast(*u8, destination)) % 2) == 0 and (@ptrToInt(@ptrCast(*const u8, source)) % 2) == 0) { alignedMemcpy(u16, @ptrCast([*]align(2) volatile u8, @alignCast(2, destination)), @ptrCast([*]align(2) const u8, @alignCast(2, source)), count); } else { genericMemcpy(@ptrCast([*]volatile u8, destination), @ptrCast([*]const u8, source), count); } } } pub fn alignedMemcpy(comptime T: type, noalias destination: [*]align(@alignOf(T)) volatile u8, noalias source: [*]align(@alignOf(T)) const u8, count: usize) void { @setRuntimeSafety(false); const alignSize = count / @sizeOf(T); const remainderSize = count % @sizeOf(T); const alignDestination = @ptrCast([*]volatile T, destination); const alignSource = @ptrCast([*]const T, source); var index: usize = 0; while (index != alignSize) : (index += 1) { alignDestination[index] = alignSource[index]; } index = count - remainderSize; while (index != count) : (index += 1) { destination[index] = source[index]; } } pub fn genericMemcpy(noalias destination: [*]volatile u8, noalias source: [*]const u8, count: usize) void { @setRuntimeSafety(false); var index: usize = 0; while (index != count) : (index += 1) { destination[index] = source[index]; } } // TODO: maybe put it in IWRAM ? pub fn memset32(destination: anytype, value: u32, count: usize) void { if ((@ptrToInt(@ptrCast(*u8, destination)) % 4) == 0) { alignedMemset(u32, @ptrCast([*]align(4) volatile u8, @alignCast(4, destination)), value, count); } else { genericMemset(u32, @ptrCast([*]volatile u8, destination), value, count); } } pub fn memset16(destination: anytype, value: u16, count: usize) void { if ((@ptrToInt(@ptrCast(*u8, destination)) % 4) == 0) { alignedMemset(u16, @ptrCast([*]align(2) volatile u8, @alignCast(2, destination)), value, count); } else { genericMemset(u16, @ptrCast([*]volatile u8, destination), value, count); } } pub fn alignedMemset(comptime T: type, destination: [*]align(@alignOf(T)) volatile u8, value: T, count: usize) void { @setRuntimeSafety(false); const alignedDestination = @ptrCast([*]volatile T, destination); var index: usize = 0; while (index != count) : (index += 1) { alignedDestination[index] = value; } } pub fn genericMemset(comptime T: type, destination: [*]volatile u8, value: T, count: usize) void { @setRuntimeSafety(false); const valueBytes = @ptrCast([*]const u8, &value); var index: usize = 0; while (index != count) : (index += 1) { comptime var expandIndex = 0; inline while (expandIndex < @sizeOf(T)) : (expandIndex += 1) { destination[(index * @sizeOf(T)) + expandIndex] = valueBytes[expandIndex]; } } } pub fn registerVBlankISR() void { GBA.REG_IME.* = 0x00; GBA.REG_ISR_MAIN.* = interruptHandler; GBA.REG_DISPSTAT.* |= GBA.DSTAT_VBL_IRQ; GBA.REG_IE.* |= GBA.INT_VBLANK; GBA.REG_IME.* = 0x01; } fn interruptHandler() callconv(.Naked) void { // interrupt handler will be called in arm mode so we need to switch to thumb mode asm volatile ( \\.arm \\.cpu arm7tdmi \\adr r0, thumb_handler+1 \\bx r0 \\thumb_handler: ); var ie: u16 = GBA.REG_IE.*; var ieif: u16 = ie & GBA.REG_IF.*; GBA.REG_IF.* = ieif; GBA.REG_IF_BIOS.* |= ieif; } }; export fn GBAMain() linksection(".gbamain") callconv(.Naked) noreturn { // Assembly init code asm volatile ( \\.arm \\.cpu arm7tdmi \\mov r0, #0x4000000 \\str r0, [r0, #0x208] \\ \\mov r0, #0x12 \\msr cpsr, r0 \\ldr sp, =__sp_irq \\mov r0, #0x1f \\msr cpsr, r0 \\ldr sp, =__sp_usr \\add r0, pc, #1 \\bx r0 ); GBAZigStartup(); } extern var __bss_lma: u8; extern var __bss_start__: u8; extern var __bss_end__: u8; extern var __data_lma: u8; extern var __data_start__: u8; extern var __data_end__: u8; fn GBAZigStartup() noreturn { // Use BIOS function to clear all data BIOS.registerRamReset(BIOS.RamResetFlags.All); // Clear .bss GBA.memset32(@ptrCast([*]volatile u8, &__bss_start__), 0, @ptrToInt(&__bss_end__) - @ptrToInt(&__bss_start__)); // Copy .data section to EWRAM GBA.memcpy32(@ptrCast([*]volatile u8, &__data_start__), @ptrCast([*]const u8, &__data_lma), @ptrToInt(&__data_end__) - @ptrToInt(&__data_start__)); GBA.registerVBlankISR(); // call user's main if (@hasDecl(root, "main")) { root.main(); } else { while (true) {} } }
GBA/core.zig
const std = @import("std"); const Context = @import("context.zig").Context; const SourceLocation = @import("context.zig").SourceLocation; const SourceRange = @import("context.zig").SourceRange; const fail = @import("fail.zig").fail; pub const TokenType = union(enum) { illegal, end_of_file, name, number: f32, enum_value, sym_asterisk, sym_colon, sym_comma, sym_equals, sym_left_paren, sym_minus, sym_plus, sym_right_paren, sym_slash, kw_begin, kw_defcurve, kw_defmodule, kw_deftrack, kw_delay, kw_end, kw_false, kw_feedback, kw_from, kw_out, kw_true, }; pub const Token = struct { source_range: SourceRange, tt: TokenType, }; pub const Tokenizer = struct { ctx: Context, loc: SourceLocation, pub fn init(ctx: Context) Tokenizer { return .{ .ctx = ctx, .loc = .{ .line = 0, .index = 0 }, }; } fn makeToken(loc0: SourceLocation, loc1: SourceLocation, tt: TokenType) Token { return .{ .source_range = .{ .loc0 = loc0, .loc1 = loc1 }, .tt = tt, }; } pub fn next(self: *Tokenizer) !Token { const src = self.ctx.source.contents; var loc = self.loc; defer self.loc = loc; while (true) { while (loc.index < src.len and isWhitespace(src[loc.index])) { if (src[loc.index] == '\r') { loc.index += 1; if (loc.index == src.len or src[loc.index] != '\n') { loc.line += 1; continue; } } if (src[loc.index] == '\n') { loc.line += 1; } loc.index += 1; } if (loc.index + 2 < src.len and src[loc.index] == '/' and src[loc.index + 1] == '/') { while (loc.index < src.len and src[loc.index] != '\r' and src[loc.index] != '\n') { loc.index += 1; } continue; } if (loc.index == src.len) { return makeToken(loc, loc, .end_of_file); } const start = loc; inline for (@typeInfo(TokenType).Union.fields) |field| { if (comptime std.mem.startsWith(u8, field.name, "sym_")) { const tt = @unionInit(TokenType, field.name, {}); const symbol_string = getSymbolString(tt); if (std.mem.startsWith(u8, src[loc.index..], symbol_string)) { loc.index += symbol_string.len; return makeToken(start, loc, tt); } } } if (src[loc.index] == '.') { loc.index += 1; const start2 = loc; if (loc.index == src.len or !isValidNameHeadChar(src[loc.index])) { const sr: SourceRange = .{ .loc0 = start, .loc1 = start2 }; return fail(self.ctx, sr, "dot must be followed by an identifier", .{}); } loc.index += 1; while (loc.index < src.len and isValidNameTailChar(src[loc.index])) { loc.index += 1; } return makeToken(start2, loc, .enum_value); } if (getNumber(src[loc.index..])) |len| { loc.index += len; const n = std.fmt.parseFloat(f32, src[start.index..loc.index]) catch { const sr: SourceRange = .{ .loc0 = start, .loc1 = loc }; return fail(self.ctx, sr, "malformatted number", .{}); }; return makeToken(start, loc, .{ .number = n }); } if (isValidNameHeadChar(src[loc.index])) { loc.index += 1; while (loc.index < src.len and isValidNameTailChar(src[loc.index])) { loc.index += 1; } const string = src[start.index..loc.index]; inline for (@typeInfo(TokenType).Union.fields) |field| { if (comptime std.mem.startsWith(u8, field.name, "kw_")) { const tt = @unionInit(TokenType, field.name, {}); if (std.mem.eql(u8, string, getKeywordString(tt))) { return makeToken(start, loc, tt); } } } return makeToken(start, loc, .name); } loc.index += 1; return makeToken(start, loc, .illegal); } } pub fn peek(self: *Tokenizer) !Token { const loc = self.loc; defer self.loc = loc; return try self.next(); } pub fn failExpected(self: *Tokenizer, desc: []const u8, found: Token) error{Failed} { if (found.tt == .end_of_file) { return fail(self.ctx, found.source_range, "expected #, found end of file", .{desc}); } else { return fail(self.ctx, found.source_range, "expected #, found `<`", .{desc}); } } // use this for requiring the next token to be a specific symbol or keyword pub fn expectNext(self: *Tokenizer, tt: var) !void { const token = try self.next(); if (token.tt == tt) return; const desc = if (comptime std.mem.startsWith(u8, @tagName(tt), "sym_")) "`" ++ getSymbolString(tt) ++ "`" else if (comptime std.mem.startsWith(u8, @tagName(tt), "kw_")) "`" ++ getKeywordString(tt) ++ "`" else unreachable; return self.failExpected(desc, token); } }; inline fn isWhitespace(ch: u8) bool { return ch == ' ' or ch == '\t' or ch == '\r' or ch == '\n'; } // leading underscore is not allowed inline fn isValidNameHeadChar(ch: u8) bool { return (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z'); } inline fn isValidNameTailChar(ch: u8) bool { return (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z') or (ch >= '0' and ch <= '9') or ch == '_'; } fn getNumber(string: []const u8) ?usize { if (string[0] >= '0' and string[0] <= '9') { var i: usize = 1; while (i < string.len and ((string[i] >= '0' and string[i] <= '9') or string[i] == '.')) { i += 1; } return i; } return null; } fn getSymbolString(tt: TokenType) []const u8 { switch (tt) { .sym_asterisk => return "*", .sym_colon => return ":", .sym_comma => return ",", .sym_equals => return "=", .sym_left_paren => return "(", .sym_minus => return "-", .sym_plus => return "+", .sym_right_paren => return ")", .sym_slash => return "/", else => unreachable, } } fn getKeywordString(tt: TokenType) []const u8 { switch (tt) { .kw_begin => return "begin", .kw_defcurve => return "defcurve", .kw_defmodule => return "defmodule", .kw_deftrack => return "deftrack", .kw_delay => return "delay", .kw_end => return "end", .kw_false => return "false", .kw_feedback => return "feedback", .kw_from => return "from", .kw_out => return "out", .kw_true => return "true", else => unreachable, } }
src/zangscript/tokenize.zig
const std = @import("std"); const OpCode = @import("chunk.zig").OpCode; const Chunk = @import("chunk.zig").Chunk; const Stack = @import("stack.zig").Stack; const value = @import("value.zig"); pub const trace_execution = true; pub const print_code = true; fn simpleInstruction(writer: anytype, offset: usize, name: []const u8) !usize { try writer.print("{:<16}\n", .{name}); return offset + 1; } fn constantInstruction(writer: anytype, chunk: *const Chunk, offset: usize, name: []const u8) !usize { const index = chunk.code.items[offset + 1]; try writer.print("{:<16} {x:0>2} '{}'\n", .{ name, index, chunk.constants.items[index] }); return offset + 2; } fn byteInstruction(writer: anytype, chunk: *const Chunk, offset: usize, name: []const u8) !usize { const slot = chunk.code.items[offset + 1]; try writer.print("{:<16} {x:0>2}\n", .{ name, slot }); return offset + 2; } fn jumpInstruction(writer: anytype, chunk: *const Chunk, offset: usize, sign: isize, name: []const u8) !usize { var jump: u16 = @as(u16, chunk.code.items[offset + 1]) << 8; jump |= chunk.code.items[offset + 2]; try writer.print("{:<16} {x:0>4} -> {x:0>4}\n", .{ name, jump, @intCast(usize, @intCast(isize, offset) + 3 + sign * @as(isize, jump)) }); return offset + 3; } pub fn disassembleInstruction(writer: anytype, chunk: *const Chunk, offset: usize, detail: bool) !usize { const op: OpCode = @intToEnum(OpCode, chunk.code.items[offset]); switch (op) { .return_ => return try simpleInstruction(writer, offset, "OP_RETURN"), .call => return try byteInstruction(writer, chunk, offset, "OP_CALL"), .closure => { var result = offset + 1; const constant = chunk.code.items[result]; result += 1; try writer.print("{:<16} {x:0>4} '{}'\n", .{ "OP_CLOSURE", constant, chunk.constants.items[constant], }); if (detail) { var func = chunk.constants.items[constant].cast(*value.Function).?; var i: usize = 0; while (i < func.upvalue_count) : (i += 1) { var is_local = chunk.code.items[result] != 0; result += 1; var index = chunk.code.items[result]; result += 1; var kind: []const u8 = if (is_local) "local" else "upvalue"; try writer.print("{x:0>4} | {s} {}\n", .{ result - 2, kind, index, }); } } return result; }, .pop => return try simpleInstruction(writer, offset, "OP_POP"), .close_upvalue => return try simpleInstruction(writer, offset, "OP_CLOSE_UPVALUE"), .constant => return try constantInstruction(writer, chunk, offset, "OP_CONSTANT"), .print => return try simpleInstruction(writer, offset, "OP_PRINT"), .negate => return try simpleInstruction(writer, offset, "OP_NEGATE"), .add => return try simpleInstruction(writer, offset, "OP_ADD"), .subtract => return try simpleInstruction(writer, offset, "OP_SUBTRACT"), .multiply => return try simpleInstruction(writer, offset, "OP_MULTIPLY"), .divide => return try simpleInstruction(writer, offset, "OP_DIVIDE"), .false_ => return try simpleInstruction(writer, offset, "OP_FALSE"), .true_ => return try simpleInstruction(writer, offset, "OP_TRUE"), .nil => return try simpleInstruction(writer, offset, "OP_NIL"), .not => return try simpleInstruction(writer, offset, "OP_NOT"), .equal => return try simpleInstruction(writer, offset, "OP_EQUAL"), .not_equal => return try simpleInstruction(writer, offset, "OP_NOT_EQUAL"), .less => return try simpleInstruction(writer, offset, "OP_LESS"), .less_equal => return try simpleInstruction(writer, offset, "OP_LESS_EQUAL"), .greater => return try simpleInstruction(writer, offset, "OP_GREATER"), .greater_equal => return try simpleInstruction(writer, offset, "OP_GREATER_EQUAL"), .define_global => return constantInstruction(writer, chunk, offset, "OP_DEFINE_GLOBAL"), .get_global => return constantInstruction(writer, chunk, offset, "OP_GET_GLOBAL"), .get_upvalue => return try byteInstruction(writer, chunk, offset, "OP_GET_UPVALUE"), .get_local => return byteInstruction(writer, chunk, offset, "OP_GET_LOCAL"), .set_global => return constantInstruction(writer, chunk, offset, "OP_SET_GLOBAL"), .set_upvalue => return try byteInstruction(writer, chunk, offset, "OP_SET_UPVALUE"), .set_local => return byteInstruction(writer, chunk, offset, "OP_SET_LOCAL"), .jump_if_false => return jumpInstruction(writer, chunk, offset, 1, "OP_JUMP_IF_FALSE"), .jump_if_true => return jumpInstruction(writer, chunk, offset, 1, "OP_JUMP_IF_TRUE"), .jump => return jumpInstruction(writer, chunk, offset, 1, "OP_JUMP"), .loop => return jumpInstruction(writer, chunk, offset, -1, "OP_LOOP"), } } /// Disassemble a chunk of code, writing the output to the writer object. pub fn disassembleChunk(writer: anytype, chunk: *const Chunk, name: []const u8) !void { try writer.print("== {} ==\n", .{name}); var offset: usize = 0; while (offset < chunk.code.items.len) { try writer.print("{x:0>4} ", .{offset}); var line_number = chunk.lines.items[offset]; var is_new_line = offset == 0 or line_number != chunk.lines.items[offset - 1]; if (is_new_line) { try writer.print("{:4} ", .{line_number}); } else { try writer.print(" | ", .{}); } offset = try disassembleInstruction(writer, chunk, offset, true); } } pub fn dumpValueStack(writer: anytype, stack: []value.Value) !void { _ = try writer.write(" "); for (stack) |v| { try writer.print("[ {} ]", .{v}); } _ = try writer.write("\n"); } fn expectLine(buffer: []const u8, expected: []const u8) usize { const expect = std.testing.expect; const eql = std.mem.eql; const search_result = std.mem.indexOf(u8, buffer, "\n"); expect(search_result != null); const line_end = search_result.?; expect(eql(u8, buffer[0..line_end], expected)); return line_end + 1; } test "disassembleChunk op_return" { var chunk = Chunk.init(std.testing.allocator); defer chunk.deinit(); try chunk.writeOp(OpCode.op_return, 0); var buffer: [64]u8 = undefined; var writer = std.io.fixedBufferStream(&buffer).writer(); try disassembleChunk(writer, &chunk, "test chunk"); var line_start: usize = 0; line_start += expectLine(buffer[line_start..], "== test chunk =="); line_start += expectLine(buffer[line_start..], "0000 0 OP_RETURN "); } test "disassembleChunk op_constant" { var chunk = Chunk.init(std.testing.allocator); defer chunk.deinit(); const index = try chunk.addConstant(1.2); try chunk.writeOp(OpCode.op_constant, 0); try chunk.write(index, 0); var buffer: [64]u8 = undefined; var writer = std.io.fixedBufferStream(&buffer).writer(); try disassembleChunk(writer, &chunk, "test chunk"); var line_start: usize = 0; line_start += expectLine(buffer[line_start..], "== test chunk =="); line_start += expectLine(buffer[line_start..], "0000 0 OP_CONSTANT 00 '1.2'"); } test "disassembleChunk line numbers" { var chunk = Chunk.init(std.testing.allocator); defer chunk.deinit(); try chunk.writeOp(OpCode.op_return, 0); try chunk.writeOp(OpCode.op_return, 0); try chunk.writeOp(OpCode.op_return, 0); try chunk.writeOp(OpCode.op_return, 1); try chunk.writeOp(OpCode.op_return, 1); try chunk.writeOp(OpCode.op_return, 2); var buffer: [256]u8 = undefined; var writer = std.io.fixedBufferStream(&buffer).writer(); try disassembleChunk(writer, &chunk, "test chunk"); var line_start: usize = 0; line_start += expect_line(buffer[line_start..], "== test chunk =="); line_start += expect_line(buffer[line_start..], "0000 0 OP_RETURN "); line_start += expect_line(buffer[line_start..], "0001 | OP_RETURN "); line_start += expect_line(buffer[line_start..], "0002 | OP_RETURN "); line_start += expect_line(buffer[line_start..], "0003 1 OP_RETURN "); line_start += expect_line(buffer[line_start..], "0004 | OP_RETURN "); line_start += expect_line(buffer[line_start..], "0005 2 OP_RETURN "); }
src/debug.zig
const std = @import("std"); const builtin = @import("builtin"); // Using io_mode = .evented already creates its own event loop and you can get that instance using std.event.Loop.instance.?.* pub const io_mode = .evented; var testRunDetachedData: usize = 0; pub fn main() !void { var loop: std.event.Loop = std.event.Loop.instance.?.*; try loop.initMultiThreaded(); defer loop.deinit(); // Schedule the execution, won't actually start until we start the // event loop. try loop.runDetached(std.testing.allocator, testRunDetached, .{}); try loop.runDetached(std.testing.allocator, a, .{}); try loop.runDetached(std.testing.allocator, b, .{}); try loop.runDetached(std.testing.allocator, c, .{}); try loop.runDetached(std.testing.allocator, d, .{}); try loop.runDetached(std.testing.allocator, e, .{}); try loop.runDetached(std.testing.allocator, f, .{}); try loop.runDetached(std.testing.allocator, g, .{}); try loop.runDetached(std.testing.allocator, h, .{}); try loop.runDetached(std.testing.allocator, i, .{}); try loop.runDetached(std.testing.allocator, j, .{}); // Now we can start the event loop. The function will return only // after all tasks have been completed, allowing us to synchonize // with the previous runDetached. loop.run(); std.testing.expect(testRunDetachedData == 1); } fn testRunDetached() void { testRunDetachedData += 1; std.debug.print("ThreadID = {} => \ttestRunDetachedData = {}\n", .{std.Thread.getCurrentId(), testRunDetachedData}); } fn a() void { std.debug.print("ThreadID = {} => \tDispatch a\n", .{std.Thread.getCurrentId()}); } fn b() void { std.debug.print("ThreadID = {} => \tDispatch b\n", .{std.Thread.getCurrentId()}); } fn c() void { std.debug.print("ThreadID = {} => \tDispatch c\n", .{std.Thread.getCurrentId()}); } fn d() void { std.debug.print("ThreadID = {} => \tDispatch d\n", .{std.Thread.getCurrentId()}); } fn e() void { std.debug.print("ThreadID = {} => \tDispatch e\n", .{std.Thread.getCurrentId()}); } fn f() void { std.debug.print("ThreadID = {} => \tDispatch f\n", .{std.Thread.getCurrentId()}); } fn g() void { std.debug.print("ThreadID = {} => \tDispatch g\n", .{std.Thread.getCurrentId()}); } fn h() void { std.debug.print("ThreadID = {} => \tDispatch h\n", .{std.Thread.getCurrentId()}); } fn i() void { std.debug.print("ThreadID = {} => \tDispatch i\n", .{std.Thread.getCurrentId()}); } fn j() void { std.debug.print("ThreadID = {} => \tDispatch j\n", .{std.Thread.getCurrentId()}); }
Mutlithreading/multiple_tasks_ with_event_loop.zig
const std = @import("std"); usingnamespace @import("chunk_alloc.zig"); const page_alloc = @import("page_alloc.zig"); const assert = std.debug.assert; const mem = std.mem; const math = std.math; const Allocator = mem.Allocator; const DirectAllocation = struct { next: ?*DirectAllocation, mem: []u8, }; const ArenaMark = struct { current_offset: usize, num_chunks: usize, first_direct_alloc: ?*DirectAllocation, total_waste_bytes: usize, total_used_bytes: usize, }; /// An allocator without free, where reset() frees all allocations. /// Also supports mark() and restore() if you want to do a partial free. pub fn Arena(comptime in_chunk_size: usize) type { return struct { pub const chunk_size = in_chunk_size; /// Chunks will be allocated from the parent parent: *ThreadsafeChunkAllocator(chunk_size), /// The head of the list of allocated chunks /// New allocations are always performed on the head page. /// The head page is never null, when pages are freed the /// front page is kept. list_head: *ChunkHeader, /// The tail of the list of allocated chunks /// Tracked to relocate the list into the allocator. list_tail: *ChunkHeader, /// The current offset in bytes on the list_head page. current_offset: usize, /// The number of chunks in the linked list. Will always /// be at least 1. num_chunks: usize, /// The head of a linked list of large allocations, embedded /// in the normal list pages. Large allocations are mapped /// directly, and one of these records is linked in. When /// resetting the list, all of these are freed. first_direct_alloc: ?*DirectAllocation, /// The total number of bytes lost to padding or internal tracking. total_waste_bytes: usize, /// The total number of bytes allocated to callers. Large allocations /// that are mapped directly do not count towards this value. total_used_bytes: usize, /// Creates an arena allocator. Must allocate one page, which may error. pub fn init(parent: *ThreadsafeChunkAllocator(chunk_size)) !@This() { const init_chunk = try parent.allocChunk(); const init_head = @ptrCast(*ChunkHeader, init_chunk); return @This(){ .parent = parent, .list_head = init_head, .list_tail = init_head, .current_offset = @sizeOf(ChunkHeader), .num_chunks = 1, .first_direct_alloc = null, .total_waste_bytes = 0, .total_used_bytes = 0, }; } /// Allocates a number of bytes, obtaining an extra page if necessary. /// Very large allocations will be mapped directly, but noted and freed /// on reset. pub fn allocBytes(self: *@This(), size: usize, alignment: u29) Error![*]u8 { const aligned_offset = mem.alignForward(self.current_offset, alignment); // fast path: allocation fits on page if (aligned_offset + size <= chunk_size) { // track stats self.total_used_bytes += size; self.total_waste_bytes += (aligned_offset - self.current_offset); // bump alloc self.current_offset = aligned_offset + size; return @ptrCast([*]u8, self.list_head) + aligned_offset; } else { // allocation doesn't fit on this page // check if this allocation fits in a chunk at all if (math.max(size, alignment) <= mem.page_size / 2) { // gotta get a new chunk const new_chunk = try self.parent.allocChunk(); const new_head = @ptrCast(*ChunkHeader, new_chunk); // link it new_head.next = self.list_head; self.list_head = new_head; // track stats and reset self.total_waste_bytes += (chunk_size - self.current_offset); self.current_offset = @sizeOf(ChunkHeader); // alloc from new chunk const new_aligned_offset = mem.alignForward(@sizeOf(ChunkHeader), alignment); assert(new_aligned_offset + size < chunk_size); // track stats self.total_used_bytes += size; self.total_waste_bytes += (new_aligned_offset - self.current_offset); // offset the pointer self.current_offset = new_aligned_offset + size; return @ptrCast([*]u8, new_head) + aligned_offset; } else { // allocation doesn't fit on any page // this needs to be a direct allocation const allocation = try page_alloc.allocAligned(size, alignment); errdefer page_alloc.free(allocation[0..size]); // store it in the linked list so we can free it on reset const direct = try self.create(DirectAllocation); // don't count the direct allocation as used self.total_used_bytes -= @sizeOf(DirectAllocation); self.total_waste_bytes += @sizeOf(DirectAllocation); // link in the new node direct.* = DirectAllocation{ .next = self.first_direct_alloc, .mem = allocation[0..size], }; self.first_direct_alloc = direct; return allocation; } } } /// Reallocates bytes, changing their allocated size or alignment. /// May relocate the passed slice. Returns a pointer to the new memory. pub fn reallocBytes(self: *@This(), bytes: []u8, alignment: u29, new_size: usize, new_alignment: u29) Error![*]u8 { const bytes_end = bytes.ptr + bytes.len; const page_end = @ptrCast([*]u8, self.list_head) + self.current_offset; // If it fits in the existing allocation, just return the same pointer. // We can free up some space if this is the last allocation. if (new_size == 0 or (new_size <= bytes.len and mem.isAligned(bytes.ptr, new_alignment))) { if (bytes_end == page_end) { self.current_offset -= bytes.len - new_size; } return bytes.ptr; } // Otherwise we need to make a new allocation. // If this was the last thing we allocated, we can "free" it first. if (bytes_end == page_end) { self.current_offset -= bytes.len; } // If the new allocation fails, restore the original allocation. errdefer if (bytes_end == page_end) { self.current_offset += bytes.len; }; // Allocate new memory const new_mem = try self.allocBytes(new_size, new_alignment); // If it's not the same pointer, we need to copy the data. // It may be the same pointer if the alignment is the same // and we just "freed" the original. if (new_mem != bytes.ptr) { const copy_size = math.min(bytes.len, new_size); // check if the slices overlap. // they can only overlap forwards, never backwards. if (new_mem - bytes.ptr < copy_size) { var i = copy_size; while (i > 0) { i -= 1; // "unsafe" slice access here to avoid bounds // check on every access in safe modes new_mem[i] = bytes.ptr[i]; } } else { // no alias, use a fast memcpy @memcpy(new_mem, bytes.ptr, copy_size); } } return new_mem; } /// Allocates a slice pub fn alloc(self: *@This(), comptime T: type, count: usize) ![]T { const ptr = try self.allocBytes(@sizeOf(T) * count, @alignOf(T)); return @ptrCast([*]T, @alignCast(@alignOf(T), ptr))[0..count]; } /// Allocates an aligned slice pub fn allocAligned(self: *@This(), comptime T: type, count: usize, comptime alignment: comptime_int) ![]align(alignment) T { const ptr = try self.allocBytes(@sizeOf(T) * count, alignment); return @ptrCast([*]align(alignment) T, @alignCast(alignment, ptr))[0..count]; } /// Allocates a single instance pub fn create(self: *@This(), comptime T: type) !*T { const ptr = try self.allocBytes(@sizeOf(T), @alignOf(T)); return @ptrCast(*T, @alignCast(@alignOf(T), ptr)); } /// Allocates a single aligned instance pub fn createAligned(self: *@This(), comptime T: type, comptime alignment: comptime_int) !*align(alignment) T { const ptr = try self.allocBytes(@sizeOf(T), alignment); return @ptrCast(*align(alignment) T, @alignCast(alignment, ptr)); } /// Duplicates a slice pub fn dupe(self: *@This(), comptime T: type, src: []const T) ![]T { const dest = try self.alloc(T, src.len); mem.copy(T, dest, src); return dest; } /// Creates a restore point. `restore` can be called later to free everything /// allocated after this point. The mark is invalidated if the arena is reset, /// or if a previous mark is restored. pub fn mark(self: @This()) ArenaMark { return ArenaMark{ .current_offset = self.current_offset, .num_chunks = self.num_chunks, .first_direct_alloc = self.first_direct_alloc, .total_waste_bytes = self.total_waste_bytes, .total_used_bytes = self.total_used_bytes, }; } /// Restores the arena to a mark point. pub fn restore(self: *@This(), the_mark: ArenaMark) void { // free direct allocations down to the target var direct_alloc = self.first_direct_alloc; while (direct_alloc != the_mark.first_direct_alloc) { const direct = direct_alloc.?; page_alloc.free(direct.mem); direct_alloc = direct.next; } // free any extra pages const pages_to_free = self.num_chunks - the_mark.num_chunks; if (pages_to_free > 0) { const first_page = self.list_head; var last_page = first_page; var pages_left = pages_to_free - 1; while (pages_left > 0) : (pages_left -= 1) { last_page = last_page.next.?; } self.list_head = last_page.next.?; last_page.next = null; self.parent.freeChunks(first_page, last_page, pages_to_free); } // restore the state self.current_offset = the_mark.current_offset; self.num_chunks = the_mark.num_chunks; self.first_direct_alloc = the_mark.first_direct_alloc; self.total_waste_bytes = the_mark.total_waste_bytes; self.total_used_bytes = the_mark.total_used_bytes; } /// Resets the allocator, freeing all allocations. Note that /// one chunk from the parent allocator is retained. Call /// deinit() instead if you want to release everything. pub fn reset(self: *@This()) void { // free all direct allocations var direct_alloc = self.first_direct_alloc; while (direct_alloc) |direct| : (direct_alloc = direct.next) { page_alloc.free(direct.mem); } // return pages to shared pool, except head if (self.list_head.next != null) { self.parent.freeChunks(self.list_head.next.?, self.list_tail, self.num_chunks); self.list_head.next = null; self.list_tail = self.list_head; } // reset state self.current_offset = @sizeOf(ChunkHeader); self.num_chunks = 1; self.first_direct_alloc = null; self.total_waste_bytes = 0; self.total_used_bytes = 0; } /// Frees all allocations and releases all chunks back to the parent. /// Leaves this allocator in an undefined state. pub fn deinit(self: *@This()) void { // free all direct allocations var direct_alloc = self.first_direct_alloc; while (direct_alloc) |direct| : (direct_alloc = direct.next) { page_alloc.free(direct.mem); } // return pages to shared pool, including head self.parent.freeChunks(self.list_head, self.list_tail, self.num_chunks); self.* = undefined; } }; } test "Arena" { const chunk_size = 16 * 1024; var root = ThreadsafeChunkAllocator(chunk_size).init(); var arena = try Arena(chunk_size).init(&root); _ = try arena.alloc(u32, 10); _ = try arena.create(u32); const mark = arena.mark(); _ = try arena.allocAligned(u32, 1, 1); _ = try arena.createAligned(u32, 1); _ = try arena.dupe(u8, "TheString"); arena.restore(mark); arena.reset(); arena.deinit(); }
arena.zig
const std = @import("std"); pub fn bit(comptime field_type: type, comptime shamt: usize) type { return bit_t(field_type, u1, shamt); } test "bit" { const S = extern union { low: bit(u32, 0), high: bit(u32, 1), val: u32, }; std.testing.expect(@sizeOf(S) == 4); std.testing.expect(@bitSizeOf(S) == 32); var s: S = .{ .val = 1 }; std.testing.expect(s.low.read() == 1); std.testing.expect(s.high.read() == 0); s.low.write(0); s.high.write(1); std.testing.expect(s.val == 2); } pub fn boolean(comptime field_type: type, comptime shamt: usize) type { return bit_t(field_type, bool, shamt); } test "boolean" { const S = extern union { low: boolean(u32, 0), high: boolean(u32, 1), val: u32, }; std.testing.expect(@sizeOf(S) == 4); std.testing.expect(@bitSizeOf(S) == 32); var s: S = .{ .val = 2 }; std.testing.expect(s.low.read() == false); std.testing.expect(s.high.read() == true); s.low.write(true); s.high.write(false); std.testing.expect(s.val == 1); } pub fn bitfield(comptime field_type: type, comptime shamt: usize, comptime num_bits: usize) type { if (shamt + num_bits > @bitSizeOf(field_type)) @compileError("bitfield doesn't fit"); const self_mask: field_type = ((1 << num_bits) - 1) << shamt; const val_t = std.meta.Int(.unsigned, num_bits); return struct { dummy: field_type, fn field(self: anytype) field_t(@This(), @TypeOf(self), field_type) { return @ptrCast(field_t(@This(), @TypeOf(self), field_type), self); } pub fn write(self: anytype, val: val_t) void { self.field().* &= ~self_mask; self.field().* |= @intCast(field_type, val) << shamt; } pub fn read(self: anytype) val_t { const val: field_type = self.field().*; return @intCast(val_t, (val & self_mask) >> shamt); } }; } test "bitfield" { const S = extern union { low: bitfield(u32, 0, 16), high: bitfield(u32, 16, 16), val: u32, }; std.testing.expect(@sizeOf(S) == 4); std.testing.expect(@bitSizeOf(S) == 32); var s: S = .{ .val = 0x13376969 }; std.testing.expect(s.low.read() == 0x6969); std.testing.expect(s.high.read() == 0x1337); s.low.write(0x1337); s.high.write(0x6969); std.testing.expect(s.val == 0x69691337); } fn field_t(comptime self_t: type, comptime t: type, comptime val_t: type) type { return switch (t) { *self_t => *val_t, *const self_t => *const val_t, *volatile self_t => *volatile val_t, *const volatile self_t => *const volatile val_t, else => @compileError("wtf you doing"), }; } fn bit_t(comptime field_type: type, comptime val_t: type, comptime shamt: usize) type { const self_bit: field_type = (1 << shamt); return struct { bits: bitfield(field_type, shamt, 1), pub fn set(self: anytype) void { self.bits.field().* |= self_bit; } pub fn unset(self: anytype) void { self.bits.field().* &= ~self_bit; } pub fn read(self: anytype) val_t { return @bitCast(val_t, @truncate(u1, self.bits.field().* >> shamt)); } // Since these are mostly used with MMIO, I want to avoid // reading the memory just to write it again, also races pub fn write(self: anytype, val: val_t) void { if (@bitCast(bool, val)) { self.set(); } else { self.unset(); } } }; }
src/lib/bitfields.zig
const std = @import("std"); const compare = @import("../src/generic"); const debug = std.debug; const mem = std.mem; const math = std.math; const testing = std.testing; /// Determin the max runtime size requirement to a union of N types. fn runtimeSize(comptime fields: var) comptime_int { var res = 0; for (fields) |field| { if (res < @sizeOf(field.Payload)) res = @sizeOf(field.Payload); } return res; } pub fn Field(comptime T: type) type { return struct { key: T, Payload: type, pub fn init(key: T, comptime Payload: type) @This() { return @This(){ .key = key, .Payload = Payload, }; } }; } pub fn Union(comptime Key: type, comptime field_array: var) type { for (field_array) |a, i| { for (field_array[i + 1 ..]) |b| { // TODO: Abitrary key equal debug.assert(a.key != b.key); } } return struct { pub const fields = field_array; // In order for us to store the eithers values, we have // to type erase away the values, and store them as bytes. payload: [runtimeSize(fields)]u8, key: usize, // TODO: Log2Int pub fn init(comptime key: Key, value: GetField(key).Payload) @This() { var res: @This() = undefined; res.key = comptime index(key); res.ptr(key).?.* = value; return res; } pub fn field(u: @This(), comptime key: Key) ?GetField(key).Payload { if (u.ptrConst(key)) |p| return p.*; return null; } pub fn ptr(u: *@This(), comptime key: Key) ?*align(1) GetField(key).Payload { const i = comptime index(key); if (u.key != i) return null; return &std.mem.bytesAsSlice(GetField(key).Payload, u.payload[0..])[0]; } pub fn ptrConst(u: *const @This(), comptime key: Key) ?*align(1) const GetField(key).Payload { const i = comptime index(key); if (u.key != i) return null; return &std.mem.bytesAsSlice(GetField(key).Payload, u.payload[0..])[0]; } fn GetField(comptime key: Key) Field(Key) { return fields[index(key)]; } fn index(comptime key: Key) usize { inline for (fields) |f, i| { if (f.key == key) return i; } unreachable; } }; } test "union" { const T = Union(u8, [_]Field(u8){ Field(u8).init(0, u8), Field(u8).init(1, u16), Field(u8).init(2, f32), }); const a = T.init(0, 11); const b = T.init(1, 22); const c = T.init(2, 33); testing.expectEqual(a.field(0).?, 11); testing.expectEqual(b.field(0), null); testing.expectEqual(c.field(0), null); testing.expectEqual(a.field(1), null); testing.expectEqual(b.field(1).?, 22); testing.expectEqual(c.field(1), null); testing.expectEqual(a.field(2), null); testing.expectEqual(b.field(2), null); testing.expectEqual(c.field(2).?, 33); }
src/union.zig
const std = @import("std"); const util = @import("util.zig"); const data = @embedFile("../data/day06.txt"); /// Simulates lanternfish according to specified algorithm. Returns number of lanternfish after /// simulation completes. pub fn simulateLanternfish2(allocator: *util.Allocator, initial_lanternfish: []const u8, days: u32) !u64 { // Use array of each possible lifetime value (0-8) to track lanternfish. const lifetime_states = try allocator.alloc(u64, 9); defer allocator.free(lifetime_states); // Zero out initial values std.mem.set(u64, lifetime_states, 0); // Initialize with the given starting fish. for (initial_lanternfish) |lifetime_state| { lifetime_states[lifetime_state] += 1; } // Temporary variable we'll use for existing fish whose lifetime is reset (which spawns a new fish // as well) var resetting_fish: u64 = 0; var day: u32 = 1; while (day <= days) : (day += 1) { // Iterate through the other lifetimes and simply move the values down since all the values // decrement for (lifetime_states) |num_fish, idx| { //util.print("Handling: {d} w/ {d}:\n", .{ idx, num_fish }); if (idx == 0) { // Handle resetting fish and spawning new ones. each 0 resets to 6 and spawns a new fish // with a state of 8. We store it in a temporary value so we can avoid overwriting this day's // 6 and 8 values until we've processed them. resetting_fish = num_fish; } else { // Simply move fish in the current lifetime state down to the next one. lifetime_states[idx - 1] = num_fish; } } // Add the new fish that were created, as well as the ones that reset their states lifetime_states[6] += resetting_fish; lifetime_states[8] = resetting_fish; } // Sum up fish in each state to get the total number of fish var sum: u64 = 0; for (lifetime_states) |num_fish| { sum += num_fish; } return sum; } pub fn main() !void { defer { const leaks = util.gpa_impl.deinit(); std.debug.assert(!leaks); } var lanternfish = util.List(u8).init(util.gpa); defer lanternfish.deinit(); // Parse initial list of ages var it = util.tokenize(u8, data, ","); while (it.next()) |num_data| { try lanternfish.append(util.parseInt(u8, num_data, 10) catch { return error.InvalidInput; }); } const days_pt1 = 80; const num_fish_pt1 = try simulateLanternfish2(util.gpa, lanternfish.items, days_pt1); util.print("Part 1: After {d} days, there are {d} lanternfish.\n", .{ days_pt1, num_fish_pt1 }); const days_pt2 = 256; const num_fish_pt2 = try simulateLanternfish2(util.gpa, lanternfish.items, days_pt2); util.print("Part 2: After {d} days, there are {d} lanternfish.\n", .{ days_pt2, num_fish_pt2 }); }
src/day06.zig
const inputFile = @embedFile("./input/day10.txt"); const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const Str = []const u8; const BitSet = std.DynamicBitSet; const assert = std.debug.assert; const tokenize = std.mem.tokenize; const print = std.debug.print; fn sort(comptime T: type, items: []T) void { std.sort.sort(T, items, {}, comptime std.sort.asc(T)); } const BracketType = enum { Round, Square, Curly, Angle }; const Score = struct { const round = 3; const square = 57; const curly = 1197; const angle = 25137; }; fn corruptedScore(line: Str, allocator: Allocator) !usize { var stack = try ArrayList(BracketType).initCapacity(allocator, line.len); defer stack.deinit(); for (line) |c| { switch (c) { // Opening '(' => stack.appendAssumeCapacity(.Round), '[' => stack.appendAssumeCapacity(.Square), '{' => stack.appendAssumeCapacity(.Curly), '<' => stack.appendAssumeCapacity(.Angle), // Closing ')' => { if (stack.popOrNull()) |last| { if (last != .Round) return Score.round; } else { return Score.round; } }, ']' => { if (stack.popOrNull()) |last| { if (last != .Square) return Score.square; } else { return Score.square; } }, '}' => { if (stack.popOrNull()) |last| { if (last != .Curly) return Score.curly; } else { return Score.curly; } }, '>' => { if (stack.popOrNull()) |last| { if (last != .Angle) return Score.angle; } else { return Score.angle; } }, else => unreachable, } } // No errors return 0; } fn partOne(input: Str, allocator: Allocator) !usize { var result: usize = 0; var it = tokenize(u8, input, "\n"); while (it.next()) |line| { const score = try corruptedScore(line, allocator); result += score; } return result; } const PartTwoScore = struct { const round = 1; const square = 2; const curly = 3; const angle = 4; }; fn incompleteScore(line: Str, allocator: Allocator) !usize { var stack = try ArrayList(BracketType).initCapacity(allocator, line.len); defer stack.deinit(); // this for loop is basically the same as in part 1, just copy-pasted it // for simplicity for (line) |c| { switch (c) { // Opening '(' => stack.appendAssumeCapacity(.Round), '[' => stack.appendAssumeCapacity(.Square), '{' => stack.appendAssumeCapacity(.Curly), '<' => stack.appendAssumeCapacity(.Angle), // Closing ')' => { if (stack.popOrNull()) |last| { if (last != .Round) return 0; // corrupted } else { return 0; } }, ']' => { if (stack.popOrNull()) |last| { if (last != .Square) return 0; } else { return 0; } }, '}' => { if (stack.popOrNull()) |last| { if (last != .Curly) return 0; } else { return 0; } }, '>' => { if (stack.popOrNull()) |last| { if (last != .Angle) return 0; } else { return 0; } }, else => unreachable, } } std.mem.reverse(BracketType, stack.items); var result: usize = 0; for (stack.items) |c| { switch (c) { .Round => result = result * 5 + PartTwoScore.round, .Square => result = result * 5 + PartTwoScore.square, .Curly => result = result * 5 + PartTwoScore.curly, .Angle => result = result * 5 + PartTwoScore.angle, } } return result; } fn partTwo(input: Str, allocator: Allocator) !usize { var scores = ArrayList(usize).init(allocator); defer scores.deinit(); var it = tokenize(u8, input, "\n"); while (it.next()) |line| { const score = try incompleteScore(line, allocator); if (score != 0) { try scores.append(score); } } sort(usize, scores.items); return scores.items[scores.items.len / 2]; } pub fn main() !void { // Standard boilerplate for Aoc problems const stdout = std.io.getStdOut().writer(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var gpaAllocator = gpa.allocator(); defer assert(!gpa.deinit()); // Check for memory leaks var arena = std.heap.ArenaAllocator.init(gpaAllocator); defer arena.deinit(); var allocator = arena.allocator(); // use an arena const p1 = try partOne(inputFile, allocator); const p2 = try partTwo(inputFile, allocator); try stdout.print("Part1: {d}\nPart2: {d}", .{ p1, p2 }); } test "part 1" { const testInput = \\[({(<(())[]>[[{[]{<()<>> \\[(()[<>])]({[<{<<[]>>( \\{([(<{}[<>[]}>{[]{[(<()> \\(((({<>}<{<{<>}{[]{[]{} \\[[<[([]))<([[{}[[()]]] \\[{[{({}]{}}([{[{{{}}([] \\{<[[]]>}<{[{[{[]{()[[[] \\[<(<(<(<{}))><([]([]() \\<{([([[(<>()){}]>(<<{{ \\<{([{{}}[<[[[<>{}]]]>[]] \\ ; var allocator = std.testing.allocator; const p1 = try partOne(testInput, allocator); try std.testing.expectEqual(@as(usize, 26397), p1); } test "part 2 - single" { const testInput = "[({(<(())[]>[[{[]{<()<>>"; var allocator = std.testing.allocator; try std.testing.expectEqual(@as(usize, 288957), try incompleteScore(testInput, allocator)); } test "part 2 - single" { const testInput = \\[({(<(())[]>[[{[]{<()<>> \\[(()[<>])]({[<{<<[]>>( \\{([(<{}[<>[]}>{[]{[(<()> \\(((({<>}<{<{<>}{[]{[]{} \\[[<[([]))<([[{}[[()]]] \\[{[{({}]{}}([{[{{{}}([] \\{<[[]]>}<{[{[{[]{()[[[] \\[<(<(<(<{}))><([]([]() \\<{([([[(<>()){}]>(<<{{ \\<{([{{}}[<[[[<>{}]]]>[]] \\ ; var allocator = std.testing.allocator; try std.testing.expectEqual(@as(usize, 288957), try partTwo(testInput, allocator)); }
src/day10.zig
const Video = @This(); const SDL = @import("sdl2"); const std = @import("std"); const ROM = @import("ROM.zig"); const Sprite = struct { id: u6 = 0, x_flip: bool = false, y_flip: bool = false, color: u8 = 0, x_pos: u8 = 0, y_pos: u8 = 0, pub fn readAttrs(self: Sprite) u8 { return (@as(u8, self.id) << 2) | (@as(u8, @boolToInt(self.x_flip)) << 1) | @boolToInt(self.y_flip); } pub fn writeAttrs(self: *Sprite, attrs: u8) void { self.y_flip = (attrs & 1) != 0; self.x_flip = (attrs & 2) != 0; self.id = @intCast(u6, attrs >> 2); } }; const SCREEN_WIDTH = 224; const SCREEN_HEIGHT = 288; const BGTiles = [256][8][8]u2; const FGTiles = [64][16][16]u2; const VideoRAM = [0x400]u8; /// game window window: SDL.Window, /// game renderer renderer: SDL.Renderer, /// graphics drawn here canvas: SDL.Texture, // rom data bg_tiles: *BGTiles, fg_tiles: *FGTiles, palettes: *[32][4]SDL.Color, // runtime data vram: *VideoRAM, cram: *VideoRAM, sprites: [8]Sprite = [_]Sprite{.{}} ** 8, flip: bool = false, const TEXTURE_FORMAT = switch (@import("builtin").cpu.arch.endian()) { .Big => .rgba8888, .Little => .abgr8888, }; fn decodePixel(b: u8) u2 { return @truncate(u2, (b & 1) | ((b >> 3) & 2)); } fn decodeGfxBlock(comptime span: u8, out: *[span][span]u2, in: [*]const u8) [*]const u8 { const z_loop_count = span / 4; const y_out_mask = span - 1; const ptr_jump = (span * 2) - 8; var xout = span; var ptr = in; while (xout > 0) { xout -= 1; var y: u3 = 0; while (y < 4) : (y += 1) { var z: usize = 0; var yout = y_out_mask - y; while (z < z_loop_count) : (z += 1) { out[yout][xout] = decodePixel(ptr[z * 8] >> y); yout = (yout + 4) & y_out_mask; } } ptr += 1; if ((xout & 7) == 0) { ptr += ptr_jump; } } return ptr; } fn scale8(value: u8) u8 { return (value * 36) + (value >> 2); } pub fn init(allocator: std.mem.Allocator, rom: *const ROM) !Video { const window = try SDL.createWindow( "PAC-MAN", .centered, .centered, SCREEN_WIDTH * 2, SCREEN_HEIGHT * 2, .{ .resizable = true }, ); errdefer window.destroy(); const renderer = try SDL.createRenderer(window, 0, .{}); errdefer renderer.destroy(); const canvas = try SDL.createTexture( renderer, TEXTURE_FORMAT, .streaming, SCREEN_WIDTH, SCREEN_HEIGHT, ); errdefer canvas.destroy(); const bg_tiles = try allocator.create(BGTiles); errdefer allocator.destroy(bg_tiles); const fg_tiles = try allocator.create(FGTiles); errdefer allocator.destroy(fg_tiles); var ptr = @as([*]const u8, &rom.bg_tiles); for (bg_tiles) |*tile| { ptr = decodeGfxBlock(8, tile, ptr); } ptr = @as([*]const u8, &rom.fg_tiles); for (fg_tiles) |*tile| { ptr = decodeGfxBlock(16, tile, ptr); } var colors: [32]SDL.Color = undefined; for (rom.colors) |color, i| { colors[i] = .{ .r = scale8(color & 7), .g = scale8((color >> 3) & 7), .b = (color >> 6) * 85, .a = 255, }; } colors[0].a = 0; const palettes = try allocator.create([32][4]SDL.Color); errdefer allocator.destroy(palettes); var i: u16 = 0; for (palettes) |*pal| { for (pal) |*color| { color.* = colors[rom.palettes[i]]; i += 1; } } const vram = try allocator.create(VideoRAM); errdefer allocator.destroy(vram); std.mem.set(u8, vram, 0); const cram = try allocator.create(VideoRAM); errdefer allocator.destroy(cram); std.mem.set(u8, cram, 0); return Video{ .window = window, .renderer = renderer, .canvas = canvas, .bg_tiles = bg_tiles, .fg_tiles = fg_tiles, .palettes = palettes, .vram = vram, .cram = cram, }; } pub fn deinit(self: Video, allocator: std.mem.Allocator) void { allocator.destroy(self.bg_tiles); allocator.destroy(self.fg_tiles); allocator.destroy(self.palettes); allocator.destroy(self.vram); allocator.destroy(self.cram); self.canvas.destroy(); self.renderer.destroy(); self.window.destroy(); } fn plotPixel(pixels: SDL.Texture.PixelData, x: usize, y: usize, color: SDL.Color) void { @ptrCast([*]align(1) SDL.Color, &pixels.pixels[y * pixels.stride])[x] = color; } fn drawChar(self: Video, pixels: SDL.Texture.PixelData, x: usize, y: usize, address: usize) void { var addr = address; var mask: u8 = 0; if (self.flip) { addr ^= 0x3ff; mask = 7; } const palette = self.palettes[self.cram[addr] & 31]; for (self.bg_tiles[self.vram[addr]]) |row, py| { for (row) |pixel, px| { plotPixel(pixels, x + (px ^ mask), y + (py ^ mask), palette[pixel]); } } } fn drawBackground(self: Video, pixels: SDL.Texture.PixelData) void { var x: usize = 0; while (x < SCREEN_WIDTH / 8) : (x += 1) { self.drawChar(pixels, x << 3, 0x00 << 3, 0x3dd - x); self.drawChar(pixels, x << 3, 0x01 << 3, 0x3fd - x); self.drawChar(pixels, x << 3, 0x22 << 3, 0x01d - x); self.drawChar(pixels, x << 3, 0x23 << 3, 0x03d - x); } var y: usize = 2; while (y < SCREEN_HEIGHT / 8 - 2) : (y += 1) { x = 0; while (x < SCREEN_WIDTH / 8) : (x += 1) { self.drawChar(pixels, x << 3, y << 3, 0x39e + y - (x << 5)); } } } fn drawSprite(self: Video, pixels: SDL.Texture.PixelData, index: u8) void { const sprite = self.sprites[index]; const x = -%sprite.x_pos -% 17 -% @boolToInt(index < 3); const y = -%sprite.y_pos +% 16; const xm: u8 = if (sprite.x_flip) 0x0f else 0x00; const ym: u8 = if (sprite.y_flip) 0x0f else 0x00; const palette = self.palettes[sprite.color & 31]; for (self.fg_tiles[sprite.id]) |row, py| { const sy = @as(u16, y +% (@intCast(u8, py) ^ ym) -% 16) + 16; for (row) |pixel, px| { const sx = x +% (@intCast(u8, px) ^ xm); if (sx >= SCREEN_WIDTH) continue; const color = palette[pixel]; if (color.a == 0) continue; plotPixel(pixels, sx, sy, color); } } } fn drawScreen(self: Video, pixels: SDL.Texture.PixelData) void { self.drawBackground(pixels); var i: u8 = 6; while (i >= 1) : (i -= 1) { self.drawSprite(pixels, i); } } pub fn update(self: Video) !void { var pixels = try self.canvas.lock(null); defer pixels.release(); self.drawScreen(pixels); } pub fn present(self: Video) !void { try self.renderer.copy(self.canvas, null, null); self.renderer.present(); }
src/Video.zig
const std = @import("std"); const expect = std.testing.expect; const luhnmod10 = @import("luhnmod10.zig"); test "benchmark" { const count: i64 = 14_000; var timer = try std.time.Timer.start(); var i: i64 = 0; while (i < count) : (i += 1) { const number = "4242424242424242"; _ = luhnmod10.valid(number); } const ns = timer.read(); std.log.warn("count {}", .{i}); const nsOp = @divTrunc(ns, count); std.log.warn("{} ns/op", .{nsOp}); } test { const number = "0"; const valid = luhnmod10.valid(number); try expect(valid == true); } test { const number = "00"; const valid = luhnmod10.valid(number); try expect(valid == true); } test { const number = "18"; const valid = luhnmod10.valid(number); try expect(valid == true); } test { const number = "0000000000000000"; const valid = luhnmod10.valid(number); try expect(valid == true); } test { const number = "4242424242424240"; const valid = luhnmod10.valid(number); try expect(valid == false); } test { const number = "4242424242424241"; const valid = luhnmod10.valid(number); try expect(valid == false); } test { const number = "4242424242424242"; const valid = luhnmod10.valid(number); try expect(valid == true); } test { const number = "4242424242424243"; const valid = luhnmod10.valid(number); try expect(valid == false); } test { const number = "4242424242424244"; const valid = luhnmod10.valid(number); try expect(valid == false); } test { const number = "4242424242424245"; const valid = luhnmod10.valid(number); try expect(valid == false); } test { const number = "4242424242424246"; const valid = luhnmod10.valid(number); try expect(valid == false); } test { const number = "4242424242424247"; const valid = luhnmod10.valid(number); try expect(valid == false); } test { const number = "4242424242424248"; const valid = luhnmod10.valid(number); try expect(valid == false); } test { const number = "4242424242424249"; const valid = luhnmod10.valid(number); try expect(valid == false); } test { const number = "42424242424242426"; const valid = luhnmod10.valid(number); try expect(valid == true); } test { const number = "424242424242424267"; const valid = luhnmod10.valid(number); try expect(valid == true); } test { const number = "4242424242424242675"; const valid = luhnmod10.valid(number); try expect(valid == true); } test { const number = "000000018"; const valid = luhnmod10.valid(number); try expect(valid == true); } test { const number = "99999999999999999999"; const valid = luhnmod10.valid(number); try expect(valid == true); } test { const number = "99999999999999999999999999999999999999999999999999999999999999999997"; const valid = luhnmod10.valid(number); try expect(valid == true); }
luhnmod10_tests.zig
usingnamespace @import("root").preamble; const CoreID = os.platform.CoreID; /// Maximum number of supported CPUs const max_cpus = comptime config.kernel.max_cpus; /// CPUs data var core_datas: [max_cpus]CoreData = [1]CoreData{undefined} ** max_cpus; /// Count of CPUs that have not finished booting. /// Assigned in stivale2.zig pub var cpus_left: usize = undefined; /// Pointer to CPUS data pub var cpus: []CoreData = core_datas[0..1]; pub const CoreData = struct { current_task: *os.thread.Task = undefined, booted: bool, panicked: bool, acpi_id: u64, executable_tasks: os.thread.ReadyQueue, tasks_count: usize, platform_data: os.platform.thread.CoreData, int_stack: usize, sched_stack: usize, pub fn id(self: *@This()) usize { return lib.util.pointers.getIndex(self, cpus); } fn bootstrap_stack(size: usize) usize { const guard_size = os.platform.thread.stack_guard_size; const total_size = guard_size + size; // Allocate non-backing virtual memory const nonbacked = os.memory.vmm.nonbacked(); const virt = @ptrToInt(os.vital(nonbacked.allocFn(nonbacked, total_size, 1, 1, 0), "bootstrap stack valloc").ptr); // Map pages os.vital(os.memory.paging.map(.{ .virt = virt + guard_size, .size = size, .perm = os.memory.paging.rw(), .memtype = .MemoryWriteBack, }), "bootstrap stack map"); return virt + total_size; } // Called from BSP to bootstrap stacks for AP pub fn bootstrap_stacks(self: *@This()) void { self.int_stack = CoreData.bootstrap_stack(os.platform.thread.int_stack_size); self.sched_stack = CoreData.bootstrap_stack(os.platform.thread.sched_stack_size); } // Called from AP when AP is ready to get tasks to run pub fn bootstrap_tasking(self: *@This()) noreturn { const bootstrap_handler = struct { // Wait for the first task and run it pub fn bootstrap(frame: *os.platform.InterruptFrame, _: usize) void { _ = @atomicRmw(usize, &os.platform.smp.cpus_left, .Sub, 1, .AcqRel); const cpu = os.platform.thread.get_current_cpu(); const task = cpu.executable_tasks.dequeue(); frame.* = task.registers; task.paging_context.apply(); os.platform.set_current_task(task); task.platform_data.loadState(); } }.bootstrap; // Call bootstrap callback on a scheduler stack os.platform.sched_call(bootstrap_handler, undefined); unreachable; } }; pub fn prepare() void { os.platform.thread.set_current_cpu(&cpus[0]); cpus[0].panicked = false; cpus[0].tasks_count = 1; cpus[0].platform_data = .{}; } pub fn init(num_cores: usize) void { if (num_cores < 2) return; cpus.len = std.math.min(num_cores, max_cpus); // for(cpus[1..]) |*c| { // AAAAAAAAAAAAAAAAAAAAA https://github.com/ziglang/zig/issues/7968 // Nope, can't do that. Instead we have to do the following: var i: usize = 1; while (i < cpus.len) : (i += 1) { const c = &cpus[i]; // ugh. c.panicked = false; c.tasks_count = 0; c.executable_tasks.init(c); c.bootstrap_stacks(); c.platform_data = .{}; } }
subprojects/flork/src/platform/smp.zig
const std = @import("std"); const tres = @import("tres.zig"); test "tres.parse bool" { var tree_parser = std.json.Parser.init(std.testing.allocator, false); defer tree_parser.deinit(); { const tree = try tree_parser.parse("true"); const parsed = try tres.parse(bool, tree.root, null); try std.testing.expectEqual(true, parsed); } tree_parser.reset(); { const tree = try tree_parser.parse("false"); const parsed = try tres.parse(bool, tree.root, null); try std.testing.expectEqual(false, parsed); } tree_parser.reset(); { const tree = try tree_parser.parse("[]"); try std.testing.expectError(error.UnexpectedFieldType, tres.parse(bool, tree.root, null)); } } test "tres.parse float" { var tree_parser = std.json.Parser.init(std.testing.allocator, false); defer tree_parser.deinit(); { const tree = try tree_parser.parse("1.2"); const parsed = try tres.parse(f64, tree.root, null); try std.testing.expectEqual(@as(f64, 1.2), parsed); } tree_parser.reset(); { const tree = try tree_parser.parse("1"); const parsed = try tres.parse(f32, tree.root, null); try std.testing.expectEqual(@as(f32, 1), parsed); } tree_parser.reset(); { const tree = try tree_parser.parse("10000000000000000000000000000000"); const parsed = try tres.parse(f64, tree.root, null); try std.testing.expectEqual(@as(f64, 10000000000000000000000000000000), parsed); } tree_parser.reset(); { const tree = try tree_parser.parse("[]"); try std.testing.expectError(error.UnexpectedFieldType, tres.parse(f32, tree.root, null)); } } test "tres.parse integer" { var tree_parser = std.json.Parser.init(std.testing.allocator, false); defer tree_parser.deinit(); { const tree = try tree_parser.parse("1"); const parsed = try tres.parse(u32, tree.root, null); try std.testing.expectEqual(@as(u32, 1), parsed); } tree_parser.reset(); { const tree = try tree_parser.parse("-100"); const parsed = try tres.parse(i16, tree.root, null); try std.testing.expectEqual(@as(i16, -100), parsed); } tree_parser.reset(); { const tree = try tree_parser.parse("10000000000000000000000000000000"); const parsed = try tres.parse(u128, tree.root, null); try std.testing.expectEqual(@as(u128, 10000000000000000000000000000000), parsed); } tree_parser.reset(); { const tree = try tree_parser.parse("1000"); try std.testing.expectError(error.Overflow, tres.parse(u8, tree.root, null)); } tree_parser.reset(); { const tree = try tree_parser.parse("10000000000000000000000000000000"); try std.testing.expectError(error.Overflow, tres.parse(u8, tree.root, null)); } tree_parser.reset(); { const tree = try tree_parser.parse("[]"); try std.testing.expectError(error.UnexpectedFieldType, tres.parse(u21, tree.root, null)); } } test "tres.parse optional" { var tree_parser = std.json.Parser.init(std.testing.allocator, false); defer tree_parser.deinit(); { const tree = try tree_parser.parse("true"); const parsed = try tres.parse(?bool, tree.root, null); try std.testing.expectEqual(@as(?bool, true), parsed); } tree_parser.reset(); { const tree = try tree_parser.parse("false"); const parsed = try tres.parse(?bool, tree.root, null); try std.testing.expectEqual(@as(?bool, false), parsed); } tree_parser.reset(); { const tree = try tree_parser.parse("null"); const parsed = try tres.parse(?bool, tree.root, null); try std.testing.expectEqual(@as(?bool, null), parsed); } tree_parser.reset(); { const tree = try tree_parser.parse("[]"); try std.testing.expectError(error.UnexpectedFieldType, tres.parse(?bool, tree.root, null)); } } // test "json.parse simple struct" { // @setEvalBranchQuota(10_000); // const Role = enum(i64) { crewmate, impostor, ghost }; // const Union = union(enum) { // a: i64, // b: []const u8, // }; // const Substruct = struct { // value: std.json.Value, // slice_of_values: []std.json.Value, // union_a: Union, // union_b: Union, // }; // const Player = struct { // name: []const u8, // based: bool, // }; // const MyTuple = std.meta.Tuple(&[_]type{ i64, bool }); // const Struct = struct { // bool_true: bool, // bool_false: bool, // integer: u8, // float: f64, // optional: ?f32, // an_enum: Role, // an_enum_string: Role, // slice: []i64, // substruct: Substruct, // random_map: std.json.ObjectMap, // number_map: std.StringArrayHashMap(i64), // players: std.StringHashMap(Player), // my_tuple: MyTuple, // my_array: [2]u8, // a_pointer: *u8, // a_weird_string: [*:0]u8, // }; // const json = // \\{ // \\ "bool_true": true, // \\ "bool_false": false, // \\ "integer": 100, // \\ "float": 4.2069, // \\ "optional": null, // \\ "an_enum": 1, // \\ "an_enum_string": "crewmate", // \\ "slice": [1, 2, 3, 4, 5, 6], // \\ "substruct": { // \\ "value": "hello", // \\ "slice_of_values": ["hello", "world"], // \\ "union_a": -42, // \\ "union_b": "hello" // \\ }, // \\ "random_map": { // \\ "a": 123, // \\ "b": "Amogus!!" // \\ }, // \\ "number_map": { // \\ "a": 123, // \\ "b": 456 // \\ }, // \\ "players": { // \\ "aurame": {"name": "Auguste", "based": true}, // \\ "mattnite": {"name": "Matt", "based": true} // \\ }, // \\ "my_tuple": [10, false], // \\ "my_array": [1, 255], // \\ "a_pointer": 5, // \\ "a_weird_string": "hello" // \\} // ; // // NOTE: In practice, we're going to use an arena, thus no parseFree exists because it is not required :) // var arena = std.heap.ArenaAllocator.init(std.testing.allocator); // defer arena.deinit(); // var testing_parser = std.json.Parser.init(std.testing.allocator, false); // defer testing_parser.deinit(); // const tree = try testing_parser.parse(json); // const parsed = try tres.parse(Struct, tree.root, std.testing.allocator); // defer tres.parseFree(parsed, std.testing.allocator); // try std.testing.expectEqual(true, parsed.bool_true); // try std.testing.expectEqual(false, parsed.bool_false); // try std.testing.expectEqual(@as(u8, 100), parsed.integer); // try std.testing.expectApproxEqRel(@as(f64, 4.2069), parsed.float, std.math.epsilon(f64)); // try std.testing.expectEqual(@as(?f32, null), parsed.optional); // try std.testing.expectEqual(Role.impostor, parsed.an_enum); // try std.testing.expectEqual(Role.crewmate, parsed.an_enum_string); // try std.testing.expectEqualSlices(i64, &[_]i64{ 1, 2, 3, 4, 5, 6 }, parsed.slice); // try std.testing.expect(parsed.substruct.value == .String); // try std.testing.expectEqualStrings("hello", parsed.substruct.value.String); // try std.testing.expect(parsed.substruct.slice_of_values.len == 2); // try std.testing.expect(parsed.substruct.slice_of_values[0] == .String); // try std.testing.expectEqualStrings("hello", parsed.substruct.slice_of_values[0].String); // try std.testing.expect(parsed.substruct.slice_of_values[1] == .String); // try std.testing.expectEqualStrings("world", parsed.substruct.slice_of_values[1].String); // try std.testing.expect(parsed.substruct.union_a == .a); // try std.testing.expectEqual(@as(i64, -42), parsed.substruct.union_a.a); // try std.testing.expect(parsed.substruct.union_b == .b); // try std.testing.expectEqualStrings("hello", parsed.substruct.union_b.b); // try std.testing.expectEqual(@as(i64, 123), parsed.random_map.get("a").?.Integer); // try std.testing.expectEqualStrings("Amogus!!", parsed.random_map.get("b").?.String); // try std.testing.expectEqual(@as(i64, 123), parsed.number_map.get("a").?); // try std.testing.expectEqual(@as(i64, 456), parsed.number_map.get("b").?); // try std.testing.expectEqualStrings("Auguste", parsed.players.get("aurame").?.name); // try std.testing.expectEqualStrings("Matt", parsed.players.get("mattnite").?.name); // try std.testing.expectEqual(true, parsed.players.get("aurame").?.based); // try std.testing.expectEqual(true, parsed.players.get("mattnite").?.based); // try std.testing.expectEqual(MyTuple{ 10, false }, parsed.my_tuple); // try std.testing.expectEqual([2]u8{ 1, 255 }, parsed.my_array); // try std.testing.expectEqual(@as(u8, 5), parsed.a_pointer.*); // try std.testing.expectEqualStrings("hello", std.mem.sliceTo(parsed.a_weird_string, 0)); // } // test "json.parse missing field" { // const Struct = struct { // my_super_duper_important_field: bool, // }; // const json = // \\{} // ; // var arena = std.heap.ArenaAllocator.init(std.testing.allocator); // defer arena.deinit(); // var testing_parser = std.json.Parser.init(arena.allocator(), false); // const tree = try testing_parser.parse(json); // const parsed = tres.parse(Struct, tree.root, arena.allocator()); // try std.testing.expectError(error.MissingRequiredField, parsed); // } // test "json.parse undefinedable fields and default values" { // const Struct = struct { // meh: tres.Undefinedable(i64), // meh2: tres.Undefinedable(i64), // default: u8 = 123, // }; // const json = // \\{ // \\ "meh": 42069 // \\} // ; // var arena = std.heap.ArenaAllocator.init(std.testing.allocator); // defer arena.deinit(); // var testing_parser = std.json.Parser.init(arena.allocator(), false); // const tree = try testing_parser.parse(json); // const parsed = try tres.parse(Struct, tree.root, arena.allocator()); // try std.testing.expectEqual(@as(i64, 42069), parsed.meh.value); // try std.testing.expectEqual(true, parsed.meh2.missing); // try std.testing.expectEqual(@as(u8, 123), parsed.default); // } // test "json.parse comptime fields" { // const YoureTheImpostorMessage = struct { // comptime method: []const u8 = "ship/impostor", // sussiness: f64, // }; // const YoureCuteUwUMessage = struct { // comptime method: []const u8 = "a/cutiepie", // cuteness: i64, // }; // const Message = union(enum) { // youre_the_impostor: YoureTheImpostorMessage, // youre_cute_uwu: YoureCuteUwUMessage, // }; // const first_message = // \\{ // \\ "method": "ship/impostor", // \\ "sussiness": 69.420 // \\} // ; // const second_message = // \\{ // \\ "method": "a/cutiepie", // \\ "cuteness": 100 // \\} // ; // var arena = std.heap.ArenaAllocator.init(std.testing.allocator); // defer arena.deinit(); // var testing_parser = std.json.Parser.init(arena.allocator(), false); // const first_tree = try testing_parser.parse(first_message); // const first_parsed = try tres.parse(Message, first_tree.root, arena.allocator()); // try std.testing.expect(first_parsed == .youre_the_impostor); // testing_parser.reset(); // const second_tree = try testing_parser.parse(second_message); // const second_parsed = try tres.parse(Message, second_tree.root, arena.allocator()); // try std.testing.expect(second_parsed == .youre_cute_uwu); // } // test "json.parse custom check functions for unions" { // // jsonrpc request // const RequestId = union(enum) { string: []const u8, integer: i64 }; // const AmogusRequest = struct { // const method = "spaceship/amogus"; // sussy: bool, // }; // const MinecraftNotification = struct { // const method = "game/minecraft"; // crafted: i64, // mined: i64, // }; // const RequestParams = union(enum) { // amogus: AmogusRequest, // minecraft: MinecraftNotification, // }; // const RequestOrNotification = struct { // const Self = @This(); // jsonrpc: []const u8, // id: ?RequestId = null, // method: []const u8, // params: RequestParams, // fn RequestOrNotificationParseError() type { // var err = tres.ParseInternalError(RequestId); // inline for (std.meta.fields(RequestParams)) |field| { // err = err || tres.ParseInternalError(field.field_type); // } // return err; // } // pub fn tresParse(value: std.json.Value, allocator: ?std.mem.Allocator) RequestOrNotificationParseError()!Self { // // var allocator = options.allocator orelse return error.AllocatorRequired; // var object = value.Object; // var request_or_notif: Self = undefined; // request_or_notif.jsonrpc = object.get("jsonrpc").?.String; // request_or_notif.id = if (object.get("id")) |id| try tres.parse(RequestId, id, allocator) else null; // request_or_notif.method = object.get("method").?.String; // inline for (std.meta.fields(RequestParams)) |field| { // if (std.mem.eql(u8, request_or_notif.method, field.field_type.method)) { // request_or_notif.params = @unionInit(RequestParams, field.name, try tres.parse(field.field_type, object.get("params").?, allocator)); // } // } // return request_or_notif; // } // }; // const first_message = // \\{ // \\ "jsonrpc": "2.0", // \\ "id": 10, // \\ "method": "spaceship/amogus", // \\ "params": {"sussy": true} // \\} // ; // var arena = std.heap.ArenaAllocator.init(std.testing.allocator); // defer arena.deinit(); // var testing_parser = std.json.Parser.init(arena.allocator(), false); // const first_tree = try testing_parser.parse(first_message); // const first_parsed = try tres.parse(RequestOrNotification, first_tree.root, arena.allocator()); // try std.testing.expectEqualStrings("2.0", first_parsed.jsonrpc); // try std.testing.expect(first_parsed.id != null); // try std.testing.expect(first_parsed.id.? == .integer); // try std.testing.expectEqual(@as(i64, 10), first_parsed.id.?.integer); // try std.testing.expectEqualStrings("spaceship/amogus", first_parsed.method); // try std.testing.expect(first_parsed.params == .amogus); // try std.testing.expectEqual(true, first_parsed.params.amogus.sussy); // // TODO: Add second test // } // test "json.parse allocator required errors" { // var arena = std.heap.ArenaAllocator.init(std.testing.allocator); // defer arena.deinit(); // var testing_parser = std.json.Parser.init(arena.allocator(), false); // try std.testing.expectError(error.AllocatorRequired, tres.parse([]i64, (try testing_parser.parse("[1, 2, 3, 4]")).root, null)); // testing_parser.reset(); // try std.testing.expectError(error.AllocatorRequired, tres.parse(std.StringArrayHashMap(i64), (try testing_parser.parse( // \\{"a": 123, "b": -69} // )).root, null)); // }
tests.zig
const mon13 = @import("mon13"); const std = @import("std"); const expect = std.testing.expect; const mem = std.mem; test "convert year 0" { const c0 = &mon13.tranquility_year_zero; const mjd = try mon13.mjdFromYmd(c0, -1639577, 7, 2); const c1 = &mon13.tranquility; var year: i32 = 0; var month: u8 = 0; var day: u8 = 0; try mon13.mjdToYmd(mjd, c1, &year, &month, &day); try expect(year == -1639578); try expect(month == 7); try expect(day == 2); } test "strange add gregorian" { const d_year: i32 = -2055615; const d_month: u8 = 08; const d_day: u8 = 19; const a2: i64 = 2763584833174830080; const c = &mon13.gregorian_year_zero; const mjd = try mon13.mjdFromYmd(c, d_year, d_month, d_day); const offset: i32 = @truncate(i32, a2); const res_mjd = mon13.addYears(mjd, c, offset) catch return; var res_year: i32 = 0; try mon13.mjdToYmd(res_mjd, c, &res_year, null, null); try expect(res_year == (d_year +% offset)); } test "add zero years" { const d_year = -89713; const d_month = 2; const d_day = 29; const c = &mon13.gregorian; const mjd0 = try mon13.mjdFromYmd(c, d_year, d_month, d_day); const mjd1 = try mon13.addYears(mjd0, c, 0); try expect(mjd0 == mjd1); } fn skip_import(x: i64) bool { return (x > (std.math.maxInt(i32) / 2)) or (x < -(std.math.maxInt(i32) / 2)); } test "strange convert" { const rd0: i64 = 5385873414131997696 % std.math.maxInt(i32); const offset: i32 = 6356633119034338304 % std.math.maxInt(i32); const mjd0 = try mon13.mjdFromRd(rd0); const mjd1 = mjd0 + offset; _ = mon13.mjdToRd(mjd1) catch return; } test "Tranquility strange add" { const c_yz = &mon13.tranquility_year_zero; const offset: i32 = 544641169; const mjd = try mon13.mjdFromYmd(c_yz, -2796441, 0, 1); _ = mon13.addMonths(mjd, c_yz, offset) catch return; } test "holocene" { const mjd = try mon13.mjdFromYmd(&mon13.gregorian_year_zero, -9999, 1, 1); var hl_year: i32 = 0; var hl_month: u8 = 0; var hl_day: u8 = 0; try mon13.mjdToYmd(mjd, &mon13.holocene, &hl_year, &hl_month, &hl_day); try expect(hl_year == 1); try expect(hl_month == 1); try expect(hl_day == 1); } test "Cotsworth format" { const c = &mon13.cotsworth; const n = &mon13.names_en_US_cotsworth; const mjd = try mon13.mjdFromYmd(c, -2823980, 6, 29); const buf_size = 100; var buf = [_]u8{0} ** buf_size; _ = try mon13.format(mjd, c, n, "%A", buf[0..buf_size]); const expected = "Leap Day"; for (expected) |ch, i| { try expect(buf[i] == ch); } } test "Cotsworth add many months" { const mjd = try mon13.mjdFromYmd(&mon13.cotsworth, 992456, 6, 29); _ = mon13.addMonths(mjd, &mon13.cotsworth, 209601470) catch return; } test "Valid" { try expect(mon13.validYmd(&mon13.tranquility, 1, 1, 1)); } test "Invalid" { try expect(!mon13.validYmd(&mon13.tranquility, 1, 20, 20)); } test "Tempting overflow" { const c = &mon13.tranquility_year_zero; _ = mon13.mjdFromYmd(c, -2147483641, 0, 2) catch return; } test "Day of Year" { const c = &mon13.holocene; const mjd = 383540235; try expect((try mon13.mjdToDayOfYear(mjd, c)) < 366); } test "Add Year Error 1" { const mjd0 = -1956022137; const offset = 257; const c = &mon13.tranquility_year_zero; const res = try mon13.addYears(mjd0, c, offset); try expect(res != 0); } test "Day not found? But why?" { const mjd0 = 1890882699; const c = &mon13.symmetry454; var y: i32 = 0; var m: u8 = 0; var d: u8 = 0; try mon13.mjdToYmd(mjd0, c, &y, &m, &d); try expect(m < 13); } test "Bad Calendar? But why?" { const mjd0 = -1347826664; const c = &mon13.symmetry454; var y: i32 = 0; var m: u8 = 0; var d: u8 = 0; try mon13.mjdToYmd(mjd0, c, &y, &m, &d); try expect(m < 13); } test "Date not found? But why?" { const mjd0 = -1786122197; const offset = -305900; const c = &mon13.symmetry454; const res = try mon13.addYears(mjd0, c, offset); try expect(res != 0); } test "Moon Landing Day" { const mjd = 40422; const c = &mon13.tranquility_year_zero; const n = &mon13.names_en_US_tranquility; const expected = "Moon Landing Day"; var buf = [_]u8{0} ** 100; const res = try mon13.format(mjd, c, n, "%B", buf[0..buf.len]); try expect(res == expected.len); try expect( mem.eql( u8, expected[0..@intCast(usize, res)], buf[0..@intCast(usize, res)], ), ); } test "Add Years on La Fête de la Révolution" { const mjd0 = -1294533640; const offset = 2568471; const c = &mon13.french_revolutionary_romme_sub1; const leap0 = try mon13.mjdToIsLeapYear(mjd0, c); try expect(leap0); var y0: i32 = 0; var m0: u8 = 0; var d0: u8 = 0; try mon13.mjdToYmd(mjd0, c, &y0, &m0, &d0); try expect(m0 == 0); try expect(d0 == 6); const mjd1 = try mon13.addYears(mjd0, c, offset); var y1: i32 = 0; var m1: u8 = 0; var d1: u8 = 0; try mon13.mjdToYmd(mjd1, c, &y1, &m1, &d1); const leap1 = try mon13.mjdToIsLeapYear(mjd1 - 2, c); try expect(!leap1); try expect(y1 == (y0 + offset + 1)); try expect(m1 == 1); try expect(d1 == 1); } test "Rata Die Overflow Message" { const offset = 1389779633; const mjd = 757702997 + offset; try std.testing.expectError(mon13.Err.Overflow, mon13.mjdToRd(mjd)); const msg = mon13.errorMessage(mon13.Err.Overflow); const expected = "Overflow occurred (internal)"; try expect(mem.eql( u8, expected[0..expected.len], msg[0..expected.len], )); } test "basic parse numeric" { const cal = &mon13.gregorian; var result: i32 = 0; _ = try mon13.parse(cal, null, "%Y-%m-%d", "2021-12-26", &result); const expected = try mon13.mjdFromYmd(cal, 2021, 12, 26); try std.testing.expectEqual(result, expected); } test "Julian Christmas" { const gr = &mon13.gregorian; const jl = &mon13.julian; const mjd_jl = try mon13.mjdFromYmd(jl, 2021, 12, 25); const mjd_gr = try mon13.mjdFromYmd(gr, 2022, 1, 7); try std.testing.expectEqual(mjd_gr, mjd_jl); } test "Basic parse name" { const cal = &mon13.gregorian; const n = &mon13.names_en_US_gregorian; var result: i32 = 0; _ = try mon13.parse(cal, n, "%d %B %|Y %q", "26 December 2021 Before Common Era", &result); const expected = try mon13.mjdFromYmd(cal, -2021, 12, 26); try std.testing.expectEqual(result, expected); } test "Parse Moon Landing Day, Year 0" { const cal = &mon13.tranquility_year_zero; const n = &mon13.names_en_US_tranquility; var result: i32 = 0; _ = try mon13.parse(cal, n, "%B", "Moon Landing Day", &result); const expected = try mon13.mjdFromYmd(cal, 0, 0, 1); try std.testing.expectEqual(result, expected); } test "Parse Moon Landing Day, No Year 0" { const cal = &mon13.tranquility; const n = &mon13.names_en_US_tranquility; var result: i32 = 0; _ = try mon13.parse(cal, n, "%B", "Moon Landing Day", &result); const expected = try mon13.mjdFromYmd(cal, -1, 0, 1); try std.testing.expectEqual(result, expected); } test "Negative year" { const cal = &mon13.tranquility; const fmt = "%Y-%m-%d"; const mjd: i32 = -45864173; var buf = [_]u8{0} ** 100; const len_f = try mon13.format(mjd, cal, null, fmt, buf[0..]); var res1: i32 = 0; const len_p = try mon13.parse(cal, null, fmt, buf[0..], &res1); try std.testing.expectEqual(mjd, res1); try std.testing.expectEqual(len_f, len_p); } test "Negative year, and also `" { const cal = &mon13.tranquility; const fmt = "%Y-%m-%d`"; const mjd: i32 = -45864173; var buf = [_]u8{0} ** 100; const len_f = try mon13.format(mjd, cal, null, fmt, buf[0..]); var res1: i32 = 0; const len_p = try mon13.parse(cal, null, fmt, buf[0..], &res1); try std.testing.expectEqual(mjd, res1); try std.testing.expectEqual(len_f, len_p); } test "Format Unreachable?" { const mjd_f: i32 = 1286369277; const placeholder = 13; const fmt = "%tcW $U+%u' )\\^4ZU @+\"?UA%As %tXc ZLl %m%%U\" p` "; const c = &mon13.gregorian_year_zero; const n = &mon13.names_en_US_gregorian; const ASCII_COPY_BUF = 512; var buf0 = [_]u8{placeholder} ** ASCII_COPY_BUF; _ = try mon13.format(mjd_f, c, n, fmt, buf0[0..]); var buf1 = [_]u8{placeholder} ** ASCII_COPY_BUF; std.mem.copy(u8, buf1[0..], buf0[0..]); var dummy: i32 = 0; try std.testing.expectError(error.DateNotFound, mon13.parse(c, n, fmt, buf0[0..], &dummy)); } test "Parse weird" { const cal = &mon13.gregorian_year_zero; const n = &mon13.names_en_US_gregorian; const mjd: i32 = 128180363; const res0 = try mon13.mjdFromYmd(cal, 352804, 10, 16); try std.testing.expectEqual(mjd, res0); const fmt = "$z%BCD 76X%u7|vZ8+%d la < G: F;%YK%B6pnaJW%%dN"; var buf = [_]u8{0} ** 512; _ = try mon13.format(mjd, cal, n, fmt, buf[0..]); var dummy: i32 = 0; try std.testing.expectError(error.DateNotFound, mon13.parse(cal, n, fmt, buf[0..], &dummy)); }
test/unit.zig
// Here's how I solved it by hand: // list1 = [14,13,15,13,-2,10,13,-15,11,-9,-9,-7,-4,-6] // list2 = [00,12,14,00,03,15,11, 12,01,12,03,10,14,12] // i = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 // for i in range(14): // x = peek() + list1[i] // if list1[i] < 0: // pop() // if x != n[i]: // push(n[i] + list2[i]) // Each index where list1 is negative matches some other // index where it's positive, like a stack. // The lists provide dummy numbers that are added to the // value contained in the stack, from which we extract // the following equations: // in[3] + 0 - 2 == in[4] // in[6] + 11 - 15 == in[7] // in[8] + 1 - 9 == in[9] // in[5] + 15 - 9 == in[10] // in[2] + 14 - 7 == in[11] // in[1] + 12 - 4 == in[12] // in[0] + 0 - 6 == in[13] // in[3] - 2 == in[4] // in[6] - 4 == in[7] // in[8] - 8 == in[9] // in[5] + 6 == in[10] // in[2] + 7 == in[11] // in[1] + 8 == in[12] // in[0] - 6 == in[13] // -- Part 1 -- // in[3] == 9 // in[4] == 7 // in[6] == 9 // in[7] == 5 // in[8] == 9 // in[9] == 1 // in[5] == 3 // in[10] == 9 // in[2] == 2 // in[11] == 9 // in[1] == 1 // in[12] == 9 // in[0] == 9 // in[13] == 3 // in[0] == 9 // in[1] == 1 // in[2] == 2 // in[3] == 9 // in[4] == 7 // in[5] == 3 // in[6] == 9 // in[7] == 5 // in[8] == 9 // in[9] == 1 // in[10] == 9 // in[11] == 9 // in[12] == 9 // in[13] == 3 // 91297395919993 // -- Part 2 -- // in[3] = 3 // in[4] = 1 // in[6] = 5 // in[7] = 1 // in[8] = 9 // in[9] = 1 // in[5] = 1 // in[10] = 7 // in[2] = 1 // in[11] = 8 // in[1] = 1 // in[12] = 9 // in[0] = 7 // in[13] = 1 // in[0] = 7 // in[1] = 1 // in[2] = 1 // in[3] = 3 // in[4] = 1 // in[5] = 1 // in[6] = 5 // in[7] = 1 // in[8] = 9 // in[9] = 1 // in[10] = 7 // in[11] = 8 // in[12] = 9 // in[13] = 1 // 71131151917891 const std = @import("std"); const helper = @import("helper.zig"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const HashMap = std.AutoHashMap; const input = @embedFile("../inputs/day24.txt"); pub fn run(alloc: Allocator, stdout_: anytype) !void { const instructions = try parseInstructions(alloc, input); defer alloc.free(instructions); var consteval = ConstEval.init(alloc); defer consteval.deinit(); consteval.evalMany(instructions); if (stdout_) |stdout| { try consteval.get(.z).print(stdout); try stdout.print("\n{}\n", .{consteval.minmax.get(consteval.get(.z))}); } } const Reg = enum(usize) { w, x, y, z, pub fn fromLetter(letter: u8) Reg { return switch (letter) { 'w' => .w, 'x' => .x, 'y' => .y, 'z' => .z, else => unreachable, }; } }; const RegNum = union(enum) { reg: Reg, num: i64 }; const RegPair = struct { a: Reg, b: RegNum }; const Inst = union(enum) { inp: Reg, add: RegPair, mul: RegPair, div: RegPair, mod: RegPair, eql: RegPair, pub fn parse(line: []const u8) !Inst { var splut = split(u8, line, " "); const opcode = splut.next().?; const reg1 = Reg.fromLetter(splut.next().?[0]); if (std.mem.eql(u8, opcode, "inp")) { return Inst{ .inp = reg1 }; } const reg2str = splut.next().?; var reg2: RegNum = undefined; if (std.ascii.isDigit(reg2str[0]) or reg2str[0] == '-') { reg2 = .{ .num = try parseInt(i64, reg2str, 10) }; } else { reg2 = .{ .reg = Reg.fromLetter(reg2str[0]) }; } const pair = RegPair{ .a = reg1, .b = reg2 }; return if (std.mem.eql(u8, opcode, "add")) Inst{ .add = pair } else if (std.mem.eql(u8, opcode, "mul")) Inst{ .mul = pair } else if (std.mem.eql(u8, opcode, "div")) Inst{ .div = pair } else if (std.mem.eql(u8, opcode, "mod")) Inst{ .mod = pair } else if (std.mem.eql(u8, opcode, "eql")) Inst{ .eql = pair } else unreachable; } }; fn parseInstructions(alloc: Allocator, inp: []const u8) ![]const Inst { var list = ArrayList(Inst).init(alloc); var lines = helper.getlines(inp); while (lines.next()) |line| try list.append(try Inst.parse(line)); return list.toOwnedSlice(); } const ExprPair = struct { a: *const Expr, b: *const Expr }; const ExprKind = enum { value, variable, add, mul, div, mod, eql }; const Expr = union(ExprKind) { value: i64, variable: u8, // variable index add: ExprPair, mul: ExprPair, div: ExprPair, mod: ExprPair, eql: ExprPair, const Self = @This(); pub fn equals(self: *const Self, other: *const Self) bool { const kind1: ExprKind = self.*; const kind2: ExprKind = other.*; if (kind1 != kind2) return false; return switch (self.*) { .value => |val| val == other.value, .variable => |val| val == other.variable, .add => |pair| return pair.a.equals(other.add.a) and pair.b.equals(other.add.b) or pair.a.equals(other.add.b) and pair.b.equals(other.add.a), .mul => |pair| return pair.a.equals(other.mul.a) and pair.b.equals(other.mul.b) or pair.a.equals(other.mul.b) and pair.b.equals(other.mul.a), .div => |pair| return pair.a.equals(other.div.a) and pair.b.equals(other.div.b), .mod => |pair| return pair.a.equals(other.mod.a) and pair.b.equals(other.mod.b), .eql => |pair| return pair.a.equals(other.eql.a) and pair.b.equals(other.eql.b) or pair.a.equals(other.eql.b) and pair.b.equals(other.eql.a), }; } pub fn print(self: *const Self, stdout: anytype) @TypeOf(stdout).Error!void { switch (self.*) { .value => |num| try stdout.print("{}", .{num}), .variable => |num| try stdout.print("x{}", .{num}), .add => |pair| try printPair(pair, stdout, '+'), .mul => |pair| try printPair(pair, stdout, '*'), .div => |pair| try printPair(pair, stdout, '/'), .mod => |pair| try printPair(pair, stdout, '%'), .eql => |pair| try printPair(pair, stdout, '='), } } pub fn printPair(pair: ExprPair, stdout: anytype, op: u8) !void { if (op != '*') try stdout.print("(", .{}); try pair.a.print(stdout); try stdout.print(" {c} ", .{op}); try pair.b.print(stdout); if (op != '*') try stdout.print(")", .{}); } }; const MinMax = struct { min: i64, max: i64 }; const MinMaxManager = struct { memo: HashMap(*const Expr, MinMax), const Self = @This(); pub fn init(alloc: Allocator) Self { return .{ .memo = HashMap(*const Expr, MinMax).init(alloc) }; } pub fn deinit(self: *Self) void { self.memo.deinit(); } pub fn get(self: *Self, expr: *const Expr) MinMax { if (self.memo.get(expr)) |minmax| return minmax; var minmax: MinMax = undefined; switch (expr.*) { .value => |num| { minmax.min = num; minmax.max = num; }, .variable => { minmax.min = 1; minmax.max = 9; }, .add => |pair| { const minmax1 = self.get(pair.a); const minmax2 = self.get(pair.b); minmax.min = minmax1.min + minmax2.min; minmax.max = minmax1.max + minmax2.max; }, .mul => |pair| { minmax = self.naiveMinMax(pair, mulop); }, .div => |pair| { minmax = self.naiveMinMax(pair, divop); }, .mod => |pair| { const bminmax = self.get(pair.b); minmax = .{ .min = 0, .max = bminmax.max - 1 }; }, .eql => { minmax.min = 0; minmax.max = 1; }, } self.memo.put(expr, minmax) catch unreachable; return minmax; } fn naiveMinMax(self: *Self, pair: ExprPair, op: fn (i64, i64) i64) MinMax { const minmax1 = self.get(pair.a); const minmax2 = self.get(pair.b); const val1 = op(minmax1.min, minmax2.min); const val2 = op(minmax1.min, minmax2.max); const val3 = op(minmax1.max, minmax2.min); const val4 = op(minmax1.max, minmax2.max); const min = std.math.min(std.math.min3(val1, val2, val3), val4); const max = std.math.max(std.math.max3(val1, val2, val3), val4); return MinMax{ .min = min, .max = max }; } }; fn mulop(x: i64, y: i64) i64 { return x * y; } fn divop(x: i64, y: i64) i64 { return @divTrunc(x, y); } const ConstEval = struct { regs: [4]*const Expr, var_counter: u8 = 1, arena: std.heap.ArenaAllocator, minmax: MinMaxManager, const Self = @This(); pub fn init(alloc: Allocator) Self { var arena = std.heap.ArenaAllocator.init(alloc); var self = Self{ .regs = undefined, .arena = arena, .minmax = MinMaxManager.init(alloc), }; self.initRegs(); return self; } pub fn deinit(self: *Self) void { self.arena.deinit(); self.minmax.deinit(); } pub fn evalMany(self: *Self, insts: []const Inst) void { for (insts) |inst| self.eval(inst); } pub fn eval(self: *Self, inst: Inst) void { switch (inst) { .inp => |reg| self.evalInp(reg), .add => |regpair| self.evalOp(regpair, add), .mul => |regpair| self.evalOp(regpair, mul), .div => |regpair| self.evalOp(regpair, div), .mod => |regpair| self.evalOp(regpair, mod), .eql => |regpair| self.evalOp(regpair, eql), } } fn aexpr(self: *Self, expr: Expr) *Expr { const alloc = self.arena.allocator(); const ptr = alloc.create(Expr) catch unreachable; ptr.* = expr; return ptr; } fn initRegs(self: *Self) void { for (self.regs) |*reg| { reg.* = self.aexpr(.{ .value = 0 }); } } fn evalInp(self: *Self, reg: Reg) void { self.set(reg, self.aexpr(.{ .variable = self.var_counter })); self.var_counter += 1; } fn evalOp(self: *Self, regpair: RegPair, comptime op: fn (*Self, *const Expr, *const Expr) Expr) void { const reg1 = regpair.a; const expr1 = self.get(reg1); const expr2 = switch (regpair.b) { .reg => |reg2| self.get(reg2), .num => |num| self.aexpr(.{ .value = num }), }; const expr = self.aexpr(op(self, expr1, expr2)); const minmax = self.minmax.get(expr); if (minmax.min == minmax.max) { self.set(reg1, self.aexpr(.{ .value = minmax.min })); } else { self.set(reg1, expr); } } fn add(self: *Self, expr1: *const Expr, expr2: *const Expr) Expr { const kind1: ExprKind = expr1.*; const kind2: ExprKind = expr2.*; if (kind2 == .value and expr2.value == 0) { return expr1.*; } else if (kind1 == .value and expr1.value == 0) { return expr2.*; } else if (kind1 == .value and kind2 == .value) { return .{ .value = expr1.value + expr2.value }; } else if (isNiceAdd(expr1) and kind2 == .value) { return .{ .add = .{ .a = expr1.add.a, .b = self.aexpr(self.add(expr1.add.b, expr2)) } }; } else if (isNiceAdd(expr2) and kind1 == .value) { return self.add(expr2, expr1); // previous case } else if (isNiceAdd(expr1) and isNiceAdd(expr2)) { const add_first = self.aexpr(.{ .add = .{ .a = expr1.add.a, .b = expr2.add.a } }); return .{ .add = .{ .a = add_first, .b = self.aexpr(self.add(expr1.add.b, expr2.add.b)) } }; } else if (isNiceAdd(expr1)) { const add_first = self.aexpr(.{ .add = .{ .a = expr1.add.a, .b = expr2 } }); return .{ .add = .{ .a = add_first, .b = self.aexpr(.{ .value = expr1.add.b.value }) } }; } else if (isNiceAdd(expr2)) { const add_first = self.aexpr(.{ .add = .{ .a = expr2.add.a, .b = expr1 } }); return .{ .add = .{ .a = add_first, .b = self.aexpr(.{ .value = expr2.add.b.value }) } }; } else if (kind1 == .value) { return .{ .add = .{ .a = expr2, .b = expr1 } }; } else { return .{ .add = .{ .a = expr1, .b = expr2 } }; } } fn mul(self: *Self, expr1: *const Expr, expr2: *const Expr) Expr { const kind1: ExprKind = expr1.*; const kind2: ExprKind = expr2.*; if (kind2 == .value and expr2.value == 0) { return expr2.*; // 0 } else if (kind1 == .value and expr1.value == 0) { return expr1.*; // 0 } else if (kind2 == .value and expr2.value == 1) { return expr1.*; // do nothing } else if (kind1 == .value and expr1.value == 1) { return expr2.*; // do nothing } else if (kind1 == .value and kind2 == .value) { return .{ .value = expr1.value * expr2.value }; } else if (isNiceMul(expr1) and kind2 == .value) { return .{ .mul = .{ .a = expr1.mul.a, .b = self.aexpr(self.mul(expr1.mul.b, expr2)) } }; } else if (isNiceMul(expr2) and kind1 == .value) { return self.mul(expr2, expr1); // previous case } else if (isNiceMul(expr1) and isNiceMul(expr2)) { const mul_first = self.aexpr(.{ .mul = .{ .a = expr1.mul.a, .b = expr2.mul.a } }); return .{ .add = .{ .a = mul_first, .b = self.aexpr(self.mul(expr1.mul.b, expr2.mul.b)) } }; } else if (kind1 == .add) { return self.add(self.aexpr(self.mul(expr1.add.a, expr2)), self.aexpr(self.mul(expr1.add.b, expr2))); } else if (kind2 == .add) { return self.mul(expr2, expr1); // previous case } else if (kind1 == .value) { return .{ .mul = .{ .a = expr2, .b = expr1 } }; } else { return .{ .mul = .{ .a = expr1, .b = expr2 } }; } } fn div(self: *Self, expr1: *const Expr, expr2: *const Expr) Expr { const kind1: ExprKind = expr1.*; const kind2: ExprKind = expr2.*; if (kind2 == .value and (expr2.value == 0 or expr2.value == 1)) { return expr1.*; } else if (kind1 == .value and kind2 == .value) { return Expr{ .value = @divTrunc(expr1.value, expr2.value) }; } else if (isNiceMul(expr1) and kind2 == .value) { const abs2 = std.math.absInt(expr2.value) catch unreachable; const coeff = expr1.mul.b.value; if (@mod(coeff, abs2) == 0) { return .{ .mul = .{ .a = expr1.mul.a, .b = self.aexpr(.{ .value = @divExact(coeff, expr2.value) }) } }; } } return .{ .div = .{ .a = expr1, .b = expr2 } }; } fn mod(self: *Self, expr1: *const Expr, expr2: *const Expr) Expr { const kind1: ExprKind = expr1.*; const kind2: ExprKind = expr2.*; if (kind2 == .value and expr2.value <= 0) { return expr1.*; } else if (kind1 == .value and expr1.value < 0) { return expr1.*; } else if (kind1 == .value and kind2 == .value) { return Expr{ .value = @mod(expr1.value, expr2.value) }; } else if (isNiceMul(expr1) and kind2 == .value) { if (expr1.mul.b.value > 0) { const mul_first = self.aexpr(self.mod(expr1.mul.a, expr2)); return self.mul(mul_first, expr1.mul.b); } } return .{ .mod = .{ .a = expr1, .b = expr2 } }; } fn eql(self: *Self, expr1: *const Expr, expr2: *const Expr) Expr { _ = self; const kind1: ExprKind = expr1.*; const kind2: ExprKind = expr2.*; if (kind1 == .value and kind2 == .value) { return Expr{ .value = @boolToInt(expr1.value == expr2.value) }; } else if (expr1.equals(expr2)) { return Expr{ .value = 1 }; } const minmax1 = self.minmax.get(expr1); const minmax2 = self.minmax.get(expr2); if (minmax1.max < minmax2.min or minmax2.max < minmax1.min) { return Expr{ .value = 0 }; } return Expr{ .eql = .{ .a = expr1, .b = expr2 } }; } fn isNiceAdd(expr: *const Expr) bool { return expr.* == .add and expr.add.b.* == .value; } fn isNiceMul(expr: *const Expr) bool { return expr.* == .mul and expr.mul.b.* == .value; } pub fn get(self: Self, reg: Reg) *const Expr { return self.regs[@enumToInt(reg)]; } pub fn set(self: *Self, reg: Reg, expr: *const Expr) void { self.regs[@enumToInt(reg)] = expr; } }; const tokenize = std.mem.tokenize; const split = std.mem.split; const count = std.mem.count; const parseUnsigned = std.fmt.parseUnsigned; const parseInt = std.fmt.parseInt; const sort = std.sort.sort;
src/day24.zig
const std = @import("std"); const mem = std.mem; const print = std.debug.print; const assert = std.debug.assert; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = &gpa.allocator; { // Solution 1 var input = [9]u8{3, 2, 6, 5, 1, 9, 4, 7, 8}; var curr: usize = 0; { var move: usize = 0; while (move < 100) : (move += 1) { const removed = [_]u8 { input[@mod(curr + 1, input.len)], input[@mod(curr + 2, input.len)], input[@mod(curr + 3, input.len)], }; var target = input[curr] - 1; while (true) { if (target == 0) target = input.len; if (target != removed[0] and target != removed[1] and target != removed[2]) break; target -= 1; } var src = @mod(curr + 4, input.len); var dst = @mod(curr + 1, input.len); while (true) { input[dst] = input[src]; if (input[dst] == target) { input[@mod(dst + 1, input.len)] = removed[0]; input[@mod(dst + 2, input.len)] = removed[1]; input[@mod(dst + 3, input.len)] = removed[2]; break; } src = @mod(src + 1, input.len); dst = @mod(dst + 1, input.len); } curr = @mod(curr + 1, input.len); //printMoveU8(input[0..], move, curr); }} var idx1: usize = 0; for (input) |v, i| { if (v == 1) { idx1 = i; break; } } print("Day 23 - Solution 1: ", .{}); var i: usize = 1; while (i < 9) : (i += 1) { print("{}", .{input[@mod(idx1 + i, 9)]}); } print("\n", .{}); } { // Solution 2 print("Day 23 - Solution 2: {}\n", .{0}); } } fn printMoveU8(items: []u8, move: usize, curr: usize) void { print("Move: {} - ", .{move}); for (items) |v, i| { if (i == curr) { print("({}) ", .{v}); } // else if (v <= 9) { print("|{}| ", .{v}); } else { print("{} ", .{v}); } } print("\n", .{}); } fn printMoveU32(items: []u32, move: usize, curr: usize) void { print("Move: {} - ", .{move}); for (items) |v, i| { if (i == curr) { print("({}) ", .{v}); } // else if (v <= 9) { print("|{}| ", .{v}); } else { print("{} ", .{v}); } } print("\n", .{}); }
2020/src/day_23.zig
const TexturePack = @import("main.zig").TexturePack; const t = 0x00000000; const W = 0xffffffff; const B = 0x11000000; const _actorsprites = [_][32*32]const u32 { { t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,W,W,W,W,W,W,W,W,W,W,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,W,W,W,W,W,W,W,W,W,W,W,W,W,t,t,W,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,W,W,W,t,t,t,t,t,t,t,t,t,W,W,W,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,W,W,W,t,t,t,t,t,t,t,t,t,t,t,t,W,W,t,t,t,t,t,t,t,t,t, t,t,t,t,t,W,W,W,t,t,t,W,W,t,t,t,t,W,W,t,t,W,W,t,t,t,t,t,t,t,t,t, t,t,t,t,W,W,W,t,t,t,W,t,W,t,t,t,t,W,W,W,t,t,W,W,t,t,t,t,t,t,t,t, t,t,t,t,W,W,t,t,t,t,W,t,t,W,t,t,W,W,t,t,W,W,W,W,t,t,t,t,W,t,t,t, t,t,t,t,W,W,t,t,t,W,t,t,t,W,W,t,W,t,t,t,t,W,t,W,t,t,t,t,t,t,t,t, t,t,t,t,W,W,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,W,W,t,t,t,t,t,t,t,t, t,t,t,t,W,W,W,t,t,t,t,t,W,W,t,t,t,t,W,W,t,t,W,W,t,t,t,t,t,t,t,t, t,t,t,t,W,W,W,t,t,t,t,t,t,W,W,W,W,W,W,t,t,W,W,W,t,t,t,t,t,t,t,t, t,t,t,t,t,W,W,W,W,t,t,t,t,t,t,t,t,t,t,t,W,W,W,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,W,W,W,W,W,W,W,W,W,W,W,t,t,t,t,t,t,W,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,W,W,t,t,t,t,t,W,W,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,W,W,t,t,t,t,t,W,W,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,W,W,t,t,t,t,t,W,W,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,W,W,t,t,W,W,W,W,W,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,W,W,W,W,W,W,W,W,W,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,W,W,W,W,t,t,t,W,W,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,W,W,t,t,t,t,t,W,W,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,W,W,t,t,t,t,t,W,W,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,W,W,W,W,t,t,t,W,W,W,W,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,W,W,W,W,t,t,t,W,W,W,W,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t }, { t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,W,W,W,W,W,W,W,W,W,W,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,W,W,W,W,W,W,W,W,W,W,W,W,W,t,t,W,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,W,W,W,t,t,t,t,t,t,t,t,t,W,W,W,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,W,W,W,t,t,t,t,t,t,t,t,t,t,t,t,W,W,t,t,t,t,t,t,t,t,t, t,t,t,t,t,W,W,W,t,t,t,W,W,t,t,t,t,W,W,t,t,W,W,t,t,t,t,t,t,t,t,t, t,t,t,t,W,W,W,t,t,t,W,t,W,t,t,t,t,W,W,W,t,t,W,W,t,t,t,t,t,t,t,t, t,t,t,t,W,W,t,t,t,t,W,t,t,W,t,t,W,W,t,t,W,W,W,W,t,t,t,t,W,t,t,t, t,t,t,t,W,W,t,t,t,W,t,t,t,W,W,t,W,t,t,t,t,W,t,W,t,t,t,t,t,t,t,t, t,t,t,t,W,W,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,W,W,t,t,t,t,t,t,t,t, t,t,t,t,W,W,W,t,t,t,t,t,W,W,t,t,t,t,W,W,t,t,W,W,t,t,t,t,t,t,t,t, t,t,t,t,W,W,W,t,t,t,t,t,t,W,W,W,W,W,W,t,t,W,W,W,t,t,t,t,t,t,t,t, t,t,t,t,t,W,W,W,W,t,t,t,t,t,t,t,t,t,t,t,W,W,W,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,W,W,W,W,W,W,W,W,W,W,W,t,t,t,t,t,t,W,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,W,W,t,t,t,t,t,W,W,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,W,W,t,t,t,t,t,W,W,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,W,W,t,t,t,t,t,t,W,W,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,W,W,t,t,t,W,W,W,W,W,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,W,W,W,W,W,W,W,W,W,W,W,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,W,W,W,W,W,W,t,t,t,t,W,W,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,W,W,W,W,t,t,t,t,t,t,t,t,t,W,W,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,W,W,t,t,t,t,t,t,t,t,t,t,t,W,W,t,W,W,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,W,W,W,W,t,t,t,t,t,t,t,t,t,W,W,W,W,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,W,W,W,W,t,t,t,t,t,t,t,t,t,W,W,W,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t, t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t } }; pub fn ActorSprites() !TexturePack { var ActSpr = TexturePack.init(); for _actorsprites |raw| { _ = try TexturePack.appendRaw(raw, 32, 32); } return ActSpr; }
src/sprites.zig
const std = @import("std"); usingnamespace @import("kira").log; const utils = @import("kira").utils; const glfw = @import("kira").glfw; const gl = @import("kira").gl; const renderer = @import("kira").renderer; const window = @import("kira").window; const input = @import("kira").input; const math = @import("kira").math; const Mat4x4f = math.mat4x4.Generic(f32); const Vec2f = math.vec2.Generic(f32); const Vertex = comptime renderer.VertexGeneric(false, Vec2f); const Batch = renderer.BatchGeneric(1024, 6, 4, Vertex); const Colour = renderer.ColourGeneric(f32); const Ship = struct { firerate: f32 = 0.5, firetimer: f32 = 0, firecount: u32 = 0, position: Vec2f = Vec2f{}, speed: Vec2f = Vec2f{}, size: Vec2f = Vec2f{}, colour: Colour = Colour.rgba(255, 255, 255, 255), pub fn draw(self: Ship, batch: *Batch) anyerror!void { try batch.submitDrawable([Batch.max_vertex_count]Vertex{ .{ .position = self.position, .colour = self.colour }, .{ .position = .{ .x = self.position.x + self.size.x, .y = self.position.y }, .colour = self.colour }, .{ .position = .{ .x = self.position.x + self.size.x, .y = self.position.y + self.size.y }, .colour = self.colour }, .{ .position = .{ .x = self.position.x, .y = self.position.y + self.size.y }, .colour = self.colour }, }); } }; const Bullet = struct { position: Vec2f = Vec2f{}, velocity: Vec2f = Vec2f{}, size: Vec2f = Vec2f{}, colour: Colour = Colour.rgba(255, 255, 255, 255), alive: bool = false, pub fn draw(self: Bullet, batch: *Batch) anyerror!void { try batch.submitDrawable([Batch.max_vertex_count]Vertex{ .{ .position = self.position, .colour = self.colour }, .{ .position = .{ .x = self.position.x + self.size.x, .y = self.position.y }, .colour = self.colour }, .{ .position = .{ .x = self.position.x + self.size.x, .y = self.position.y + self.size.y }, .colour = self.colour }, .{ .position = .{ .x = self.position.x, .y = self.position.y + self.size.y }, .colour = self.colour }, }); } }; const BulletFactory = struct { pub const maxcount: u32 = 500; list: [maxcount]Bullet = undefined, pub fn clear(self: *BulletFactory) void { var i: u32 = 0; while (i < maxcount) : (i += 1) { self.list[i].alive = false; } } pub fn draw(self: BulletFactory, batch: *Batch) !void { var i: u32 = 0; while (i < maxcount) : (i += 1) { if (self.list[i].alive) { try self.list[i].draw(batch); } } } pub fn update(self: *BulletFactory) void { var i: u32 = 0; while (i < maxcount) : (i += 1) { if (self.list[i].alive) { self.list[i].position = self.list[i].position.addValues(self.list[i].velocity.x * @floatCast(f32, targetfps), self.list[i].velocity.y * @floatCast(f32, targetfps)); if (self.list[i].velocity.y > 0.1 and self.list[i].position.y > 1000 or self.list[i].velocity.y < -0.1 and self.list[i].position.y < -100) { self.list[i].alive = false; } } } } pub fn add(self: *BulletFactory, bullet: Bullet) !void { var i: u32 = 0; while (i < maxcount) : (i += 1) { if (!self.list[i].alive) { self.list[i] = bullet; self.list[i].alive = true; return; } } try utils.check(true, "Unable to add bullet(filled list)!", .{}); } }; var win_running = false; var targetfps: f64 = 1.0 / 60.0; var inp = input.Info{}; var player = Ship{ .firerate = 0.1, .firetimer = 0.0, .firecount = 100, .position = Vec2f{ .x = 1024 / 2 - 15, .y = 768 - 30 * 2 }, .speed = Vec2f{ .x = 0, .y = 0 }, .size = Vec2f{ .x = 30, .y = 30 }, .colour = Colour.rgba(30, 70, 230, 255), }; const vertex_shader = \\#version 330 core \\layout (location = 0) in vec3 aPos; \\layout (location = 1) in vec4 aColor; \\out vec4 ourColor; \\uniform mat4 MVP; \\void main() { \\ gl_Position = MVP * vec4(aPos, 1.0); \\ ourColor = aColor; \\} ; const fragment_shader = \\#version 330 core \\out vec4 final; \\in vec4 ourColor; \\void main() { \\ final = ourColor; \\} ; fn closeCallback(handle: ?*c_void) void { win_running = false; } fn resizeCallback(handle: ?*c_void, w: i32, h: i32) void { gl.viewport(0, 0, w, h); } fn keyboardCallback(handle: ?*c_void, key: i32, sc: i32, ac: i32, mods: i32) void { inp.handleKeyboard(key, ac) catch unreachable; } fn shaderAttribs() void { const stride = @sizeOf(Vertex); gl.shaderProgramSetVertexAttribArray(0, true); gl.shaderProgramSetVertexAttribArray(1, true); gl.shaderProgramSetVertexAttribPointer(0, 3, f32, false, stride, @intToPtr(?*const c_void, @byteOffsetOf(Vertex, "position"))); gl.shaderProgramSetVertexAttribPointer(1, 4, f32, false, stride, @intToPtr(?*const c_void, @byteOffsetOf(Vertex, "colour"))); } fn submitFn(self: *Batch, vertex: [Batch.max_vertex_count]Vertex) renderer.Error!void { try self.submitVertex(self.submission_counter, 0, vertex[0]); try self.submitVertex(self.submission_counter, 1, vertex[1]); try self.submitVertex(self.submission_counter, 2, vertex[2]); try self.submitVertex(self.submission_counter, 3, vertex[3]); if (self.submission_counter == 0) { try self.submitIndex(self.submission_counter, 0, 0); try self.submitIndex(self.submission_counter, 1, 1); try self.submitIndex(self.submission_counter, 2, 2); try self.submitIndex(self.submission_counter, 3, 2); try self.submitIndex(self.submission_counter, 4, 3); try self.submitIndex(self.submission_counter, 5, 0); } else { const back = self.index_list[self.submission_counter - 1]; var i: u8 = 0; while (i < Batch.max_index_count) : (i += 1) { try self.submitIndex(self.submission_counter, i, back[i] + 4); try self.submitIndex(self.submission_counter, i, back[i] + 4); try self.submitIndex(self.submission_counter, i, back[i] + 4); try self.submitIndex(self.submission_counter, i, back[i] + 4); try self.submitIndex(self.submission_counter, i, back[i] + 4); try self.submitIndex(self.submission_counter, i, back[i] + 4); } } self.submission_counter += 1; } pub fn main() !void { try glfw.init(); defer glfw.deinit(); glfw.resizable(false); glfw.initGLProfile(); var win = window.Info{}; var frametime = window.FrameTime{}; win.title = "Simple shooter"; win.callbacks.close = closeCallback; win.callbacks.resize = resizeCallback; win.callbacks.keyinp = keyboardCallback; const sw = glfw.getScreenWidth(); const sh = glfw.getScreenHeight(); win.position.x = @divTrunc((sw - win.size.width), 2); win.position.y = @divTrunc((sh - win.size.height), 2); try win.create(false); defer win.destroy() catch unreachable; inp.bindKey('A') catch |err| { if (err == input.Error.NoEmptyBinding) { inp.clearAllBindings(); try inp.bindKey('A'); } else return err; }; try inp.bindKey('D'); try inp.bindKey('F'); glfw.makeContext(win.handle); glfw.vsync(true); gl.init(); defer gl.deinit(); var shaderprogram = try gl.shaderProgramCreate(std.heap.page_allocator, vertex_shader, fragment_shader); defer gl.shaderProgramDelete(shaderprogram); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const alloc = &arena.allocator; var batch = try alloc.create(Batch); try batch.create(shaderprogram, shaderAttribs); defer batch.destroy(); batch.submitfn = submitFn; var cam = try alloc.create(math.Camera2D); cam.ortho = Mat4x4f.ortho(0, @intToFloat(f32, win.size.width), @intToFloat(f32, win.size.height), 0, -1, 1); cam.view = Mat4x4f.identity(); cam.zoom = .{ .x = 1, .y = 1 }; var playerbulletfactory = try alloc.create(BulletFactory); playerbulletfactory.clear(); win_running = true; while (win_running) { frametime.start(); { const keyA = try inp.keyState('A'); const keyD = try inp.keyState('D'); const keyF = try inp.keyState('F'); const acc = 50.0; const maxspd = 300.0; const friction = 10.0; const bullet = Bullet{ .size = .{ .x = 10, .y = 10 }, .position = .{ .x = player.position.x + player.size.x / 2 - 5, .y = player.position.y }, .velocity = .{ .x = 0, .y = -200 }, .colour = Colour.rgba(200, 150, 50, 255), }; if (keyD == input.Info.State.down and player.speed.x <= maxspd) { player.speed.x += acc; } if (keyA == input.Info.State.down and player.speed.x >= -maxspd) { player.speed.x -= acc; } if (player.speed.x > 0.1) { player.speed.x -= friction; } else if (player.speed.x < -0.1) { player.speed.x += friction; } if (player.firetimer < player.firerate) { player.firetimer += 1 * @floatCast(f32, frametime.delta); } else if (player.firecount > 0) { if (keyF == input.Info.State.down) { player.firetimer = 0.0; player.firecount -= 1; std.log.notice("player: fire({})", .{player.firecount}); playerbulletfactory.add(bullet) catch |err| { if (err == utils.Error.CheckFailed) { player.firecount += 1; } }; } } if (player.position.x > @intToFloat(f32, win.size.width) - player.size.x or player.position.x <= 0) player.speed.x = -player.speed.x; player.position.x += player.speed.x * @floatCast(f32, targetfps); } playerbulletfactory.update(); inp.handle(); gl.clearColour(0.1, 0.1, 0.1, 1.0); gl.clearBuffers(gl.BufferBit.colour); gl.shaderProgramUse(shaderprogram); cam.attach(); defer cam.detach(); gl.shaderProgramSetMat4x4f(gl.shaderProgramGetUniformLocation(shaderprogram, "MVP"), @ptrCast([*]const f32, &cam.view.toArray())); try player.draw(batch); try playerbulletfactory.draw(batch); try batch.draw(gl.DrawMode.triangles); defer batch.cleanAll(); defer batch.submission_counter = 0; glfw.sync(win.handle); glfw.processEvents(); frametime.stop(); frametime.sleep(targetfps); } }
examples/primitive-simpleshooter.zig
const std = @import("std"); const assert = std.debug.assert; const warn = std.debug.warn; const Allocator = std.mem.Allocator; const math = std.math; const geo = @import("index.zig"); const V2f32 = geo.V2f32; const V3f32 = geo.V3f32; const M44f32 = geo.M44f32; const DBG = false; const DBG1 = false; pub const Face = struct { a: usize, b: usize, c: usize, normal: V3f32, pub fn init(a: usize, b: usize, c: usize, normal: V3f32) Face { return Face { .a = a, .b = b, .c = c, .normal = normal }; } pub fn initComputeNormal(vertexes: []const Vertex, a: usize, b: usize, c: usize) Face { var normal = computeFaceNormal(vertexes, a, b, c); return Face.init(a, b, c, normal); } }; pub fn computeFaceNormal(vertexes: []const Vertex, a: usize, b: usize, c: usize) V3f32 { // Get the corresponding vertice coordinates const v3a = vertexes[a].coord; const v3b = vertexes[b].coord; const v3c = vertexes[c].coord; // Use two edges and compute the face normal and return it var ab: V3f32 = v3a.sub(&v3b); var bc: V3f32 = v3b.sub(&v3c); return ab.cross(&bc); } pub const Vertex = struct { pub fn init(x: f32, y: f32, z: f32) Vertex { return Vertex{ .coord = V3f32.init(x, y, z), .world_coord = V3f32.init(0, 0, 0), .normal_coord = V3f32.init(0, 0, 0), .texture_coord = V2f32.init(0, 0), }; } pub coord: V3f32, pub world_coord: V3f32, pub normal_coord: V3f32, pub texture_coord: V2f32, }; pub const Mesh = struct { const Self = @This(); pub pAllocator: *Allocator, pub name: []const u8, pub position: V3f32, pub rotation: V3f32, pub vertices: []Vertex, pub faces: []Face, pub fn init(pAllocator: *Allocator, name: []const u8, vertices_count: usize, faces_count: usize) !Self { return Self{ .pAllocator = pAllocator, .name = name, .position = V3f32.init(0.0, 0.0, 0.0), .rotation = V3f32.init(0.0, 0.0, 0.0), .vertices = try pAllocator.alloc(Vertex, vertices_count), .faces = try pAllocator.alloc(Face, faces_count), }; } pub fn deinit(pSelf: *Self) void { pSelf.pAllocator.free(pSelf.vertices); pSelf.pAllocator.free(pSelf.faces); } }; /// Compute the normal for each vertice. Assume the faces in the mesh /// are ordered counter clockwise so the computed normal always points /// "out". /// /// Note: From http://www.iquilezles.org/www/articles/normals/normals.htm pub fn computeVerticeNormalsDbg(comptime dbg: bool, meshes: []Mesh) void { if (dbg) warn("computeVn:\n"); // Loop over each mesh for (meshes) |msh| { // Zero the normal_coord of each vertex for (msh.vertices) |*vertex, i| { vertex.normal_coord = V3f32.initVal(0); } // Calculate the face normal and sum the normal into its vertices for (msh.faces) |face| { if (dbg) warn(" v{}:v{}:v{}\n", face.a, face.b, face.c); var nm = computeFaceNormal(msh.vertices, face.a, face.b, face.c); if (dbg) warn(" nm={}\n", nm); // Sum the face normals into this faces vertices.normal_coord msh.vertices[face.a].normal_coord = msh.vertices[face.a].normal_coord.add(&nm); msh.vertices[face.b].normal_coord = msh.vertices[face.b].normal_coord.add(&nm); msh.vertices[face.c].normal_coord = msh.vertices[face.c].normal_coord.add(&nm); if (dbg) { warn(" s {}={} {}={} {}={}\n", face.a, msh.vertices[face.a].normal_coord, face.b, msh.vertices[face.b].normal_coord, face.c, msh.vertices[face.c].normal_coord); } } // Normalize each vertex for (msh.vertices) |*vertex, i| { if (dbg) warn(" nrm v{}.normal_coord={}", i, vertex.normal_coord); vertex.normal_coord = vertex.normal_coord.normalize(); if (dbg) warn(" v{}.normal_coord.normalized={}\n", i, vertex.normal_coord); } } } /// Compute the normal for each vertice. Assume the faces in the mesh /// are ordered counter clockwise so the computed normal always points /// "out". pub fn computeVerticeNormals(meshes: []Mesh) void { computeVerticeNormalsDbg(false, meshes); } test "mesh" { if (DBG or DBG1) warn("\n"); var direct_allocator = std.heap.DirectAllocator.init(); var arena_allocator = std.heap.ArenaAllocator.init(&direct_allocator.allocator); defer arena_allocator.deinit(); var pAllocator = &arena_allocator.allocator; var mesh = try Mesh.init(pAllocator, "mesh1", 8, 12); defer mesh.deinit(); assert(std.mem.eql(u8, mesh.name[0..], "mesh1")); assert(mesh.position.x() == 0.0); assert(mesh.position.data[1] == 0.0); assert(mesh.position.data[2] == 0.0); assert(mesh.rotation.data[0] == 0.0); assert(mesh.rotation.data[1] == 0.0); assert(mesh.rotation.data[2] == 0.0); // Unit cube about 0,0,0 mesh.vertices[0] = Vertex{ .coord = V3f32.init(-1, 1, 1), .world_coord = undefined, .normal_coord = undefined, .texture_coord = undefined, }; assert(mesh.vertices[0].coord.x() == -1); assert(mesh.vertices[0].coord.y() == 1); assert(mesh.vertices[0].coord.z() == 1); mesh.vertices[1] = Vertex{ .coord = V3f32.init(1, 1, 1), .world_coord = undefined, .normal_coord = undefined, .texture_coord = undefined, }; assert(mesh.vertices[1].coord.x() == 1); assert(mesh.vertices[1].coord.y() == 1); assert(mesh.vertices[1].coord.z() == 1); mesh.vertices[2] = Vertex{ .coord = V3f32.init(-1, -1, 1), .world_coord = undefined, .normal_coord = undefined, .texture_coord = undefined, }; assert(mesh.vertices[2].coord.x() == -1); assert(mesh.vertices[2].coord.y() == -1); assert(mesh.vertices[2].coord.z() == 1); mesh.vertices[3] = Vertex{ .coord = V3f32.init(1, -1, 1), .world_coord = undefined, .normal_coord = undefined, .texture_coord = undefined, }; assert(mesh.vertices[3].coord.x() == 1); assert(mesh.vertices[3].coord.y() == -1); assert(mesh.vertices[3].coord.z() == 1); mesh.vertices[4] = Vertex{ .coord = V3f32.init(-1, 1, -1), .world_coord = undefined, .normal_coord = undefined, .texture_coord = undefined, }; assert(mesh.vertices[4].coord.x() == -1); assert(mesh.vertices[4].coord.y() == 1); assert(mesh.vertices[4].coord.z() == -1); mesh.vertices[5] = Vertex{ .coord = V3f32.init(1, 1, -1), .world_coord = undefined, .normal_coord = undefined, .texture_coord = undefined, }; assert(mesh.vertices[5].coord.x() == 1); assert(mesh.vertices[5].coord.y() == 1); assert(mesh.vertices[5].coord.z() == -1); mesh.vertices[6] = Vertex{ .coord = V3f32.init(1, -1, -1), .world_coord = undefined, .normal_coord = undefined, .texture_coord = undefined, }; assert(mesh.vertices[6].coord.x() == 1); assert(mesh.vertices[6].coord.y() == -1); assert(mesh.vertices[6].coord.z() == -1); mesh.vertices[7] = Vertex{ .coord = V3f32.init(-1, -1, -1), .world_coord = undefined, .normal_coord = undefined, .texture_coord = undefined, }; assert(mesh.vertices[7].coord.x() == -1); assert(mesh.vertices[7].coord.y() == -1); assert(mesh.vertices[7].coord.z() == -1); // The cube has 6 side each composed // of 2 trianglar faces on the side // for 12 faces; mesh.faces[0] = Face.initComputeNormal(mesh.vertices, 0, 1, 2); mesh.faces[1] = Face.initComputeNormal(mesh.vertices, 1, 2, 3); mesh.faces[2] = Face.initComputeNormal(mesh.vertices, 1, 3, 6); mesh.faces[3] = Face.initComputeNormal(mesh.vertices, 1, 5, 6); mesh.faces[4] = Face.initComputeNormal(mesh.vertices, 0, 1, 4); mesh.faces[5] = Face.initComputeNormal(mesh.vertices, 1, 4, 5); mesh.faces[6] = Face.initComputeNormal(mesh.vertices, 2, 3, 7); mesh.faces[7] = Face.initComputeNormal(mesh.vertices, 3, 6, 7); mesh.faces[8] = Face.initComputeNormal(mesh.vertices, 0, 2, 7); mesh.faces[9] = Face.initComputeNormal(mesh.vertices, 0, 4, 7); mesh.faces[10] = Face.initComputeNormal(mesh.vertices, 4, 5, 6); mesh.faces[11] = Face.initComputeNormal(mesh.vertices, 4, 6, 7); }
mesh.zig
pub const Planet = enum(u4) { mercury, venus, earth, mars, jupiter, saturn, uranus, neptune, }; pub const SpaceAge = struct { seconds: f64, const EARTH_YEAR_IN_SECONDS = 31557600; pub fn init(seconds: isize) SpaceAge { return SpaceAge { .seconds = @intToFloat(f64, seconds), }; } fn getOrbitalPeriodInSecondsFromEarthYearsOf(planet: Planet) f64 { return EARTH_YEAR_IN_SECONDS * getOrbitalPeriodInEarthYearsOf(planet); } fn getOrbitalPeriodInEarthYearsOf(planet: Planet) f64 { return switch (planet) { .mercury => 0.2408467, .venus => 0.61419726, .earth => 1.0, .mars => 1.8808158, .jupiter => 11.862615, .saturn => 29.447498, .uranus => 84.016846, .neptune => 164.79132, }; } pub fn onMercury(self: SpaceAge) f64 { return self.seconds / getOrbitalPeriodInSecondsFromEarthYearsOf(.mercury); } pub fn onVenus(self: SpaceAge) f64 { return self.seconds / getOrbitalPeriodInSecondsFromEarthYearsOf(.venus); } pub fn onEarth(self: SpaceAge) f64 { return self.seconds / getOrbitalPeriodInSecondsFromEarthYearsOf(.earth); } pub fn onMars(self: SpaceAge) f64 { return self.seconds / getOrbitalPeriodInSecondsFromEarthYearsOf(.mars); } pub fn onJupiter(self: SpaceAge) f64 { return self.seconds / getOrbitalPeriodInSecondsFromEarthYearsOf(.jupiter); } pub fn onSaturn(self: SpaceAge) f64 { return self.seconds / getOrbitalPeriodInSecondsFromEarthYearsOf(.saturn); } pub fn onUranus(self: SpaceAge) f64 { return self.seconds / getOrbitalPeriodInSecondsFromEarthYearsOf(.uranus); } pub fn onNeptune(self: SpaceAge) f64 { return self.seconds / getOrbitalPeriodInSecondsFromEarthYearsOf(.neptune); } };
exercises/practice/space-age/.meta/example.zig
const Id = @import("zig_grammar.tokens.zig").Id; pub fn idToString(id: Id) []const u8 { switch (id) { .Builtin => return "@builtin", .Ampersand => return "&", .AmpersandAmpersand => return "&&", .AmpersandEqual => return "&=", .Asterisk => return "*", .AsteriskAsterisk => return "**", .AsteriskEqual => return "*=", .AsteriskPercent => return "*%", .AsteriskPercentEqual => return "*%=", .Caret => return "^", .CaretEqual => return "^=", .Colon => return ":", .Comma => return ",", .Period => return ".", .PeriodAsterisk => return ".*", .PeriodQuestionMark => return ".?", .Ellipsis2 => return "..", .Ellipsis3 => return "...", .Equal => return "=", .EqualEqual => return "==", .EqualAngleBracketRight => return "=>", .Bang => return "!", .BangEqual => return "!=", .AngleBracketLeft => return "<", .AngleBracketAngleBracketLeft => return "<<", .AngleBracketAngleBracketLeftEqual => return "<<=", .AngleBracketLeftEqual => return "<=", .LCurly => return "{", .LBrace => return "{", .LBracket => return "[", .LParen => return "(", .Minus => return "-", .MinusEqual => return "-=", .MinusAngleBracketRight => return "->", .MinusPercent => return "-%", .MinusPercentEqual => return "-%=", .Percent => return "%", .PercentEqual => return "%=", .Pipe => return "|", .PipePipe => return "||", .PipeEqual => return "|=", .Plus => return "+", .PlusPlus => return "++", .PlusEqual => return "+=", .PlusPercent => return "+%", .PlusPercentEqual => return "+%=", .BracketStarCBracket => return "[*c]", .BracketStarBracket => return "[*]", .QuestionMark => return "?", .AngleBracketRight => return ">", .AngleBracketAngleBracketRight => return ">>", .AngleBracketAngleBracketRightEqual => return ">>=", .AngleBracketRightEqual => return ">=", .RBrace => return "}", .RBracket => return "]", .RParen => return ")", .Semicolon => return ";", .Slash => return "/", .SlashEqual => return "/=", .Tilde => return "~", .Keyword_align => return "align", .Keyword_allowzero => return "allowzero", .Keyword_and => return "and", .Keyword_asm => return "asm", .Keyword_async => return "async", .Keyword_await => return "await", .Keyword_break => return "break", .Keyword_catch => return "catch", .Keyword_cancel => return "cancel", .Keyword_comptime => return "comptime", .Keyword_const => return "const", .Keyword_continue => return "continue", .Keyword_defer => return "defer", .Keyword_else => return "else", .Keyword_enum => return "enum", .Keyword_errdefer => return "errdefer", .Keyword_error => return "error", .Keyword_export => return "export", .Keyword_extern => return "extern", .Keyword_false => return "false", .Keyword_fn => return "fn", .Keyword_for => return "for", .Keyword_if => return "if", .Keyword_inline => return "inline", .Keyword_nakedcc => return "nakedcc", .Keyword_noalias => return "noalias", .Keyword_null => return "null", .Keyword_or => return "or", .Keyword_orelse => return "orelse", .Keyword_packed => return "packed", .Keyword_promise => return "promise", .Keyword_pub => return "pub", .Keyword_resume => return "resume", .Keyword_return => return "return", .Keyword_linksection => return "linksection", .Keyword_stdcallcc => return "stdcallcc", .Keyword_struct => return "struct", .Keyword_suspend => return "suspend", .Keyword_switch => return "switch", .Keyword_test => return "test", .Keyword_threadlocal => return "threadlocal", .Keyword_true => return "true", .Keyword_try => return "try", .Keyword_undefined => return "undefined", .Keyword_union => return "union", .Keyword_unreachable => return "unreachable", .Keyword_use => return "use", .Keyword_usingnamespace => return "usingnamespace", .Keyword_var => return "var", .Keyword_volatile => return "volatile", .Keyword_while => return "while", .Invalid => return "$invalid", .Eof => return "$eof", .Newline => return "$newline", .Ignore => return "$ignore", .ShebangLine => return "#!", .LineComment => return "//", .DocComment => return "///", .RootDocComment => return "///", .LineString => return "\\", .LineCString => return "c\\", .Identifier => return "Identifier", .CharLiteral => return "CharLiteral", .StringLiteral => return "StringLiteral", .IntegerLiteral => return "IntegerLiteral", .FloatLiteral => return "FloatLiteral", .Recovery => return "$error", //else => unreachable, } }
zig/zig_grammar.debug.zig
const std = @import("std"); const zap = @import("zap"); const hyperia = @import("hyperia.zig"); const Socket = @import("socket.zig").Socket; const Reactor = @import("reactor.zig").Reactor; const io = std.io; const os = std.os; const net = std.net; const mpsc = hyperia.mpsc; const testing = std.testing; pub const AsyncSocket = struct { pub const Error = error{Cancelled}; const Self = @This(); const READY = 0; const CANCELLED = 1; socket: Socket, readable: mpsc.AsyncAutoResetEvent(usize) = .{}, writable: mpsc.AsyncAutoResetEvent(usize) = .{}, handle: Reactor.Handle = .{ .onEventFn = onEvent }, pub fn init(domain: u32, socket_type: u32, flags: u32) !Self { return Self{ .socket = try Socket.init(domain, socket_type | os.SOCK_NONBLOCK, flags) }; } pub fn deinit(self: *Self) void { self.socket.deinit(); } pub fn from(socket: Socket) Self { return Self{ .socket = socket }; } pub fn shutdown(self: *Self, how: os.ShutdownHow) !void { return self.socket.shutdown(how); } pub fn bind(self: *Self, address: net.Address) !void { return self.socket.bind(address); } pub fn listen(self: *Self, max_backlog_size: usize) !void { return self.socket.listen(max_backlog_size); } pub fn setReuseAddress(self: *Self, enabled: bool) !void { return self.socket.setReuseAddress(enabled); } pub fn setReusePort(self: *Self, enabled: bool) !void { return self.socket.setReusePort(enabled); } pub fn setNoDelay(self: *Self, enabled: bool) !void { return self.socket.setNoDelay(enabled); } pub fn setFastOpen(self: *Self, enabled: bool) !void { return self.socket.setFastOpen(enabled); } pub fn setQuickAck(self: *Self, enabled: bool) !void { return self.socket.setQuickAck(enabled); } pub fn getName(self: *Self) !net.Address { return self.socket.getName(); } pub fn getReadBufferSize(self: *Self) !u32 { return self.socket.getReadBufferSize(); } pub fn getWriteBufferSize(self: *Self) !u32 { return self.socket.getWriteBufferSize(); } pub fn setReadBufferSize(self: *Self, size: u32) !void { return self.socket.setReadBufferSize(size); } pub fn setWriteBufferSize(self: *Self, size: u32) !void { return self.socket.setWriteBufferSize(size); } pub fn setReadTimeout(self: *Self, milliseconds: usize) !void { return self.socket.setReadTimeout(milliseconds); } pub fn setWriteTimeout(self: *Self, milliseconds: usize) !void { return self.socket.setWriteTimeout(milliseconds); } pub fn tryRead(self: *Self, buf: []u8) os.ReadError!usize { return self.socket.read(buf); } pub fn tryRecv(self: *Self, buf: []u8, flags: u32) os.RecvFromError!usize { return self.socket.recv(buf, flags); } pub fn tryWrite(self: *Self, buf: []const u8) os.WriteError!usize { return self.socket.write(buf); } pub fn trySend(self: *Self, buf: []const u8, flags: u32) os.SendError!usize { return self.socket.send(buf, flags); } pub fn tryConnect(self: *Self, address: net.Address) os.ConnectError!void { return self.socket.connect(address); } pub fn tryAccept(self: *Self, flags: u32) !Socket.Connection { return self.socket.accept(flags); } pub const ReadError = os.ReadError || Error; pub fn read(self: *Self, buf: []u8) ReadError!usize { while (true) { const num_bytes = self.tryRead(buf) catch |err| switch (err) { error.WouldBlock => { if (self.readable.wait() == CANCELLED) { return error.Cancelled; } continue; }, else => return err, }; return num_bytes; } } pub const RecvFromError = os.RecvFromError || Error; pub fn recv(self: *Self, buf: []u8, flags: u32) RecvFromError!usize { while (true) { const num_bytes = self.tryRecv(buf, flags) catch |err| switch (err) { error.WouldBlock => { if (self.readable.wait() == CANCELLED) { return error.Cancelled; } continue; }, else => return err, }; return num_bytes; } } pub const WriteError = os.WriteError || Error; pub fn write(self: *Self, buf: []const u8) WriteError!usize { while (true) { const num_bytes = self.tryWrite(buf) catch |err| switch (err) { error.WouldBlock => { if (self.writable.wait() == CANCELLED) { return error.Cancelled; } continue; }, else => return err, }; return num_bytes; } } pub const SendError = os.SendError || Error; pub fn send(self: *Self, buf: []const u8, flags: u32) SendError!usize { while (true) { const num_bytes = self.trySend(buf, flags) catch |err| switch (err) { error.WouldBlock => { if (self.writable.wait() == CANCELLED) { return error.Cancelled; } continue; }, else => return err, }; return num_bytes; } } pub fn Sender(comptime flags: i32) type { return io.Writer(*Self, SendError, struct { pub fn call(self: *Self, buf: []const u8) SendError!usize { return self.send(buf, flags); } }.call); } pub fn sender(self: *Self, comptime flags: i32) Sender(flags) { return Sender(flags){ .context = self }; } pub const ConnectError = os.ConnectError || Error; pub fn connect(self: *Self, address: net.Address) ConnectError!void { while (true) { return self.tryConnect(address) catch |err| switch (err) { error.WouldBlock => { if (self.writable.wait() == CANCELLED) { return error.Cancelled; } continue; }, else => return err, }; } } pub const AcceptError = os.AcceptError || Error; pub fn accept(self: *Self, flags: u32) AcceptError!Socket.Connection { while (true) { const connection = self.tryAccept(flags) catch |err| switch (err) { error.WouldBlock => { if (self.readable.wait() == CANCELLED) { return error.Cancelled; } continue; }, else => return err, }; return connection; } } pub fn cancel(self: *Self, how: enum { read, write, connect, accept, all }) void { switch (how) { .read, .accept => { if (self.readable.set(CANCELLED)) |runnable| { hyperia.pool.schedule(.{}, runnable); } }, .write, .connect => { if (self.writable.set(CANCELLED)) |runnable| { hyperia.pool.schedule(.{}, runnable); } }, .all => { var batch: zap.Pool.Batch = .{}; if (self.writable.set(CANCELLED)) |runnable| batch.push(runnable); if (self.readable.set(CANCELLED)) |runnable| batch.push(runnable); hyperia.pool.schedule(.{}, batch); }, } } pub fn onEvent(handle: *Reactor.Handle, batch: *zap.Pool.Batch, event: Reactor.Event) void { const self = @fieldParentPtr(AsyncSocket, "handle", handle); if (event.is_readable) { if (self.readable.set(READY)) |runnable| { batch.push(runnable); } } if (event.is_writable) { if (self.writable.set(READY)) |runnable| { batch.push(runnable); } } if (event.is_hup) { if (self.readable.set(READY)) |runnable| batch.push(runnable); if (self.writable.set(READY)) |runnable| batch.push(runnable); } } }; test { testing.refAllDecls(@This()); } test "socket/async" { hyperia.init(); defer hyperia.deinit(); const reactor = try Reactor.init(os.EPOLL_CLOEXEC); defer reactor.deinit(); var a = try AsyncSocket.init(os.AF_INET, os.SOCK_STREAM | os.SOCK_CLOEXEC, os.IPPROTO_TCP); defer a.deinit(); try reactor.add(a.socket.fd, &a.handle, .{ .readable = true }); try reactor.poll(1, struct { expected_data: usize, pub fn call(self: @This(), event: Reactor.Event) void { testing.expectEqual( Reactor.Event{ .data = self.expected_data, .is_error = false, .is_hup = true, .is_readable = false, .is_writable = false, }, event, ); } }{ .expected_data = @ptrToInt(&a.handle) }, null); try a.bind(net.Address.initIp4([_]u8{ 0, 0, 0, 0 }, 0)); try a.listen(128); const binded_address = try a.getName(); var b = try AsyncSocket.init(os.AF_INET, os.SOCK_STREAM | os.SOCK_CLOEXEC, os.IPPROTO_TCP); defer b.deinit(); try reactor.add(b.socket.fd, &b.handle, .{ .readable = true, .writable = true }); try reactor.poll(1, struct { expected_data: usize, pub fn call(self: @This(), event: Reactor.Event) void { testing.expectEqual( Reactor.Event{ .data = self.expected_data, .is_error = false, .is_hup = true, .is_readable = false, .is_writable = true, }, event, ); var batch: zap.Pool.Batch = .{}; defer hyperia.pool.schedule(.{}, batch); const handle = @intToPtr(*Reactor.Handle, event.data); handle.call(&batch, event); } }{ .expected_data = @ptrToInt(&b.handle) }, null); var connect_frame = async b.connect(binded_address); try reactor.poll(1, struct { expected_data: usize, pub fn call(self: @This(), event: Reactor.Event) void { testing.expectEqual( Reactor.Event{ .data = self.expected_data, .is_error = false, .is_hup = false, .is_readable = false, .is_writable = true, }, event, ); var batch: zap.Pool.Batch = .{}; defer hyperia.pool.schedule(.{}, batch); const handle = @intToPtr(*Reactor.Handle, event.data); handle.call(&batch, event); } }{ .expected_data = @ptrToInt(&b.handle) }, null); try nosuspend await connect_frame; try reactor.poll(1, struct { expected_data: usize, pub fn call(self: @This(), event: Reactor.Event) void { testing.expectEqual( Reactor.Event{ .data = self.expected_data, .is_error = false, .is_hup = false, .is_readable = true, .is_writable = false, }, event, ); var batch: zap.Pool.Batch = .{}; defer hyperia.pool.schedule(.{}, batch); const handle = @intToPtr(*Reactor.Handle, event.data); handle.call(&batch, event); } }{ .expected_data = @ptrToInt(&a.handle) }, null); var ab = try nosuspend a.accept(os.SOCK_CLOEXEC | os.SOCK_NONBLOCK); defer ab.socket.deinit(); }
async_socket.zig
const std = @import("std"); const debuginator_c = @import("c.zig"); pub export fn draw_rect(position: [*c]debuginator_c.DebuginatorVector2, size: [*c]debuginator_c.DebuginatorVector2, color: [*c]debuginator_c.DebuginatorColor, userdata: ?*c_void) void {} pub export fn draw_text(text: [*c]const u8, position: [*c]debuginator_c.DebuginatorVector2, color: [*c]debuginator_c.DebuginatorColor, font: [*c]debuginator_c.DebuginatorFont, userdata: ?*c_void) void {} pub export fn text_size(text: [*c]const u8, font: [*c]debuginator_c.DebuginatorFont, userdata: ?*c_void) debuginator_c.DebuginatorVector2 { var size = debuginator_c.DebuginatorVector2{ .x = 30, .y = 10, }; return size; } pub export fn word_wrap(text: [*c]const u8, font: [*c]debuginator_c.DebuginatorFont, max_width: f32, row_count: [*c]c_int, row_lengths: [*c]c_int, row_lengths_buffer_size: c_int, userdata: ?*c_void) void { // std.debug.print("WW {}\n", .{max_width}); } pub export fn log(text: [*c]const u8, userdata: ?*c_void) void { std.debug.print("LOG {}\n", .{text}); } pub fn main() void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const buffer_size = 1024 * 1024; var buffer = arena.allocator.alloc(u8, buffer_size) catch unreachable; var config = std.mem.zeroes(debuginator_c.TheDebuginatorConfig); debuginator_c.debuginator_get_default_config(&config); config.memory_arena = @ptrCast([*c]u8, buffer); config.memory_arena_capacity = buffer_size; config.draw_rect = draw_rect; config.draw_text = draw_text; config.text_size = text_size; config.word_wrap = word_wrap; config.log = log; config.size.x = 300; config.size.y = 1000; config.screen_resolution.x = 1200; config.screen_resolution.y = config.size.y; config.app_user_data = &config; std.debug.print("BEGIN {}\n", .{config.create_default_debuginator_items}); var debuginator: ?*debuginator_c.TheDebuginator = debuginator_c.alloc_debuginator(); std.debug.assert(debuginator != null); std.debug.print("CREATE {}\n", .{config.create_default_debuginator_items}); debuginator_c.debuginator_create(&config, debuginator); std.debug.print("UPDATE {}\n", .{config.create_default_debuginator_items}); debuginator_c.debuginator_update(debuginator, 0.1); debuginator_c.debuginator_draw(debuginator, 0.1); std.debug.print("END {}\n", .{config.create_default_debuginator_items}); }
tests/zig-minimal/src/main.zig
usingnamespace @import("root").preamble; const log = lib.output.log.scoped(.{ .prefix = "gpu/virtio", .filter = .info, }).write; const virtio_pci = os.drivers.misc.virtio_pci; /// virtio-gpu driver instance const Driver = struct { transport: virtio_pci.Driver, inflight: u32 = 0, display_region: lib.graphics.image_region.ImageRegion = undefined, // Initialize the virtio transport, but don't change modes pub fn init(pciaddr: os.platform.pci.Addr) !Driver { var v = try virtio_pci.Driver.init(pciaddr, 0, 0); var d: Driver = .{ .transport = v }; return d; } fn invalidateRectFunc(region: *lib.graphics.image_region.ImageRegion, x: usize, y: usize, width: usize, height: usize) void { const self = @fieldParentPtr(Driver, "display_region", region); self.updateRect(@ptrToInt(self.display_region.subregion(x, y, width, height).bytes.ptr) - @ptrToInt(self.display_region.bytes.ptr), .{ .x = @intCast(u32, x), .y = @intCast(u32, y), .width = @intCast(u32, width), .height = @intCast(u32, height), }); } // Do a modeswitch to the described mode pub fn modeset(self: *Driver, phys: usize) void { var iter = self.transport.iter(0); { var msg: ResourceCreate2D = .{ .hdr = .{ .cmdtype = virtio_gpu_cmd_res_create_2d, .flags = 0, .fenceid = 0, .ctxid = 0, }, .resid = 1, .format = 1, .width = @intCast(u32, self.display_region.width), .height = @intCast(u32, self.display_region.height), }; var resp: ConfHdr = undefined; iter.begin(); iter.put(&msg, @sizeOf(ResourceCreate2D), virtio_pci.vring_desc_flag_next); iter.put(&resp, @sizeOf(ConfHdr), virtio_pci.vring_desc_flag_write); self.inflight += 1; } { var msg: ResourceAttachBacking = .{ .hdr = .{ .cmdtype = virtio_gpu_cmd_res_attach_backing, .flags = 0, .fenceid = 0, .ctxid = 0, }, .resid = 1, .entrynum = 1, }; var msg1: ResourceAttachBackingEntry = .{ .addr = phys, .len = @intCast(u32, self.display_region.width) * @intCast(u32, self.display_region.height) * 4, }; var resp: ConfHdr = undefined; iter.begin(); iter.put(&msg, @sizeOf(ResourceAttachBacking), virtio_pci.vring_desc_flag_next); iter.put(&msg1, @sizeOf(ResourceAttachBackingEntry), virtio_pci.vring_desc_flag_next); iter.put(&resp, @sizeOf(ConfHdr), virtio_pci.vring_desc_flag_write); self.inflight += 1; } { var msg: SetScanout = .{ .hdr = .{ .cmdtype = virtio_gpu_cmd_set_scanout, .flags = 0, .fenceid = 0, .ctxid = 0, }, .resid = 1, .scanid = 0, .rect = .{ .x = 0, .y = 0, .width = @intCast(u32, self.display_region.width), .height = @intCast(u32, self.display_region.height), }, }; var resp: ConfHdr = undefined; iter.begin(); iter.put(&msg, @sizeOf(SetScanout), virtio_pci.vring_desc_flag_next); iter.put(&resp, @sizeOf(ConfHdr), virtio_pci.vring_desc_flag_write); self.inflight += 1; } self.transport.start(0); self.wait(); } /// Update *only* the rectangle pub fn updateRect(self: *Driver, offset: u64, rect: Rect) void { var iter = self.transport.iter(0); { var msg: TransferHost2D = .{ .hdr = .{ .cmdtype = virtio_gpu_cmd_transfer_to_host_2d, .flags = 0, .fenceid = 0, .ctxid = 0, }, .resid = 1, .offset = offset, .rect = rect, }; var resp: ConfHdr = undefined; iter.begin(); iter.put(&msg, @sizeOf(TransferHost2D), virtio_pci.vring_desc_flag_next); iter.put(&resp, @sizeOf(ConfHdr), virtio_pci.vring_desc_flag_write); self.inflight += 1; } { var msg: ResourceFlush = .{ .hdr = .{ .cmdtype = virtio_gpu_cmd_res_flush, .flags = 0, .fenceid = 0, .ctxid = 0, }, .resid = 1, .rect = rect, }; var resp: ConfHdr = undefined; iter.begin(); iter.put(&msg, @sizeOf(ResourceFlush), virtio_pci.vring_desc_flag_next); iter.put(&resp, @sizeOf(ConfHdr), virtio_pci.vring_desc_flag_write); self.inflight += 1; } self.transport.start(0); self.wait(); } /// Wait for request to finish. fn wait(self: *Driver) void { while (true) { var a: *volatile u32 = &self.inflight; if (a.* == 0) break; self.transport.process(0, process, self); } } }; const ConfHdr = packed struct { cmdtype: u32, flags: u32, fenceid: u64, ctxid: u32, _: u32 = 0, }; const ResourceCreate2D = packed struct { hdr: ConfHdr, resid: u32, format: u32, width: u32, height: u32 }; const ResourceAttachBacking = packed struct { hdr: ConfHdr, resid: u32, entrynum: u32 }; const ResourceAttachBackingEntry = packed struct { addr: u64, len: u32, _: u32 = 0, }; const Rect = packed struct { x: u32, y: u32, width: u32, height: u32 }; const SetScanout = packed struct { hdr: ConfHdr, rect: Rect, scanid: u32, resid: u32, }; const TransferHost2D = packed struct { hdr: ConfHdr, rect: Rect, offset: u64, resid: u32, _: u32 = 0 }; const ResourceFlush = packed struct { hdr: ConfHdr, rect: Rect, resid: u32, _: u32 = 0 }; // Feature bits const virtio_feature_version_1 = 32; const virtio_feature_access_platform = 33; const virtio_feature_ring_packed = 34; const virtio_feature_order_platform = 36; const virtio_feature_sr_iov = 37; // 2D cmds const virtio_gpu_cmd_get_display_info = 0x0100; const virtio_gpu_cmd_res_create_2d = 0x101; const virtio_gpu_cmd_res_unref = 0x102; const virtio_gpu_cmd_set_scanout = 0x103; const virtio_gpu_cmd_res_flush = 0x104; const virtio_gpu_cmd_transfer_to_host_2d = 0x105; const virtio_gpu_cmd_res_attach_backing = 0x106; const virtio_gpu_cmd_res_detatch_backing = 0x107; const virtio_gpu_cmd_get_capset_info = 0x108; const virtio_gpu_cmd_get_capset = 0x109; const virtio_gpu_cmd_get_edid = 0x10A; // Cursor cmds const virtio_gpu_cmd_update_cursor = 0x0300; const virtio_gpu_cmd_move_cursor = 0x301; // Success const virtio_gpu_resp_ok_nodata = 0x1100; const virtio_gpu_resp_ok_display_info = 0x1101; const virtio_gpu_resp_ok_capset_info = 0x1102; const virtio_gpu_resp_ok_capset = 0x1103; const virtio_gpu_resp_ok_edid = 0x1104; // Error const virtio_gpu_resp_err_unspecified = 0x1200; const virtio_gpu_resp_err_out_of_mem = 0x1201; const virtio_gpu_resp_err_invalid_scanout_id = 0x1202; const virtio_gpu_resp_err_invalid_res_id = 0x1203; const virtio_gpu_resp_err_invalid_ctx_id = 0x1204; const virtio_gpu_resp_err_invalid_parameter = 0x1205; const virtio_gpu_flag_fence = (1 << 0); fn process(self: *Driver, i: u8, head: virtio_pci.Descriptor) void { self.transport.freeChain(i, head); self.inflight -= 1; } /// Global rectangle update, but with a global context fn updater( bb: [*]u8, yoff_src: usize, yoff_dest: usize, ysize: usize, pitch: usize, ctx: usize, ) void { var self = @intToPtr(*Driver, ctx); self.updateRect(self.pitch * yoff_src, .{ .x = 0, .y = @truncate(u32, yoff_dest), .width = self.width, .height = @truncate(u32, ysize), }); } pub fn registerController(addr: os.platform.pci.Addr) void { if (comptime (!config.drivers.gpu.virtio_gpu.enable)) return; const alloc = os.memory.pmm.phys_heap; const drv = alloc.create(Driver) catch { log(.crit, "Virtio display controller: Allocation failure", .{}); return; }; errdefer alloc.destroy(drv); drv.* = Driver.init(addr) catch { log(.crit, "Virtio display controller: Init has failed!", .{}); return; }; errdefer drv.deinit(); if (comptime (!config.drivers.output.vesa_log.enable)) return; // @TODO: Get the actual screen resolution const res = config.drivers.gpu.virtio_gpu.default_resolution; const num_bytes = res.width * res.height * 4; const phys = os.memory.pmm.allocPhys(num_bytes) catch return; errdefer os.memory.pmm.freePhys(phys, num_bytes); drv.display_region = .{ .bytes = os.platform.phys_ptr([*]u8).from_int(phys).get_writeback()[0..num_bytes], .pitch = res.width * 4, .width = res.width, .height = res.height, .invalidateRectFunc = Driver.invalidateRectFunc, .pixel_format = .rgbx, }; drv.modeset(phys); os.drivers.output.vesa_log.use(&drv.display_region); } /// General callback on an interrupt, context is a pointer to a Driver structure pub fn interrupt(frame: *os.platform.InterruptFrame, context: u64) void { var driver = @intToPtr(*Driver, context); driver.transport.acknowledge(); driver.transport.process(0, process, driver); }
subprojects/flork/src/drivers/gpu/virtio_gpu.zig
const std = @import("std"); const interop = @import("interop.zig"); const iup = @import("iup.zig"); const debug = std.debug; const trait = std.meta.trait; const Element = iup.Element; const Dialog = iup.Dialog; const Handle = iup.Handle; const VBox = iup.VBox; const Menu = iup.Menu; const SubMenu = iup.SubMenu; const Error = iup.Error; const ChildrenIterator = iup.ChildrenIterator; // TODO: Improves the organization in separated files // Needs some use cases from other elements to define the better way to organize // // May we use "pub usingnamespace Impl(Self);" to import all methods on every element? pub fn Impl(comptime T: type) type { return struct { /// /// Updates the size and layout of all controls in the same dialog. /// To be used after changing size attributes, or attributes that affect the size of the control. Can be used for any element inside a dialog, but the layout of the dialog and all controls will be updated. It can change the layout of all the controls inside the dialog because of the dynamic layout positioning. pub fn refresh(self: *T) void { interop.refresh(self); } pub fn appendChildren(self: *T, tuple: anytype) !void { const typeOf = @TypeOf(tuple); if (comptime trait.isTuple(typeOf)) { const typeInfo = @typeInfo(typeOf).Struct; if (T == Dialog) { // Dialogs can have just one child, and one Menu // This sintax-sugar adds the top-level Menu along the children list var children_qty: usize = 0; inline for (typeInfo.fields) |field| { var element = try getArgHandle(@field(tuple, field.name)); if (element == .Menu) { self.setMenu(element.Menu); } else if (element == .SubMenu) { try appendDialogSubMenu(self, element.SubMenu); } else { children_qty += 1; } } if (children_qty > 1) return Error.InvalidChild; inline for (typeInfo.fields) |field| { var element = try getArgHandle(@field(tuple, field.name)); if (element != .Menu and element != .SubMenu) { try appendChild(self, element); } } } else { // Regular appendChild method for most containers inline for (typeInfo.fields) |field| { try appendChild(self, @field(tuple, field.name)); } } } else { try appendChild(self, tuple); } } pub fn appendChild(self: *T, child: anytype) !void { var element = try getArgHandle(child); if (T == Dialog) { if (element == .Menu) { self.setMenu(element.Menu); } else if (element == .SubMenu) { try appendDialogSubMenu(self, element.SubMenu); } else { var parent_handle = if (self.children().next()) |container| container.getHandle() else interop.getHandle(self); try interop.append(parent_handle, element); } } else if (T == SubMenu and (element == .SubMenu or element == .Item or element == .Separator)) { // IUP needs a menu inside a subMenu to hold childrens var innerMenu: *Handle = undefined; if (self.children().next()) |valid| { innerMenu = valid.getHandle(); } else { var valid = interop.getHandle(try iup.Menu.init().unwrap()); try interop.append(self, valid); innerMenu = valid; } try interop.append(innerMenu, element); } else { try interop.append(self, element); } } fn appendDialogSubMenu(self: *T, submenu: *SubMenu) !void { if (T == Dialog) { if (self.getMenu()) |top_level_menu| { try top_level_menu.appendChild(submenu); } else { var menu = try (Menu.init() .setChildren( .{ submenu, }, ).unwrap()); self.setMenu(menu); } } else { return Error.InvalidChild; } } /// /// Converts a (lin, col) character positioning into an absolute position. lin and col starts at 1, pos starts at 0. For single line controls pos is always ""col - 1"". (since 3.0) pub fn convertLinColToPos(self: *T, lin: i32, col: i32) ?i32 { return interop.convertLinColToPos(self, lin, col); } /// /// Converts a (lin, col) character positioning into an absolute position. lin and col starts at 1, pos starts at 0. For single line controls pos is always ""col - 1"". (since 3.0) pub fn convertPosToLinCol(self: *T, pos: i32) ?iup.LinColPos { return interop.convertPosToLinCol(self, pos); } pub fn messageDialogAlert(parent: ?*Dialog, title: ?[:0]const u8, message: [:0]const u8) !void { var dialog = try (iup.MessageDlg.init() .setValue(message) .setDialogType(.Warning) .unwrap()); defer dialog.deinit(); if (title) |valid| dialog.setTitle(valid); if (parent) |valid| { if (title == null) dialog.setTitle(valid.getTitle()); try dialog.setParentDialog(valid); } _ = try dialog.popup(.CenterParent, .CenterParent); } pub fn messageDialogConfirm(parent: ?*Dialog, title: ?[:0]const u8, message: [:0]const u8) !bool { var dialog = try (iup.MessageDialog.init() .setValue(message) .setDialogType(.Question) .setButtons(.YesNo) .unwrap()); defer dialog.deinit(); if (title) |valid| dialog.setTitle(valid); if (parent) |valid| { if (title == null) dialog.setTitle(valid.getTitle()); dialog.setParentDialog(valid); } var ret = try dialog.popup(.CenterParent, .CenterParent); return ret == .Button1; } }; } /// Helper functions fn getArgsLen(comptime T: type) comptime_int { if (!comptime trait.isTuple(T)) { @compileError("Expected tuple argument, found " ++ @typeName(T)); } return @typeInfo(T).Struct.fields.len + 1; } fn getArgHandle(arg: anytype) !Element { const argType = @TypeOf(arg); if (argType == Element) return arg; const argTypeInfo = @typeInfo(argType); const errorMessage = "Tuple argument " ++ @typeName(argType) ++ " no supported"; switch (argTypeInfo) { .Struct => { if (comptime canUnwrap(argType)) { // Verify previous errors var value = try arg.unwrap(); return Element.fromRef(value); } else { @compileError(errorMessage); } }, .Pointer => |pointerInfo| { const pointerTypeInfo = @typeInfo(pointerInfo.child); if (pointerTypeInfo == .Struct) { if (comptime canUnwrap(pointerInfo.child)) { // Verify previous errors var value = try arg.unwrap(); return Element.fromRef(value); } else { @compileError(errorMessage); } } else { return Element.fromType(@TypeOf(arg), arg); } }, else => @compileError(errorMessage), } } fn canUnwrap(comptime T: type) bool { return comptime trait.hasFunctions(T, .{"unwrap"}); }
src/impl.zig
const std = @import("std"); pub const Color = [4]u8; pub const BlendMode = enum(u1) { alpha, replace, }; pub const ColorLayer = enum(u1) { foreground, background, }; pub const black = Color{ 0, 0, 0, 0xff }; pub fn eql(a: Color, b: Color) bool { return a[0] == b[0] and a[1] == b[1] and a[2] == b[2] and a[3] == b[3]; } fn mul8(a: u8, b: u8) u8 { return @truncate(u8, (@as(u16, a) * @as(u16, b)) / 0xff); } fn div8(a: u8, b: u8) u8 { return @truncate(u8, @divTrunc(@as(u16, a) * 0xff, @as(u16, b))); } // blend color a over b (Porter Duff) // a_out = a_a + a_b * (1 - a_a) // c_out = (c_a * a_a + c_b * a_b * (1 - a_a)) / a_out pub fn blend(a: []const u8, b: []const u8) Color { var out: Color = [_]u8{0} ** 4; const fac = mul8(b[3], 0xff - a[3]); out[3] = a[3] + fac; if (out[3] > 0) { out[0] = div8(mul8(a[0], a[3]) + mul8(b[0], fac), out[3]); out[1] = div8(mul8(a[1], a[3]) + mul8(b[1], fac), out[3]); out[2] = div8(mul8(a[2], a[3]) + mul8(b[2], fac), out[3]); } return out; } pub fn distanceSqr(a: []const u8, b: []const u8) f32 { const d = [_]f32{ @intToFloat(f32, a[0]) - @intToFloat(f32, b[0]), @intToFloat(f32, a[1]) - @intToFloat(f32, b[1]), @intToFloat(f32, a[2]) - @intToFloat(f32, b[2]), @intToFloat(f32, a[3]) - @intToFloat(f32, b[3]), }; return d[0] * d[0] + d[1] * d[1] + d[2] * d[2] + d[3] * d[3]; } pub fn findNearest(colors: []const u8, color: []const u8) usize { var nearest: f32 = std.math.f32_max; var nearest_i: usize = 0; var i: usize = 0; while (i < colors.len and nearest > 0) : (i += 4) { const distance = distanceSqr(colors[i..], color); if (distance < nearest) { nearest = distance; nearest_i = i; } } return nearest_i / 4; } pub fn trimBlackColorsRight(colors: []u8) []u8 { var len = colors.len / 4; while (len > 0 and std.mem.eql(u8, colors[4 * len - 4 ..][0..4], &black)) : (len -= 1) {} return colors[0 .. 4 * len]; }
src/color.zig
const u = @import("util.zig"); const std = @import("std"); const Expr = @import("Expr.zig"); const IR = @import("IR.zig"); const p = @import("Wat/parse.zig"); const Codegen = @import("Wat/Codegen.zig"); pub const emit = @import("Wat/Emit.zig").emit; const TopDefinition = enum { type, import, func, data, @"export", memory, table, elem, global }; /// child_allocator is used as gpa() arena: std.heap.ArenaAllocator, /// Work in progress IR.Module I: struct { // (type (func ...)) funcTypes: UnmanagedIndex(IR.Func.Sig) = .{}, funcs: UnmanagedIndex(FuncProgress) = .{}, funcImportCount: usize = 0, datas: UnmanagedIndex(union(enum) { args: []const Expr, done: IR.Data, }) = .{}, globals: UnmanagedIndex(void) = .{}, exports: std.ArrayListUnmanaged([]const Expr) = .{}, memory: ?IR.Memory = null, } = .{}, /// Parsing pointer at: ?Expr = null, err: ErrData = null, const Ctx = @This(); pub const ErrData = ?union(enum) { typeMismatch: struct { expect: ?Codegen.Stack, got: ?Codegen.Stack, index: ?usize = null, }, pub fn format( self: @This(), comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype, ) !void { switch (self) { .typeMismatch => |m| { try writer.print("Expected {} got {}", .{ m.expect, m.got }); if (m.index) |i| try writer.print(" at index {}", .{i}); }, } } }; const Result = u.Result(IR.Module, struct { kind: anyerror, data: ErrData = null, at: ?Expr = null, }); pub fn tryLoad(exprs: []const Expr, allocator: std.mem.Allocator, loader: anytype) Result { //TODO: load recussive with (use ?id name) _ = loader.load; var module: ?IR.Module = null; for (exprs) |expr| { const func = p.asFuncNamed(expr, "module") orelse continue; const child = switch (tryLoadModule(func.args, allocator)) { .ok => |m| m, .err => |err| return .{ .err = err }, }; if (module) |parent| { module = IR.Module.link(&[_]IR.Module{ parent, child }, allocator) catch |err| return .{ .err = .{ .kind = err } }; parent.deinit(); } else { module = child; } } return if (module) |m| .{ .ok = m } else // without top module tryLoadModule(exprs, allocator); } fn tryLoadModule(exprs: []const Expr, allocator: std.mem.Allocator) Result { var ctx = Ctx{ .arena = std.heap.ArenaAllocator.init(allocator) }; const module = ctx._loadModule(exprs) catch |err| return .{ .err = .{ .kind = err, .data = ctx.err, .at = ctx.at } }; return .{ .ok = module }; } fn _loadModule(ctx: *Ctx, exprs: []const Expr) !IR.Module { // name = if (exprs[0] dollared) ident else "env" for (exprs) |expr| try ctx.buildIndex(expr); const datas = try ctx.m_allocator().alloc(IR.Data, ctx.I.datas.items.len); for (ctx.I.datas.items) |*data, i| { const done = try ctx.loadData(data.val.args, data.id); data.val = .{ .done = done }; datas[i] = done; } for (ctx.I.exports.items) |expr| try ctx.loadExport(expr); const funcs = try ctx.m_allocator().alloc(IR.Func, ctx.I.funcs.items.len); for (ctx.I.funcs.items) |*f, i| { if (i > ctx.I.funcImportCount and f.val == .unused and p.asFuncNamed(f.val.unused.args[0], "export") == null) std.log.warn("Unused func {}({s})", .{ i, f.id }); try ctx.loadFunc(&f.val, f.id); funcs[i] = f.val.done; } ctx.I.funcTypes.deinit(ctx.gpa()); ctx.I.funcs.deinit(ctx.gpa()); ctx.I.datas.deinit(ctx.gpa()); ctx.I.globals.deinit(ctx.gpa()); ctx.I.exports.deinit(ctx.gpa()); return IR.Module{ .arena = ctx.arena, .funcs = funcs, .tables = &[_]IR.Table{}, .memory = ctx.I.memory, .globals = &[_]IR.Global{}, .start = null, .elements = &[_]IR.Elem{}, .datas = datas, //.linking = Linking, .customs = &[_]IR.Section.Custom{}, }; } inline fn buildIndex(ctx: *Ctx, expr: Expr) !void { const func = p.asFunc(expr) orelse return error.NotFuncTopValue; const section = std.meta.stringToEnum(TopDefinition, func.name) orelse return error.UnknownSection; if (func.args.len == 0) return error.Empty; ctx.at = expr; switch (section) { .type => try ctx.buildType(func), .func => try ctx.buildFunc(func, null), .table => @panic("TODO:"), .memory => try ctx.buildMemory(func, null), .global => @panic("TODO:"), .@"export" => try ctx.I.exports.append(ctx.gpa(), func.args), .elem => @panic("TODO:"), .data => { try indexFreeId(ctx.I.datas, func.id); try ctx.I.datas.append(ctx.gpa(), .{ .id = try ctx.dupeN(func.id), .val = .{ .args = func.args } }); }, .import => try ctx.buildImport(func.args), } } inline fn buildType(ctx: *Ctx, func: p.Func) !void { if (func.args.len > 1) return error.TooMany; const inner = p.asFuncNamed(func.args[0], "func") orelse return error.NotFunc; const use = try ctx.typedef(inner.args); use.deinit(ctx); if (use.remain.len > 0) return error.TooMany; try indexFreeId(ctx.I.funcTypes, func.id); try ctx.I.funcTypes.append(ctx.gpa(), .{ .id = func.id, .val = use.val }); } const FuncProgress = union(enum) { unused: struct { args: []const Expr, importParent: ?IR.ImportName, }, typed: struct { it: IR.Func, insts: []const Expr, params: []const ?u.Txt, wip: bool = false, }, done: IR.Func, }; fn buildFunc(ctx: *Ctx, func: p.Func, importParent: ?IR.ImportName) !void { const importAbbrev = try hasImportAbbrev(func.args, importParent != null); try indexFreeId(ctx.I.funcs, func.id); const f = IndexField(FuncProgress){ .id = try ctx.dupeN(func.id), .val = .{ .unused = .{ .args = func.args, .importParent = importParent } } }; if (importAbbrev or importParent != null) { try ctx.I.funcs.insert(ctx.gpa(), ctx.I.funcImportCount, f); ctx.I.funcImportCount += 1; } else { try ctx.I.funcs.append(ctx.gpa(), f); } } fn buildMemory(ctx: *Ctx, func: p.Func, importParent: ?IR.ImportName) !void { if (ctx.I.memory != null) return error.MultipleMemory; const importAbbrev = try hasImportAbbrev(func.args, importParent != null); const io = try ctx.exportsImportNames(func.args, importAbbrev, func.id); //TODO: data abbrev const memtyp = try limit(io.remain); ctx.I.memory = .{ .id = try ctx.dupeN(func.id), .exports = io.exports, .import = importParent orelse io.import, .size = memtyp, }; } inline fn buildImport(ctx: *Ctx, args: []const Expr) !void { if (args.len != 3) return error.Empty; const name = try ctx.importName(args[0..2]); ctx.at = args[2]; const func = p.asFunc(args[2]) orelse return error.BadImport; const kind = std.meta.stringToEnum(TopDefinition, func.name) orelse return error.BadImport; switch (kind) { .func => try ctx.buildFunc(func, name), .table => @panic("TODO:"), .memory => try ctx.buildMemory(func, name), .global => @panic("TODO:"), else => return error.BadImport, } } pub fn typeFunc(ctx: *Ctx, fp: *FuncProgress, id: ?u.Txt) !*IR.Func { return switch (fp.*) { .done => &fp.done, .typed => &fp.typed.it, .unused => |f| { if (f.args.len > 0) ctx.at = f.args[0]; const importAbbrev = try hasImportAbbrev(f.args, f.importParent != null); const io = try ctx.exportsImportNames(f.args, importAbbrev, id); var typ = try ctx.typeuse(io.remain); if (f.importParent orelse io.import) |import| { typ.deinit(ctx); if (typ.remain.len > 0) return error.ImportWithBody; fp.* = .{ .done = .{ .body = .{ .import = import }, .id = id, .exports = io.exports, .type = typ.val, } }; return &fp.done; } else { fp.* = .{ .typed = .{ .it = .{ .body = .{ .code = .{ .bytes = "" } }, .id = id, .exports = io.exports, .type = typ.val, }, .insts = typ.remain, .params = typ.params } }; return &fp.typed.it; } }, }; } fn loadFunc(ctx: *Ctx, fp: *FuncProgress, id: ?u.Txt) !void { switch (fp.*) { .done => return, .typed => {}, .unused => { _ = try ctx.typeFunc(fp, id); if (fp.* == .done) return; }, } const t = &fp.typed; if (t.wip) return error.DependencyLoop; t.wip = true; if (t.insts.len > 0) ctx.at = t.insts[0]; // locals const locals = try ctx.valtypesAlloc(t.insts, "local"); var local_ids = try u.constSliceExpand(?u.Txt, ctx.gpa(), &t.params, locals.types.len); defer ctx.gpa().free(t.params); const insts = try ctx.valtypesRead(t.insts, "local", locals.types, local_ids); const code = try Codegen.load(ctx, insts, t.it.type, locals.types, t.params); t.it.body = .{ .code = code }; fp.* = .{ .done = t.it }; } inline fn loadExport(ctx: *Ctx, args: []const Expr) !void { if (args.len != 2) return error.Empty; const name = try ctx.string(args[0]); ctx.at = args[1]; const func = p.asFunc(args[1]) orelse return error.BadExport; const kind = std.meta.stringToEnum(TopDefinition, func.name) orelse return error.BadExport; const exports: *[]const IR.ExportName = switch (kind) { .func => blk: { const i = try indexFindByF(ctx.I.funcs, func); const fp = &ctx.I.funcs.items[i]; const f = try ctx.typeFunc(&fp.val, fp.id); break :blk &f.exports; }, .table => @panic("TODO:"), .memory => blk: { const m = ctx.I.memory orelse return error.NotFound; if (func.id) |id| { if (m.id == null or !u.strEql(id, m.id.?)) return error.NotFound; } else if (func.args.len != 1 or (try p.u32_(func.args[0])) != 0) return error.NotFound; break :blk &ctx.I.memory.?.exports; }, .global => @panic("TODO:"), else => return error.BadExport, }; const new = try u.constSliceExpand(IR.ExportName, ctx.m_allocator(), exports, 1); new[0] = name; } fn loadData(ctx: *Ctx, args: []const Expr, id: ?u.Txt) !IR.Data { var d = IR.Data{ .id = id, .body = .{ .passive = "" } }; var i: usize = 0; if (args.len > 0) { if (p.asFunc(args[0])) |first| { // active if (u.strEql("memory", first.name)) { //TODO: read mem id if (args.len < 2) return error.Empty; i += 1; } const exprs = if (p.asFuncNamed(args[i], "offset")) |func| func.args else args[i .. i + 1]; const typ = IR.Func.Sig{ .results = &[_]IR.Sigtype{.i32} }; const offset = try Codegen.load(ctx, exprs, typ, null, null); d.body = .{ .active = .{ .mem = 0, .content = "", .offset = try constExpr(offset.bytes), } }; i += 1; } } var len: usize = 0; for (args[i..]) |arg| { const str = arg.val.asString() orelse return error.NotString; len += str.len; } const datastring = try ctx.m_allocator().alloc(u8, len); len = 0; for (args[i..]) |arg| { const str = arg.val.asString() orelse unreachable; std.mem.copy(u8, datastring[len..], str); len += str.len; } switch (d.body) { .active => |*act| act.content = datastring, .passive => |*pas| pas.* = datastring, } return d; } fn IndexField(comptime Val: type) type { return struct { id: ?u.Txt, val: Val }; } fn UnmanagedIndex(comptime Val: type) type { return std.ArrayListUnmanaged(IndexField(Val)); } inline fn indexFreeId(idx: anytype, may_id: ?u.Txt) !void { if (indexFindById(idx, may_id orelse return) != null) return error.DuplicatedId; } pub fn indexFindById(idx: anytype, id: u.Txt) ?u32 { for (idx.items) |item, i| if (item.id) |other| if (u.strEql(id, other)) return @truncate(u32, i); return null; } inline fn indexFindByF(idx: anytype, f: p.Func) !u32 { if (f.id) |id| { return indexFindById(idx, id) orelse error.NotFound; } else { if (f.args.len != 1) return error.Empty; const i = try p.u32_(f.args[0]); if (i >= idx.items.len) return error.NotFound; return i; } } fn constExpr(buf: u.Bin) !IR.InitExpr { const Wasm = @import("Wasm.zig"); var reader = Wasm.Reader.init(buf); const ret = try reader.constExpr(); if (!reader.finished()) return error.NotOp; return ret; } fn limit(args: []const Expr) !std.wasm.Limits { return switch (args.len) { 0 => error.Empty, 1 => .{ .min = try p.u32_(args[0]), .max = null }, 2 => .{ .min = try p.u32_(args[0]), .max = try p.u32_(args[1]) }, else => error.TooMany, }; } fn hasImportAbbrev(args: []const Expr, importParent: bool) !bool { for (args) |arg| { if (p.asFuncNamed(arg, "import") != null) { if (importParent) return error.MultipleImport; return true; } } return false; } fn string(ctx: *Ctx, arg: Expr) !u.Bin { const str = arg.val.asString() orelse return error.NotString; return try ctx.m_allocator().dupe(u8, str); } inline fn dupeN(ctx: *Ctx, str: ?u.Bin) !?u.Bin { return if (str) |v| try ctx.m_allocator().dupe(u8, v) else null; } fn importName(ctx: *Ctx, args: []const Expr) !IR.ImportName { if (args.len < 2) return error.Empty; if (args.len > 2) return error.TooMany; return IR.ImportName{ .module = try ctx.string(args[0]), .name = try ctx.string(args[1]), }; } const ExportsImportName = struct { exports: []const IR.ExportName, import: ?IR.ImportName, remain: []const Expr, }; fn exportsImportNames(ctx: *Ctx, args: []const Expr, withImport: bool, fallbackExport: ?u.Txt) !ExportsImportName { var i: usize = 0; while (i < args.len and p.asFuncNamed(args[i], "export") != null) : (i += 1) {} const exports = try ctx.m_allocator().alloc(IR.ExportName, i); i = 0; while (i < args.len) : (i += 1) { const expor = p.asFuncNamed(args[i], "export") orelse break; ctx.at = args[i]; exports[i] = switch (expor.args.len) { 1 => try ctx.string(expor.args[0]), 0 => fallbackExport orelse return error.Empty, else => return error.TooMany, }; } var import: ?IR.ImportName = null; if (withImport) { ctx.at = args[i]; const impor = p.asFuncNamed(args[i], "import") orelse return error.BadImport; import = try ctx.importName(impor.args); i += 1; } return ExportsImportName{ .exports = exports, .import = import, .remain = args[i..] }; } const TypeUse = struct { val: IR.Func.Sig, params: []?u.Txt, remain: []const Expr, pub inline fn deinit(self: TypeUse, ctx: *Ctx) void { ctx.gpa().free(self.params); } }; fn ValtypesIter(comptime name: u.Txt) type { return struct { i: usize = 0, j: usize = 0, args: []const Expr, fn next(it: *@This()) !?Ret { while (it.i < it.args.len) : (it.i += 1) { const param = p.asFuncNamed(it.args[it.i], name) orelse break; if (it.j < param.args.len) { const id = if (it.j == 0) param.id else null; //TODO: abbrev ident const v = p.enumKv(IR.Sigtype)(param.args[it.j]) orelse return error.NotValtype; it.j += 1; return Ret{ .id = id, .v = v }; } it.j = 0; } return null; } const Ret = struct { id: ?u.Txt, v: IR.Sigtype, }; }; } const AllocVatypes = struct { types: []IR.Sigtype, remain: []const Expr, }; fn valtypesAlloc(ctx: *Ctx, args: []const Expr, comptime name: u.Txt) !AllocVatypes { var it = ValtypesIter(name){ .args = args }; var n: usize = 0; while ((try it.next()) != null) n += 1; return AllocVatypes{ .types = try ctx.m_allocator().alloc(IR.Sigtype, n), .remain = args[it.i..] }; } fn valtypesRead(_: *Ctx, args: []const Expr, comptime name: u.Txt, types: []IR.Sigtype, ids: ?[]?u.Txt) ![]const Expr { var it = ValtypesIter(name){ .args = args }; var n: usize = 0; while (try it.next()) |v| { if (ids) |slice| slice[n] = v.id; types[n] = v.v; n += 1; } std.debug.assert(n == types.len); return args[it.i..]; } fn valtypesCheck(self: *Ctx, args: []const Expr, comptime name: u.Txt, types: []const IR.Sigtype, ids: ?[]?u.Txt) ![]const Expr { var it = ValtypesIter(name){ .args = args }; var n: usize = 0; while (try it.next()) |v| { if (ids) |slice| slice[n] = v.id; if (!types[n].eql(v.v)) { self.err = .{ .typeMismatch = .{ .expect = .{ .val = types[n] }, .got = .{ .val = v.v }, .index = n, } }; return error.TypeMismatch; } n += 1; } return args[it.i..]; } fn typedef(ctx: *Ctx, args: []const Expr) !TypeUse { const ps = try ctx.valtypesAlloc(args, "param"); const rs = try ctx.valtypesAlloc(ps.remain, "result"); const params = try ctx.gpa().alloc(?u.Txt, ps.types.len); var remain = try ctx.valtypesRead(args, "param", ps.types, params); remain = try ctx.valtypesRead(remain, "result", rs.types, null); return TypeUse{ .val = .{ .params = ps.types, .results = rs.types }, .params = params, .remain = remain }; } pub fn typeuse(ctx: *Ctx, args: []const Expr) !TypeUse { if (args.len > 0) if (p.asFuncNamed(args[0], "type")) |func| { const i = try indexFindByF(ctx.I.funcTypes, func); const sig = ctx.I.funcTypes.items[i].val; const params = try ctx.gpa().alloc(?u.Txt, sig.params.len); var remain = try ctx.valtypesCheck(args[1..], "param", sig.params, params); remain = try ctx.valtypesCheck(remain, "result", sig.results, null); return TypeUse{ .val = sig, .params = params, .remain = remain }; }; return ctx.typedef(args); } inline fn pop(ctx: *Ctx, comptime field: []const u8, import: bool) *@TypeOf(@field(ctx.m, field)[0]) { var i = &@field(ctx.I, field); if (import) { i.nextImport += 1; return &@field(ctx.m, field)[i.nextImport - 1]; } else { i.nextLocal += 1; return &@field(ctx.m, field)[i.nextLocal - 1]; } } inline fn m_allocator(ctx: *Ctx) std.mem.Allocator { return ctx.arena.allocator(); } inline fn gpa(ctx: *Ctx) std.mem.Allocator { return ctx.arena.child_allocator; }
src/Wat.zig
const std = @import("std"); const expect = std.testing.expect; const mem = std.mem; test "arrays" { var array: [5]u32 = undefined; var i: u32 = 0; while (i < 5) { array[i] = i + 1; i = array[i]; } i = 0; var accumulator = u32(0); while (i < 5) { accumulator += array[i]; i += 1; } expect(accumulator == 15); expect(getArrayLen(array) == 5); } fn getArrayLen(a: []const u32) usize { return a.len; } test "void arrays" { var array: [4]void = undefined; array[0] = void{}; array[1] = array[2]; expect(@sizeOf(@typeOf(array)) == 0); expect(array.len == 4); } test "array literal" { const hex_mult = [_]u16{ 4096, 256, 16, 1, }; expect(hex_mult.len == 4); expect(hex_mult[1] == 256); } test "array dot len const expr" { expect(comptime x: { break :x some_array.len == 4; }); } const ArrayDotLenConstExpr = struct { y: [some_array.len]u8, }; const some_array = [_]u8{ 0, 1, 2, 3, }; test "nested arrays" { const array_of_strings = [_][]const u8{ "hello", "this", "is", "my", "thing", }; for (array_of_strings) |s, i| { if (i == 0) expect(mem.eql(u8, s, "hello")); if (i == 1) expect(mem.eql(u8, s, "this")); if (i == 2) expect(mem.eql(u8, s, "is")); if (i == 3) expect(mem.eql(u8, s, "my")); if (i == 4) expect(mem.eql(u8, s, "thing")); } } var s_array: [8]Sub = undefined; const Sub = struct { b: u8, }; const Str = struct { a: []Sub, }; test "set global var array via slice embedded in struct" { var s = Str{ .a = s_array[0..] }; s.a[0].b = 1; s.a[1].b = 2; s.a[2].b = 3; expect(s_array[0].b == 1); expect(s_array[1].b == 2); expect(s_array[2].b == 3); } test "array literal with specified size" { var array = [2]u8{ 1, 2, }; expect(array[0] == 1); expect(array[1] == 2); } test "array child property" { var x: [5]i32 = undefined; expect(@typeOf(x).Child == i32); } test "array len property" { var x: [5]i32 = undefined; expect(@typeOf(x).len == 5); } test "array len field" { var arr = [4]u8{ 0, 0, 0, 0 }; var ptr = &arr; expect(arr.len == 4); comptime expect(arr.len == 4); expect(ptr.len == 4); comptime expect(ptr.len == 4); } test "single-item pointer to array indexing and slicing" { testSingleItemPtrArrayIndexSlice(); comptime testSingleItemPtrArrayIndexSlice(); } fn testSingleItemPtrArrayIndexSlice() void { var array = "aaaa"; doSomeMangling(&array); expect(mem.eql(u8, "azya", array)); } fn doSomeMangling(array: *[4]u8) void { array[1] = 'z'; array[2..3][0] = 'y'; } test "implicit cast single-item pointer" { testImplicitCastSingleItemPtr(); comptime testImplicitCastSingleItemPtr(); } fn testImplicitCastSingleItemPtr() void { var byte: u8 = 100; const slice = (*[1]u8)(&byte)[0..]; slice[0] += 1; expect(byte == 101); } fn testArrayByValAtComptime(b: [2]u8) u8 { return b[0]; } test "comptime evalutating function that takes array by value" { const arr = [_]u8{ 0, 1 }; _ = comptime testArrayByValAtComptime(arr); _ = comptime testArrayByValAtComptime(arr); } test "implicit comptime in array type size" { var arr: [plusOne(10)]bool = undefined; expect(arr.len == 11); } fn plusOne(x: u32) u32 { return x + 1; } test "runtime initialize array elem and then implicit cast to slice" { var two: i32 = 2; const x: []const i32 = [_]i32{two}; expect(x[0] == 2); } test "array literal as argument to function" { const S = struct { fn entry(two: i32) void { foo([_]i32{ 1, 2, 3, }); foo([_]i32{ 1, two, 3, }); foo2(true, [_]i32{ 1, 2, 3, }); foo2(true, [_]i32{ 1, two, 3, }); } fn foo(x: []const i32) void { expect(x[0] == 1); expect(x[1] == 2); expect(x[2] == 3); } fn foo2(trash: bool, x: []const i32) void { expect(trash); expect(x[0] == 1); expect(x[1] == 2); expect(x[2] == 3); } }; S.entry(2); comptime S.entry(2); } test "double nested array to const slice cast in array literal" { const S = struct { fn entry(two: i32) void { const cases = [_][]const []const i32{ [_][]const i32{[_]i32{1}}, [_][]const i32{[_]i32{ 2, 3 }}, [_][]const i32{ [_]i32{4}, [_]i32{ 5, 6, 7 }, }, }; check(cases); const cases2 = [_][]const i32{ [_]i32{1}, &[_]i32{ two, 3 }, }; expect(cases2.len == 2); expect(cases2[0].len == 1); expect(cases2[0][0] == 1); expect(cases2[1].len == 2); expect(cases2[1][0] == 2); expect(cases2[1][1] == 3); const cases3 = [_][]const []const i32{ [_][]const i32{[_]i32{1}}, &[_][]const i32{&[_]i32{ two, 3 }}, [_][]const i32{ [_]i32{4}, [_]i32{ 5, 6, 7 }, }, }; check(cases3); } fn check(cases: []const []const []const i32) void { expect(cases.len == 3); expect(cases[0].len == 1); expect(cases[0][0].len == 1); expect(cases[0][0][0] == 1); expect(cases[1].len == 1); expect(cases[1][0].len == 2); expect(cases[1][0][0] == 2); expect(cases[1][0][1] == 3); expect(cases[2].len == 2); expect(cases[2][0].len == 1); expect(cases[2][0][0] == 4); expect(cases[2][1].len == 3); expect(cases[2][1][0] == 5); expect(cases[2][1][1] == 6); expect(cases[2][1][2] == 7); } }; S.entry(2); comptime S.entry(2); } test "read/write through global variable array of struct fields initialized via array mult" { const S = struct { fn doTheTest() void { expect(storage[0].term == 1); storage[0] = MyStruct{ .term = 123 }; expect(storage[0].term == 123); } pub const MyStruct = struct { term: usize, }; var storage: [1]MyStruct = [_]MyStruct{MyStruct{ .term = 1 }} ** 1; }; S.doTheTest(); }
test/stage1/behavior/array.zig
const std = @import("std"); const fs = std.fs; const assert = std.debug.assert; const json = std.json; const KnownOpt = struct { name: []const u8, /// Corresponds to stage.zig ClangArgIterator.Kind ident: []const u8, }; const known_options = [_]KnownOpt{ .{ .name = "target", .ident = "target", }, .{ .name = "o", .ident = "o", }, .{ .name = "c", .ident = "c", }, .{ .name = "l", .ident = "l", }, .{ .name = "pipe", .ident = "ignore", }, .{ .name = "help", .ident = "driver_punt", }, .{ .name = "fPIC", .ident = "pic", }, .{ .name = "fno-PIC", .ident = "no_pic", }, .{ .name = "nostdlib", .ident = "nostdlib", }, .{ .name = "no-standard-libraries", .ident = "nostdlib", }, .{ .name = "shared", .ident = "shared", }, .{ .name = "rdynamic", .ident = "rdynamic", }, .{ .name = "Wl,", .ident = "wl", }, .{ .name = "E", .ident = "preprocess", }, .{ .name = "preprocess", .ident = "preprocess", }, .{ .name = "S", .ident = "driver_punt", }, .{ .name = "assemble", .ident = "driver_punt", }, .{ .name = "O1", .ident = "optimize", }, .{ .name = "O2", .ident = "optimize", }, .{ .name = "Og", .ident = "optimize", }, .{ .name = "O", .ident = "optimize", }, .{ .name = "Ofast", .ident = "optimize", }, .{ .name = "optimize", .ident = "optimize", }, .{ .name = "g", .ident = "debug", }, .{ .name = "debug", .ident = "debug", }, .{ .name = "g-dwarf", .ident = "debug", }, .{ .name = "g-dwarf-2", .ident = "debug", }, .{ .name = "g-dwarf-3", .ident = "debug", }, .{ .name = "g-dwarf-4", .ident = "debug", }, .{ .name = "g-dwarf-5", .ident = "debug", }, .{ .name = "fsanitize", .ident = "sanitize", }, }; const blacklisted_options = [_][]const u8{}; fn knownOption(name: []const u8) ?[]const u8 { const chopped_name = if (std.mem.endsWith(u8, name, "=")) name[0 .. name.len - 1] else name; for (known_options) |item| { if (std.mem.eql(u8, chopped_name, item.name)) { return item.ident; } } return null; } pub fn main() anyerror!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); if (args.len <= 1) { usageAndExit(std.io.getStdErr(), args[0], 1); } if (std.mem.eql(u8, args[1], "--help")) { usageAndExit(std.io.getStdOut(), args[0], 0); } if (args.len < 3) { usageAndExit(std.io.getStdErr(), args[0], 1); } const llvm_tblgen_exe = args[1]; if (std.mem.startsWith(u8, llvm_tblgen_exe, "-")) { usageAndExit(std.io.getStdErr(), args[0], 1); } const llvm_src_root = args[2]; if (std.mem.startsWith(u8, llvm_src_root, "-")) { usageAndExit(std.io.getStdErr(), args[0], 1); } const child_args = [_][]const u8{ llvm_tblgen_exe, "--dump-json", try std.fmt.allocPrint(allocator, "{}/clang/include/clang/Driver/Options.td", .{llvm_src_root}), try std.fmt.allocPrint(allocator, "-I={}/llvm/include", .{llvm_src_root}), try std.fmt.allocPrint(allocator, "-I={}/clang/include/clang/Driver", .{llvm_src_root}), }; const child_result = try std.ChildProcess.exec2(.{ .allocator = allocator, .argv = &child_args, .max_output_bytes = 100 * 1024 * 1024, }); std.debug.warn("{}\n", .{child_result.stderr}); const json_text = switch (child_result.term) { .Exited => |code| if (code == 0) child_result.stdout else { std.debug.warn("llvm-tblgen exited with code {}\n", .{code}); std.process.exit(1); }, else => { std.debug.warn("llvm-tblgen crashed\n", .{}); std.process.exit(1); }, }; var parser = json.Parser.init(allocator, false); const tree = try parser.parse(json_text); const root_map = &tree.root.Object; var all_objects = std.ArrayList(*json.ObjectMap).init(allocator); { var it = root_map.iterator(); it_map: while (it.next()) |kv| { if (kv.key.len == 0) continue; if (kv.key[0] == '!') continue; if (kv.value != .Object) continue; if (!kv.value.Object.contains("NumArgs")) continue; if (!kv.value.Object.contains("Name")) continue; for (blacklisted_options) |blacklisted_key| { if (std.mem.eql(u8, blacklisted_key, kv.key)) continue :it_map; } if (kv.value.Object.get("Name").?.value.String.len == 0) continue; try all_objects.append(&kv.value.Object); } } // Some options have multiple matches. As an example, "-Wl,foo" matches both // "W" and "Wl,". So we sort this list in order of descending priority. std.sort.sort(*json.ObjectMap, all_objects.span(), objectLessThan); var stdout_bos = std.io.bufferedOutStream(std.io.getStdOut().outStream()); const stdout = stdout_bos.outStream(); try stdout.writeAll( \\// This file is generated by tools/update_clang_options.zig. \\// zig fmt: off \\usingnamespace @import("clang_options.zig"); \\pub const data = blk: { @setEvalBranchQuota(6000); break :blk &[_]CliArg{ \\ ); for (all_objects.span()) |obj| { const name = obj.get("Name").?.value.String; var pd1 = false; var pd2 = false; var pslash = false; for (obj.get("Prefixes").?.value.Array.span()) |prefix_json| { const prefix = prefix_json.String; if (std.mem.eql(u8, prefix, "-")) { pd1 = true; } else if (std.mem.eql(u8, prefix, "--")) { pd2 = true; } else if (std.mem.eql(u8, prefix, "/")) { pslash = true; } else { std.debug.warn("{} has unrecognized prefix '{}'\n", .{ name, prefix }); std.process.exit(1); } } const syntax = objSyntax(obj); if (knownOption(name)) |ident| { try stdout.print( \\.{{ \\ .name = "{}", \\ .syntax = {}, \\ .zig_equivalent = .{}, \\ .pd1 = {}, \\ .pd2 = {}, \\ .psl = {}, \\}}, \\ , .{ name, syntax, ident, pd1, pd2, pslash }); } else if (pd1 and !pd2 and !pslash and syntax == .flag) { try stdout.print("flagpd1(\"{}\"),\n", .{name}); } else if (pd1 and !pd2 and !pslash and syntax == .joined) { try stdout.print("joinpd1(\"{}\"),\n", .{name}); } else if (pd1 and !pd2 and !pslash and syntax == .joined_or_separate) { try stdout.print("jspd1(\"{}\"),\n", .{name}); } else if (pd1 and !pd2 and !pslash and syntax == .separate) { try stdout.print("sepd1(\"{}\"),\n", .{name}); } else { try stdout.print( \\.{{ \\ .name = "{}", \\ .syntax = {}, \\ .zig_equivalent = .other, \\ .pd1 = {}, \\ .pd2 = {}, \\ .psl = {}, \\}}, \\ , .{ name, syntax, pd1, pd2, pslash }); } } try stdout.writeAll( \\};}; \\ ); try stdout_bos.flush(); } // TODO we should be able to import clang_options.zig but currently this is problematic because it will // import stage2.zig and that causes a bunch of stuff to get exported const Syntax = union(enum) { /// A flag with no values. flag, /// An option which prefixes its (single) value. joined, /// An option which is followed by its value. separate, /// An option which is either joined to its (non-empty) value, or followed by its value. joined_or_separate, /// An option which is both joined to its (first) value, and followed by its (second) value. joined_and_separate, /// An option followed by its values, which are separated by commas. comma_joined, /// An option which consumes an optional joined argument and any other remaining arguments. remaining_args_joined, /// An option which is which takes multiple (separate) arguments. multi_arg: u8, pub fn format( self: Syntax, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: var, ) !void { switch (self) { .multi_arg => |n| return out_stream.print(".{{.{}={}}}", .{ @tagName(self), n }), else => return out_stream.print(".{}", .{@tagName(self)}), } } }; fn objSyntax(obj: *json.ObjectMap) Syntax { const num_args = @intCast(u8, obj.get("NumArgs").?.value.Integer); for (obj.get("!superclasses").?.value.Array.span()) |superclass_json| { const superclass = superclass_json.String; if (std.mem.eql(u8, superclass, "Joined")) { return .joined; } else if (std.mem.eql(u8, superclass, "CLJoined")) { return .joined; } else if (std.mem.eql(u8, superclass, "CLIgnoredJoined")) { return .joined; } else if (std.mem.eql(u8, superclass, "CLCompileJoined")) { return .joined; } else if (std.mem.eql(u8, superclass, "JoinedOrSeparate")) { return .joined_or_separate; } else if (std.mem.eql(u8, superclass, "CLJoinedOrSeparate")) { return .joined_or_separate; } else if (std.mem.eql(u8, superclass, "CLCompileJoinedOrSeparate")) { return .joined_or_separate; } else if (std.mem.eql(u8, superclass, "Flag")) { return .flag; } else if (std.mem.eql(u8, superclass, "CLFlag")) { return .flag; } else if (std.mem.eql(u8, superclass, "CLIgnoredFlag")) { return .flag; } else if (std.mem.eql(u8, superclass, "Separate")) { return .separate; } else if (std.mem.eql(u8, superclass, "JoinedAndSeparate")) { return .joined_and_separate; } else if (std.mem.eql(u8, superclass, "CommaJoined")) { return .comma_joined; } else if (std.mem.eql(u8, superclass, "CLRemainingArgsJoined")) { return .remaining_args_joined; } else if (std.mem.eql(u8, superclass, "MultiArg")) { return .{ .multi_arg = num_args }; } } const name = obj.get("Name").?.value.String; if (std.mem.eql(u8, name, "<input>")) { return .flag; } else if (std.mem.eql(u8, name, "<unknown>")) { return .flag; } const kind_def = obj.get("Kind").?.value.Object.get("def").?.value.String; if (std.mem.eql(u8, kind_def, "KIND_FLAG")) { return .flag; } const key = obj.get("!name").?.value.String; std.debug.warn("{} (key {}) has unrecognized superclasses:\n", .{ name, key }); for (obj.get("!superclasses").?.value.Array.span()) |superclass_json| { std.debug.warn(" {}\n", .{superclass_json.String}); } std.process.exit(1); } fn syntaxMatchesWithEql(syntax: Syntax) bool { return switch (syntax) { .flag, .separate, .multi_arg, => true, .joined, .joined_or_separate, .joined_and_separate, .comma_joined, .remaining_args_joined, => false, }; } fn objectLessThan(a: *json.ObjectMap, b: *json.ObjectMap) bool { // Priority is determined by exact matches first, followed by prefix matches in descending // length, with key as a final tiebreaker. const a_syntax = objSyntax(a); const b_syntax = objSyntax(b); const a_match_with_eql = syntaxMatchesWithEql(a_syntax); const b_match_with_eql = syntaxMatchesWithEql(b_syntax); if (a_match_with_eql and !b_match_with_eql) { return true; } else if (!a_match_with_eql and b_match_with_eql) { return false; } if (!a_match_with_eql and !b_match_with_eql) { const a_name = a.get("Name").?.value.String; const b_name = b.get("Name").?.value.String; if (a_name.len != b_name.len) { return a_name.len > b_name.len; } } const a_key = a.get("!name").?.value.String; const b_key = b.get("!name").?.value.String; return std.mem.lessThan(u8, a_key, b_key); } fn usageAndExit(file: fs.File, arg0: []const u8, code: u8) noreturn { file.outStream().print( \\Usage: {} /path/to/llvm-tblgen /path/to/git/llvm/llvm-project \\ \\Prints to stdout Zig code which you can use to replace the file src-self-hosted/clang_options_data.zig. \\ , .{arg0}) catch std.process.exit(1); std.process.exit(code); }
tools/update_clang_options.zig
const std = @import("../std.zig"); const assert = std.debug.assert; const maxInt = std.math.maxInt; const State = enum { Complete, Value, ArrayStart, Array, ObjectStart, Object, }; /// Writes JSON ([RFC8259](https://tools.ietf.org/html/rfc8259)) formatted data /// to a stream. `max_depth` is a comptime-known upper bound on the nesting depth. /// TODO A future iteration of this API will allow passing `null` for this value, /// and disable safety checks in release builds. pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type { return struct { const Self = @This(); pub const Stream = OutStream; /// The string used for indenting. one_indent: []const u8 = " ", /// The string used as a newline character. newline: []const u8 = "\n", /// The string used as spacing. space: []const u8 = " ", stream: OutStream, state_index: usize, state: [max_depth]State, pub fn init(stream: OutStream) Self { var self = Self{ .stream = stream, .state_index = 1, .state = undefined, }; self.state[0] = .Complete; self.state[1] = .Value; return self; } pub fn beginArray(self: *Self) !void { assert(self.state[self.state_index] == State.Value); // need to call arrayElem or objectField try self.stream.writeByte('['); self.state[self.state_index] = State.ArrayStart; } pub fn beginObject(self: *Self) !void { assert(self.state[self.state_index] == State.Value); // need to call arrayElem or objectField try self.stream.writeByte('{'); self.state[self.state_index] = State.ObjectStart; } pub fn arrayElem(self: *Self) !void { const state = self.state[self.state_index]; switch (state) { .Complete => unreachable, .Value => unreachable, .ObjectStart => unreachable, .Object => unreachable, .Array, .ArrayStart => { if (state == .Array) { try self.stream.writeByte(','); } self.state[self.state_index] = .Array; self.pushState(.Value); try self.indent(); }, } } pub fn objectField(self: *Self, name: []const u8) !void { const state = self.state[self.state_index]; switch (state) { .Complete => unreachable, .Value => unreachable, .ArrayStart => unreachable, .Array => unreachable, .Object, .ObjectStart => { if (state == .Object) { try self.stream.writeByte(','); } self.state[self.state_index] = .Object; self.pushState(.Value); try self.indent(); try self.writeEscapedString(name); try self.stream.writeAll(":"); try self.stream.writeAll(self.space); }, } } pub fn endArray(self: *Self) !void { switch (self.state[self.state_index]) { .Complete => unreachable, .Value => unreachable, .ObjectStart => unreachable, .Object => unreachable, .ArrayStart => { try self.stream.writeByte(']'); self.popState(); }, .Array => { try self.indent(); self.popState(); try self.stream.writeByte(']'); }, } } pub fn endObject(self: *Self) !void { switch (self.state[self.state_index]) { .Complete => unreachable, .Value => unreachable, .ArrayStart => unreachable, .Array => unreachable, .ObjectStart => { try self.stream.writeByte('}'); self.popState(); }, .Object => { try self.indent(); self.popState(); try self.stream.writeByte('}'); }, } } pub fn emitNull(self: *Self) !void { assert(self.state[self.state_index] == State.Value); try self.stream.writeAll("null"); self.popState(); } pub fn emitBool(self: *Self, value: bool) !void { assert(self.state[self.state_index] == State.Value); if (value) { try self.stream.writeAll("true"); } else { try self.stream.writeAll("false"); } self.popState(); } pub fn emitNumber( self: *Self, /// An integer, float, or `std.math.BigInt`. Emitted as a bare number if it fits losslessly /// in a IEEE 754 double float, otherwise emitted as a string to the full precision. value: var, ) !void { assert(self.state[self.state_index] == State.Value); switch (@typeInfo(@TypeOf(value))) { .Int => |info| { if (info.bits < 53) { try self.stream.print("{}", .{value}); self.popState(); return; } if (value < 4503599627370496 and (!info.is_signed or value > -4503599627370496)) { try self.stream.print("{}", .{value}); self.popState(); return; } }, .Float => if (@floatCast(f64, value) == value) { try self.stream.print("{}", .{value}); self.popState(); return; }, else => {}, } try self.stream.print("\"{}\"", .{value}); self.popState(); } pub fn emitString(self: *Self, string: []const u8) !void { try self.writeEscapedString(string); self.popState(); } fn writeEscapedString(self: *Self, string: []const u8) !void { try self.stream.writeByte('"'); for (string) |s| { switch (s) { '"' => try self.stream.writeAll("\\\""), '\t' => try self.stream.writeAll("\\t"), '\r' => try self.stream.writeAll("\\r"), '\n' => try self.stream.writeAll("\\n"), 8 => try self.stream.writeAll("\\b"), 12 => try self.stream.writeAll("\\f"), '\\' => try self.stream.writeAll("\\\\"), else => try self.stream.writeByte(s), } } try self.stream.writeByte('"'); } /// Writes the complete json into the output stream pub fn emitJson(self: *Self, json: std.json.Value) Stream.Error!void { switch (json) { .Null => try self.emitNull(), .Bool => |inner| try self.emitBool(inner), .Integer => |inner| try self.emitNumber(inner), .Float => |inner| try self.emitNumber(inner), .String => |inner| try self.emitString(inner), .Array => |inner| { try self.beginArray(); for (inner.span()) |elem| { try self.arrayElem(); try self.emitJson(elem); } try self.endArray(); }, .Object => |inner| { try self.beginObject(); var it = inner.iterator(); while (it.next()) |entry| { try self.objectField(entry.key); try self.emitJson(entry.value); } try self.endObject(); }, } } fn indent(self: *Self) !void { assert(self.state_index >= 1); try self.stream.writeAll(self.newline); var i: usize = 0; while (i < self.state_index - 1) : (i += 1) { try self.stream.writeAll(self.one_indent); } } fn pushState(self: *Self, state: State) void { self.state_index += 1; self.state[self.state_index] = state; } fn popState(self: *Self) void { self.state_index -= 1; } }; } pub fn writeStream( out_stream: var, comptime max_depth: usize, ) WriteStream(@TypeOf(out_stream), max_depth) { return WriteStream(@TypeOf(out_stream), max_depth).init(out_stream); } test "json write stream" { var out_buf: [1024]u8 = undefined; var slice_stream = std.io.fixedBufferStream(&out_buf); const out = slice_stream.outStream(); var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_allocator.deinit(); var w = std.json.writeStream(out, 10); try w.emitJson(try getJson(&arena_allocator.allocator)); const result = slice_stream.getWritten(); const expected = \\{ \\ "object": { \\ "one": 1, \\ "two": 2.0e+00 \\ }, \\ "string": "This is a string", \\ "array": [ \\ "Another string", \\ 1, \\ 3.14e+00 \\ ], \\ "int": 10, \\ "float": 3.14e+00 \\} ; std.testing.expect(std.mem.eql(u8, expected, result)); } fn getJson(allocator: *std.mem.Allocator) !std.json.Value { var value = std.json.Value{ .Object = std.json.ObjectMap.init(allocator) }; _ = try value.Object.put("string", std.json.Value{ .String = "This is a string" }); _ = try value.Object.put("int", std.json.Value{ .Integer = @intCast(i64, 10) }); _ = try value.Object.put("float", std.json.Value{ .Float = 3.14 }); _ = try value.Object.put("array", try getJsonArray(allocator)); _ = try value.Object.put("object", try getJsonObject(allocator)); return value; } fn getJsonObject(allocator: *std.mem.Allocator) !std.json.Value { var value = std.json.Value{ .Object = std.json.ObjectMap.init(allocator) }; _ = try value.Object.put("one", std.json.Value{ .Integer = @intCast(i64, 1) }); _ = try value.Object.put("two", std.json.Value{ .Float = 2.0 }); return value; } fn getJsonArray(allocator: *std.mem.Allocator) !std.json.Value { var value = std.json.Value{ .Array = std.json.Array.init(allocator) }; var array = &value.Array; _ = try array.append(std.json.Value{ .String = "Another string" }); _ = try array.append(std.json.Value{ .Integer = @intCast(i64, 1) }); _ = try array.append(std.json.Value{ .Float = 3.14 }); return value; }
lib/std/json/write_stream.zig
const std = @import("../std.zig"); const math = std.math; const Random = std.rand.Random; pub fn next_f64(random: *Random, comptime tables: ZigTable) f64 { while (true) { // We manually construct a float from parts as we can avoid an extra random lookup here by // using the unused exponent for the lookup table entry. const bits = random.int(u64); const i = @as(usize, @truncate(u8, bits)); const u = blk: { if (tables.is_symmetric) { // Generate a value in the range [2, 4) and scale into [-1, 1) const repr = ((0x3ff + 1) << 52) | (bits >> 12); break :blk @bitCast(f64, repr) - 3.0; } else { // Generate a value in the range [1, 2) and scale into (0, 1) const repr = (0x3ff << 52) | (bits >> 12); break :blk @bitCast(f64, repr) - (1.0 - math.f64_epsilon / 2.0); } }; const x = u * tables.x[i]; const test_x = if (tables.is_symmetric) math.fabs(x) else x; // equivalent to |u| < tables.x[i+1] / tables.x[i] (or u < tables.x[i+1] / tables.x[i]) if (test_x < tables.x[i + 1]) { return x; } if (i == 0) { return tables.zero_case(random, u); } // equivalent to f1 + DRanU() * (f0 - f1) < 1 if (tables.f[i + 1] + (tables.f[i] - tables.f[i + 1]) * random.float(f64) < tables.pdf(x)) { return x; } } } pub const ZigTable = struct { r: f64, x: [257]f64, f: [257]f64, // probability density function used as a fallback pdf: fn (f64) f64, // whether the distribution is symmetric is_symmetric: bool, // fallback calculation in the case we are in the 0 block zero_case: fn (*Random, f64) f64, }; // zigNorInit fn ZigTableGen( comptime is_symmetric: bool, comptime r: f64, comptime v: f64, comptime f: fn (f64) f64, comptime f_inv: fn (f64) f64, comptime zero_case: fn (*Random, f64) f64, ) ZigTable { var tables: ZigTable = undefined; tables.is_symmetric = is_symmetric; tables.r = r; tables.pdf = f; tables.zero_case = zero_case; tables.x[0] = v / f(r); tables.x[1] = r; for (tables.x[2..256]) |*entry, i| { const last = tables.x[2 + i - 1]; entry.* = f_inv(v / last + f(last)); } tables.x[256] = 0; for (tables.f[0..]) |*entry, i| { entry.* = f(tables.x[i]); } return tables; } // N(0, 1) pub const NormDist = blk: { @setEvalBranchQuota(30000); break :blk ZigTableGen(true, norm_r, norm_v, norm_f, norm_f_inv, norm_zero_case); }; const norm_r = 3.6541528853610088; const norm_v = 0.00492867323399; fn norm_f(x: f64) f64 { return math.exp(-x * x / 2.0); } fn norm_f_inv(y: f64) f64 { return math.sqrt(-2.0 * math.ln(y)); } fn norm_zero_case(random: *Random, u: f64) f64 { var x: f64 = 1; var y: f64 = 0; while (-2.0 * y < x * x) { x = math.ln(random.float(f64)) / norm_r; y = math.ln(random.float(f64)); } if (u < 0) { return x - norm_r; } else { return norm_r - x; } } test "ziggurant normal dist sanity" { var prng = std.rand.DefaultPrng.init(0); var i: usize = 0; while (i < 1000) : (i += 1) { _ = prng.random.floatNorm(f64); } } // Exp(1) pub const ExpDist = blk: { @setEvalBranchQuota(30000); break :blk ZigTableGen(false, exp_r, exp_v, exp_f, exp_f_inv, exp_zero_case); }; const exp_r = 7.69711747013104972; const exp_v = 0.0039496598225815571993; fn exp_f(x: f64) f64 { return math.exp(-x); } fn exp_f_inv(y: f64) f64 { return -math.ln(y); } fn exp_zero_case(random: *Random, _: f64) f64 { return exp_r - math.ln(random.float(f64)); } test "ziggurant exp dist sanity" { var prng = std.rand.DefaultPrng.init(0); var i: usize = 0; while (i < 1000) : (i += 1) { _ = prng.random.floatExp(f64); } } test "ziggurat table gen" { const table = NormDist; }
lib/std/rand/ziggurat.zig
const std = @import("std"); const ArenaAllocator = std.heap.ArenaAllocator; const xml = @import("lib.zig"); const Parser = @This(); const logger = std.log.scoped(.@"zupnp.xml.Parser"); usingnamespace @import("traverser.zig").StructTraverser(Parser); pub fn DecodeResult(comptime T: type) type { return struct { result: *T, arena: ArenaAllocator, pub fn deinit(self: *@This()) void { self.arena.deinit(); } }; } arena: ArenaAllocator, pub fn init(allocator: std.mem.Allocator) Parser { return .{ .arena = ArenaAllocator.init(allocator) }; } pub fn cleanup(self: *Parser) void { self.arena.deinit(); } pub fn parseDocument(self: *Parser, comptime T: type, doc: xml.Document) !DecodeResult(T) { var result = try self.arena.allocator().create(T); try self.traverseStruct(result, try doc.toNode()); return DecodeResult(T) { .result = result, .arena = self.arena, }; } pub fn handleSubStruct(self: *Parser, comptime name: []const u8, input: anytype, parent: xml.Node) !void { var child = switch (parent) { .Document => |d| d.getElementsByTagName(name ++ "\x00"), .Element => |e| e.getElementsByTagName(name ++ "\x00"), else => { logger.warn("Invalid type for node named {s}", .{name}); return xml.Error; } }.getSingleItem() catch { logger.warn("Missing element {s}", .{name}); return xml.Error; }; try self.traverseStruct(input, child); } pub fn handlePointer(self: *Parser, comptime name: []const u8, input: anytype, parent: xml.Element) !void { const PointerChild = @typeInfo(@TypeOf(input.*)).Pointer.child; var iterator = parent.getElementsByTagName(name ++ "\x00").iterator(); if (iterator.length > 0) { var resultants = try self.arena.allocator().alloc(PointerChild, iterator.length); for (resultants) |*res| { try self.traverseField(res, name, (try iterator.next()).?); } input.* = resultants; } else { input.* = &[_]PointerChild {}; } } pub fn handleOptional(self: *Parser, comptime name: []const u8, input: anytype, parent: xml.Element) !void { const list = parent.getElementsByTagName(name ++ "\x00"); switch (list.getLength()) { 1 => { var subopt: @typeInfo(@TypeOf(input.*)).Optional.child = undefined; try self.traverseField(&subopt, name, try list.getSingleItem()); input.* = subopt; }, 0 => input.* = null, else => |l| { logger.warn("Expecting 0 or 1 {s} elements, found {d}", .{name, l}); return xml.Error; } } } pub fn handleString(self: *Parser, comptime name: []const u8, input: anytype, parent: xml.Element) !void { var text_node = (try parent.getFirstChild()) orelse { // TODO text element might be present, but empty // logger.warn("Text element {s} has no text", .{name}); // return xml.Error; input.* = ""; return; }; switch (text_node) { .TextNode => |tn| input.* = try self.arena.allocator().dupe(u8, tn.getValue()), else => { logger.warn("Element {s} is not a text element", .{name}); return xml.Error; } } } pub fn handleInt(_: *Parser, comptime name: []const u8, input: anytype, parent: xml.Element) !void { input.* = try std.fmt.parseInt(@TypeOf(input.*), try getTextNode(name, parent), 0); } pub fn handleBool(_: *Parser, comptime name: []const u8, input: anytype, parent: xml.Element) !void { const maybe_bool = try getTextNode(name, parent); var actual_bool: bool = undefined; if (std.ascii.eqlIgnoreCase(maybe_bool, "true") or std.mem.eql(u8, maybe_bool, "1")) { actual_bool = true; } else if (std.ascii.eqlIgnoreCase(maybe_bool, "false") or std.mem.eql(u8, maybe_bool, "0")) { actual_bool = false; } else { logger.warn("Element {s} is not a valid bool", .{name}); return xml.Error; } input.* = actual_bool; } pub fn handleAttributes(self: *Parser, input: anytype, parent: xml.Element) !void { var attributes = parent.getAttributes(); inline for (@typeInfo(@TypeOf(input.*)).Struct.fields) |field| { const value = blk: { var node = attributes.getNamedItem(field.name ++ "\x00") orelse break :blk null; break :blk try self.arena.allocator().dupe(u8, node.getValue()); }; @field(input, field.name) = switch (field.field_type) { ?[]const u8, ?[]u8 => value, []const u8, []u8 => value orelse return xml.Error, else => @compileError("Invalid field '" ++ field.name ++ "' for attribute struct") }; } } pub fn handleSingleItem(self: *Parser, comptime name: []const u8, input: anytype, parent: xml.Element) !void { var element = parent.getElementsByTagName(name ++ "\x00").getSingleItem() catch { logger.warn("Missing element {s}", .{name}); return xml.Error; }; try self.traverseField(input, "__item__", element); } fn getTextNode(comptime name: []const u8, parent: xml.Element) ![:0]const u8 { var text_node = (try parent.getFirstChild()) orelse { logger.warn("Text element {s} has no text", .{name}); return xml.Error; }; switch (text_node) { .TextNode => |tn| return tn.getValue(), else => { logger.warn("Element {s} is not a text element", .{name}); return xml.Error; } } }
src/parser.zig
const std = @import("std"); const Ed25519 = std.crypto.sign.Ed25519; const SHA512 = std.crypto.hash.sha2.Sha512; const b64decoder = std.base64.standard.Decoder; const b64encoder = std.base64.standard.Encoder; const endian = @import("builtin").target.cpu.arch.endian(); const zero = std.crypto.utils.secureZero; const bcrypt_pbkdf = @import("bcrypt_pbkdf.zig").bcrypt_pbkdf; const comment_hdr = "untrusted comment: "; pub const Signature = packed struct { /// This is always "Ed" for Ed25519. pkalg: [2]u8, /// A random 64-bit integer which is used to tell if the correct pubkey is used for verification. keynum: [8]u8, /// Ed25519 signature sig: [Ed25519.signature_length]u8, fn check(self: Signature) !void { if (!std.mem.eql(u8, &self.pkalg, "Ed")) return error.UnsupportedAlgorithm; } }; pub const PubKey = packed struct { pkalg: [2]u8, keynum: [8]u8, pubkey: [Ed25519.public_length]u8, fn check(self: PubKey) !void { if (!std.mem.eql(u8, &self.pkalg, "Ed")) return error.UnsupportedAlgorithm; } }; /// A possibly encrypted secret key. pub const SecretKey = packed struct { pkalg: [2]u8, /// BK = bcrypt_pbkdf kdfalg: [2]u8, /// Number of bcrypt_pbkdf rounds, but if 0, skip bcrypt entirely (no passphrase) kdfrounds: u32, /// bcrypt salt salt: [16]u8, /// first eight bytes of the SHA-512 hash of the *decrypted* private key checksum: [8]u8, keynum: [8]u8, /// Ed25519 private key XORed with output of bcrypt_pbkdf (or nulls, if kdfrounds=0). seckey: [Ed25519.secret_length]u8, fn check(self: *SecretKey) !void { if (!std.mem.eql(u8, &self.pkalg, "Ed")) return error.UnsupportedAlgorithm; if (!std.mem.eql(u8, &self.kdfalg, "BK")) return error.UnsupportedAlgorithm; self.kdfrounds = std.mem.bigToNative(u32, self.kdfrounds); } pub fn is_encrypted(self: SecretKey) bool { return self.kdfrounds > 0; } pub fn decrypt(self: SecretKey, passphrase: []const u8) !DecryptedSecretKey { var xorkey: [Ed25519.secret_length]u8 = undefined; var enckey: [Ed25519.secret_length]u8 = self.seckey; if (!self.is_encrypted()) return DecryptedSecretKey{ .keynum = self.keynum, .seckey = self.seckey }; try bcrypt_pbkdf(passphrase, self.salt[0..], xorkey[0..], self.kdfrounds); for (xorkey) |keybyte, index| enckey[index] ^= keybyte; var key_digest: [SHA512.digest_length]u8 = undefined; SHA512.hash(&enckey, &key_digest, .{}); if (!std.mem.eql(u8, key_digest[0..8], &self.checksum)) return error.WrongPassphrase; return DecryptedSecretKey{ .keynum = self.keynum, .seckey = enckey }; } }; pub const DecryptedSecretKey = struct { keynum: [8]u8, seckey: [Ed25519.secret_length]u8, }; pub const KeyPair = struct { pubkey: PubKey, seckey: SecretKey, }; pub fn generate_keypair(passphrase: []const u8) !KeyPair { var keypair = try Ed25519.KeyPair.create(null); // null seed means random defer zerosingle(&keypair); const checksum = checksum: { var key_digest: [SHA512.digest_length]u8 = undefined; SHA512.hash(&keypair.secret_key, &key_digest, .{}); break :checksum key_digest[0..8]; }; const kdfrounds: u32 = if (passphrase.len > 0) 42 else 0; // 42 rounds is used by signify const kdfsalt: [16]u8 = secure_random(16); const encrypted_key = if (kdfrounds > 0) key: { var xorkey: [Ed25519.secret_length]u8 = undefined; var enckey: [Ed25519.secret_length]u8 = keypair.secret_key; try bcrypt_pbkdf(passphrase, kdfsalt[0..], xorkey[0..], kdfrounds); for (xorkey) |keybyte, index| enckey[index] ^= keybyte; break :key enckey; } else key: { break :key keypair.secret_key; }; const pubkey = PubKey{ .pkalg = "Ed".*, .keynum = secure_random(8), .pubkey = keypair.public_key, }; const seckey = SecretKey{ .pkalg = "Ed".*, .kdfalg = "BK".*, .kdfrounds = std.mem.nativeToBig(u32, kdfrounds), .salt = kdfsalt, .checksum = checksum.*, .keynum = pubkey.keynum, .seckey = encrypted_key, }; return KeyPair{ .pubkey = pubkey, .seckey = seckey }; } pub fn sign_message(privatekey: DecryptedSecretKey, msg: []const u8) !Signature { const keypair = Ed25519.KeyPair.fromSecretKey(privatekey.seckey); const sig = try Ed25519.sign(msg, keypair, null); return Signature{ .pkalg = "Ed".*, .keynum = privatekey.keynum, .sig = sig }; } pub fn verify_message(pubkey: PubKey, signature: Signature, msg: []const u8) !void { if (!std.mem.eql(u8, &pubkey.keynum, &signature.keynum)) { return error.WrongPublicKey; } return Ed25519.verify(signature.sig, msg, pubkey.pubkey); } /// read signify-base64 file at *path*. If *data_len* is specified, /// the file is assumed to be in <header><payload> format and data_len /// will receive the length of the header (in bytes). pub fn read_base64_file(path: []const u8, data_len: ?*usize, allocator: std.mem.Allocator) ![]u8 { var contents_buf: [2048]u8 = undefined; const contents = try std.fs.cwd().readFile(path, &contents_buf); var iter = std.mem.split(u8, contents, "\n"); var line = iter.next() orelse return error.InvalidFile; var length = line.len; if (std.mem.startsWith(u8, line, comment_hdr)) { line = iter.next() orelse return error.InvalidFile; length += line.len + 1; // +1 due to \n not being part of line } const empty_line = iter.next() orelse return error.InvalidFile; if (data_len != null) { length += 1; data_len.?.* = length; } else { // If no data follows the base64 portion, check that the file is terminated with \n. if (empty_line.len > 0) { return error.GarbageAtEndOfFile; } if (iter.next() != null) { return error.GarbageAtEndOfFile; } } const dec = try allocator.alloc(u8, try b64decoder.calcSizeForSlice(line)); try b64decoder.decode(dec[0..dec.len], line); return dec; } pub fn write_base64_file(path: []const u8, comment: []const u8, data: []const u8, allocator: std.mem.Allocator) !void { var encode_buf = try allocator.alloc(u8, b64encoder.calcSize(data.len)); defer allocator.free(encode_buf); const encoded = b64encoder.encode(encode_buf, data); const file = try std.fs.cwd().createFile(path, .{ .exclusive = true }); defer file.close(); try file.writeAll(comment_hdr); try file.writeAll(comment); try file.writeAll("\n"); try file.writeAll(encoded); try file.writeAll("\n"); } fn secure_random(comptime nbytes: u32) [nbytes]u8 { var ret: [nbytes]u8 = undefined; std.crypto.random.bytes(&ret); return ret; } fn from_bytes(comptime T: type, bytes: []const u8) !T { const size = @sizeOf(T); if (bytes.len != size) return error.InvalidLength; var self = @bitCast(T, bytes[0..size].*); try self.check(); return self; } pub fn from_file(comptime T: type, path: []const u8, data_len: ?*usize, allocator: std.mem.Allocator) !T { const data = try read_base64_file(path, data_len, allocator); defer allocator.free(data); return from_bytes(T, data); } pub fn as_bytes(self: anytype) []const u8 { return @bitCast([@sizeOf(@TypeOf(self))]u8, self)[0..]; } pub fn zerosingle(obj: anytype) void { zero(@TypeOf(obj.*), @as(*[1]@TypeOf(obj.*), obj)); }
signify-format.zig
const std = @import("std"); const Elephant = struct { letter: u8, tail: ?*Elephant = null, visited: bool = false, // New Elephant methods! pub fn getTail(self: *Elephant) *Elephant { return self.tail.?; // Remember, this means "orelse unreachable" } pub fn hasTail(self: *Elephant) bool { return (self.tail != null); } pub fn visit(self: *Elephant) void { self.visited = true; } pub fn print(self: *Elephant) void { // Prints elephant letter and [v]isited var v: u8 = if (self.visited) 'v' else ' '; std.debug.print("{u}{u} ", .{ self.letter, v }); } }; pub fn main() void { var elephantA = Elephant{ .letter = 'A' }; var elephantB = Elephant{ .letter = 'B' }; var elephantC = Elephant{ .letter = 'C' }; // This links the elephants so that each tail "points" to the next. elephantA.tail = &elephantB; elephantB.tail = &elephantC; visitElephants(&elephantA); std.debug.print("\n", .{}); } // This function visits all elephants once, starting with the // first elephant and following the tails to the next elephant. fn visitElephants(first_elephant: *Elephant) void { var e = first_elephant; while (true) { e.print(); e.visit(); // This gets the next elephant or stops. if (e.hasTail()) { e = e.tail.?; // Which method do we want here? } else { break; } } } // Zig's enums can also have methods! This comment originally asked // if anyone could find instances of enum methods in the wild. The // first five pull requests were accepted and here they are: // // 1) drforester - I found one in the Zig source: // https://github.com/ziglang/zig/blob/041212a41cfaf029dc3eb9740467b721c76f406c/src/Compilation.zig#L2495 // // 2) bbuccianti - I found one! // https://github.com/ziglang/zig/blob/6787f163eb6db2b8b89c2ea6cb51d63606487e12/lib/std/debug.zig#L477 // // 3) GoldsteinE - Found many, here's one // https://github.com/ziglang/zig/blob/ce14bc7176f9e441064ffdde2d85e35fd78977f2/lib/std/target.zig#L65 // // 4) SpencerCDixon - Love this language so far :-) // https://github.com/ziglang/zig/blob/a502c160cd51ce3de80b3be945245b7a91967a85/src/zir.zig#L530 // // 5) tomkun - here's another enum method // https://github.com/ziglang/zig/blob/4ca1f4ec2e3ae1a08295bc6ed03c235cb7700ab9/src/codegen/aarch64.zig#L24
exercises/048_methods2.zig
const std = @import("std"); const upaya = @import("../upaya.zig"); usingnamespace @import("imgui"); const Color = upaya.math.Color; pub const Tileset = struct { tile_size: usize, spacing: usize, tex: upaya.Texture = undefined, tiles_per_row: usize = 0, selected: u8 = 0, pub fn init(tile_size: usize) Tileset { var ts = Tileset{ .tile_size = tile_size, .spacing = 0, }; ts.setTexture(generateTexture()); return ts; } pub fn deinit(self: Tileset) void { self.tex.deinit(); } pub fn loadTexture(self: *Tileset, file: []const u8) void { var spacing: usize = 0; if (!validateImage(file, self.tile_size, &spacing)) { std.debug.print("invalid file. failed validation\n", .{}); } self.tex.deinit(); self.spacing = spacing; self.setTexture(upaya.Texture.initFromFile(file, .nearest) catch unreachable); } /// ensures the image is a valid tileset fn validateImage(file: []const u8, tile_size: usize, spacing: *usize) bool { spacing.* = 0; var w: c_int = 0; var h: c_int = 0; if (upaya.Texture.getTextureSize(file, &w, &h)) { const max_tiles = @intCast(usize, w) / tile_size; while (spacing.* <= 4) : (spacing.* += 1) { var i: usize = 3; while (i <= max_tiles) : (i += 1) { const space = (2 * spacing.*) + (i - 1) * spacing.*; const filled = i * tile_size; if (space + filled == w) { return true; } } } return false; } return false; } /// generates a texture with 4x4, 16px blocks of color fn generateTexture() upaya.Texture { var colors = [_]u32{ Color.white.value, Color.black.value, Color.gray.value, Color.aya.value, Color.yellow.value, Color.orange.value, Color.pink.value, Color.red.value, Color.lime.value, Color.blue.value, Color.beige.value, Color.voilet.value, Color.magenta.value, Color.green.value, Color.maroon.value, Color.sky_blue.value, }; var pixels: [16 * 4 * 16 * 4]u32 = undefined; var y: usize = 0; while (y < 16 * 4) : (y += 1) { var x: usize = 0; while (x < 16 * 4) : (x += 1) { const xx = @divTrunc(x, 16); const yy = @divTrunc(y, 16); pixels[x + y * 16 * 4] = colors[xx + yy * 2]; } } return upaya.Texture.initWithColorData(&pixels, 16 * 4, 16 * 4, .nearest); } pub fn setTexture(self: *Tileset, tex: upaya.Texture) void { self.tex = tex; // calculate tiles_per_row var accum: usize = self.spacing * 2; while (true) { self.tiles_per_row += 1; accum += self.tile_size + self.spacing; if (accum >= self.tex.width) { break; } } } pub fn drawTileset(self: *@This(), name: [*c]const u8) void { defer igEnd(); if (!igBegin(name, null, ImGuiWindowFlags_None)) return; var origin = ogGetCursorScreenPos(); const zoom: usize = if (self.tex.width < 200 and self.tex.height < 200) 2 else 1; ogImage(self.tex.imTextureID(), self.tex.width * @intCast(i32, zoom), self.tex.height * @intCast(i32, zoom)); // draw selected tile addTileToDrawList(self.tile_size * zoom, origin, self.selected, self.tiles_per_row, self.spacing * zoom); // check input for toggling state if (igIsItemHovered(ImGuiHoveredFlags_None)) { if (igIsMouseClicked(ImGuiMouseButton_Left, false)) { var tile = tileIndexUnderPos(igGetIO().MousePos, @intCast(usize, self.tile_size * zoom + self.spacing * zoom), origin); self.selected = @intCast(u8, tile.x + tile.y * self.tiles_per_row); } } } pub fn uvsForTile(self: Tileset, tile: usize) upaya.math.RectF { const x = @intToFloat(f32, @mod(tile, self.tiles_per_row)); const y = @intToFloat(f32, @divTrunc(tile, self.tiles_per_row)); const inv_w = 1.0 / @intToFloat(f32, self.tex.width); const inv_h = 1.0 / @intToFloat(f32, self.tex.height); return .{ .x = (x * @intToFloat(f32, self.tile_size + self.spacing) + @intToFloat(f32, self.spacing)) * inv_w, .y = (y * @intToFloat(f32, self.tile_size + self.spacing) + @intToFloat(f32, self.spacing)) * inv_h, .width = @intToFloat(f32, self.tile_size) * inv_w, .height = @intToFloat(f32, self.tile_size) * inv_h, }; } }; // TODO: duplicated in editor.zig pub fn tileIndexUnderPos(pos: ImVec2, rect_size: usize, origin: ImVec2) struct { x: usize, y: usize } { const final_pos = pos.subtract(origin); return .{ .x = @divTrunc(@floatToInt(usize, final_pos.x), rect_size), .y = @divTrunc(@floatToInt(usize, final_pos.y), rect_size) }; } /// adds a tile selection indicator to the draw list with an outline rectangle and a fill rectangle. Works for both tilesets and palettes. pub fn addTileToDrawList(tile_size: usize, content_start_pos: ImVec2, tile: u8, per_row: usize, tile_spacing: usize) void { const x = @mod(tile, per_row); const y = @divTrunc(tile, per_row); var tl = ImVec2{ .x = @intToFloat(f32, x) * @intToFloat(f32, tile_size + tile_spacing), .y = @intToFloat(f32, y) * @intToFloat(f32, tile_size + tile_spacing) }; tl.x += content_start_pos.x + @intToFloat(f32, tile_spacing); tl.y += content_start_pos.y + @intToFloat(f32, tile_spacing); ogAddQuadFilled(igGetWindowDrawList(), tl, @intToFloat(f32, tile_size), upaya.colors.rgbaToU32(116, 252, 253, 100)); // offset by 1 extra pixel because quad outlines are drawn larger than the size passed in and we shrink the size by our outline width tl.x += 1; tl.y += 1; ogAddQuad(igGetWindowDrawList(), tl, @intToFloat(f32, tile_size - 2), upaya.colors.rgbToU32(116, 252, 253), 2); }
src/tilemaps/tileset.zig
const std = @import("std"); const builtin = @import("builtin"); const zwl = @import("zwl.zig"); const log = std.log.scoped(.zwl); const Allocator = std.mem.Allocator; const gl = @import("opengl.zig"); pub const windows = struct { pub const kernel32 = @import("windows/kernel32.zig"); pub const user32 = @import("windows/user32.zig"); pub const gdi32 = @import("windows/gdi32.zig"); usingnamespace @import("windows/bits.zig"); }; const classname = std.unicode.utf8ToUtf16LeStringLiteral("ZWL"); pub fn Platform(comptime Parent: anytype) type { return struct { const Self = @This(); parent: Parent, instance: windows.HINSTANCE, revent: ?Parent.Event = null, libgl: ?windows.HMODULE, pub fn init(allocator: Allocator, options: zwl.PlatformOptions) !*Parent { var self = try allocator.create(Self); errdefer allocator.destroy(self); const module_handle = windows.kernel32.GetModuleHandleW(null) orelse unreachable; const window_class_info = windows.user32.WNDCLASSEXW{ .style = windows.user32.CS_OWNDC | windows.user32.CS_HREDRAW | windows.user32.CS_VREDRAW, .lpfnWndProc = windowProc, .cbClsExtra = 0, .cbWndExtra = @sizeOf(usize), .hInstance = @ptrCast(windows.HINSTANCE, module_handle), .hIcon = null, .hCursor = null, .hbrBackground = null, .lpszMenuName = null, .lpszClassName = classname, .hIconSm = null, }; if (windows.user32.RegisterClassExW(&window_class_info) == 0) { return error.RegisterClassFailed; } self.* = .{ .parent = .{ .allocator = allocator, .type = .Windows, .window = undefined, .windows = if (!Parent.settings.single_window) &[0]*Parent.Window{} else undefined, }, .instance = @ptrCast(windows.HINSTANCE, module_handle), .libgl = null, }; if (Parent.settings.backends_enabled.opengl) { self.libgl = windows.kernel32.LoadLibraryA("opengl32.dll") orelse return error.MissingOpenGL; } log.info("Platform Initialized: Windows", .{}); return @ptrCast(*Parent, self); } pub fn deinit(self: *Self) void { if (self.libgl) |libgl| { _ = windows.kernel32.FreeLibrary(libgl); } _ = windows.user32.UnregisterClassW(classname, self.instance); self.parent.allocator.destroy(self); } pub fn getOpenGlProcAddress(self: *Self, entry_point: [:0]const u8) ?*c_void { // std.debug.print("lookup {} with ", .{ // std.mem.span(entry_point), // }); if (self.libgl) |libgl| { const T = fn (entry_point: [*:0]const u8) ?*c_void; if (windows.kernel32.GetProcAddress(libgl, "wglGetProcAddress")) |wglGetProcAddress| { if (@ptrCast(T, wglGetProcAddress)(entry_point.ptr)) |ptr| { // std.debug.print("dynamic wglGetProcAddress: {}\n", .{ptr}); return @ptrCast(*c_void, ptr); } } if (windows.kernel32.GetProcAddress(libgl, entry_point.ptr)) |ptr| { // std.debug.print("GetProcAddress: {}\n", .{ptr}); return @ptrCast(*c_void, ptr); } } if (windows.gdi32.wglGetProcAddress(entry_point.ptr)) |ptr| { // std.debug.print("wglGetProcAddress: {}\n", .{ptr}); return ptr; } // std.debug.print("none.\n", .{}); return null; } fn windowProc(hwnd: windows.HWND, uMsg: c_uint, wParam: usize, lParam: ?*c_void) callconv(std.os.windows.WINAPI) ?*c_void { const msg = @intToEnum(windows.user32.WM, uMsg); switch (msg) { .CLOSE => { _ = windows.user32.DestroyWindow(hwnd); }, .DESTROY => { var window_opt = @intToPtr(?*Window, @bitCast(usize, windows.user32.GetWindowLongPtrW(hwnd, 0))); if (window_opt) |window| { var platform = @ptrCast(*Self, window.parent.platform); window.handle = null; platform.revent = Parent.Event{ .WindowDestroyed = @ptrCast(*Parent.Window, window) }; } else { log.emerg("Received message {} for unknown window {}", .{ msg, hwnd }); } }, .CREATE => { const create_info_opt = @ptrCast(?*windows.user32.CREATESTRUCTW, @alignCast(@alignOf(windows.user32.CREATESTRUCTW), lParam)); if (create_info_opt) |create_info| { _ = windows.user32.SetWindowLongPtrW(hwnd, 0, @bitCast(isize, @ptrToInt(create_info.lpCreateParams))); } else { return @intToPtr(windows.LRESULT, @bitCast(usize, @as(isize, -1))); } }, .SIZE => { var window_opt = @intToPtr(?*Window, @bitCast(usize, windows.user32.GetWindowLongPtrW(hwnd, 0))); if (window_opt) |window| { const dim = @bitCast([2]u16, @intCast(u32, @ptrToInt(lParam))); if (dim[0] != window.width or dim[1] != window.height) { var platform = @ptrCast(*Self, window.parent.platform); window.width = dim[0]; window.height = dim[1]; if (window.backend == .software) { if (window.backend.software.createBitmap(window.width, window.height)) |new_bmp| { window.backend.software.bitmap.destroy(); window.backend.software.bitmap = new_bmp; } else |err| { log.emerg("failed to recreate software framebuffer: {}", .{err}); } } platform.revent = Parent.Event{ .WindowResized = @ptrCast(*Parent.Window, window) }; } } else { log.emerg("Received message {} for unknown window {}", .{ msg, hwnd }); } }, .PAINT => { var window_opt = @intToPtr(?*Window, @bitCast(usize, windows.user32.GetWindowLongPtrW(hwnd, 0))); if (window_opt) |window| { var platform = @ptrCast(*Self, window.parent.platform); var ps = std.mem.zeroes(windows.user32.PAINTSTRUCT); if (windows.user32.BeginPaint(hwnd, &ps)) |hDC| { defer _ = windows.user32.EndPaint(hwnd, &ps); if (window.backend == .software) { const render_context = &window.backend.software; const hOldBmp = windows.gdi32.SelectObject( render_context.memory_dc, render_context.bitmap.handle.toGdiObject(), ); defer _ = windows.gdi32.SelectObject(render_context.memory_dc, hOldBmp); _ = windows.gdi32.BitBlt( hDC, 0, 0, render_context.bitmap.width, render_context.bitmap.height, render_context.memory_dc, 0, 0, @enumToInt(windows.gdi32.TernaryRasterOperation.SRCCOPY), ); } } platform.revent = Parent.Event{ .WindowVBlank = @ptrCast(*Parent.Window, window) }; } else { log.emerg("Received message {} for unknown window {}", .{ msg, hwnd }); } }, // https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-mousemove .MOUSEMOVE => { var window_opt = @intToPtr(?*Window, @bitCast(usize, windows.user32.GetWindowLongPtrW(hwnd, 0))); if (window_opt) |window| { var platform = @ptrCast(*Self, window.parent.platform); const pos = @bitCast([2]u16, @intCast(u32, @ptrToInt(lParam))); platform.revent = Parent.Event{ .MouseMotion = .{ .x = @intCast(i16, pos[0]), .y = @intCast(i16, pos[1]), }, }; } else { log.emerg("Received message {} for unknown window {}", .{ msg, hwnd }); } }, .LBUTTONDOWN, // https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-lbuttondown .LBUTTONUP, // https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-lbuttonup .RBUTTONDOWN, // https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-rbuttondown .RBUTTONUP, // https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-rbuttonup .MBUTTONDOWN, // https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-mbuttondown .MBUTTONUP, // https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-mbuttonup => { var window_opt = @intToPtr(?*Window, @bitCast(usize, windows.user32.GetWindowLongPtrW(hwnd, 0))); if (window_opt) |window| { var platform = @ptrCast(*Self, window.parent.platform); const pos = @bitCast([2]u16, @intCast(u32, @ptrToInt(lParam))); var data = zwl.MouseButtonEvent{ .x = @intCast(i16, pos[0]), .y = @intCast(i16, pos[1]), .button = switch (msg) { .LBUTTONDOWN, .LBUTTONUP => .left, .MBUTTONDOWN, .MBUTTONUP => .middle, .RBUTTONDOWN, .RBUTTONUP => .right, else => unreachable, }, }; platform.revent = if ((msg == .LBUTTONDOWN) or (msg == .MBUTTONDOWN) or (msg == .RBUTTONDOWN)) Parent.Event{ .MouseButtonDown = data } else Parent.Event{ .MouseButtonUp = data }; } else { log.emerg("Received message {} for unknown window {}", .{ msg, hwnd }); } }, .KEYDOWN, // https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-keydown .KEYUP, // https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-keydown => { var window_opt = @intToPtr(?*Window, @bitCast(usize, windows.user32.GetWindowLongPtrW(hwnd, 0))); if (window_opt) |window| { var platform = @ptrCast(*Self, window.parent.platform); var kevent = zwl.KeyEvent{ .scancode = @truncate(u8, @ptrToInt(lParam) >> 16), // 16-23 is the OEM scancode }; platform.revent = if (msg == .KEYDOWN) Parent.Event{ .KeyDown = kevent } else Parent.Event{ .KeyUp = kevent }; } else { log.emerg("Received message {} for unknown window {}", .{ msg, hwnd }); } }, else => { // log.debug("default windows message: 0x{X:0>4}", .{uMsg}); return windows.user32.DefWindowProcW(hwnd, uMsg, wParam, lParam); }, } return null; } pub fn waitForEvent(self: *Self) !Parent.Event { var msg: windows.user32.MSG = undefined; while (true) { if (self.revent) |rev| { self.revent = null; return rev; } const ret = windows.user32.GetMessageW(&msg, null, 0, 0); if (ret == -1) unreachable; if (ret == 0) return Parent.Event{ .ApplicationTerminated = undefined }; _ = windows.user32.TranslateMessage(&msg); _ = windows.user32.DispatchMessageW(&msg); } } pub fn createWindow(self: *Self, options: zwl.WindowOptions) !*Parent.Window { var window = try self.parent.allocator.create(Window); errdefer self.parent.allocator.destroy(window); try window.init(self, options); return @ptrCast(*Parent.Window, window); } pub const Window = struct { const Backend = union(enum) { none, software: RenderContext, opengl: windows.gdi32.HGLRC, }; parent: Parent.Window, handle: ?windows.HWND, width: u16, height: u16, backend: Backend, pub fn init(self: *Window, platform: *Self, options: zwl.WindowOptions) !void { self.* = .{ .parent = .{ .platform = @ptrCast(*Parent, platform), }, .width = options.width orelse 800, .height = options.height orelse 600, .handle = undefined, .backend = .none, }; var namebuf: [512]u8 = undefined; var name_allocator = std.heap.FixedBufferAllocator.init(&namebuf); const title = try std.unicode.utf8ToUtf16LeWithNull(name_allocator.allocator(), options.title orelse ""); var style: u32 = 0; style += if (options.visible == true) @as(u32, windows.user32.WS_VISIBLE) else 0; style += if (options.decorations == true) @as(u32, windows.user32.WS_CAPTION | windows.user32.WS_MAXIMIZEBOX | windows.user32.WS_MINIMIZEBOX | windows.user32.WS_SYSMENU) else 0; style += if (options.resizeable == true) @as(u32, windows.user32.WS_SIZEBOX) else 0; // mode, transparent... // CLIENT_RECT stuff... GetClientRect, GetWindowRect var rect = windows.user32.RECT{ .left = 0, .top = 0, .right = self.width, .bottom = self.height }; _ = windows.user32.AdjustWindowRectEx(&rect, style, 0, 0); const x = windows.user32.CW_USEDEFAULT; const y = windows.user32.CW_USEDEFAULT; const w = rect.right - rect.left; const h = rect.bottom - rect.top; const handle = windows.user32.CreateWindowExW(0, classname, title, style, x, y, w, h, null, null, platform.instance, self) orelse return error.CreateWindowFailed; self.handle = handle; self.backend = switch (options.backend) { .software => blk: { const hDC = windows.user32.getDC(handle) catch return error.CreateWindowFailed; defer _ = windows.user32.releaseDC(handle, hDC); var render_context = RenderContext{ .memory_dc = undefined, .bitmap = undefined, }; render_context.memory_dc = windows.gdi32.CreateCompatibleDC(hDC) orelse return error.CreateWindowFailed; errdefer _ = windows.gdi32.DeleteDC(render_context.memory_dc); render_context.bitmap = render_context.createBitmap(self.width, self.height) catch return error.CreateWindowFailed; errdefer render_context.bitmap.destroy(); break :blk Backend{ .software = render_context }; }, .opengl => |requested_gl| blk: { if (Parent.settings.backends_enabled.opengl) { const pfd = windows.gdi32.PIXELFORMATDESCRIPTOR{ .nVersion = 1, .dwFlags = windows.gdi32.PFD_DRAW_TO_WINDOW | windows.gdi32.PFD_SUPPORT_OPENGL | windows.gdi32.PFD_DOUBLEBUFFER, .iPixelType = windows.gdi32.PFD_TYPE_RGBA, .cColorBits = 32, .cRedBits = 0, .cRedShift = 0, .cGreenBits = 0, .cGreenShift = 0, .cBlueBits = 0, .cBlueShift = 0, .cAlphaBits = 0, .cAlphaShift = 0, .cAccumBits = 0, .cAccumRedBits = 0, .cAccumGreenBits = 0, .cAccumBlueBits = 0, .cAccumAlphaBits = 0, .cDepthBits = 24, .cStencilBits = 8, .cAuxBuffers = 0, .iLayerType = windows.gdi32.PFD_MAIN_PLANE, .bReserved = 0, .dwLayerMask = 0, .dwVisibleMask = 0, .dwDamageMask = 0, }; const hDC = windows.user32.GetDC(handle) orelse @panic("couldn't get DC!"); defer _ = windows.user32.ReleaseDC(handle, hDC); const dummy_pixel_format = windows.gdi32.ChoosePixelFormat(hDC, &pfd); _ = windows.gdi32.SetPixelFormat(hDC, dummy_pixel_format, &pfd); const dummy_gl_context = windows.gdi32.wglCreateContext(hDC) orelse @panic("Couldn't create OpenGL context"); _ = windows.gdi32.wglMakeCurrent(hDC, dummy_gl_context); // defer _ = windows.gdi32.wglMakeCurrent(hDC, null); errdefer _ = windows.gdi32.wglDeleteContext(dummy_gl_context); const wglChoosePixelFormatARB = @ptrCast( fn ( hdc: windows.user32.HDC, piAttribIList: ?[*:0]const c_int, pfAttribFList: ?[*:0]const f32, nMaxFormats: c_uint, piFormats: [*]c_int, nNumFormats: *c_uint, ) callconv(windows.WINAPI) windows.BOOL, windows.gdi32.wglGetProcAddress("wglChoosePixelFormatARB") orelse return error.InvalidOpenGL, ); const wglCreateContextAttribsARB = @ptrCast( fn ( hDC: windows.user32.HDC, hshareContext: ?windows.user32.HGLRC, attribList: ?[*:0]const c_int, ) callconv(windows.WINAPI) ?windows.user32.HGLRC, windows.gdi32.wglGetProcAddress("wglCreateContextAttribsARB") orelse return error.InvalidOpenGL, ); const pf_attributes = [_:0]c_int{ windows.gdi32.WGL_DRAW_TO_WINDOW_ARB, gl.GL_TRUE, windows.gdi32.WGL_SUPPORT_OPENGL_ARB, gl.GL_TRUE, windows.gdi32.WGL_DOUBLE_BUFFER_ARB, gl.GL_TRUE, windows.gdi32.WGL_PIXEL_TYPE_ARB, windows.gdi32.WGL_TYPE_RGBA_ARB, windows.gdi32.WGL_COLOR_BITS_ARB, 32, windows.gdi32.WGL_DEPTH_BITS_ARB, 24, windows.gdi32.WGL_STENCIL_BITS_ARB, 8, 0, // End }; var pixelFormat: c_int = undefined; var numFormats: c_uint = undefined; if (wglChoosePixelFormatARB(hDC, &pf_attributes, null, 1, @ptrCast([*]c_int, &pixelFormat), &numFormats) == windows.FALSE) return error.InvalidOpenGL; if (numFormats == 0) // AMD driver may return numFormats > nMaxFormats, see issue #14 return error.InvalidOpenGL; if (dummy_pixel_format != pixelFormat) @panic("This case is not implemented yet: Recreation of the window is required here!"); const ctx_attributes = [_:0]c_int{ windows.gdi32.WGL_CONTEXT_MAJOR_VERSION_ARB, requested_gl.major, windows.gdi32.WGL_CONTEXT_MINOR_VERSION_ARB, requested_gl.minor, windows.gdi32.WGL_CONTEXT_FLAGS_ARB, windows.gdi32.WGL_CONTEXT_DEBUG_BIT_ARB, windows.gdi32.WGL_CONTEXT_PROFILE_MASK_ARB, if (requested_gl.core) windows.gdi32.WGL_CONTEXT_CORE_PROFILE_BIT_ARB else windows.gdi32.WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, 0, }; const gl_context = wglCreateContextAttribsARB( hDC, null, &ctx_attributes, ) orelse return error.InvalidOpenGL; errdefer _ = windows.gdi32.wglDeleteContext(gl_context); if (windows.gdi32.wglMakeCurrent(hDC, gl_context) == windows.FALSE) return error.InvalidOpenGL; break :blk Backend{ .opengl = gl_context }; } else { @panic("OpenGL support not enabled"); } }, else => .none, }; } pub fn deinit(self: *Window) void { switch (self.backend) { .none => {}, .software => |*render_context| { render_context.bitmap.destroy(); _ = windows.gdi32.DeleteDC(render_context.memory_dc); }, .opengl => |gl_context| { if (Parent.settings.backends_enabled.opengl) { const hDC = windows.user32.GetDC(self.handle) orelse @panic("couldn't get DC!"); defer _ = windows.user32.ReleaseDC(self.handle, hDC); _ = windows.gdi32.wglMakeCurrent(hDC, gl_context); _ = windows.gdi32.wglDeleteContext(gl_context); } else { unreachable; } }, } if (self.handle) |handle| { _ = windows.user32.SetWindowLongPtrW(handle, 0, 0); _ = windows.user32.DestroyWindow(handle); } var platform = @ptrCast(*Self, self.parent.platform); platform.parent.allocator.destroy(self); } pub fn configure(self: *Window, options: zwl.WindowOptions) !void { return error.Unimplemented; } pub fn getSize(self: *Window) [2]u16 { return [2]u16{ self.width, self.height }; } pub fn present(self: *Window) !void { switch (self.backend) { .none => {}, .software => return error.InvalidRenderBackend, .opengl => |hglrc| { if (self.handle) |handle| { const hDC = windows.user32.GetDC(handle) orelse @panic("couldn't get DC!"); defer _ = windows.user32.ReleaseDC(handle, hDC); _ = windows.gdi32.SwapBuffers(hDC); _ = windows.user32.InvalidateRect( handle, null, windows.FALSE, // We paint over *everything* ); } }, } } pub fn mapPixels(self: *Window) !zwl.PixelBuffer { switch (self.backend) { .software => |render_ctx| { var platform = @ptrCast(*Self, self.parent.platform); return zwl.PixelBuffer{ .data = render_ctx.bitmap.pixels, .width = render_ctx.bitmap.width, .height = render_ctx.bitmap.height, }; }, else => return error.InvalidRenderBackend, } } pub fn submitPixels(self: *Window, updates: []const zwl.UpdateArea) !void { if (self.backend != .software) return error.InvalidRenderBackend; if (self.handle) |handle| { _ = windows.user32.InvalidateRect( handle, null, windows.FALSE, // We paint over *everything* ); } } const RenderContext = struct { const Bitmap = struct { handle: windows.gdi32.HBITMAP, pixels: [*]u32, width: u16, height: u16, fn destroy(self: *@This()) void { _ = windows.gdi32.DeleteObject(self.handle.toGdiObject()); self.* = undefined; } }; memory_dc: windows.user32.HDC, bitmap: Bitmap, fn createBitmap(self: @This(), width: u16, height: u16) !Bitmap { var bmi = std.mem.zeroes(windows.gdi32.BITMAPINFO); bmi.bmiHeader.biSize = @sizeOf(windows.gdi32.BITMAPINFOHEADER); bmi.bmiHeader.biWidth = width; bmi.bmiHeader.biHeight = -@as(i32, height); bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = @enumToInt(windows.gdi32.Compression.BI_RGB); var bmp = Bitmap{ .width = width, .height = height, .handle = undefined, .pixels = undefined, }; bmp.handle = windows.gdi32.CreateDIBSection( self.memory_dc, &bmi, @enumToInt(windows.gdi32.DIBColors.DIB_RGB_COLORS), @ptrCast(**c_void, &bmp.pixels), null, 0, ) orelse return error.CreateBitmapError; return bmp; } }; }; }; }
didot-zwl/zwl/src/windows.zig
const std = @import("std"); const windows = @import("../windows.zig"); const ws2_32 = windows.ws2_32; pub usingnamespace ws2_32; const IOC_VOID = 0x80000000; const IOC_OUT = 0x40000000; const IOC_IN = 0x80000000; const IOC_WS2 = 0x08000000; pub const SIO_BSP_HANDLE = IOC_OUT | IOC_WS2 | 27; pub const SIO_BSP_HANDLE_SELECT = IOC_OUT | IOC_WS2 | 28; pub const SIO_BSP_HANDLE_POLL = IOC_OUT | IOC_WS2 | 29; pub const SIO_GET_EXTENSION_FUNCTION_POINTER = IOC_OUT | IOC_IN | IOC_WS2 | 6; pub const SO_UPDATE_CONNECT_CONTEXT = 0x7010; pub const SO_UPDATE_ACCEPT_CONTEXT = 0x700B; pub const SD_RECEIVE = 0; pub const SD_SEND = 1; pub const SD_BOTH = 2; pub const LINGER = extern struct { l_onoff: windows.USHORT, // Whether or not a socket should remain open to send queued dataa after closesocket() is called. l_linger: windows.USHORT, // Number of seconds on how long a socket should remain open after closesocket() is called. }; pub const WSAID_CONNECTEX = windows.GUID{ .Data1 = 0x25a207b9, .Data2 = 0xddf3, .Data3 = 0x4660, .Data4 = [8]u8{ 0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e }, }; pub const WSAID_ACCEPTEX = windows.GUID{ .Data1 = 0xb5367df1, .Data2 = 0xcbac, .Data3 = 0x11cf, .Data4 = [8]u8{ 0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 }, }; pub const WSAID_GETACCEPTEXSOCKADDRS = windows.GUID{ .Data1 = 0xb5367df2, .Data2 = 0xcbac, .Data3 = 0x11cf, .Data4 = [8]u8{ 0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 }, }; pub const sockaddr_storage = extern struct { family: ws2_32.ADDRESS_FAMILY, __ss_padding: [128 - @sizeOf(windows.ULONGLONG) - @sizeOf(ws2_32.ADDRESS_FAMILY)]u8, __ss_align: windows.ULONGLONG, }; pub extern "ws2_32" fn getsockopt( s: ws2_32.SOCKET, level: c_int, optname: c_int, optval: [*]u8, optlen: *c_int, ) callconv(.Stdcall) c_int; pub extern "ws2_32" fn shutdown( s: ws2_32.SOCKET, how: c_int, ) callconv(.Stdcall) c_int; pub extern "ws2_32" fn recv( s: ws2_32.SOCKET, buf: [*]u8, len: c_int, flags: c_int, ) callconv(.Stdcall) c_int; pub const ConnectEx = fn ( s: ws2_32.SOCKET, name: *const ws2_32.sockaddr, namelen: c_int, lpSendBuffer: ?*anyopaque, dwSendDataLength: windows.DWORD, lpdwBytesSent: ?*windows.DWORD, lpOverlapped: *windows.OVERLAPPED, ) callconv(.Stdcall) windows.BOOL; pub const AcceptEx = fn ( sListenSocket: ws2_32.SOCKET, sAcceptSocket: ws2_32.SOCKET, lpOutputBuffer: [*]u8, dwReceiveDataLength: windows.DWORD, dwLocalAddressLength: ws2_32.socklen_t, dwRemoteAddressLength: ws2_32.socklen_t, lpdwBytesReceived: ?*windows.DWORD, lpOverlapped: *windows.OVERLAPPED, ) callconv(.Stdcall) windows.BOOL; pub const GetAcceptExSockaddrs = fn ( lpOutputBuffer: [*]const u8, dwReceiveDataLength: windows.DWORD, dwLocalAddressLength: ws2_32.socklen_t, dwRemoteAddressLength: ws2_32.socklen_t, LocalSockaddr: **ws2_32.sockaddr, LocalSockaddrLength: *windows.INT, RemoteSockaddr: **ws2_32.sockaddr, RemoteSockaddrLength: *windows.INT, ) callconv(.Stdcall) void;
os/windows/ws2_32.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const handlers = @import("handlers.zig").handlers; // Interrupt Descriptor Table pub var idt: []IdtEntry = undefined; pub fn init(allocator: *Allocator) void { // place IDT to Extended memory idt = allocator.allocWithOptions(IdtEntry, 256, 4096, null) catch { @panic("Error allocate IDT."); }; for (idt) |*entry, i| { const off = @ptrToInt(handlers[i]); const cs = 0x18; // code segment selector in GDT const typ = 0xe; // 32-bit interrupt gate const ist: u1 = switch (i) { // NMI, #DF, #MC use the IST 2, 8, 18, => 1, else => 0, }; entry.* = IdtEntry.init(cs, off, typ, ist, 0); } const idt_table = IdtTable{ .limit = @truncate(u16, idt.len * @sizeOf(IdtEntry) - 1), .base = @ptrToInt(idt.ptr), }; std.debug.assert(idt_table.limit == 0x07FF); std.debug.assert(idt_table.base == 0x0010_0000); idt_table.load(); } const IdtEntry = packed struct { offset_1: u16, selector: u16, zeroes: u8, type_attr: u8, offset_2: u16, fn init(cs: u16, off: u32, typ: u4, ist: u1, dpl: u2) @This() { return .{ .offset_1 = @truncate(u16, off), .selector = cs, .zeroes = 0, .type_attr = @as(u8, 1) << 7 | // P - present @as(u8, dpl) << 5 | // DPL - Descriptor Privilege Level @as(u8, ist) << 4 | // S - Storage Segment @as(u8, typ), // Type - Gate Type .offset_2 = @truncate(u16, off >> 16), }; } pub fn dump(self: *const @This(), writer: anytype) !void { const entry = @ptrCast([*]const u8, self)[0..8]; try writer.print("{}, offset 0x{x:0>8}\n", .{ std.fmt.fmtSliceHexLower(entry), @as(u32, self.offset_1) | (@as(u32, self.offset_2) << 16), }); } }; const IdtTable = packed struct { limit: u16, base: u32, fn load(self: @This()) void { asm volatile ("lidt (%%eax)" :: [self] "{eax}" (self) : "memory"); } }; pub fn printIDTR(writer: anytype) !void { var idtr: [6]u8 = undefined; asm volatile ("sidt (%%eax)" :: [idtr] "{eax}" (idtr) : "memory"); try writer.print("{}\n", .{std.fmt.fmtSliceHexLower(&idtr)}); }
src/interrupts/idt.zig
const std = @import("std"); const testing = std.testing; const StringTable = @import("./strtab.zig").StringTable; const allocator = std.heap.page_allocator; pub const Validator = struct { const Rule = struct { parts: std.ArrayList(usize), pub fn init() *Rule { var self = allocator.create(Rule) catch unreachable; self.*.parts = std.ArrayList(usize).init(allocator); return self; } pub fn deinit(self: *Rule) void { self.parts.deinit(); } }; const RuleSet = struct { leaf: u8, rules: std.ArrayList(*Rule), pub fn init() *RuleSet { var self = allocator.create(RuleSet) catch unreachable; self.*.leaf = 0; self.*.rules = std.ArrayList(*Rule).init(allocator); return self; } pub fn deinit(self: *RuleSet) void { self.rules.deinit(); } pub fn add_rule(self: *RuleSet, parts: []const usize) void { var rule = Rule.init(); rule.*.parts.appendSlice(parts) catch unreachable; self.*.rules.append(rule) catch unreachable; } }; rules: std.AutoHashMap(usize, *RuleSet), messages: std.ArrayList(usize), strings: StringTable, zone: usize, pub fn init() Validator { return Validator{ .rules = std.AutoHashMap(usize, *RuleSet).init(allocator), .messages = std.ArrayList(usize).init(allocator), .strings = StringTable.init(allocator), .zone = 0, }; } pub fn deinit(self: *Validator) void { self.strings.deinit(); self.messages.deinit(); self.rules.deinit(); } pub fn add_line(self: *Validator, line: []const u8) void { if (line.len == 0) { self.zone += 1; return; } if (self.zone == 0) { var it_colon = std.mem.tokenize(u8, line, ":"); const code = std.fmt.parseInt(usize, it_colon.next().?, 10) catch unreachable; var ruleset = RuleSet.init(); var it_pipe = std.mem.tokenize(u8, it_colon.next().?, "|"); PIPE: while (it_pipe.next()) |rules| { var it_space = std.mem.tokenize(u8, rules, " "); var rule = Rule.init(); while (it_space.next()) |r| { if (r[0] == '"') { rule.deinit(); ruleset.*.leaf = r[1]; break :PIPE; } const n = std.fmt.parseInt(usize, r, 10) catch unreachable; rule.*.parts.append(n) catch unreachable; } ruleset.*.rules.append(rule) catch unreachable; } _ = self.rules.put(code, ruleset) catch unreachable; return; } if (self.zone == 1) { const code = self.strings.add(line); self.messages.append(code) catch unreachable; return; } @panic("ZONE"); } pub fn show(self: Validator) void { std.debug.warn("---------------------\n", .{}); std.debug.warn("Validator with {} rules\n", .{self.rules.count()}); var its = self.rules.iterator(); while (its.next()) |kvs| { const code = kvs.key; const rs = kvs.value; std.debug.warn("{}", .{code}); if (rs.leaf > 0) { std.debug.warn(": \"{c}\"\n", .{rs.leaf}); continue; } var pr: usize = 0; while (pr < rs.rules.items.len) : (pr += 1) { const sep: []const u8 = if (pr == 0) ":" else " |"; std.debug.warn("{}", .{sep}); const r = rs.rules.items[pr]; const parts = r.parts; var pp: usize = 0; while (pp < parts.items.len) : (pp += 1) { std.debug.warn(" {}", .{parts.items[pp]}); } } std.debug.warn("\n", .{}); } } // match against a complex ruleset, that is, against any of the sets of // rules separated by "|" fn match_complex_ruleset(self: *Validator, level: usize, str: []const u8, ruleset: *RuleSet, stack: *std.ArrayList(usize)) bool { var match = false; const rules = ruleset.rules.items; // any of the sets of rules in a ruleset could match, try them all var pr: usize = 0; while (!match and pr < rules.len) : (pr += 1) { // clone stack var copy = std.ArrayList(usize).init(allocator); defer copy.deinit(); copy.appendSlice(stack.items) catch unreachable; // add all parts of current rule, in reverse order const rule = rules[pr]; const parts = rule.parts.items; var pp: usize = 0; while (pp < parts.len) : (pp += 1) { const cs = parts[parts.len - 1 - pp]; copy.append(cs) catch unreachable; } // try to match with current rule match = self.match_rule(level + 1, str, &copy); } return match; } // match against a leaf ruleset, that is, one defined as a single "X" character fn match_leaf_ruleset(self: *Validator, level: usize, str: []const u8, ruleset: *RuleSet, stack: *std.ArrayList(usize)) bool { const match = str[0] == ruleset.leaf; // if it doesn't match the leaf character, we are busted if (!match) return false; // clone stack var copy = std.ArrayList(usize).init(allocator); defer copy.deinit(); copy.appendSlice(stack.items) catch unreachable; // this leaf matches, try to match rest of string with rest of rules return self.match_rule(level + 1, str[1..], &copy); } // match against a single rule, consuming both characters from the string // and pending rules to be matched fn match_rule(self: *Validator, level: usize, str: []const u8, stack: *std.ArrayList(usize)) bool { // not enough pending rules, given the length of the remaining string if (stack.items.len > str.len) return false; // if we ran out of pending rules OR characters in the string: // return true if we ran out of BOTH at the same time if (stack.items.len == 0 or str.len == 0) return stack.items.len == 0 and str.len == 0; // pop the first pending rule from the stack and try to match against that // of course, successive attempts will not use this popped rule anymore const cs = stack.pop(); const ruleset = self.rules.get(cs).?; var match = false; if (ruleset.leaf > 0) { match = self.match_leaf_ruleset(level, str, ruleset, stack); } else { match = self.match_complex_ruleset(level, str, ruleset, stack); } return match; } pub fn count_valid(self: *Validator) usize { var count: usize = 0; var pm: usize = 0; while (pm < self.messages.items.len) : (pm += 1) { const cm = self.messages.items[pm]; const message = self.strings.get_str(cm).?; // we need a stack of pending rules to match; initially empty var stack = std.ArrayList(usize).init(allocator); defer stack.deinit(); // we will start matching against rule 0 const ruleset = self.rules.get(0).?; const match = self.match_complex_ruleset(0, message, ruleset, &stack); if (match) count += 1; } return count; } pub fn fixup_rules(self: *Validator) void { const parts8 = [_]usize{ 42, 8 }; self.rules.get(8).?.add_rule(parts8[0..]); const parts11 = [_]usize{ 42, 11, 31 }; self.rules.get(11).?.add_rule(parts11[0..]); } }; test "sample part a" { const data: []const u8 = \\0: 4 1 5 \\1: 2 3 | 3 2 \\2: 4 4 | 5 5 \\3: 4 5 | 5 4 \\4: "a" \\5: "b" \\ \\ababbb \\bababa \\abbbab \\aaabbb \\aaaabbb ; var validator = Validator.init(); defer validator.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { validator.add_line(line); } const count = validator.count_valid(); try testing.expect(count == 2); } test "samples part b" { const data: []const u8 = \\42: 9 14 | 10 1 \\9: 14 27 | 1 26 \\10: 23 14 | 28 1 \\1: "a" \\11: 42 31 \\5: 1 14 | 15 1 \\19: 14 1 | 14 14 \\12: 24 14 | 19 1 \\16: 15 1 | 14 14 \\31: 14 17 | 1 13 \\6: 14 14 | 1 14 \\2: 1 24 | 14 4 \\0: 8 11 \\13: 14 3 | 1 12 \\15: 1 | 14 \\17: 14 2 | 1 7 \\23: 25 1 | 22 14 \\28: 16 1 \\4: 1 1 \\20: 14 14 | 1 15 \\3: 5 14 | 16 1 \\27: 1 6 | 14 18 \\14: "b" \\21: 14 1 | 1 14 \\25: 1 1 | 1 14 \\22: 14 14 \\8: 42 \\26: 14 22 | 1 20 \\18: 15 15 \\7: 14 5 | 1 21 \\24: 14 1 \\ \\abbbbbabbbaaaababbaabbbbabababbbabbbbbbabaaaa \\bbabbbbaabaabba \\babbbbaabbbbbabbbbbbaabaaabaaa \\aaabbbbbbaaaabaababaabababbabaaabbababababaaa \\bbbbbbbaaaabbbbaaabbabaaa \\bbbababbbbaaaaaaaabbababaaababaabab \\ababaaaaaabaaab \\ababaaaaabbbaba \\baabbaaaabbaaaababbaababb \\abbbbabbbbaaaababbbbbbaaaababb \\aaaaabbaabaaaaababaa \\aaaabbaaaabbaaa \\aaaabbaabbaaaaaaabbbabbbaaabbaabaaa \\babaaabbbaaabaababbaabababaaab \\aabbbbbaabbbaaaaaabbbbbababaaaaabbaaabba ; { var validator = Validator.init(); defer validator.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { validator.add_line(line); } const count = validator.count_valid(); try testing.expect(count == 3); } { var validator = Validator.init(); defer validator.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { validator.add_line(line); } validator.fixup_rules(); const count = validator.count_valid(); try testing.expect(count == 12); } } test "gonzo" { const data: []const u8 = \\0: 8 92 \\8: 42 \\11: 42 31 \\42: "a" \\91: "a" \\92: "b" \\ \\ab \\aab ; var validator = Validator.init(); defer validator.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { validator.add_line(line); } // validator.show(); const count = validator.count_valid(); try testing.expect(count == 1); }
2020/p19/validator.zig
const std = @import("std"); const imgui = @import("imgui"); const glfw = @import("glfw"); const engine = @import("engine.zig"); // TODO: No vulkan allowed at this layer!! const vk = @import("vk"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; // ----------------------- Render submodules ------------------------- // TODO: Select module to import as "backend" based on backend selection (Vulkan, D3D, etc) pub const backend = @import("render_vulkan.zig"); // ----------------------- Render state ------------------------- // (there is none yet) // ----------------------- Render types ------------------------- pub const UpdateRate = enum { /// Never changed STATIC, /// Changed occasionally DYNAMIC, /// Changed every frame STREAMING, }; pub const MappedRange = struct { const Self = @This(); buffer: *Buffer, byteOffset: usize, data: []u8, fn flush(self: *Self) !void { try backend.flushMappedRange(&self.buffer.backend, self.data.ptr, self.byteOffset, self.data.len); } fn flushPart(self: *Self, comptime T: type, byteOffset: usize, count: usize) !void { const lenBytes = count * @sizeOf(T); assert(byteOffset + lenBytes <= self.data.len); try backend.flushMappedRange(&self.buffer.backend, self.data.ptr, self.byteOffset + byteOffset, lenBytes); } fn get(self: *Self, comptime T: type) []T { const count = self.data.len / @sizeOf(T); return @intToPtr([*]T, @ptrToInt(self.data.ptr))[0..count]; } fn getPart(self: *Self, comptime T: type, byteOffset: usize, count: usize) []T { assert(byteOffset + count * @sizeOf(T) < self.data.len); return @intToPtr([*]T, @ptrToInt(self.data.ptr) + byteOffset)[0..count]; } fn end(self: *Self) void { backend.unmapBuffer(&self.buffer.backend, self.data.ptr, self.byteOffset, self.data.len); } }; pub const Buffer = struct { const Self = @This(); len: usize, backend: backend.Buffer, pub fn beginMap(self: *Buffer) !MappedRange { return MappedRange{ .buffer = self, .byteOffset = 0, .data = (try backend.mapBuffer(&self.backend, 0, self.len))[0..self.len], }; } pub fn beginMapPart(self: *Buffer, comptime T: type, byteOffset: usize, itemCount: usize) !MappedRange { const mapLengthBytes = itemCount * @sizeOf(T); assert(mapLengthBytes + byteOffset <= self.mapLengthBytes); return MappedRange{ .buffer = self, .byteOffset = byteOffset, .data = (try backend.mapBuffer(&self.backend, byteOffset, mapLengthBytes))[0..mapLengthBytes], }; } pub fn destroy(self: *Buffer) void { backend.destroyBuffer(&self.backend); } }; pub const Upload = struct { const Self = @This(); frame: *Frame, backend: backend.RenderUpload, managedBuffers: std.ArrayList(Buffer), pub fn copyBuffer(self: *Self, source: *Buffer, dest: *Buffer) void { assert(dest.len >= source.len); backend.uploadCopyBuffer(&self.frame.backend, &self.backend, &source.backend, 0, &dest.backend, 0, source.len); } pub fn copyBufferPart(self: *Self, source: *Buffer, sourceOffset: usize, dest: *Buffer, destOffset: usize, len: usize) void { assert(sourceOffset + len <= source.len); assert(destOffset + len <= dest.len); backend.uploadCopyBuffer(&self.frame.backend, &self.backend, &source.backend, sourceOffset, &dest.backend, destOffset, len); } pub fn setBufferData(self: *Self, buffer: *Buffer, offset: usize, data: []const u8) !void { assert(offset + data.len <= buffer.len); const stagingBuffer = try self.newManagedStagingBuffer(data.len); { var map = try stagingBuffer.beginMap(); defer map.end(); @memcpy(map.data.ptr, data.ptr, data.len); try map.flush(); } self.copyBufferPart(stagingBuffer, 0, buffer, offset, data.len); } pub fn abort(self: *Self) void { assert(self.frame.state == .UPLOAD); self.frame.state = .IDLE; backend.abortUpload(&self.frame.backend, &self.backend); self._deleteManagedBuffers(); } pub fn endAndWait(self: *Self) void { assert(self.frame.state == .UPLOAD); self.frame.state = .IDLE; backend.endUploadAndWait(&self.frame.backend, &self.backend); self._deleteManagedBuffers(); } pub fn newManagedStagingBuffer(self: *Self, size: usize) !*Buffer { const bufPtr = try self.managedBuffers.addOne(); errdefer _ = self.managedBuffers.pop(); bufPtr.* = try createStagingBuffer(size); errdefer bufPtr.destroy(); return bufPtr; } pub fn _deleteManagedBuffers(self: *Self) void { for (self.managedBuffers.items) |*buffer| buffer.destroy(); self.managedBuffers.deinit(); } }; pub const Pass = struct { const Self = @This(); frame: *Frame, backend: backend.RenderPass, pub fn end(self: *Self) void { assert(self.frame.state == .RENDER); self.frame.state = .IDLE; backend.endRenderPass(&self.frame.backend, &self.backend); } }; pub const Frame = struct { const Self = @This(); const State = enum { IDLE, RENDER, UPLOAD, }; state: State, backend: backend.RenderFrame, pub fn end(self: *Self) void { backend.endRender(&self.backend); } pub fn beginUpload(self: *Self) !Upload { // TODO: Allow upload and render simultaneously assert(self.state == .IDLE); self.state = .UPLOAD; errdefer self.state = .IDLE; return Upload{ .frame = self, .backend = try backend.beginUpload(&self.backend), .managedBuffers = std.ArrayList(Buffer).init(engine.allocator), }; } pub fn beginColorPass(self: *Self, clearColor: imgui.Vec4) !Pass { assert(self.state == .IDLE); self.state = .RENDER; errdefer self.state = .IDLE; return Pass{ .frame = self, .backend = try backend.beginColorPass(&self.backend, clearColor), }; } }; // ----------------------- Public functions ------------------------- pub fn beginRender() !Frame { return Frame{ .state = .IDLE, .backend = try backend.beginRender(), }; } pub fn renderImgui(pass: *Pass) !void { imgui.Render(); try backend.renderImgui(&pass.frame.backend, &pass.backend); } pub fn createStagingBuffer(size: usize) !Buffer { return Buffer{ .len = size, .backend = try backend.createStagingBuffer(size), }; } // TODO: No vulkan allowed at this layer!! pub fn createGpuBuffer(size: usize, flags: vk.BufferUsageFlags) !Buffer { return Buffer{ .len = size, .backend = try backend.createGpuBuffer(size, flags), }; } // ----------------------- Internal functions ------------------------- pub fn _init(allocator: *Allocator, window: *glfw.GLFWwindow) !void { try backend.init(allocator, window); } pub fn _deinit() void { backend.deinit(); } pub fn _initImgui(allocator: *Allocator) !void { // Setup Dear ImGui context imgui.CHECKVERSION(); _ = imgui.CreateContext(); var io = imgui.GetIO(); //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style imgui.StyleColorsDark(); //imgui.StyleColorsClassic(); try backend.initImgui(allocator); } pub fn _deinitImgui() void { backend.deinitImgui(); imgui.DestroyContext(); } pub fn _beginFrame() !void { try backend.beginFrame(); } pub fn _beginImgui() void { backend.beginImgui(); imgui.NewFrame(); }
src/render.zig
const std = @import("std"); const heap = std.heap; const log = std.log; const mem = std.mem; const net = std.net; const big = std.math.big; const cql = @import("lib.zig"); const casstest = @import("casstest.zig"); /// Runs a single SELECT reading all data from the age_to_ids table. /// /// This function demonstrates multiple things: /// * executing a query without preparation /// * iterating over the result iterator /// * using the paging state and page size fn doQuery(allocator: *mem.Allocator, client: *cql.Client) !void { // We want query diagonistics in case of failure. var diags = cql.Client.QueryOptions.Diagnostics{}; errdefer { log.warn("diags: {}", .{diags}); } var paging_state_buffer: [1024]u8 = undefined; var paging_state_allocator = std.heap.FixedBufferAllocator.init(&paging_state_buffer); // Read max 48 rows per query. var options = cql.Client.QueryOptions{ .page_size = 48, .paging_state = null, .diags = &diags, }; var total: usize = 0; { // Demonstrate how to USE a keyspace. // All following queries which don't provide the keyspace directly // will assume the keyspace is "foobar". var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); _ = try client.query(&arena.allocator, options, "USE foobar", .{}); } // Execute queries as long as there's more data available. while (true) { // Use an arena per query. var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); var iter = (try client.query( &arena.allocator, options, "SELECT age, name, ids, balance FROM age_to_ids", .{}, )).?; const count = try iterate(&arena.allocator, &iter); total += count; // If there's more data Caassandra will respond with a valid paging state. // If there's no paging state we know we're done. if (iter.metadata.paging_state) |paging_state| { paging_state_allocator.reset(); options.paging_state = try mem.dupe(&paging_state_allocator.allocator, u8, paging_state); } else { break; } } log.info("read {} rows", .{total}); } fn doPrepare(allocator: *mem.Allocator, client: *cql.Client) ![]const u8 { // We want query diagonistics in case of failure. var diags = cql.Client.QueryOptions.Diagnostics{}; var options = cql.Client.QueryOptions{ .diags = &diags, }; const query_id = client.prepare( allocator, options, "SELECT ids, age, name FROM foobar.age_to_ids WHERE age in (?, ?)", .{ .age1 = @as(u32, 0), .age2 = @as(u32, 0), }, ) catch |err| switch (err) { error.QueryPreparationFailed => { std.debug.panic("query preparation failed, received cassandra error: {s}\n", .{diags.message}); }, else => return err, }; log.info("prepared query id is {s}", .{std.fmt.fmtSliceHexLower(query_id)}); return query_id; } fn doExecute(allocator: *mem.Allocator, client: *cql.Client, query_id: []const u8) !void { var result_arena = std.heap.ArenaAllocator.init(allocator); defer result_arena.deinit(); const result_allocator = &result_arena.allocator; // We want query diagonistics in case of failure. var diags = cql.Client.QueryOptions.Diagnostics{}; var options = cql.Client.QueryOptions{ .diags = &diags, }; var iter = (try client.execute( result_allocator, options, query_id, .{ .age1 = @as(u32, 120), .age2 = @as(u32, 124), }, )).?; _ = try iterate(allocator, &iter); } fn doPrepareThenExec(allocator: *mem.Allocator, client: *cql.Client, n: usize) !void { var i: usize = 0; while (i < n) : (i += 1) { const query_id = try doPrepare(allocator, client); try doExecute(allocator, client, query_id); } } fn doPrepareOnceThenExec(allocator: *mem.Allocator, client: *cql.Client, n: usize) !void { const query_id = try doPrepare(allocator, client); var i: usize = 0; while (i < n) : (i += 1) { try doExecute(allocator, client, query_id); } } fn doInsert(allocator: *mem.Allocator, client: *cql.Client, n: usize) !void { // We want query diagonistics in case of failure. var diags = cql.Client.QueryOptions.Diagnostics{}; var options = cql.Client.QueryOptions{ .diags = &diags, }; const query_id = client.prepare( allocator, options, "INSERT INTO foobar.age_to_ids(age, name, ids, balance) VALUES(?, ?, ?, ?)", casstest.Args.AgeToIDs{}, ) catch |err| switch (err) { error.QueryPreparationFailed => { std.debug.panic("query preparation failed, received cassandra error: {s}\n", .{diags.message}); }, else => return err, }; var positive_varint = try big.int.Managed.init(allocator); try positive_varint.setString(10, "40502020"); var negative_varint = try big.int.Managed.init(allocator); try negative_varint.setString(10, "-350956306"); var buffer: [16384]u8 = undefined; var fba = heap.FixedBufferAllocator.init(&buffer); var i: usize = 0; while (i < n) : (i += 1) { fba.reset(); const args = casstest.Args.AgeToIDs{ .age = @intCast(u32, i) * @as(u32, 10), .name = if (i % 2 == 0) @as([]const u8, try std.fmt.allocPrint(&fba.allocator, "Vincent {}", .{i})) else null, .ids = [_]u8{ 0, 2, 4, 8 }, .balance = if (i % 2 == 0) positive_varint.toConst() else negative_varint.toConst(), }; _ = client.execute( &fba.allocator, options, query_id, args, ) catch |err| switch (err) { error.QueryExecutionFailed => { log.warn("error message: {s}\n", .{diags.message}); }, error.InvalidPreparedStatementExecuteArgs => { log.warn("execute diags: ({s})\n", .{diags.execute}); }, else => |e| return e, }; } } /// Iterate over every row in the iterator provided. fn iterate(allocator: *mem.Allocator, iter: *cql.Iterator) !usize { var row: casstest.Row.AgeToIDs = undefined; // Just for formatting here const IDs = struct { slice: []u8, pub fn format(self: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.writeByte('['); for (self.slice) |item, i| { if (i > 0) try writer.writeAll(", "); try std.fmt.format(writer, "{d}", .{item}); } try writer.writeByte(']'); } }; var count: usize = 0; while (true) : (count += 1) { // Use a single arena per iteration. // This makes it easy to discard all memory allocated while scanning the current row. var row_arena = std.heap.ArenaAllocator.init(allocator); defer row_arena.deinit(); // We want iteration diagnostics in case of failures. var iter_diags = cql.Iterator.ScanOptions.Diagnostics{}; var iter_options = cql.Iterator.ScanOptions{ .diags = &iter_diags, }; const scanned = iter.scan(&row_arena.allocator, iter_options, &row) catch |err| switch (err) { error.IncompatibleMetadata => blk: { const im = iter_diags.incompatible_metadata; const it = im.incompatible_types; if (it.cql_type_name != null and it.native_type_name != null) { std.debug.panic("metadata incompatible. CQL type {s} can't be scanned into native type {s}\n", .{ it.cql_type_name, it.native_type_name, }); } else { std.debug.panic("metadata incompatible. columns in result: {} fields in struct: {}\n", .{ im.metadata_columns, im.struct_fields, }); } break :blk false; }, else => return err, }; if (!scanned) { break; } const ids = IDs{ .slice = row.ids }; std.debug.print("age: {} id: {} name: {s} balance: {}\n", .{ row.age, ids, row.name, row.balance }); } return count; } const usage = \\usage: cli <command> [options] \\ \\Commands: \\ \\ insert \\ query \\ prepare \\ prepare-then-exec <iterations> \\ prepare-once-then-exec <iterations> \\ ; fn parseArg(comptime T: type, arg: []const u8) !T { switch (@typeInfo(T)) { .Int => return std.fmt.parseInt(T, arg, 10), .Optional => |p| { if (arg.len == 0) return null; return try parseArg(p.child, arg); }, .Pointer => |p| { switch (p.size) { .Slice => { if (p.child == u8) return arg; }, else => @compileError("invalid type " ++ @typeName(T)), } }, else => @compileError("invalid type " ++ @typeName(T)), } } fn findArg(comptime T: type, args: []const []const u8, key: []const u8, default: T) !T { for (args) |arg| { var it = mem.tokenize(arg, "="); const k = it.next().?; const v = it.next() orelse return default; if (!mem.eql(u8, key, k)) { continue; } if (T == []const u8) { return v; } return parseArg(T, v) catch default; } return default; } pub const log_level: log.Level = .debug; pub fn main() anyerror!void { var gpa = heap.GeneralPurposeAllocator(.{}){}; const allocator = &gpa.allocator; const stderr = std.io.getStdErr().writer(); const args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); if (args.len <= 1) { try stderr.writeAll("expected command argument\n\n"); try stderr.writeAll(usage); std.process.exit(1); } // Define the seed node we will connect to. We use localhost:9042. var address = net.Address.initIp4([_]u8{ 127, 0, 0, 1 }, 9042); // Connect to the seed node // // The struct InitOptions can be used to control some aspects of the CQL client, // such as the protocol version, if compression is enabled, etc. var init_options = cql.Connection.InitOptions{}; init_options.protocol_version = cql.ProtocolVersion{ .version = try findArg(u8, args, "protocol_version", 4) }; init_options.compression = blk: { const tmp = try findArg(?[]const u8, args, "compression", null); if (tmp == null) break :blk null; break :blk try cql.CompressionAlgorithm.fromString(tmp.?); }; init_options.username = "cassandra"; init_options.password = "<PASSWORD>"; // Additionally a Diagnostics struct can be provided. // If initialization fails for some reason, this struct will be populated. var init_diags = cql.Connection.InitOptions.Diagnostics{}; init_options.diags = &init_diags; var connection: cql.Connection = undefined; connection.initIp4(allocator, address, init_options) catch |err| switch (err) { error.NoUsername, error.NoPassword => { std.debug.panic("the server requires authentication, please set the username and password", .{}); }, error.AuthenticationFailed => { std.debug.panic("server authentication failed, error was: {s}", .{init_diags.message}); }, error.HandshakeFailed => { std.debug.panic("server handshake failed, error was: {s}", .{init_diags.message}); }, else => return err, }; defer connection.close(); var client = cql.Client.initWithConnection(allocator, &connection, .{}); defer client.deinit(); // Try to create the keyspace and table. { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); var options = cql.Client.QueryOptions{}; var diags = cql.Client.QueryOptions.Diagnostics{}; options.diags = &diags; inline for (casstest.DDL) |query| { _ = try client.query(&arena.allocator, options, query, .{}); } } // Parse the command and run it. const cmd = args[1]; if (mem.eql(u8, cmd, "query")) { return doQuery(allocator, &client); } else if (mem.eql(u8, cmd, "prepare")) { _ = try doPrepare(allocator, &client); } else if (mem.eql(u8, cmd, "insert")) { if (args.len < 3) { try std.fmt.format(stderr, "Usage: {s} insert <iterations>\n", .{args[0]}); std.process.exit(1); } const n = try std.fmt.parseInt(usize, args[2], 10); return doInsert(allocator, &client, n); } else if (mem.eql(u8, cmd, "prepare-then-exec")) { if (args.len < 3) { try std.fmt.format(stderr, "Usage: {s} prepared-then-exec <iterations>\n", .{args[0]}); std.process.exit(1); } const n = try std.fmt.parseInt(usize, args[2], 10); return doPrepareThenExec(allocator, &client, n); } else if (mem.eql(u8, cmd, "prepare-once-then-exec")) { if (args.len < 3) { try std.fmt.format(stderr, "Usage: {s} prepared-then-exec <iterations>\n", .{args[0]}); std.process.exit(1); } const n = try std.fmt.parseInt(usize, args[2], 10); return doPrepareOnceThenExec(allocator, &client, n); } else { try stderr.writeAll("expected command argument\n\n"); try stderr.writeAll(usage); std.process.exit(1); } }
src/example.zig
const std = @import("std"); const builtin = @import("builtin"); const log_ = @import("Log.zig"); const errLog_ = log_.errLog; const dbgLog_ = log_.dbgLog; const c_allocator = std.heap.c_allocator; const TCPServer = @import("TCPServer.zig"); const HTTPSState = @import("HTTPSState.zig").HTTPSState; const HTTPState = @import("HTTPState.zig").HTTPState; pub const Files = @import("Files.zig"); const HTTPMessageParser = @import("HTTPMessageParser.zig"); const startsWith = std.mem.startsWith; const TLS = @import("TLS.zig"); const config = @import("Config.zig").config; usingnamespace @cImport({ @cInclude("unistd.h"); }); pub fn dbgLog(comptime s: []const u8, args: var) void { dbgLog_("HTTP(S): " ++ s, args); } pub fn errLog(comptime s: []const u8, args: var) void { errLog_("HTTP(S): " ++ s, args); } fn newConnection(port: u16, conn: usize, ip: u128) ?usize { var ip_string: [46]u8 = undefined; ip_string[0] = 0; TCPServer.ipToString(ip, ip_string[0..]) catch {}; if (port == config().http_port) { dbgLog("New HTTP Connection. IP: {}. conn = {}", .{ ip_string, conn }); return HTTPState.new() catch |e| { errLog("Error creating HTTP state: {}", .{e}); return null; }; } dbgLog("New HTTPS IP: {}. conn = {}", .{ ip_string, conn }); return HTTPSState.new() catch |e| { errLog("Error creating HTTPS state: {}", .{e}); return null; }; } fn dataIn_(port: u16, user_data: usize, conn: usize, data: []const u8) !void { var reponseSent = false; if (port == config().http_port) { // HTTP const state = try HTTPState.get(user_data); dbgLog("*** HTTP data ***\n{}******", .{data[0..std.math.min(150, data.len)]}); // HTTP server just sends a permanent redirect if (try sendRedirect(conn, state, data)) { TCPServer.closeSocket(conn); } } else { // HTTPS const state = try HTTPSState.get(user_data); try state.*.read(conn, data); } } fn dataIn(port: u16, user_data: usize, conn: usize, data: []const u8) void { return dataIn_(port, user_data, conn, data) catch |e| { if (e != error.TLSShutDown and e != error.ConnectionClosed) { errLog("HTTP(S) read error: {}", .{e}); } TCPServer.closeSocket(conn); }; } fn writeDone(port: u16, user_data: usize, conn: usize, data: []const u8, meta_data: u64) void { if (port == config().http_port) { // HTTP TCPServer.closeSocket(conn); } else { // HTTPS const state = HTTPSState.get(user_data) catch return; state.writeDone(conn, data) catch |e| { errLog("HTTP writeDone error: {}", .{e}); TCPServer.closeSocket(conn); }; } } fn connLost(port: u16, user_data: usize, conn: usize) void { if (port == config().http_port) { dbgLog("HTTP Connection {} closed", .{conn}); HTTPState.free2(user_data, conn); } else { dbgLog("HTTPS Connection {} closed", .{conn}); HTTPSState.free2(user_data, conn); } } fn parseHTTPRequest(data: []const u8, http_version: *u1, host: *(?[]const u8)) !void { host.* = null; var s = data; _ = try HTTPMessageParser.getRequestType(&s); _ = try HTTPMessageParser.getRequestURL(&s); http_version.* = try HTTPMessageParser.verifyHTTPVersion(&s); while (true) { const field = try HTTPMessageParser.getNextHeaderField(&s); if (field == null) { return error.NoHost; } if (startsWith(u8, field.?, "Host: ")) { host.* = field.?[6..]; break; } } } // Returns true if sent redirect message, false if headers haven't fully sent yet fn sendRedirect(conn: usize, state: *HTTPState, data: []const u8) !bool { var http_version: u1 = undefined; var host: ?[]const u8 = null; parseHTTPRequest(data, &http_version, &host) catch |e| { if (e == error.EndOfString or e == error.EmptyString) { // TODO If entire request is not received then the redirect does not get sent return false; } else { return e; } }; if (host == null) { return error.NoHostHeader; } host = host.?[0..std.math.min(255, host.?.len)]; const S_HTTP_VER = "HTTP/1."; const S_HEADER = " 301 Moved Permanently\r\nLocation: https://"; state.response_string = try TCPServer.write_buffer_pool.alloc(); var string = state.response_string.?.*[0 .. S_HTTP_VER.len + 1 + S_HEADER.len + host.?.len + 4]; var i: usize = 0; std.mem.copy(u8, string[i .. i + S_HTTP_VER.len], S_HTTP_VER); i += S_HTTP_VER.len; string[i] = '0' + @intCast(u8, http_version); i += 1; std.mem.copy(u8, string[i .. i + S_HEADER.len], S_HEADER); i += S_HEADER.len; std.mem.copy(u8, string[i .. i + host.?.len], host.?); i += host.?.len; string[i] = '\r'; string[i + 1] = '\n'; string[i + 2] = '\r'; string[i + 3] = '\n'; dbgLog("http response: {}", .{string}); try TCPServer.sendData(conn, string, 0); return true; } threadlocal var thread_id: u32 = undefined; pub fn getThreadID() u32 { return thread_id; } fn serverThread(threadN: u32) void { thread_id = threadN; TLS.threadLocalInit(); HTTPSState.threadLocalInit(); HTTPState.threadLocalInit(); TCPServer.start(&[_]TCPServer.SocketInitInfo{ TCPServer.SocketInitInfo{ .port = config().http_port }, TCPServer.SocketInitInfo{ .port = config().https_port }, }, newConnection, dataIn, connLost, writeDone) catch |e| { errLog("ERROR: {}", .{e}); }; } pub fn start() !void { try TLS.init(); try TCPServer.oneTimeInit(); if (builtin.mode == .Debug) { std.debug.warn("Debug build, running single threaded.\n", .{}); serverThread(0); } else { var threads: [128]*std.Thread = undefined; var num_threads = config().threads; if (num_threads == 0) { num_threads = @intCast(u32, std.math.min(@intCast(c_long, threads.len), sysconf(_SC_NPROCESSORS_ONLN))); } std.debug.warn("Using {} threads\n", .{num_threads}); var i: u32 = 0; while (i < num_threads - 1) : (i += 1) { threads[i] = try std.Thread.spawn(@as(u32, 1), serverThread); } serverThread(0); // This will only run if something goes wrong on the main thread i = 0; while (i < num_threads - 1) : (i += 1) { threads[i].wait(); } } }
src/HTTP.zig
/// `isFcx` returns true if `cp` has Full Composition Exclusion. pub fn isFcx(cp: u21) bool { return switch(cp) { 0x340...0x341 => true, 0x343...0x344 => true, 0x374 => true, 0x37E => true, 0x387 => true, 0x958...0x95F => true, 0x9DC...0x9DD => true, 0x9DF => true, 0xA33 => true, 0xA36 => true, 0xA59...0xA5B => true, 0xA5E => true, 0xB5C...0xB5D => true, 0xF43 => true, 0xF4D => true, 0xF52 => true, 0xF57 => true, 0xF5C => true, 0xF69 => true, 0xF73 => true, 0xF75...0xF76 => true, 0xF78 => true, 0xF81 => true, 0xF93 => true, 0xF9D => true, 0xFA2 => true, 0xFA7 => true, 0xFAC => true, 0xFB9 => true, 0x1F71 => true, 0x1F73 => true, 0x1F75 => true, 0x1F77 => true, 0x1F79 => true, 0x1F7B => true, 0x1F7D => true, 0x1FBB => true, 0x1FBE => true, 0x1FC9 => true, 0x1FCB => true, 0x1FD3 => true, 0x1FDB => true, 0x1FE3 => true, 0x1FEB => true, 0x1FEE...0x1FEF => true, 0x1FF9 => true, 0x1FFB => true, 0x1FFD => true, 0x2000...0x2001 => true, 0x2126 => true, 0x212A...0x212B => true, 0x2329 => true, 0x232A => true, 0x2ADC => true, 0xF900...0xFA0D => true, 0xFA10 => true, 0xFA12 => true, 0xFA15...0xFA1E => true, 0xFA20 => true, 0xFA22 => true, 0xFA25...0xFA26 => true, 0xFA2A...0xFA6D => true, 0xFA70...0xFAD9 => true, 0xFB1D => true, 0xFB1F => true, 0xFB2A...0xFB36 => true, 0xFB38...0xFB3C => true, 0xFB3E => true, 0xFB40...0xFB41 => true, 0xFB43...0xFB44 => true, 0xFB46...0xFB4E => true, 0x1D15E...0x1D164 => true, 0x1D1BB...0x1D1C0 => true, 0x2F800...0x2FA1D => true, else => false, }; } /// `isNfd` returns true if `cp` is in Canoical Decomposed Normalization Form. pub fn isNfd(cp: u21) bool { return switch(cp) { 0xC0...0xC5 => false, 0xC7...0xCF => false, 0xD1...0xD6 => false, 0xD9...0xDD => false, 0xE0...0xE5 => false, 0xE7...0xEF => false, 0xF1...0xF6 => false, 0xF9...0xFD => false, 0xFF...0x10F => false, 0x112...0x125 => false, 0x128...0x130 => false, 0x134...0x137 => false, 0x139...0x13E => false, 0x143...0x148 => false, 0x14C...0x151 => false, 0x154...0x165 => false, 0x168...0x17E => false, 0x1A0...0x1A1 => false, 0x1AF...0x1B0 => false, 0x1CD...0x1DC => false, 0x1DE...0x1E3 => false, 0x1E6...0x1F0 => false, 0x1F4...0x1F5 => false, 0x1F8...0x21B => false, 0x21E...0x21F => false, 0x226...0x233 => false, 0x340...0x341 => false, 0x343...0x344 => false, 0x374 => false, 0x37E => false, 0x385 => false, 0x386 => false, 0x387 => false, 0x388...0x38A => false, 0x38C => false, 0x38E...0x390 => false, 0x3AA...0x3B0 => false, 0x3CA...0x3CE => false, 0x3D3...0x3D4 => false, 0x400...0x401 => false, 0x403 => false, 0x407 => false, 0x40C...0x40E => false, 0x419 => false, 0x439 => false, 0x450...0x451 => false, 0x453 => false, 0x457 => false, 0x45C...0x45E => false, 0x476...0x477 => false, 0x4C1...0x4C2 => false, 0x4D0...0x4D3 => false, 0x4D6...0x4D7 => false, 0x4DA...0x4DF => false, 0x4E2...0x4E7 => false, 0x4EA...0x4F5 => false, 0x4F8...0x4F9 => false, 0x622...0x626 => false, 0x6C0 => false, 0x6C2 => false, 0x6D3 => false, 0x929 => false, 0x931 => false, 0x934 => false, 0x958...0x95F => false, 0x9CB...0x9CC => false, 0x9DC...0x9DD => false, 0x9DF => false, 0xA33 => false, 0xA36 => false, 0xA59...0xA5B => false, 0xA5E => false, 0xB48 => false, 0xB4B...0xB4C => false, 0xB5C...0xB5D => false, 0xB94 => false, 0xBCA...0xBCC => false, 0xC48 => false, 0xCC0 => false, 0xCC7...0xCC8 => false, 0xCCA...0xCCB => false, 0xD4A...0xD4C => false, 0xDDA => false, 0xDDC...0xDDE => false, 0xF43 => false, 0xF4D => false, 0xF52 => false, 0xF57 => false, 0xF5C => false, 0xF69 => false, 0xF73 => false, 0xF75...0xF76 => false, 0xF78 => false, 0xF81 => false, 0xF93 => false, 0xF9D => false, 0xFA2 => false, 0xFA7 => false, 0xFAC => false, 0xFB9 => false, 0x1026 => false, 0x1B06 => false, 0x1B08 => false, 0x1B0A => false, 0x1B0C => false, 0x1B0E => false, 0x1B12 => false, 0x1B3B => false, 0x1B3D => false, 0x1B40...0x1B41 => false, 0x1B43 => false, 0x1E00...0x1E99 => false, 0x1E9B => false, 0x1EA0...0x1EF9 => false, 0x1F00...0x1F15 => false, 0x1F18...0x1F1D => false, 0x1F20...0x1F45 => false, 0x1F48...0x1F4D => false, 0x1F50...0x1F57 => false, 0x1F59 => false, 0x1F5B => false, 0x1F5D => false, 0x1F5F...0x1F7D => false, 0x1F80...0x1FB4 => false, 0x1FB6...0x1FBC => false, 0x1FBE => false, 0x1FC1 => false, 0x1FC2...0x1FC4 => false, 0x1FC6...0x1FCC => false, 0x1FCD...0x1FCF => false, 0x1FD0...0x1FD3 => false, 0x1FD6...0x1FDB => false, 0x1FDD...0x1FDF => false, 0x1FE0...0x1FEC => false, 0x1FED...0x1FEF => false, 0x1FF2...0x1FF4 => false, 0x1FF6...0x1FFC => false, 0x1FFD => false, 0x2000...0x2001 => false, 0x2126 => false, 0x212A...0x212B => false, 0x219A...0x219B => false, 0x21AE => false, 0x21CD => false, 0x21CE...0x21CF => false, 0x2204 => false, 0x2209 => false, 0x220C => false, 0x2224 => false, 0x2226 => false, 0x2241 => false, 0x2244 => false, 0x2247 => false, 0x2249 => false, 0x2260 => false, 0x2262 => false, 0x226D...0x2271 => false, 0x2274...0x2275 => false, 0x2278...0x2279 => false, 0x2280...0x2281 => false, 0x2284...0x2285 => false, 0x2288...0x2289 => false, 0x22AC...0x22AF => false, 0x22E0...0x22E3 => false, 0x22EA...0x22ED => false, 0x2329 => false, 0x232A => false, 0x2ADC => false, 0x304C => false, 0x304E => false, 0x3050 => false, 0x3052 => false, 0x3054 => false, 0x3056 => false, 0x3058 => false, 0x305A => false, 0x305C => false, 0x305E => false, 0x3060 => false, 0x3062 => false, 0x3065 => false, 0x3067 => false, 0x3069 => false, 0x3070...0x3071 => false, 0x3073...0x3074 => false, 0x3076...0x3077 => false, 0x3079...0x307A => false, 0x307C...0x307D => false, 0x3094 => false, 0x309E => false, 0x30AC => false, 0x30AE => false, 0x30B0 => false, 0x30B2 => false, 0x30B4 => false, 0x30B6 => false, 0x30B8 => false, 0x30BA => false, 0x30BC => false, 0x30BE => false, 0x30C0 => false, 0x30C2 => false, 0x30C5 => false, 0x30C7 => false, 0x30C9 => false, 0x30D0...0x30D1 => false, 0x30D3...0x30D4 => false, 0x30D6...0x30D7 => false, 0x30D9...0x30DA => false, 0x30DC...0x30DD => false, 0x30F4 => false, 0x30F7...0x30FA => false, 0x30FE => false, 0xAC00...0xD7A3 => false, 0xF900...0xFA0D => false, 0xFA10 => false, 0xFA12 => false, 0xFA15...0xFA1E => false, 0xFA20 => false, 0xFA22 => false, 0xFA25...0xFA26 => false, 0xFA2A...0xFA6D => false, 0xFA70...0xFAD9 => false, 0xFB1D => false, 0xFB1F => false, 0xFB2A...0xFB36 => false, 0xFB38...0xFB3C => false, 0xFB3E => false, 0xFB40...0xFB41 => false, 0xFB43...0xFB44 => false, 0xFB46...0xFB4E => false, 0x1109A => false, 0x1109C => false, 0x110AB => false, 0x1112E...0x1112F => false, 0x1134B...0x1134C => false, 0x114BB...0x114BC => false, 0x114BE => false, 0x115BA...0x115BB => false, 0x11938 => false, 0x1D15E...0x1D164 => false, 0x1D1BB...0x1D1C0 => false, 0x2F800...0x2FA1D => false, else => true, }; } /// `isNfc` returns true if `cp` is in Canoical Composed Normalization Form. pub fn isNfc(cp: u21) bool { return switch(cp) { 0x340...0x341 => false, 0x343...0x344 => false, 0x374 => false, 0x37E => false, 0x387 => false, 0x958...0x95F => false, 0x9DC...0x9DD => false, 0x9DF => false, 0xA33 => false, 0xA36 => false, 0xA59...0xA5B => false, 0xA5E => false, 0xB5C...0xB5D => false, 0xF43 => false, 0xF4D => false, 0xF52 => false, 0xF57 => false, 0xF5C => false, 0xF69 => false, 0xF73 => false, 0xF75...0xF76 => false, 0xF78 => false, 0xF81 => false, 0xF93 => false, 0xF9D => false, 0xFA2 => false, 0xFA7 => false, 0xFAC => false, 0xFB9 => false, 0x1F71 => false, 0x1F73 => false, 0x1F75 => false, 0x1F77 => false, 0x1F79 => false, 0x1F7B => false, 0x1F7D => false, 0x1FBB => false, 0x1FBE => false, 0x1FC9 => false, 0x1FCB => false, 0x1FD3 => false, 0x1FDB => false, 0x1FE3 => false, 0x1FEB => false, 0x1FEE...0x1FEF => false, 0x1FF9 => false, 0x1FFB => false, 0x1FFD => false, 0x2000...0x2001 => false, 0x2126 => false, 0x212A...0x212B => false, 0x2329 => false, 0x232A => false, 0x2ADC => false, 0xF900...0xFA0D => false, 0xFA10 => false, 0xFA12 => false, 0xFA15...0xFA1E => false, 0xFA20 => false, 0xFA22 => false, 0xFA25...0xFA26 => false, 0xFA2A...0xFA6D => false, 0xFA70...0xFAD9 => false, 0xFB1D => false, 0xFB1F => false, 0xFB2A...0xFB36 => false, 0xFB38...0xFB3C => false, 0xFB3E => false, 0xFB40...0xFB41 => false, 0xFB43...0xFB44 => false, 0xFB46...0xFB4E => false, 0x1D15E...0x1D164 => false, 0x1D1BB...0x1D1C0 => false, 0x2F800...0x2FA1D => false, else => true, }; } /// `isNfkd` returns true if `cp` is in Compatibility Decomposition Normalization Form. pub fn isNfkd(cp: u21) bool { return switch(cp) { 0xA0 => false, 0xA8 => false, 0xAA => false, 0xAF => false, 0xB2...0xB3 => false, 0xB4 => false, 0xB5 => false, 0xB8 => false, 0xB9 => false, 0xBA => false, 0xBC...0xBE => false, 0xC0...0xC5 => false, 0xC7...0xCF => false, 0xD1...0xD6 => false, 0xD9...0xDD => false, 0xE0...0xE5 => false, 0xE7...0xEF => false, 0xF1...0xF6 => false, 0xF9...0xFD => false, 0xFF...0x10F => false, 0x112...0x125 => false, 0x128...0x130 => false, 0x132...0x137 => false, 0x139...0x140 => false, 0x143...0x149 => false, 0x14C...0x151 => false, 0x154...0x165 => false, 0x168...0x17F => false, 0x1A0...0x1A1 => false, 0x1AF...0x1B0 => false, 0x1C4...0x1DC => false, 0x1DE...0x1E3 => false, 0x1E6...0x1F5 => false, 0x1F8...0x21B => false, 0x21E...0x21F => false, 0x226...0x233 => false, 0x2B0...0x2B8 => false, 0x2D8...0x2DD => false, 0x2E0...0x2E4 => false, 0x340...0x341 => false, 0x343...0x344 => false, 0x374 => false, 0x37A => false, 0x37E => false, 0x384...0x385 => false, 0x386 => false, 0x387 => false, 0x388...0x38A => false, 0x38C => false, 0x38E...0x390 => false, 0x3AA...0x3B0 => false, 0x3CA...0x3CE => false, 0x3D0...0x3D6 => false, 0x3F0...0x3F2 => false, 0x3F4...0x3F5 => false, 0x3F9 => false, 0x400...0x401 => false, 0x403 => false, 0x407 => false, 0x40C...0x40E => false, 0x419 => false, 0x439 => false, 0x450...0x451 => false, 0x453 => false, 0x457 => false, 0x45C...0x45E => false, 0x476...0x477 => false, 0x4C1...0x4C2 => false, 0x4D0...0x4D3 => false, 0x4D6...0x4D7 => false, 0x4DA...0x4DF => false, 0x4E2...0x4E7 => false, 0x4EA...0x4F5 => false, 0x4F8...0x4F9 => false, 0x587 => false, 0x622...0x626 => false, 0x675...0x678 => false, 0x6C0 => false, 0x6C2 => false, 0x6D3 => false, 0x929 => false, 0x931 => false, 0x934 => false, 0x958...0x95F => false, 0x9CB...0x9CC => false, 0x9DC...0x9DD => false, 0x9DF => false, 0xA33 => false, 0xA36 => false, 0xA59...0xA5B => false, 0xA5E => false, 0xB48 => false, 0xB4B...0xB4C => false, 0xB5C...0xB5D => false, 0xB94 => false, 0xBCA...0xBCC => false, 0xC48 => false, 0xCC0 => false, 0xCC7...0xCC8 => false, 0xCCA...0xCCB => false, 0xD4A...0xD4C => false, 0xDDA => false, 0xDDC...0xDDE => false, 0xE33 => false, 0xEB3 => false, 0xEDC...0xEDD => false, 0xF0C => false, 0xF43 => false, 0xF4D => false, 0xF52 => false, 0xF57 => false, 0xF5C => false, 0xF69 => false, 0xF73 => false, 0xF75...0xF79 => false, 0xF81 => false, 0xF93 => false, 0xF9D => false, 0xFA2 => false, 0xFA7 => false, 0xFAC => false, 0xFB9 => false, 0x1026 => false, 0x10FC => false, 0x1B06 => false, 0x1B08 => false, 0x1B0A => false, 0x1B0C => false, 0x1B0E => false, 0x1B12 => false, 0x1B3B => false, 0x1B3D => false, 0x1B40...0x1B41 => false, 0x1B43 => false, 0x1D2C...0x1D2E => false, 0x1D30...0x1D3A => false, 0x1D3C...0x1D4D => false, 0x1D4F...0x1D6A => false, 0x1D78 => false, 0x1D9B...0x1DBF => false, 0x1E00...0x1E9B => false, 0x1EA0...0x1EF9 => false, 0x1F00...0x1F15 => false, 0x1F18...0x1F1D => false, 0x1F20...0x1F45 => false, 0x1F48...0x1F4D => false, 0x1F50...0x1F57 => false, 0x1F59 => false, 0x1F5B => false, 0x1F5D => false, 0x1F5F...0x1F7D => false, 0x1F80...0x1FB4 => false, 0x1FB6...0x1FBC => false, 0x1FBD => false, 0x1FBE => false, 0x1FBF...0x1FC1 => false, 0x1FC2...0x1FC4 => false, 0x1FC6...0x1FCC => false, 0x1FCD...0x1FCF => false, 0x1FD0...0x1FD3 => false, 0x1FD6...0x1FDB => false, 0x1FDD...0x1FDF => false, 0x1FE0...0x1FEC => false, 0x1FED...0x1FEF => false, 0x1FF2...0x1FF4 => false, 0x1FF6...0x1FFC => false, 0x1FFD...0x1FFE => false, 0x2000...0x200A => false, 0x2011 => false, 0x2017 => false, 0x2024...0x2026 => false, 0x202F => false, 0x2033...0x2034 => false, 0x2036...0x2037 => false, 0x203C => false, 0x203E => false, 0x2047...0x2049 => false, 0x2057 => false, 0x205F => false, 0x2070 => false, 0x2071 => false, 0x2074...0x2079 => false, 0x207A...0x207C => false, 0x207D => false, 0x207E => false, 0x207F => false, 0x2080...0x2089 => false, 0x208A...0x208C => false, 0x208D => false, 0x208E => false, 0x2090...0x209C => false, 0x20A8 => false, 0x2100...0x2101 => false, 0x2102 => false, 0x2103 => false, 0x2105...0x2106 => false, 0x2107 => false, 0x2109 => false, 0x210A...0x2113 => false, 0x2115 => false, 0x2116 => false, 0x2119...0x211D => false, 0x2120...0x2122 => false, 0x2124 => false, 0x2126 => false, 0x2128 => false, 0x212A...0x212D => false, 0x212F...0x2131 => false, 0x2133...0x2134 => false, 0x2135...0x2138 => false, 0x2139 => false, 0x213B => false, 0x213C...0x213F => false, 0x2140 => false, 0x2145...0x2149 => false, 0x2150...0x215F => false, 0x2160...0x217F => false, 0x2189 => false, 0x219A...0x219B => false, 0x21AE => false, 0x21CD => false, 0x21CE...0x21CF => false, 0x2204 => false, 0x2209 => false, 0x220C => false, 0x2224 => false, 0x2226 => false, 0x222C...0x222D => false, 0x222F...0x2230 => false, 0x2241 => false, 0x2244 => false, 0x2247 => false, 0x2249 => false, 0x2260 => false, 0x2262 => false, 0x226D...0x2271 => false, 0x2274...0x2275 => false, 0x2278...0x2279 => false, 0x2280...0x2281 => false, 0x2284...0x2285 => false, 0x2288...0x2289 => false, 0x22AC...0x22AF => false, 0x22E0...0x22E3 => false, 0x22EA...0x22ED => false, 0x2329 => false, 0x232A => false, 0x2460...0x249B => false, 0x249C...0x24E9 => false, 0x24EA => false, 0x2A0C => false, 0x2A74...0x2A76 => false, 0x2ADC => false, 0x2C7C...0x2C7D => false, 0x2D6F => false, 0x2E9F => false, 0x2EF3 => false, 0x2F00...0x2FD5 => false, 0x3000 => false, 0x3036 => false, 0x3038...0x303A => false, 0x304C => false, 0x304E => false, 0x3050 => false, 0x3052 => false, 0x3054 => false, 0x3056 => false, 0x3058 => false, 0x305A => false, 0x305C => false, 0x305E => false, 0x3060 => false, 0x3062 => false, 0x3065 => false, 0x3067 => false, 0x3069 => false, 0x3070...0x3071 => false, 0x3073...0x3074 => false, 0x3076...0x3077 => false, 0x3079...0x307A => false, 0x307C...0x307D => false, 0x3094 => false, 0x309B...0x309C => false, 0x309E => false, 0x309F => false, 0x30AC => false, 0x30AE => false, 0x30B0 => false, 0x30B2 => false, 0x30B4 => false, 0x30B6 => false, 0x30B8 => false, 0x30BA => false, 0x30BC => false, 0x30BE => false, 0x30C0 => false, 0x30C2 => false, 0x30C5 => false, 0x30C7 => false, 0x30C9 => false, 0x30D0...0x30D1 => false, 0x30D3...0x30D4 => false, 0x30D6...0x30D7 => false, 0x30D9...0x30DA => false, 0x30DC...0x30DD => false, 0x30F4 => false, 0x30F7...0x30FA => false, 0x30FE => false, 0x30FF => false, 0x3131...0x318E => false, 0x3192...0x3195 => false, 0x3196...0x319F => false, 0x3200...0x321E => false, 0x3220...0x3229 => false, 0x322A...0x3247 => false, 0x3250 => false, 0x3251...0x325F => false, 0x3260...0x327E => false, 0x3280...0x3289 => false, 0x328A...0x32B0 => false, 0x32B1...0x32BF => false, 0x32C0...0x33FF => false, 0xA69C...0xA69D => false, 0xA770 => false, 0xA7F2...0xA7F4 => false, 0xA7F8...0xA7F9 => false, 0xAB5C...0xAB5F => false, 0xAB69 => false, 0xAC00...0xD7A3 => false, 0xF900...0xFA0D => false, 0xFA10 => false, 0xFA12 => false, 0xFA15...0xFA1E => false, 0xFA20 => false, 0xFA22 => false, 0xFA25...0xFA26 => false, 0xFA2A...0xFA6D => false, 0xFA70...0xFAD9 => false, 0xFB00...0xFB06 => false, 0xFB13...0xFB17 => false, 0xFB1D => false, 0xFB1F...0xFB28 => false, 0xFB29 => false, 0xFB2A...0xFB36 => false, 0xFB38...0xFB3C => false, 0xFB3E => false, 0xFB40...0xFB41 => false, 0xFB43...0xFB44 => false, 0xFB46...0xFBB1 => false, 0xFBD3...0xFD3D => false, 0xFD50...0xFD8F => false, 0xFD92...0xFDC7 => false, 0xFDF0...0xFDFB => false, 0xFDFC => false, 0xFE10...0xFE16 => false, 0xFE17 => false, 0xFE18 => false, 0xFE19 => false, 0xFE30 => false, 0xFE31...0xFE32 => false, 0xFE33...0xFE34 => false, 0xFE35 => false, 0xFE36 => false, 0xFE37 => false, 0xFE38 => false, 0xFE39 => false, 0xFE3A => false, 0xFE3B => false, 0xFE3C => false, 0xFE3D => false, 0xFE3E => false, 0xFE3F => false, 0xFE40 => false, 0xFE41 => false, 0xFE42 => false, 0xFE43 => false, 0xFE44 => false, 0xFE47 => false, 0xFE48 => false, 0xFE49...0xFE4C => false, 0xFE4D...0xFE4F => false, 0xFE50...0xFE52 => false, 0xFE54...0xFE57 => false, 0xFE58 => false, 0xFE59 => false, 0xFE5A => false, 0xFE5B => false, 0xFE5C => false, 0xFE5D => false, 0xFE5E => false, 0xFE5F...0xFE61 => false, 0xFE62 => false, 0xFE63 => false, 0xFE64...0xFE66 => false, 0xFE68 => false, 0xFE69 => false, 0xFE6A...0xFE6B => false, 0xFE70...0xFE72 => false, 0xFE74 => false, 0xFE76...0xFEFC => false, 0xFF01...0xFF03 => false, 0xFF04 => false, 0xFF05...0xFF07 => false, 0xFF08 => false, 0xFF09 => false, 0xFF0A => false, 0xFF0B => false, 0xFF0C => false, 0xFF0D => false, 0xFF0E...0xFF0F => false, 0xFF10...0xFF19 => false, 0xFF1A...0xFF1B => false, 0xFF1C...0xFF1E => false, 0xFF1F...0xFF20 => false, 0xFF21...0xFF3A => false, 0xFF3B => false, 0xFF3C => false, 0xFF3D => false, 0xFF3E => false, 0xFF3F => false, 0xFF40 => false, 0xFF41...0xFF5A => false, 0xFF5B => false, 0xFF5C => false, 0xFF5D => false, 0xFF5E => false, 0xFF5F => false, 0xFF60 => false, 0xFF61 => false, 0xFF62 => false, 0xFF63 => false, 0xFF64...0xFF65 => false, 0xFF66...0xFF6F => false, 0xFF70 => false, 0xFF71...0xFF9D => false, 0xFF9E...0xFF9F => false, 0xFFA0...0xFFBE => false, 0xFFC2...0xFFC7 => false, 0xFFCA...0xFFCF => false, 0xFFD2...0xFFD7 => false, 0xFFDA...0xFFDC => false, 0xFFE0...0xFFE1 => false, 0xFFE2 => false, 0xFFE3 => false, 0xFFE4 => false, 0xFFE5...0xFFE6 => false, 0xFFE8 => false, 0xFFE9...0xFFEC => false, 0xFFED...0xFFEE => false, 0x10781...0x10785 => false, 0x10787...0x107B0 => false, 0x107B2...0x107BA => false, 0x1109A => false, 0x1109C => false, 0x110AB => false, 0x1112E...0x1112F => false, 0x1134B...0x1134C => false, 0x114BB...0x114BC => false, 0x114BE => false, 0x115BA...0x115BB => false, 0x11938 => false, 0x1D15E...0x1D164 => false, 0x1D1BB...0x1D1C0 => false, 0x1D400...0x1D454 => false, 0x1D456...0x1D49C => false, 0x1D49E...0x1D49F => false, 0x1D4A2 => false, 0x1D4A5...0x1D4A6 => false, 0x1D4A9...0x1D4AC => false, 0x1D4AE...0x1D4B9 => false, 0x1D4BB => false, 0x1D4BD...0x1D4C3 => false, 0x1D4C5...0x1D505 => false, 0x1D507...0x1D50A => false, 0x1D50D...0x1D514 => false, 0x1D516...0x1D51C => false, 0x1D51E...0x1D539 => false, 0x1D53B...0x1D53E => false, 0x1D540...0x1D544 => false, 0x1D546 => false, 0x1D54A...0x1D550 => false, 0x1D552...0x1D6A5 => false, 0x1D6A8...0x1D6C0 => false, 0x1D6C1 => false, 0x1D6C2...0x1D6DA => false, 0x1D6DB => false, 0x1D6DC...0x1D6FA => false, 0x1D6FB => false, 0x1D6FC...0x1D714 => false, 0x1D715 => false, 0x1D716...0x1D734 => false, 0x1D735 => false, 0x1D736...0x1D74E => false, 0x1D74F => false, 0x1D750...0x1D76E => false, 0x1D76F => false, 0x1D770...0x1D788 => false, 0x1D789 => false, 0x1D78A...0x1D7A8 => false, 0x1D7A9 => false, 0x1D7AA...0x1D7C2 => false, 0x1D7C3 => false, 0x1D7C4...0x1D7CB => false, 0x1D7CE...0x1D7FF => false, 0x1EE00...0x1EE03 => false, 0x1EE05...0x1EE1F => false, 0x1EE21...0x1EE22 => false, 0x1EE24 => false, 0x1EE27 => false, 0x1EE29...0x1EE32 => false, 0x1EE34...0x1EE37 => false, 0x1EE39 => false, 0x1EE3B => false, 0x1EE42 => false, 0x1EE47 => false, 0x1EE49 => false, 0x1EE4B => false, 0x1EE4D...0x1EE4F => false, 0x1EE51...0x1EE52 => false, 0x1EE54 => false, 0x1EE57 => false, 0x1EE59 => false, 0x1EE5B => false, 0x1EE5D => false, 0x1EE5F => false, 0x1EE61...0x1EE62 => false, 0x1EE64 => false, 0x1EE67...0x1EE6A => false, 0x1EE6C...0x1EE72 => false, 0x1EE74...0x1EE77 => false, 0x1EE79...0x1EE7C => false, 0x1EE7E => false, 0x1EE80...0x1EE89 => false, 0x1EE8B...0x1EE9B => false, 0x1EEA1...0x1EEA3 => false, 0x1EEA5...0x1EEA9 => false, 0x1EEAB...0x1EEBB => false, 0x1F100...0x1F10A => false, 0x1F110...0x1F12E => false, 0x1F130...0x1F14F => false, 0x1F16A...0x1F16C => false, 0x1F190 => false, 0x1F200...0x1F202 => false, 0x1F210...0x1F23B => false, 0x1F240...0x1F248 => false, 0x1F250...0x1F251 => false, 0x1FBF0...0x1FBF9 => false, 0x2F800...0x2FA1D => false, else => true, }; } /// `isNfkc` returns true if `cp` is in Compatibility Composition Normalization Form. pub fn isNFKC(cp: u21) bool { return switch(cp) { 0xA0 => false, 0xA8 => false, 0xAA => false, 0xAF => false, 0xB2...0xB3 => false, 0xB4 => false, 0xB5 => false, 0xB8 => false, 0xB9 => false, 0xBA => false, 0xBC...0xBE => false, 0x132...0x133 => false, 0x13F...0x140 => false, 0x149 => false, 0x17F => false, 0x1C4...0x1CC => false, 0x1F1...0x1F3 => false, 0x2B0...0x2B8 => false, 0x2D8...0x2DD => false, 0x2E0...0x2E4 => false, 0x340...0x341 => false, 0x343...0x344 => false, 0x374 => false, 0x37A => false, 0x37E => false, 0x384...0x385 => false, 0x387 => false, 0x3D0...0x3D6 => false, 0x3F0...0x3F2 => false, 0x3F4...0x3F5 => false, 0x3F9 => false, 0x587 => false, 0x675...0x678 => false, 0x958...0x95F => false, 0x9DC...0x9DD => false, 0x9DF => false, 0xA33 => false, 0xA36 => false, 0xA59...0xA5B => false, 0xA5E => false, 0xB5C...0xB5D => false, 0xE33 => false, 0xEB3 => false, 0xEDC...0xEDD => false, 0xF0C => false, 0xF43 => false, 0xF4D => false, 0xF52 => false, 0xF57 => false, 0xF5C => false, 0xF69 => false, 0xF73 => false, 0xF75...0xF79 => false, 0xF81 => false, 0xF93 => false, 0xF9D => false, 0xFA2 => false, 0xFA7 => false, 0xFAC => false, 0xFB9 => false, 0x10FC => false, 0x1D2C...0x1D2E => false, 0x1D30...0x1D3A => false, 0x1D3C...0x1D4D => false, 0x1D4F...0x1D6A => false, 0x1D78 => false, 0x1D9B...0x1DBF => false, 0x1E9A...0x1E9B => false, 0x1F71 => false, 0x1F73 => false, 0x1F75 => false, 0x1F77 => false, 0x1F79 => false, 0x1F7B => false, 0x1F7D => false, 0x1FBB => false, 0x1FBD => false, 0x1FBE => false, 0x1FBF...0x1FC1 => false, 0x1FC9 => false, 0x1FCB => false, 0x1FCD...0x1FCF => false, 0x1FD3 => false, 0x1FDB => false, 0x1FDD...0x1FDF => false, 0x1FE3 => false, 0x1FEB => false, 0x1FED...0x1FEF => false, 0x1FF9 => false, 0x1FFB => false, 0x1FFD...0x1FFE => false, 0x2000...0x200A => false, 0x2011 => false, 0x2017 => false, 0x2024...0x2026 => false, 0x202F => false, 0x2033...0x2034 => false, 0x2036...0x2037 => false, 0x203C => false, 0x203E => false, 0x2047...0x2049 => false, 0x2057 => false, 0x205F => false, 0x2070 => false, 0x2071 => false, 0x2074...0x2079 => false, 0x207A...0x207C => false, 0x207D => false, 0x207E => false, 0x207F => false, 0x2080...0x2089 => false, 0x208A...0x208C => false, 0x208D => false, 0x208E => false, 0x2090...0x209C => false, 0x20A8 => false, 0x2100...0x2101 => false, 0x2102 => false, 0x2103 => false, 0x2105...0x2106 => false, 0x2107 => false, 0x2109 => false, 0x210A...0x2113 => false, 0x2115 => false, 0x2116 => false, 0x2119...0x211D => false, 0x2120...0x2122 => false, 0x2124 => false, 0x2126 => false, 0x2128 => false, 0x212A...0x212D => false, 0x212F...0x2131 => false, 0x2133...0x2134 => false, 0x2135...0x2138 => false, 0x2139 => false, 0x213B => false, 0x213C...0x213F => false, 0x2140 => false, 0x2145...0x2149 => false, 0x2150...0x215F => false, 0x2160...0x217F => false, 0x2189 => false, 0x222C...0x222D => false, 0x222F...0x2230 => false, 0x2329 => false, 0x232A => false, 0x2460...0x249B => false, 0x249C...0x24E9 => false, 0x24EA => false, 0x2A0C => false, 0x2A74...0x2A76 => false, 0x2ADC => false, 0x2C7C...0x2C7D => false, 0x2D6F => false, 0x2E9F => false, 0x2EF3 => false, 0x2F00...0x2FD5 => false, 0x3000 => false, 0x3036 => false, 0x3038...0x303A => false, 0x309B...0x309C => false, 0x309F => false, 0x30FF => false, 0x3131...0x318E => false, 0x3192...0x3195 => false, 0x3196...0x319F => false, 0x3200...0x321E => false, 0x3220...0x3229 => false, 0x322A...0x3247 => false, 0x3250 => false, 0x3251...0x325F => false, 0x3260...0x327E => false, 0x3280...0x3289 => false, 0x328A...0x32B0 => false, 0x32B1...0x32BF => false, 0x32C0...0x33FF => false, 0xA69C...0xA69D => false, 0xA770 => false, 0xA7F2...0xA7F4 => false, 0xA7F8...0xA7F9 => false, 0xAB5C...0xAB5F => false, 0xAB69 => false, 0xF900...0xFA0D => false, 0xFA10 => false, 0xFA12 => false, 0xFA15...0xFA1E => false, 0xFA20 => false, 0xFA22 => false, 0xFA25...0xFA26 => false, 0xFA2A...0xFA6D => false, 0xFA70...0xFAD9 => false, 0xFB00...0xFB06 => false, 0xFB13...0xFB17 => false, 0xFB1D => false, 0xFB1F...0xFB28 => false, 0xFB29 => false, 0xFB2A...0xFB36 => false, 0xFB38...0xFB3C => false, 0xFB3E => false, 0xFB40...0xFB41 => false, 0xFB43...0xFB44 => false, 0xFB46...0xFBB1 => false, 0xFBD3...0xFD3D => false, 0xFD50...0xFD8F => false, 0xFD92...0xFDC7 => false, 0xFDF0...0xFDFB => false, 0xFDFC => false, 0xFE10...0xFE16 => false, 0xFE17 => false, 0xFE18 => false, 0xFE19 => false, 0xFE30 => false, 0xFE31...0xFE32 => false, 0xFE33...0xFE34 => false, 0xFE35 => false, 0xFE36 => false, 0xFE37 => false, 0xFE38 => false, 0xFE39 => false, 0xFE3A => false, 0xFE3B => false, 0xFE3C => false, 0xFE3D => false, 0xFE3E => false, 0xFE3F => false, 0xFE40 => false, 0xFE41 => false, 0xFE42 => false, 0xFE43 => false, 0xFE44 => false, 0xFE47 => false, 0xFE48 => false, 0xFE49...0xFE4C => false, 0xFE4D...0xFE4F => false, 0xFE50...0xFE52 => false, 0xFE54...0xFE57 => false, 0xFE58 => false, 0xFE59 => false, 0xFE5A => false, 0xFE5B => false, 0xFE5C => false, 0xFE5D => false, 0xFE5E => false, 0xFE5F...0xFE61 => false, 0xFE62 => false, 0xFE63 => false, 0xFE64...0xFE66 => false, 0xFE68 => false, 0xFE69 => false, 0xFE6A...0xFE6B => false, 0xFE70...0xFE72 => false, 0xFE74 => false, 0xFE76...0xFEFC => false, 0xFF01...0xFF03 => false, 0xFF04 => false, 0xFF05...0xFF07 => false, 0xFF08 => false, 0xFF09 => false, 0xFF0A => false, 0xFF0B => false, 0xFF0C => false, 0xFF0D => false, 0xFF0E...0xFF0F => false, 0xFF10...0xFF19 => false, 0xFF1A...0xFF1B => false, 0xFF1C...0xFF1E => false, 0xFF1F...0xFF20 => false, 0xFF21...0xFF3A => false, 0xFF3B => false, 0xFF3C => false, 0xFF3D => false, 0xFF3E => false, 0xFF3F => false, 0xFF40 => false, 0xFF41...0xFF5A => false, 0xFF5B => false, 0xFF5C => false, 0xFF5D => false, 0xFF5E => false, 0xFF5F => false, 0xFF60 => false, 0xFF61 => false, 0xFF62 => false, 0xFF63 => false, 0xFF64...0xFF65 => false, 0xFF66...0xFF6F => false, 0xFF70 => false, 0xFF71...0xFF9D => false, 0xFF9E...0xFF9F => false, 0xFFA0...0xFFBE => false, 0xFFC2...0xFFC7 => false, 0xFFCA...0xFFCF => false, 0xFFD2...0xFFD7 => false, 0xFFDA...0xFFDC => false, 0xFFE0...0xFFE1 => false, 0xFFE2 => false, 0xFFE3 => false, 0xFFE4 => false, 0xFFE5...0xFFE6 => false, 0xFFE8 => false, 0xFFE9...0xFFEC => false, 0xFFED...0xFFEE => false, 0x10781...0x10785 => false, 0x10787...0x107B0 => false, 0x107B2...0x107BA => false, 0x1D15E...0x1D164 => false, 0x1D1BB...0x1D1C0 => false, 0x1D400...0x1D454 => false, 0x1D456...0x1D49C => false, 0x1D49E...0x1D49F => false, 0x1D4A2 => false, 0x1D4A5...0x1D4A6 => false, 0x1D4A9...0x1D4AC => false, 0x1D4AE...0x1D4B9 => false, 0x1D4BB => false, 0x1D4BD...0x1D4C3 => false, 0x1D4C5...0x1D505 => false, 0x1D507...0x1D50A => false, 0x1D50D...0x1D514 => false, 0x1D516...0x1D51C => false, 0x1D51E...0x1D539 => false, 0x1D53B...0x1D53E => false, 0x1D540...0x1D544 => false, 0x1D546 => false, 0x1D54A...0x1D550 => false, 0x1D552...0x1D6A5 => false, 0x1D6A8...0x1D6C0 => false, 0x1D6C1 => false, 0x1D6C2...0x1D6DA => false, 0x1D6DB => false, 0x1D6DC...0x1D6FA => false, 0x1D6FB => false, 0x1D6FC...0x1D714 => false, 0x1D715 => false, 0x1D716...0x1D734 => false, 0x1D735 => false, 0x1D736...0x1D74E => false, 0x1D74F => false, 0x1D750...0x1D76E => false, 0x1D76F => false, 0x1D770...0x1D788 => false, 0x1D789 => false, 0x1D78A...0x1D7A8 => false, 0x1D7A9 => false, 0x1D7AA...0x1D7C2 => false, 0x1D7C3 => false, 0x1D7C4...0x1D7CB => false, 0x1D7CE...0x1D7FF => false, 0x1EE00...0x1EE03 => false, 0x1EE05...0x1EE1F => false, 0x1EE21...0x1EE22 => false, 0x1EE24 => false, 0x1EE27 => false, 0x1EE29...0x1EE32 => false, 0x1EE34...0x1EE37 => false, 0x1EE39 => false, 0x1EE3B => false, 0x1EE42 => false, 0x1EE47 => false, 0x1EE49 => false, 0x1EE4B => false, 0x1EE4D...0x1EE4F => false, 0x1EE51...0x1EE52 => false, 0x1EE54 => false, 0x1EE57 => false, 0x1EE59 => false, 0x1EE5B => false, 0x1EE5D => false, 0x1EE5F => false, 0x1EE61...0x1EE62 => false, 0x1EE64 => false, 0x1EE67...0x1EE6A => false, 0x1EE6C...0x1EE72 => false, 0x1EE74...0x1EE77 => false, 0x1EE79...0x1EE7C => false, 0x1EE7E => false, 0x1EE80...0x1EE89 => false, 0x1EE8B...0x1EE9B => false, 0x1EEA1...0x1EEA3 => false, 0x1EEA5...0x1EEA9 => false, 0x1EEAB...0x1EEBB => false, 0x1F100...0x1F10A => false, 0x1F110...0x1F12E => false, 0x1F130...0x1F14F => false, 0x1F16A...0x1F16C => false, 0x1F190 => false, 0x1F200...0x1F202 => false, 0x1F210...0x1F23B => false, 0x1F240...0x1F248 => false, 0x1F250...0x1F251 => false, 0x1FBF0...0x1FBF9 => false, 0x2F800...0x2FA1D => false, else => true, }; } /// `toNfkcCaseFold` returns the Compatibility Decomposed, Case Folded mapping for `cp`. /// The returned string is a comma separated list of code points. Empty string means /// map to `cp` itself. "0" means map to nothing. pub fn toNfkcCaseFold(cp: u21) []const u8 { return switch(cp) { 0x41 => "61", 0x42 => "62", 0x43 => "63", 0x44 => "64", 0x45 => "65", 0x46 => "66", 0x47 => "67", 0x48 => "68", 0x49 => "69", 0x4A => "6A", 0x4B => "6B", 0x4C => "6C", 0x4D => "6D", 0x4E => "6E", 0x4F => "6F", 0x50 => "70", 0x51 => "71", 0x52 => "72", 0x53 => "73", 0x54 => "74", 0x55 => "75", 0x56 => "76", 0x57 => "77", 0x58 => "78", 0x59 => "79", 0x5A => "7A", 0xA0 => "20", 0xA8 => "20,308", 0xAA => "61", 0xAD => "0", 0xAF => "20,304", 0xB2 => "32", 0xB3 => "33", 0xB4 => "20,301", 0xB5 => "3BC", 0xB8 => "20,327", 0xB9 => "31", 0xBA => "6F", 0xBC => "31,2044,34", 0xBD => "31,2044,32", 0xBE => "33,2044,34", 0xC0 => "E0", 0xC1 => "E1", 0xC2 => "E2", 0xC3 => "E3", 0xC4 => "E4", 0xC5 => "E5", 0xC6 => "E6", 0xC7 => "E7", 0xC8 => "E8", 0xC9 => "E9", 0xCA => "EA", 0xCB => "EB", 0xCC => "EC", 0xCD => "ED", 0xCE => "EE", 0xCF => "EF", 0xD0 => "F0", 0xD1 => "F1", 0xD2 => "F2", 0xD3 => "F3", 0xD4 => "F4", 0xD5 => "F5", 0xD6 => "F6", 0xD8 => "F8", 0xD9 => "F9", 0xDA => "FA", 0xDB => "FB", 0xDC => "FC", 0xDD => "FD", 0xDE => "FE", 0xDF => "73,73", 0x100 => "101", 0x102 => "103", 0x104 => "105", 0x106 => "107", 0x108 => "109", 0x10A => "10B", 0x10C => "10D", 0x10E => "10F", 0x110 => "111", 0x112 => "113", 0x114 => "115", 0x116 => "117", 0x118 => "119", 0x11A => "11B", 0x11C => "11D", 0x11E => "11F", 0x120 => "121", 0x122 => "123", 0x124 => "125", 0x126 => "127", 0x128 => "129", 0x12A => "12B", 0x12C => "12D", 0x12E => "12F", 0x130 => "69,307", 0x132...0x133 => "69,6A", 0x134 => "135", 0x136 => "137", 0x139 => "13A", 0x13B => "13C", 0x13D => "13E", 0x13F...0x140 => "6C,B7", 0x141 => "142", 0x143 => "144", 0x145 => "146", 0x147 => "148", 0x149 => "2BC,6E", 0x14A => "14B", 0x14C => "14D", 0x14E => "14F", 0x150 => "151", 0x152 => "153", 0x154 => "155", 0x156 => "157", 0x158 => "159", 0x15A => "15B", 0x15C => "15D", 0x15E => "15F", 0x160 => "161", 0x162 => "163", 0x164 => "165", 0x166 => "167", 0x168 => "169", 0x16A => "16B", 0x16C => "16D", 0x16E => "16F", 0x170 => "171", 0x172 => "173", 0x174 => "175", 0x176 => "177", 0x178 => "FF", 0x179 => "17A", 0x17B => "17C", 0x17D => "17E", 0x17F => "73", 0x181 => "253", 0x182 => "183", 0x184 => "185", 0x186 => "254", 0x187 => "188", 0x189 => "256", 0x18A => "257", 0x18B => "18C", 0x18E => "1DD", 0x18F => "259", 0x190 => "25B", 0x191 => "192", 0x193 => "260", 0x194 => "263", 0x196 => "269", 0x197 => "268", 0x198 => "199", 0x19C => "26F", 0x19D => "272", 0x19F => "275", 0x1A0 => "1A1", 0x1A2 => "1A3", 0x1A4 => "1A5", 0x1A6 => "280", 0x1A7 => "1A8", 0x1A9 => "283", 0x1AC => "1AD", 0x1AE => "288", 0x1AF => "1B0", 0x1B1 => "28A", 0x1B2 => "28B", 0x1B3 => "1B4", 0x1B5 => "1B6", 0x1B7 => "292", 0x1B8 => "1B9", 0x1BC => "1BD", 0x1C4...0x1C6 => "64,17E", 0x1C7...0x1C9 => "6C,6A", 0x1CA...0x1CC => "6E,6A", 0x1CD => "1CE", 0x1CF => "1D0", 0x1D1 => "1D2", 0x1D3 => "1D4", 0x1D5 => "1D6", 0x1D7 => "1D8", 0x1D9 => "1DA", 0x1DB => "1DC", 0x1DE => "1DF", 0x1E0 => "1E1", 0x1E2 => "1E3", 0x1E4 => "1E5", 0x1E6 => "1E7", 0x1E8 => "1E9", 0x1EA => "1EB", 0x1EC => "1ED", 0x1EE => "1EF", 0x1F1...0x1F3 => "64,7A", 0x1F4 => "1F5", 0x1F6 => "195", 0x1F7 => "1BF", 0x1F8 => "1F9", 0x1FA => "1FB", 0x1FC => "1FD", 0x1FE => "1FF", 0x200 => "201", 0x202 => "203", 0x204 => "205", 0x206 => "207", 0x208 => "209", 0x20A => "20B", 0x20C => "20D", 0x20E => "20F", 0x210 => "211", 0x212 => "213", 0x214 => "215", 0x216 => "217", 0x218 => "219", 0x21A => "21B", 0x21C => "21D", 0x21E => "21F", 0x220 => "19E", 0x222 => "223", 0x224 => "225", 0x226 => "227", 0x228 => "229", 0x22A => "22B", 0x22C => "22D", 0x22E => "22F", 0x230 => "231", 0x232 => "233", 0x23A => "2C65", 0x23B => "23C", 0x23D => "19A", 0x23E => "2C66", 0x241 => "242", 0x243 => "180", 0x244 => "289", 0x245 => "28C", 0x246 => "247", 0x248 => "249", 0x24A => "24B", 0x24C => "24D", 0x24E => "24F", 0x2B0 => "68", 0x2B1 => "266", 0x2B2 => "6A", 0x2B3 => "72", 0x2B4 => "279", 0x2B5 => "27B", 0x2B6 => "281", 0x2B7 => "77", 0x2B8 => "79", 0x2D8 => "20,306", 0x2D9 => "20,307", 0x2DA => "20,30A", 0x2DB => "20,328", 0x2DC => "20,303", 0x2DD => "20,30B", 0x2E0 => "263", 0x2E1 => "6C", 0x2E2 => "73", 0x2E3 => "78", 0x2E4 => "295", 0x340 => "300", 0x341 => "301", 0x343 => "313", 0x344 => "308,301", 0x345 => "3B9", 0x34F => "0", 0x370 => "371", 0x372 => "373", 0x374 => "2B9", 0x376 => "377", 0x37A => "20,3B9", 0x37E => "3B", 0x37F => "3F3", 0x384 => "20,301", 0x385 => "20,308,301", 0x386 => "3AC", 0x387 => "B7", 0x388 => "3AD", 0x389 => "3AE", 0x38A => "3AF", 0x38C => "3CC", 0x38E => "3CD", 0x38F => "3CE", 0x391 => "3B1", 0x392 => "3B2", 0x393 => "3B3", 0x394 => "3B4", 0x395 => "3B5", 0x396 => "3B6", 0x397 => "3B7", 0x398 => "3B8", 0x399 => "3B9", 0x39A => "3BA", 0x39B => "3BB", 0x39C => "3BC", 0x39D => "3BD", 0x39E => "3BE", 0x39F => "3BF", 0x3A0 => "3C0", 0x3A1 => "3C1", 0x3A3 => "3C3", 0x3A4 => "3C4", 0x3A5 => "3C5", 0x3A6 => "3C6", 0x3A7 => "3C7", 0x3A8 => "3C8", 0x3A9 => "3C9", 0x3AA => "3CA", 0x3AB => "3CB", 0x3C2 => "3C3", 0x3CF => "3D7", 0x3D0 => "3B2", 0x3D1 => "3B8", 0x3D2 => "3C5", 0x3D3 => "3CD", 0x3D4 => "3CB", 0x3D5 => "3C6", 0x3D6 => "3C0", 0x3D8 => "3D9", 0x3DA => "3DB", 0x3DC => "3DD", 0x3DE => "3DF", 0x3E0 => "3E1", 0x3E2 => "3E3", 0x3E4 => "3E5", 0x3E6 => "3E7", 0x3E8 => "3E9", 0x3EA => "3EB", 0x3EC => "3ED", 0x3EE => "3EF", 0x3F0 => "3BA", 0x3F1 => "3C1", 0x3F2 => "3C3", 0x3F4 => "3B8", 0x3F5 => "3B5", 0x3F7 => "3F8", 0x3F9 => "3C3", 0x3FA => "3FB", 0x3FD => "37B", 0x3FE => "37C", 0x3FF => "37D", 0x400 => "450", 0x401 => "451", 0x402 => "452", 0x403 => "453", 0x404 => "454", 0x405 => "455", 0x406 => "456", 0x407 => "457", 0x408 => "458", 0x409 => "459", 0x40A => "45A", 0x40B => "45B", 0x40C => "45C", 0x40D => "45D", 0x40E => "45E", 0x40F => "45F", 0x410 => "430", 0x411 => "431", 0x412 => "432", 0x413 => "433", 0x414 => "434", 0x415 => "435", 0x416 => "436", 0x417 => "437", 0x418 => "438", 0x419 => "439", 0x41A => "43A", 0x41B => "43B", 0x41C => "43C", 0x41D => "43D", 0x41E => "43E", 0x41F => "43F", 0x420 => "440", 0x421 => "441", 0x422 => "442", 0x423 => "443", 0x424 => "444", 0x425 => "445", 0x426 => "446", 0x427 => "447", 0x428 => "448", 0x429 => "449", 0x42A => "44A", 0x42B => "44B", 0x42C => "44C", 0x42D => "44D", 0x42E => "44E", 0x42F => "44F", 0x460 => "461", 0x462 => "463", 0x464 => "465", 0x466 => "467", 0x468 => "469", 0x46A => "46B", 0x46C => "46D", 0x46E => "46F", 0x470 => "471", 0x472 => "473", 0x474 => "475", 0x476 => "477", 0x478 => "479", 0x47A => "47B", 0x47C => "47D", 0x47E => "47F", 0x480 => "481", 0x48A => "48B", 0x48C => "48D", 0x48E => "48F", 0x490 => "491", 0x492 => "493", 0x494 => "495", 0x496 => "497", 0x498 => "499", 0x49A => "49B", 0x49C => "49D", 0x49E => "49F", 0x4A0 => "4A1", 0x4A2 => "4A3", 0x4A4 => "4A5", 0x4A6 => "4A7", 0x4A8 => "4A9", 0x4AA => "4AB", 0x4AC => "4AD", 0x4AE => "4AF", 0x4B0 => "4B1", 0x4B2 => "4B3", 0x4B4 => "4B5", 0x4B6 => "4B7", 0x4B8 => "4B9", 0x4BA => "4BB", 0x4BC => "4BD", 0x4BE => "4BF", 0x4C0 => "4CF", 0x4C1 => "4C2", 0x4C3 => "4C4", 0x4C5 => "4C6", 0x4C7 => "4C8", 0x4C9 => "4CA", 0x4CB => "4CC", 0x4CD => "4CE", 0x4D0 => "4D1", 0x4D2 => "4D3", 0x4D4 => "4D5", 0x4D6 => "4D7", 0x4D8 => "4D9", 0x4DA => "4DB", 0x4DC => "4DD", 0x4DE => "4DF", 0x4E0 => "4E1", 0x4E2 => "4E3", 0x4E4 => "4E5", 0x4E6 => "4E7", 0x4E8 => "4E9", 0x4EA => "4EB", 0x4EC => "4ED", 0x4EE => "4EF", 0x4F0 => "4F1", 0x4F2 => "4F3", 0x4F4 => "4F5", 0x4F6 => "4F7", 0x4F8 => "4F9", 0x4FA => "4FB", 0x4FC => "4FD", 0x4FE => "4FF", 0x500 => "501", 0x502 => "503", 0x504 => "505", 0x506 => "507", 0x508 => "509", 0x50A => "50B", 0x50C => "50D", 0x50E => "50F", 0x510 => "511", 0x512 => "513", 0x514 => "515", 0x516 => "517", 0x518 => "519", 0x51A => "51B", 0x51C => "51D", 0x51E => "51F", 0x520 => "521", 0x522 => "523", 0x524 => "525", 0x526 => "527", 0x528 => "529", 0x52A => "52B", 0x52C => "52D", 0x52E => "52F", 0x531 => "561", 0x532 => "562", 0x533 => "563", 0x534 => "564", 0x535 => "565", 0x536 => "566", 0x537 => "567", 0x538 => "568", 0x539 => "569", 0x53A => "56A", 0x53B => "56B", 0x53C => "56C", 0x53D => "56D", 0x53E => "56E", 0x53F => "56F", 0x540 => "570", 0x541 => "571", 0x542 => "572", 0x543 => "573", 0x544 => "574", 0x545 => "575", 0x546 => "576", 0x547 => "577", 0x548 => "578", 0x549 => "579", 0x54A => "57A", 0x54B => "57B", 0x54C => "57C", 0x54D => "57D", 0x54E => "57E", 0x54F => "57F", 0x550 => "580", 0x551 => "581", 0x552 => "582", 0x553 => "583", 0x554 => "584", 0x555 => "585", 0x556 => "586", 0x587 => "565,582", 0x61C => "0", 0x675 => "627,674", 0x676 => "648,674", 0x677 => "6C7,674", 0x678 => "64A,674", 0x958 => "915,93C", 0x959 => "916,93C", 0x95A => "917,93C", 0x95B => "91C,93C", 0x95C => "921,93C", 0x95D => "922,93C", 0x95E => "92B,93C", 0x95F => "92F,93C", 0x9DC => "9A1,9BC", 0x9DD => "9A2,9BC", 0x9DF => "9AF,9BC", 0xA33 => "A32,A3C", 0xA36 => "A38,A3C", 0xA59 => "A16,A3C", 0xA5A => "A17,A3C", 0xA5B => "A1C,A3C", 0xA5E => "A2B,A3C", 0xB5C => "B21,B3C", 0xB5D => "B22,B3C", 0xE33 => "E4D,E32", 0xEB3 => "ECD,EB2", 0xEDC => "EAB,E99", 0xEDD => "EAB,EA1", 0xF0C => "F0B", 0xF43 => "F42,FB7", 0xF4D => "F4C,FB7", 0xF52 => "F51,FB7", 0xF57 => "F56,FB7", 0xF5C => "F5B,FB7", 0xF69 => "F40,FB5", 0xF73 => "F71,F72", 0xF75 => "F71,F74", 0xF76 => "FB2,F80", 0xF77 => "FB2,F71,F80", 0xF78 => "FB3,F80", 0xF79 => "FB3,F71,F80", 0xF81 => "F71,F80", 0xF93 => "F92,FB7", 0xF9D => "F9C,FB7", 0xFA2 => "FA1,FB7", 0xFA7 => "FA6,FB7", 0xFAC => "FAB,FB7", 0xFB9 => "F90,FB5", 0x10A0 => "2D00", 0x10A1 => "2D01", 0x10A2 => "2D02", 0x10A3 => "2D03", 0x10A4 => "2D04", 0x10A5 => "2D05", 0x10A6 => "2D06", 0x10A7 => "2D07", 0x10A8 => "2D08", 0x10A9 => "2D09", 0x10AA => "2D0A", 0x10AB => "2D0B", 0x10AC => "2D0C", 0x10AD => "2D0D", 0x10AE => "2D0E", 0x10AF => "2D0F", 0x10B0 => "2D10", 0x10B1 => "2D11", 0x10B2 => "2D12", 0x10B3 => "2D13", 0x10B4 => "2D14", 0x10B5 => "2D15", 0x10B6 => "2D16", 0x10B7 => "2D17", 0x10B8 => "2D18", 0x10B9 => "2D19", 0x10BA => "2D1A", 0x10BB => "2D1B", 0x10BC => "2D1C", 0x10BD => "2D1D", 0x10BE => "2D1E", 0x10BF => "2D1F", 0x10C0 => "2D20", 0x10C1 => "2D21", 0x10C2 => "2D22", 0x10C3 => "2D23", 0x10C4 => "2D24", 0x10C5 => "2D25", 0x10C7 => "2D27", 0x10CD => "2D2D", 0x10FC => "10DC", 0x115F...0x1160 => "0", 0x13F8 => "13F0", 0x13F9 => "13F1", 0x13FA => "13F2", 0x13FB => "13F3", 0x13FC => "13F4", 0x13FD => "13F5", 0x17B4...0x17B5 => "0", 0x180B...0x180D => "0", 0x180E => "0", 0x180F => "0", 0x1C80 => "432", 0x1C81 => "434", 0x1C82 => "43E", 0x1C83 => "441", 0x1C84...0x1C85 => "442", 0x1C86 => "44A", 0x1C87 => "463", 0x1C88 => "A64B", 0x1C90 => "10D0", 0x1C91 => "10D1", 0x1C92 => "10D2", 0x1C93 => "10D3", 0x1C94 => "10D4", 0x1C95 => "10D5", 0x1C96 => "10D6", 0x1C97 => "10D7", 0x1C98 => "10D8", 0x1C99 => "10D9", 0x1C9A => "10DA", 0x1C9B => "10DB", 0x1C9C => "10DC", 0x1C9D => "10DD", 0x1C9E => "10DE", 0x1C9F => "10DF", 0x1CA0 => "10E0", 0x1CA1 => "10E1", 0x1CA2 => "10E2", 0x1CA3 => "10E3", 0x1CA4 => "10E4", 0x1CA5 => "10E5", 0x1CA6 => "10E6", 0x1CA7 => "10E7", 0x1CA8 => "10E8", 0x1CA9 => "10E9", 0x1CAA => "10EA", 0x1CAB => "10EB", 0x1CAC => "10EC", 0x1CAD => "10ED", 0x1CAE => "10EE", 0x1CAF => "10EF", 0x1CB0 => "10F0", 0x1CB1 => "10F1", 0x1CB2 => "10F2", 0x1CB3 => "10F3", 0x1CB4 => "10F4", 0x1CB5 => "10F5", 0x1CB6 => "10F6", 0x1CB7 => "10F7", 0x1CB8 => "10F8", 0x1CB9 => "10F9", 0x1CBA => "10FA", 0x1CBD => "10FD", 0x1CBE => "10FE", 0x1CBF => "10FF", 0x1D2C => "61", 0x1D2D => "E6", 0x1D2E => "62", 0x1D30 => "64", 0x1D31 => "65", 0x1D32 => "1DD", 0x1D33 => "67", 0x1D34 => "68", 0x1D35 => "69", 0x1D36 => "6A", 0x1D37 => "6B", 0x1D38 => "6C", 0x1D39 => "6D", 0x1D3A => "6E", 0x1D3C => "6F", 0x1D3D => "223", 0x1D3E => "70", 0x1D3F => "72", 0x1D40 => "74", 0x1D41 => "75", 0x1D42 => "77", 0x1D43 => "61", 0x1D44 => "250", 0x1D45 => "251", 0x1D46 => "1D02", 0x1D47 => "62", 0x1D48 => "64", 0x1D49 => "65", 0x1D4A => "259", 0x1D4B => "25B", 0x1D4C => "25C", 0x1D4D => "67", 0x1D4F => "6B", 0x1D50 => "6D", 0x1D51 => "14B", 0x1D52 => "6F", 0x1D53 => "254", 0x1D54 => "1D16", 0x1D55 => "1D17", 0x1D56 => "70", 0x1D57 => "74", 0x1D58 => "75", 0x1D59 => "1D1D", 0x1D5A => "26F", 0x1D5B => "76", 0x1D5C => "1D25", 0x1D5D => "3B2", 0x1D5E => "3B3", 0x1D5F => "3B4", 0x1D60 => "3C6", 0x1D61 => "3C7", 0x1D62 => "69", 0x1D63 => "72", 0x1D64 => "75", 0x1D65 => "76", 0x1D66 => "3B2", 0x1D67 => "3B3", 0x1D68 => "3C1", 0x1D69 => "3C6", 0x1D6A => "3C7", 0x1D78 => "43D", 0x1D9B => "252", 0x1D9C => "63", 0x1D9D => "255", 0x1D9E => "F0", 0x1D9F => "25C", 0x1DA0 => "66", 0x1DA1 => "25F", 0x1DA2 => "261", 0x1DA3 => "265", 0x1DA4 => "268", 0x1DA5 => "269", 0x1DA6 => "26A", 0x1DA7 => "1D7B", 0x1DA8 => "29D", 0x1DA9 => "26D", 0x1DAA => "1D85", 0x1DAB => "29F", 0x1DAC => "271", 0x1DAD => "270", 0x1DAE => "272", 0x1DAF => "273", 0x1DB0 => "274", 0x1DB1 => "275", 0x1DB2 => "278", 0x1DB3 => "282", 0x1DB4 => "283", 0x1DB5 => "1AB", 0x1DB6 => "289", 0x1DB7 => "28A", 0x1DB8 => "1D1C", 0x1DB9 => "28B", 0x1DBA => "28C", 0x1DBB => "7A", 0x1DBC => "290", 0x1DBD => "291", 0x1DBE => "292", 0x1DBF => "3B8", 0x1E00 => "1E01", 0x1E02 => "1E03", 0x1E04 => "1E05", 0x1E06 => "1E07", 0x1E08 => "1E09", 0x1E0A => "1E0B", 0x1E0C => "1E0D", 0x1E0E => "1E0F", 0x1E10 => "1E11", 0x1E12 => "1E13", 0x1E14 => "1E15", 0x1E16 => "1E17", 0x1E18 => "1E19", 0x1E1A => "1E1B", 0x1E1C => "1E1D", 0x1E1E => "1E1F", 0x1E20 => "1E21", 0x1E22 => "1E23", 0x1E24 => "1E25", 0x1E26 => "1E27", 0x1E28 => "1E29", 0x1E2A => "1E2B", 0x1E2C => "1E2D", 0x1E2E => "1E2F", 0x1E30 => "1E31", 0x1E32 => "1E33", 0x1E34 => "1E35", 0x1E36 => "1E37", 0x1E38 => "1E39", 0x1E3A => "1E3B", 0x1E3C => "1E3D", 0x1E3E => "1E3F", 0x1E40 => "1E41", 0x1E42 => "1E43", 0x1E44 => "1E45", 0x1E46 => "1E47", 0x1E48 => "1E49", 0x1E4A => "1E4B", 0x1E4C => "1E4D", 0x1E4E => "1E4F", 0x1E50 => "1E51", 0x1E52 => "1E53", 0x1E54 => "1E55", 0x1E56 => "1E57", 0x1E58 => "1E59", 0x1E5A => "1E5B", 0x1E5C => "1E5D", 0x1E5E => "1E5F", 0x1E60 => "1E61", 0x1E62 => "1E63", 0x1E64 => "1E65", 0x1E66 => "1E67", 0x1E68 => "1E69", 0x1E6A => "1E6B", 0x1E6C => "1E6D", 0x1E6E => "1E6F", 0x1E70 => "1E71", 0x1E72 => "1E73", 0x1E74 => "1E75", 0x1E76 => "1E77", 0x1E78 => "1E79", 0x1E7A => "1E7B", 0x1E7C => "1E7D", 0x1E7E => "1E7F", 0x1E80 => "1E81", 0x1E82 => "1E83", 0x1E84 => "1E85", 0x1E86 => "1E87", 0x1E88 => "1E89", 0x1E8A => "1E8B", 0x1E8C => "1E8D", 0x1E8E => "1E8F", 0x1E90 => "1E91", 0x1E92 => "1E93", 0x1E94 => "1E95", 0x1E9A => "61,2BE", 0x1E9B => "1E61", 0x1E9E => "73,73", 0x1EA0 => "1EA1", 0x1EA2 => "1EA3", 0x1EA4 => "1EA5", 0x1EA6 => "1EA7", 0x1EA8 => "1EA9", 0x1EAA => "1EAB", 0x1EAC => "1EAD", 0x1EAE => "1EAF", 0x1EB0 => "1EB1", 0x1EB2 => "1EB3", 0x1EB4 => "1EB5", 0x1EB6 => "1EB7", 0x1EB8 => "1EB9", 0x1EBA => "1EBB", 0x1EBC => "1EBD", 0x1EBE => "1EBF", 0x1EC0 => "1EC1", 0x1EC2 => "1EC3", 0x1EC4 => "1EC5", 0x1EC6 => "1EC7", 0x1EC8 => "1EC9", 0x1ECA => "1ECB", 0x1ECC => "1ECD", 0x1ECE => "1ECF", 0x1ED0 => "1ED1", 0x1ED2 => "1ED3", 0x1ED4 => "1ED5", 0x1ED6 => "1ED7", 0x1ED8 => "1ED9", 0x1EDA => "1EDB", 0x1EDC => "1EDD", 0x1EDE => "1EDF", 0x1EE0 => "1EE1", 0x1EE2 => "1EE3", 0x1EE4 => "1EE5", 0x1EE6 => "1EE7", 0x1EE8 => "1EE9", 0x1EEA => "1EEB", 0x1EEC => "1EED", 0x1EEE => "1EEF", 0x1EF0 => "1EF1", 0x1EF2 => "1EF3", 0x1EF4 => "1EF5", 0x1EF6 => "1EF7", 0x1EF8 => "1EF9", 0x1EFA => "1EFB", 0x1EFC => "1EFD", 0x1EFE => "1EFF", 0x1F08 => "1F00", 0x1F09 => "1F01", 0x1F0A => "1F02", 0x1F0B => "1F03", 0x1F0C => "1F04", 0x1F0D => "1F05", 0x1F0E => "1F06", 0x1F0F => "1F07", 0x1F18 => "1F10", 0x1F19 => "1F11", 0x1F1A => "1F12", 0x1F1B => "1F13", 0x1F1C => "1F14", 0x1F1D => "1F15", 0x1F28 => "1F20", 0x1F29 => "1F21", 0x1F2A => "1F22", 0x1F2B => "1F23", 0x1F2C => "1F24", 0x1F2D => "1F25", 0x1F2E => "1F26", 0x1F2F => "1F27", 0x1F38 => "1F30", 0x1F39 => "1F31", 0x1F3A => "1F32", 0x1F3B => "1F33", 0x1F3C => "1F34", 0x1F3D => "1F35", 0x1F3E => "1F36", 0x1F3F => "1F37", 0x1F48 => "1F40", 0x1F49 => "1F41", 0x1F4A => "1F42", 0x1F4B => "1F43", 0x1F4C => "1F44", 0x1F4D => "1F45", 0x1F59 => "1F51", 0x1F5B => "1F53", 0x1F5D => "1F55", 0x1F5F => "1F57", 0x1F68 => "1F60", 0x1F69 => "1F61", 0x1F6A => "1F62", 0x1F6B => "1F63", 0x1F6C => "1F64", 0x1F6D => "1F65", 0x1F6E => "1F66", 0x1F6F => "1F67", 0x1F71 => "3AC", 0x1F73 => "3AD", 0x1F75 => "3AE", 0x1F77 => "3AF", 0x1F79 => "3CC", 0x1F7B => "3CD", 0x1F7D => "3CE", 0x1F80 => "1F00,3B9", 0x1F81 => "1F01,3B9", 0x1F82 => "1F02,3B9", 0x1F83 => "1F03,3B9", 0x1F84 => "1F04,3B9", 0x1F85 => "1F05,3B9", 0x1F86 => "1F06,3B9", 0x1F87 => "1F07,3B9", 0x1F88 => "1F00,3B9", 0x1F89 => "1F01,3B9", 0x1F8A => "1F02,3B9", 0x1F8B => "1F03,3B9", 0x1F8C => "1F04,3B9", 0x1F8D => "1F05,3B9", 0x1F8E => "1F06,3B9", 0x1F8F => "1F07,3B9", 0x1F90 => "1F20,3B9", 0x1F91 => "1F21,3B9", 0x1F92 => "1F22,3B9", 0x1F93 => "1F23,3B9", 0x1F94 => "1F24,3B9", 0x1F95 => "1F25,3B9", 0x1F96 => "1F26,3B9", 0x1F97 => "1F27,3B9", 0x1F98 => "1F20,3B9", 0x1F99 => "1F21,3B9", 0x1F9A => "1F22,3B9", 0x1F9B => "1F23,3B9", 0x1F9C => "1F24,3B9", 0x1F9D => "1F25,3B9", 0x1F9E => "1F26,3B9", 0x1F9F => "1F27,3B9", 0x1FA0 => "1F60,3B9", 0x1FA1 => "1F61,3B9", 0x1FA2 => "1F62,3B9", 0x1FA3 => "1F63,3B9", 0x1FA4 => "1F64,3B9", 0x1FA5 => "1F65,3B9", 0x1FA6 => "1F66,3B9", 0x1FA7 => "1F67,3B9", 0x1FA8 => "1F60,3B9", 0x1FA9 => "1F61,3B9", 0x1FAA => "1F62,3B9", 0x1FAB => "1F63,3B9", 0x1FAC => "1F64,3B9", 0x1FAD => "1F65,3B9", 0x1FAE => "1F66,3B9", 0x1FAF => "1F67,3B9", 0x1FB2 => "1F70,3B9", 0x1FB3 => "3B1,3B9", 0x1FB4 => "3AC,3B9", 0x1FB7 => "1FB6,3B9", 0x1FB8 => "1FB0", 0x1FB9 => "1FB1", 0x1FBA => "1F70", 0x1FBB => "3AC", 0x1FBC => "3B1,3B9", 0x1FBD => "20,313", 0x1FBE => "3B9", 0x1FBF => "20,313", 0x1FC0 => "20,342", 0x1FC1 => "20,308,342", 0x1FC2 => "1F74,3B9", 0x1FC3 => "3B7,3B9", 0x1FC4 => "3AE,3B9", 0x1FC7 => "1FC6,3B9", 0x1FC8 => "1F72", 0x1FC9 => "3AD", 0x1FCA => "1F74", 0x1FCB => "3AE", 0x1FCC => "3B7,3B9", 0x1FCD => "20,313,300", 0x1FCE => "20,313,301", 0x1FCF => "20,313,342", 0x1FD3 => "390", 0x1FD8 => "1FD0", 0x1FD9 => "1FD1", 0x1FDA => "1F76", 0x1FDB => "3AF", 0x1FDD => "20,314,300", 0x1FDE => "20,314,301", 0x1FDF => "20,314,342", 0x1FE3 => "3B0", 0x1FE8 => "1FE0", 0x1FE9 => "1FE1", 0x1FEA => "1F7A", 0x1FEB => "3CD", 0x1FEC => "1FE5", 0x1FED => "20,308,300", 0x1FEE => "20,308,301", 0x1FEF => "60", 0x1FF2 => "1F7C,3B9", 0x1FF3 => "3C9,3B9", 0x1FF4 => "3CE,3B9", 0x1FF7 => "1FF6,3B9", 0x1FF8 => "1F78", 0x1FF9 => "3CC", 0x1FFA => "1F7C", 0x1FFB => "3CE", 0x1FFC => "3C9,3B9", 0x1FFD => "20,301", 0x1FFE => "20,314", 0x2000...0x200A => "20", 0x200B...0x200F => "0", 0x2011 => "2010", 0x2017 => "20,333", 0x2024 => "2E", 0x2025 => "2E,2E", 0x2026 => "2E,2E,2E", 0x202A...0x202E => "0", 0x202F => "20", 0x2033 => "2032,2032", 0x2034 => "2032,2032,2032", 0x2036 => "2035,2035", 0x2037 => "2035,2035,2035", 0x203C => "21,21", 0x203E => "20,305", 0x2047 => "3F,3F", 0x2048 => "3F,21", 0x2049 => "21,3F", 0x2057 => "2032,2032,2032,2032", 0x205F => "20", 0x2060...0x2064 => "0", 0x2065 => "0", 0x2066...0x206F => "0", 0x2070 => "30", 0x2071 => "69", 0x2074 => "34", 0x2075 => "35", 0x2076 => "36", 0x2077 => "37", 0x2078 => "38", 0x2079 => "39", 0x207A => "2B", 0x207B => "2212", 0x207C => "3D", 0x207D => "28", 0x207E => "29", 0x207F => "6E", 0x2080 => "30", 0x2081 => "31", 0x2082 => "32", 0x2083 => "33", 0x2084 => "34", 0x2085 => "35", 0x2086 => "36", 0x2087 => "37", 0x2088 => "38", 0x2089 => "39", 0x208A => "2B", 0x208B => "2212", 0x208C => "3D", 0x208D => "28", 0x208E => "29", 0x2090 => "61", 0x2091 => "65", 0x2092 => "6F", 0x2093 => "78", 0x2094 => "259", 0x2095 => "68", 0x2096 => "6B", 0x2097 => "6C", 0x2098 => "6D", 0x2099 => "6E", 0x209A => "70", 0x209B => "73", 0x209C => "74", 0x20A8 => "72,73", 0x2100 => "61,2F,63", 0x2101 => "61,2F,73", 0x2102 => "63", 0x2103 => "B0,63", 0x2105 => "63,2F,6F", 0x2106 => "63,2F,75", 0x2107 => "25B", 0x2109 => "B0,66", 0x210A => "67", 0x210B...0x210E => "68", 0x210F => "127", 0x2110...0x2111 => "69", 0x2112...0x2113 => "6C", 0x2115 => "6E", 0x2116 => "6E,6F", 0x2119 => "70", 0x211A => "71", 0x211B...0x211D => "72", 0x2120 => "73,6D", 0x2121 => "74,65,6C", 0x2122 => "74,6D", 0x2124 => "7A", 0x2126 => "3C9", 0x2128 => "7A", 0x212A => "6B", 0x212B => "E5", 0x212C => "62", 0x212D => "63", 0x212F...0x2130 => "65", 0x2131 => "66", 0x2132 => "214E", 0x2133 => "6D", 0x2134 => "6F", 0x2135 => "5D0", 0x2136 => "5D1", 0x2137 => "5D2", 0x2138 => "5D3", 0x2139 => "69", 0x213B => "66,61,78", 0x213C => "3C0", 0x213D...0x213E => "3B3", 0x213F => "3C0", 0x2140 => "2211", 0x2145...0x2146 => "64", 0x2147 => "65", 0x2148 => "69", 0x2149 => "6A", 0x2150 => "31,2044,37", 0x2151 => "31,2044,39", 0x2152 => "31,2044,31,30", 0x2153 => "31,2044,33", 0x2154 => "32,2044,33", 0x2155 => "31,2044,35", 0x2156 => "32,2044,35", 0x2157 => "33,2044,35", 0x2158 => "34,2044,35", 0x2159 => "31,2044,36", 0x215A => "35,2044,36", 0x215B => "31,2044,38", 0x215C => "33,2044,38", 0x215D => "35,2044,38", 0x215E => "37,2044,38", 0x215F => "31,2044", 0x2160 => "69", 0x2161 => "69,69", 0x2162 => "69,69,69", 0x2163 => "69,76", 0x2164 => "76", 0x2165 => "76,69", 0x2166 => "76,69,69", 0x2167 => "76,69,69,69", 0x2168 => "69,78", 0x2169 => "78", 0x216A => "78,69", 0x216B => "78,69,69", 0x216C => "6C", 0x216D => "63", 0x216E => "64", 0x216F => "6D", 0x2170 => "69", 0x2171 => "69,69", 0x2172 => "69,69,69", 0x2173 => "69,76", 0x2174 => "76", 0x2175 => "76,69", 0x2176 => "76,69,69", 0x2177 => "76,69,69,69", 0x2178 => "69,78", 0x2179 => "78", 0x217A => "78,69", 0x217B => "78,69,69", 0x217C => "6C", 0x217D => "63", 0x217E => "64", 0x217F => "6D", 0x2183 => "2184", 0x2189 => "30,2044,33", 0x222C => "222B,222B", 0x222D => "222B,222B,222B", 0x222F => "222E,222E", 0x2230 => "222E,222E,222E", 0x2329 => "3008", 0x232A => "3009", 0x2460 => "31", 0x2461 => "32", 0x2462 => "33", 0x2463 => "34", 0x2464 => "35", 0x2465 => "36", 0x2466 => "37", 0x2467 => "38", 0x2468 => "39", 0x2469 => "31,30", 0x246A => "31,31", 0x246B => "31,32", 0x246C => "31,33", 0x246D => "31,34", 0x246E => "31,35", 0x246F => "31,36", 0x2470 => "31,37", 0x2471 => "31,38", 0x2472 => "31,39", 0x2473 => "32,30", 0x2474 => "28,31,29", 0x2475 => "28,32,29", 0x2476 => "28,33,29", 0x2477 => "28,34,29", 0x2478 => "28,35,29", 0x2479 => "28,36,29", 0x247A => "28,37,29", 0x247B => "28,38,29", 0x247C => "28,39,29", 0x247D => "28,31,30,29", 0x247E => "28,31,31,29", 0x247F => "28,31,32,29", 0x2480 => "28,31,33,29", 0x2481 => "28,31,34,29", 0x2482 => "28,31,35,29", 0x2483 => "28,31,36,29", 0x2484 => "28,31,37,29", 0x2485 => "28,31,38,29", 0x2486 => "28,31,39,29", 0x2487 => "28,32,30,29", 0x2488 => "31,2E", 0x2489 => "32,2E", 0x248A => "33,2E", 0x248B => "34,2E", 0x248C => "35,2E", 0x248D => "36,2E", 0x248E => "37,2E", 0x248F => "38,2E", 0x2490 => "39,2E", 0x2491 => "31,30,2E", 0x2492 => "31,31,2E", 0x2493 => "31,32,2E", 0x2494 => "31,33,2E", 0x2495 => "31,34,2E", 0x2496 => "31,35,2E", 0x2497 => "31,36,2E", 0x2498 => "31,37,2E", 0x2499 => "31,38,2E", 0x249A => "31,39,2E", 0x249B => "32,30,2E", 0x249C => "28,61,29", 0x249D => "28,62,29", 0x249E => "28,63,29", 0x249F => "28,64,29", 0x24A0 => "28,65,29", 0x24A1 => "28,66,29", 0x24A2 => "28,67,29", 0x24A3 => "28,68,29", 0x24A4 => "28,69,29", 0x24A5 => "28,6A,29", 0x24A6 => "28,6B,29", 0x24A7 => "28,6C,29", 0x24A8 => "28,6D,29", 0x24A9 => "28,6E,29", 0x24AA => "28,6F,29", 0x24AB => "28,70,29", 0x24AC => "28,71,29", 0x24AD => "28,72,29", 0x24AE => "28,73,29", 0x24AF => "28,74,29", 0x24B0 => "28,75,29", 0x24B1 => "28,76,29", 0x24B2 => "28,77,29", 0x24B3 => "28,78,29", 0x24B4 => "28,79,29", 0x24B5 => "28,7A,29", 0x24B6 => "61", 0x24B7 => "62", 0x24B8 => "63", 0x24B9 => "64", 0x24BA => "65", 0x24BB => "66", 0x24BC => "67", 0x24BD => "68", 0x24BE => "69", 0x24BF => "6A", 0x24C0 => "6B", 0x24C1 => "6C", 0x24C2 => "6D", 0x24C3 => "6E", 0x24C4 => "6F", 0x24C5 => "70", 0x24C6 => "71", 0x24C7 => "72", 0x24C8 => "73", 0x24C9 => "74", 0x24CA => "75", 0x24CB => "76", 0x24CC => "77", 0x24CD => "78", 0x24CE => "79", 0x24CF => "7A", 0x24D0 => "61", 0x24D1 => "62", 0x24D2 => "63", 0x24D3 => "64", 0x24D4 => "65", 0x24D5 => "66", 0x24D6 => "67", 0x24D7 => "68", 0x24D8 => "69", 0x24D9 => "6A", 0x24DA => "6B", 0x24DB => "6C", 0x24DC => "6D", 0x24DD => "6E", 0x24DE => "6F", 0x24DF => "70", 0x24E0 => "71", 0x24E1 => "72", 0x24E2 => "73", 0x24E3 => "74", 0x24E4 => "75", 0x24E5 => "76", 0x24E6 => "77", 0x24E7 => "78", 0x24E8 => "79", 0x24E9 => "7A", 0x24EA => "30", 0x2A0C => "222B,222B,222B,222B", 0x2A74 => "3A,3A,3D", 0x2A75 => "3D,3D", 0x2A76 => "3D,3D,3D", 0x2ADC => "2ADD,338", 0x2C00 => "2C30", 0x2C01 => "2C31", 0x2C02 => "2C32", 0x2C03 => "2C33", 0x2C04 => "2C34", 0x2C05 => "2C35", 0x2C06 => "2C36", 0x2C07 => "2C37", 0x2C08 => "2C38", 0x2C09 => "2C39", 0x2C0A => "2C3A", 0x2C0B => "2C3B", 0x2C0C => "2C3C", 0x2C0D => "2C3D", 0x2C0E => "2C3E", 0x2C0F => "2C3F", 0x2C10 => "2C40", 0x2C11 => "2C41", 0x2C12 => "2C42", 0x2C13 => "2C43", 0x2C14 => "2C44", 0x2C15 => "2C45", 0x2C16 => "2C46", 0x2C17 => "2C47", 0x2C18 => "2C48", 0x2C19 => "2C49", 0x2C1A => "2C4A", 0x2C1B => "2C4B", 0x2C1C => "2C4C", 0x2C1D => "2C4D", 0x2C1E => "2C4E", 0x2C1F => "2C4F", 0x2C20 => "2C50", 0x2C21 => "2C51", 0x2C22 => "2C52", 0x2C23 => "2C53", 0x2C24 => "2C54", 0x2C25 => "2C55", 0x2C26 => "2C56", 0x2C27 => "2C57", 0x2C28 => "2C58", 0x2C29 => "2C59", 0x2C2A => "2C5A", 0x2C2B => "2C5B", 0x2C2C => "2C5C", 0x2C2D => "2C5D", 0x2C2E => "2C5E", 0x2C2F => "2C5F", 0x2C60 => "2C61", 0x2C62 => "26B", 0x2C63 => "1D7D", 0x2C64 => "27D", 0x2C67 => "2C68", 0x2C69 => "2C6A", 0x2C6B => "2C6C", 0x2C6D => "251", 0x2C6E => "271", 0x2C6F => "250", 0x2C70 => "252", 0x2C72 => "2C73", 0x2C75 => "2C76", 0x2C7C => "6A", 0x2C7D => "76", 0x2C7E => "23F", 0x2C7F => "240", 0x2C80 => "2C81", 0x2C82 => "2C83", 0x2C84 => "2C85", 0x2C86 => "2C87", 0x2C88 => "2C89", 0x2C8A => "2C8B", 0x2C8C => "2C8D", 0x2C8E => "2C8F", 0x2C90 => "2C91", 0x2C92 => "2C93", 0x2C94 => "2C95", 0x2C96 => "2C97", 0x2C98 => "2C99", 0x2C9A => "2C9B", 0x2C9C => "2C9D", 0x2C9E => "2C9F", 0x2CA0 => "2CA1", 0x2CA2 => "2CA3", 0x2CA4 => "2CA5", 0x2CA6 => "2CA7", 0x2CA8 => "2CA9", 0x2CAA => "2CAB", 0x2CAC => "2CAD", 0x2CAE => "2CAF", 0x2CB0 => "2CB1", 0x2CB2 => "2CB3", 0x2CB4 => "2CB5", 0x2CB6 => "2CB7", 0x2CB8 => "2CB9", 0x2CBA => "2CBB", 0x2CBC => "2CBD", 0x2CBE => "2CBF", 0x2CC0 => "2CC1", 0x2CC2 => "2CC3", 0x2CC4 => "2CC5", 0x2CC6 => "2CC7", 0x2CC8 => "2CC9", 0x2CCA => "2CCB", 0x2CCC => "2CCD", 0x2CCE => "2CCF", 0x2CD0 => "2CD1", 0x2CD2 => "2CD3", 0x2CD4 => "2CD5", 0x2CD6 => "2CD7", 0x2CD8 => "2CD9", 0x2CDA => "2CDB", 0x2CDC => "2CDD", 0x2CDE => "2CDF", 0x2CE0 => "2CE1", 0x2CE2 => "2CE3", 0x2CEB => "2CEC", 0x2CED => "2CEE", 0x2CF2 => "2CF3", 0x2D6F => "2D61", 0x2E9F => "6BCD", 0x2EF3 => "9F9F", 0x2F00 => "4E00", 0x2F01 => "4E28", 0x2F02 => "4E36", 0x2F03 => "4E3F", 0x2F04 => "4E59", 0x2F05 => "4E85", 0x2F06 => "4E8C", 0x2F07 => "4EA0", 0x2F08 => "4EBA", 0x2F09 => "513F", 0x2F0A => "5165", 0x2F0B => "516B", 0x2F0C => "5182", 0x2F0D => "5196", 0x2F0E => "51AB", 0x2F0F => "51E0", 0x2F10 => "51F5", 0x2F11 => "5200", 0x2F12 => "529B", 0x2F13 => "52F9", 0x2F14 => "5315", 0x2F15 => "531A", 0x2F16 => "5338", 0x2F17 => "5341", 0x2F18 => "535C", 0x2F19 => "5369", 0x2F1A => "5382", 0x2F1B => "53B6", 0x2F1C => "53C8", 0x2F1D => "53E3", 0x2F1E => "56D7", 0x2F1F => "571F", 0x2F20 => "58EB", 0x2F21 => "5902", 0x2F22 => "590A", 0x2F23 => "5915", 0x2F24 => "5927", 0x2F25 => "5973", 0x2F26 => "5B50", 0x2F27 => "5B80", 0x2F28 => "5BF8", 0x2F29 => "5C0F", 0x2F2A => "5C22", 0x2F2B => "5C38", 0x2F2C => "5C6E", 0x2F2D => "5C71", 0x2F2E => "5DDB", 0x2F2F => "5DE5", 0x2F30 => "5DF1", 0x2F31 => "5DFE", 0x2F32 => "5E72", 0x2F33 => "5E7A", 0x2F34 => "5E7F", 0x2F35 => "5EF4", 0x2F36 => "5EFE", 0x2F37 => "5F0B", 0x2F38 => "5F13", 0x2F39 => "5F50", 0x2F3A => "5F61", 0x2F3B => "5F73", 0x2F3C => "5FC3", 0x2F3D => "6208", 0x2F3E => "6236", 0x2F3F => "624B", 0x2F40 => "652F", 0x2F41 => "6534", 0x2F42 => "6587", 0x2F43 => "6597", 0x2F44 => "65A4", 0x2F45 => "65B9", 0x2F46 => "65E0", 0x2F47 => "65E5", 0x2F48 => "66F0", 0x2F49 => "6708", 0x2F4A => "6728", 0x2F4B => "6B20", 0x2F4C => "6B62", 0x2F4D => "6B79", 0x2F4E => "6BB3", 0x2F4F => "6BCB", 0x2F50 => "6BD4", 0x2F51 => "6BDB", 0x2F52 => "6C0F", 0x2F53 => "6C14", 0x2F54 => "6C34", 0x2F55 => "706B", 0x2F56 => "722A", 0x2F57 => "7236", 0x2F58 => "723B", 0x2F59 => "723F", 0x2F5A => "7247", 0x2F5B => "7259", 0x2F5C => "725B", 0x2F5D => "72AC", 0x2F5E => "7384", 0x2F5F => "7389", 0x2F60 => "74DC", 0x2F61 => "74E6", 0x2F62 => "7518", 0x2F63 => "751F", 0x2F64 => "7528", 0x2F65 => "7530", 0x2F66 => "758B", 0x2F67 => "7592", 0x2F68 => "7676", 0x2F69 => "767D", 0x2F6A => "76AE", 0x2F6B => "76BF", 0x2F6C => "76EE", 0x2F6D => "77DB", 0x2F6E => "77E2", 0x2F6F => "77F3", 0x2F70 => "793A", 0x2F71 => "79B8", 0x2F72 => "79BE", 0x2F73 => "7A74", 0x2F74 => "7ACB", 0x2F75 => "7AF9", 0x2F76 => "7C73", 0x2F77 => "7CF8", 0x2F78 => "7F36", 0x2F79 => "7F51", 0x2F7A => "7F8A", 0x2F7B => "7FBD", 0x2F7C => "8001", 0x2F7D => "800C", 0x2F7E => "8012", 0x2F7F => "8033", 0x2F80 => "807F", 0x2F81 => "8089", 0x2F82 => "81E3", 0x2F83 => "81EA", 0x2F84 => "81F3", 0x2F85 => "81FC", 0x2F86 => "820C", 0x2F87 => "821B", 0x2F88 => "821F", 0x2F89 => "826E", 0x2F8A => "8272", 0x2F8B => "8278", 0x2F8C => "864D", 0x2F8D => "866B", 0x2F8E => "8840", 0x2F8F => "884C", 0x2F90 => "8863", 0x2F91 => "897E", 0x2F92 => "898B", 0x2F93 => "89D2", 0x2F94 => "8A00", 0x2F95 => "8C37", 0x2F96 => "8C46", 0x2F97 => "8C55", 0x2F98 => "8C78", 0x2F99 => "8C9D", 0x2F9A => "8D64", 0x2F9B => "8D70", 0x2F9C => "8DB3", 0x2F9D => "8EAB", 0x2F9E => "8ECA", 0x2F9F => "8F9B", 0x2FA0 => "8FB0", 0x2FA1 => "8FB5", 0x2FA2 => "9091", 0x2FA3 => "9149", 0x2FA4 => "91C6", 0x2FA5 => "91CC", 0x2FA6 => "91D1", 0x2FA7 => "9577", 0x2FA8 => "9580", 0x2FA9 => "961C", 0x2FAA => "96B6", 0x2FAB => "96B9", 0x2FAC => "96E8", 0x2FAD => "9751", 0x2FAE => "975E", 0x2FAF => "9762", 0x2FB0 => "9769", 0x2FB1 => "97CB", 0x2FB2 => "97ED", 0x2FB3 => "97F3", 0x2FB4 => "9801", 0x2FB5 => "98A8", 0x2FB6 => "98DB", 0x2FB7 => "98DF", 0x2FB8 => "9996", 0x2FB9 => "9999", 0x2FBA => "99AC", 0x2FBB => "9AA8", 0x2FBC => "9AD8", 0x2FBD => "9ADF", 0x2FBE => "9B25", 0x2FBF => "9B2F", 0x2FC0 => "9B32", 0x2FC1 => "9B3C", 0x2FC2 => "9B5A", 0x2FC3 => "9CE5", 0x2FC4 => "9E75", 0x2FC5 => "9E7F", 0x2FC6 => "9EA5", 0x2FC7 => "9EBB", 0x2FC8 => "9EC3", 0x2FC9 => "9ECD", 0x2FCA => "9ED1", 0x2FCB => "9EF9", 0x2FCC => "9EFD", 0x2FCD => "9F0E", 0x2FCE => "9F13", 0x2FCF => "9F20", 0x2FD0 => "9F3B", 0x2FD1 => "9F4A", 0x2FD2 => "9F52", 0x2FD3 => "9F8D", 0x2FD4 => "9F9C", 0x2FD5 => "9FA0", 0x3000 => "20", 0x3036 => "3012", 0x3038 => "5341", 0x3039 => "5344", 0x303A => "5345", 0x309B => "20,3099", 0x309C => "20,309A", 0x309F => "3088,308A", 0x30FF => "30B3,30C8", 0x3131 => "1100", 0x3132 => "1101", 0x3133 => "11AA", 0x3134 => "1102", 0x3135 => "11AC", 0x3136 => "11AD", 0x3137 => "1103", 0x3138 => "1104", 0x3139 => "1105", 0x313A => "11B0", 0x313B => "11B1", 0x313C => "11B2", 0x313D => "11B3", 0x313E => "11B4", 0x313F => "11B5", 0x3140 => "111A", 0x3141 => "1106", 0x3142 => "1107", 0x3143 => "1108", 0x3144 => "1121", 0x3145 => "1109", 0x3146 => "110A", 0x3147 => "110B", 0x3148 => "110C", 0x3149 => "110D", 0x314A => "110E", 0x314B => "110F", 0x314C => "1110", 0x314D => "1111", 0x314E => "1112", 0x314F => "1161", 0x3150 => "1162", 0x3151 => "1163", 0x3152 => "1164", 0x3153 => "1165", 0x3154 => "1166", 0x3155 => "1167", 0x3156 => "1168", 0x3157 => "1169", 0x3158 => "116A", 0x3159 => "116B", 0x315A => "116C", 0x315B => "116D", 0x315C => "116E", 0x315D => "116F", 0x315E => "1170", 0x315F => "1171", 0x3160 => "1172", 0x3161 => "1173", 0x3162 => "1174", 0x3163 => "1175", 0x3164 => "0", 0x3165 => "1114", 0x3166 => "1115", 0x3167 => "11C7", 0x3168 => "11C8", 0x3169 => "11CC", 0x316A => "11CE", 0x316B => "11D3", 0x316C => "11D7", 0x316D => "11D9", 0x316E => "111C", 0x316F => "11DD", 0x3170 => "11DF", 0x3171 => "111D", 0x3172 => "111E", 0x3173 => "1120", 0x3174 => "1122", 0x3175 => "1123", 0x3176 => "1127", 0x3177 => "1129", 0x3178 => "112B", 0x3179 => "112C", 0x317A => "112D", 0x317B => "112E", 0x317C => "112F", 0x317D => "1132", 0x317E => "1136", 0x317F => "1140", 0x3180 => "1147", 0x3181 => "114C", 0x3182 => "11F1", 0x3183 => "11F2", 0x3184 => "1157", 0x3185 => "1158", 0x3186 => "1159", 0x3187 => "1184", 0x3188 => "1185", 0x3189 => "1188", 0x318A => "1191", 0x318B => "1192", 0x318C => "1194", 0x318D => "119E", 0x318E => "11A1", 0x3192 => "4E00", 0x3193 => "4E8C", 0x3194 => "4E09", 0x3195 => "56DB", 0x3196 => "4E0A", 0x3197 => "4E2D", 0x3198 => "4E0B", 0x3199 => "7532", 0x319A => "4E59", 0x319B => "4E19", 0x319C => "4E01", 0x319D => "5929", 0x319E => "5730", 0x319F => "4EBA", 0x3200 => "28,1100,29", 0x3201 => "28,1102,29", 0x3202 => "28,1103,29", 0x3203 => "28,1105,29", 0x3204 => "28,1106,29", 0x3205 => "28,1107,29", 0x3206 => "28,1109,29", 0x3207 => "28,110B,29", 0x3208 => "28,110C,29", 0x3209 => "28,110E,29", 0x320A => "28,110F,29", 0x320B => "28,1110,29", 0x320C => "28,1111,29", 0x320D => "28,1112,29", 0x320E => "28,AC00,29", 0x320F => "28,B098,29", 0x3210 => "28,B2E4,29", 0x3211 => "28,B77C,29", 0x3212 => "28,B9C8,29", 0x3213 => "28,BC14,29", 0x3214 => "28,C0AC,29", 0x3215 => "28,C544,29", 0x3216 => "28,C790,29", 0x3217 => "28,CC28,29", 0x3218 => "28,CE74,29", 0x3219 => "28,D0C0,29", 0x321A => "28,D30C,29", 0x321B => "28,D558,29", 0x321C => "28,C8FC,29", 0x321D => "28,C624,C804,29", 0x321E => "28,C624,D6C4,29", 0x3220 => "28,4E00,29", 0x3221 => "28,4E8C,29", 0x3222 => "28,4E09,29", 0x3223 => "28,56DB,29", 0x3224 => "28,4E94,29", 0x3225 => "28,516D,29", 0x3226 => "28,4E03,29", 0x3227 => "28,516B,29", 0x3228 => "28,4E5D,29", 0x3229 => "28,5341,29", 0x322A => "28,6708,29", 0x322B => "28,706B,29", 0x322C => "28,6C34,29", 0x322D => "28,6728,29", 0x322E => "28,91D1,29", 0x322F => "28,571F,29", 0x3230 => "28,65E5,29", 0x3231 => "28,682A,29", 0x3232 => "28,6709,29", 0x3233 => "28,793E,29", 0x3234 => "28,540D,29", 0x3235 => "28,7279,29", 0x3236 => "28,8CA1,29", 0x3237 => "28,795D,29", 0x3238 => "28,52B4,29", 0x3239 => "28,4EE3,29", 0x323A => "28,547C,29", 0x323B => "28,5B66,29", 0x323C => "28,76E3,29", 0x323D => "28,4F01,29", 0x323E => "28,8CC7,29", 0x323F => "28,5354,29", 0x3240 => "28,796D,29", 0x3241 => "28,4F11,29", 0x3242 => "28,81EA,29", 0x3243 => "28,81F3,29", 0x3244 => "554F", 0x3245 => "5E7C", 0x3246 => "6587", 0x3247 => "7B8F", 0x3250 => "70,74,65", 0x3251 => "32,31", 0x3252 => "32,32", 0x3253 => "32,33", 0x3254 => "32,34", 0x3255 => "32,35", 0x3256 => "32,36", 0x3257 => "32,37", 0x3258 => "32,38", 0x3259 => "32,39", 0x325A => "33,30", 0x325B => "33,31", 0x325C => "33,32", 0x325D => "33,33", 0x325E => "33,34", 0x325F => "33,35", 0x3260 => "1100", 0x3261 => "1102", 0x3262 => "1103", 0x3263 => "1105", 0x3264 => "1106", 0x3265 => "1107", 0x3266 => "1109", 0x3267 => "110B", 0x3268 => "110C", 0x3269 => "110E", 0x326A => "110F", 0x326B => "1110", 0x326C => "1111", 0x326D => "1112", 0x326E => "AC00", 0x326F => "B098", 0x3270 => "B2E4", 0x3271 => "B77C", 0x3272 => "B9C8", 0x3273 => "BC14", 0x3274 => "C0AC", 0x3275 => "C544", 0x3276 => "C790", 0x3277 => "CC28", 0x3278 => "CE74", 0x3279 => "D0C0", 0x327A => "D30C", 0x327B => "D558", 0x327C => "CC38,ACE0", 0x327D => "C8FC,C758", 0x327E => "C6B0", 0x3280 => "4E00", 0x3281 => "4E8C", 0x3282 => "4E09", 0x3283 => "56DB", 0x3284 => "4E94", 0x3285 => "516D", 0x3286 => "4E03", 0x3287 => "516B", 0x3288 => "4E5D", 0x3289 => "5341", 0x328A => "6708", 0x328B => "706B", 0x328C => "6C34", 0x328D => "6728", 0x328E => "91D1", 0x328F => "571F", 0x3290 => "65E5", 0x3291 => "682A", 0x3292 => "6709", 0x3293 => "793E", 0x3294 => "540D", 0x3295 => "7279", 0x3296 => "8CA1", 0x3297 => "795D", 0x3298 => "52B4", 0x3299 => "79D8", 0x329A => "7537", 0x329B => "5973", 0x329C => "9069", 0x329D => "512A", 0x329E => "5370", 0x329F => "6CE8", 0x32A0 => "9805", 0x32A1 => "4F11", 0x32A2 => "5199", 0x32A3 => "6B63", 0x32A4 => "4E0A", 0x32A5 => "4E2D", 0x32A6 => "4E0B", 0x32A7 => "5DE6", 0x32A8 => "53F3", 0x32A9 => "533B", 0x32AA => "5B97", 0x32AB => "5B66", 0x32AC => "76E3", 0x32AD => "4F01", 0x32AE => "8CC7", 0x32AF => "5354", 0x32B0 => "591C", 0x32B1 => "33,36", 0x32B2 => "33,37", 0x32B3 => "33,38", 0x32B4 => "33,39", 0x32B5 => "34,30", 0x32B6 => "34,31", 0x32B7 => "34,32", 0x32B8 => "34,33", 0x32B9 => "34,34", 0x32BA => "34,35", 0x32BB => "34,36", 0x32BC => "34,37", 0x32BD => "34,38", 0x32BE => "34,39", 0x32BF => "35,30", 0x32C0 => "31,6708", 0x32C1 => "32,6708", 0x32C2 => "33,6708", 0x32C3 => "34,6708", 0x32C4 => "35,6708", 0x32C5 => "36,6708", 0x32C6 => "37,6708", 0x32C7 => "38,6708", 0x32C8 => "39,6708", 0x32C9 => "31,30,6708", 0x32CA => "31,31,6708", 0x32CB => "31,32,6708", 0x32CC => "68,67", 0x32CD => "65,72,67", 0x32CE => "65,76", 0x32CF => "6C,74,64", 0x32D0 => "30A2", 0x32D1 => "30A4", 0x32D2 => "30A6", 0x32D3 => "30A8", 0x32D4 => "30AA", 0x32D5 => "30AB", 0x32D6 => "30AD", 0x32D7 => "30AF", 0x32D8 => "30B1", 0x32D9 => "30B3", 0x32DA => "30B5", 0x32DB => "30B7", 0x32DC => "30B9", 0x32DD => "30BB", 0x32DE => "30BD", 0x32DF => "30BF", 0x32E0 => "30C1", 0x32E1 => "30C4", 0x32E2 => "30C6", 0x32E3 => "30C8", 0x32E4 => "30CA", 0x32E5 => "30CB", 0x32E6 => "30CC", 0x32E7 => "30CD", 0x32E8 => "30CE", 0x32E9 => "30CF", 0x32EA => "30D2", 0x32EB => "30D5", 0x32EC => "30D8", 0x32ED => "30DB", 0x32EE => "30DE", 0x32EF => "30DF", 0x32F0 => "30E0", 0x32F1 => "30E1", 0x32F2 => "30E2", 0x32F3 => "30E4", 0x32F4 => "30E6", 0x32F5 => "30E8", 0x32F6 => "30E9", 0x32F7 => "30EA", 0x32F8 => "30EB", 0x32F9 => "30EC", 0x32FA => "30ED", 0x32FB => "30EF", 0x32FC => "30F0", 0x32FD => "30F1", 0x32FE => "30F2", 0x32FF => "4EE4,548C", 0x3300 => "30A2,30D1,30FC,30C8", 0x3301 => "30A2,30EB,30D5,30A1", 0x3302 => "30A2,30F3,30DA,30A2", 0x3303 => "30A2,30FC,30EB", 0x3304 => "30A4,30CB,30F3,30B0", 0x3305 => "30A4,30F3,30C1", 0x3306 => "30A6,30A9,30F3", 0x3307 => "30A8,30B9,30AF,30FC,30C9", 0x3308 => "30A8,30FC,30AB,30FC", 0x3309 => "30AA,30F3,30B9", 0x330A => "30AA,30FC,30E0", 0x330B => "30AB,30A4,30EA", 0x330C => "30AB,30E9,30C3,30C8", 0x330D => "30AB,30ED,30EA,30FC", 0x330E => "30AC,30ED,30F3", 0x330F => "30AC,30F3,30DE", 0x3310 => "30AE,30AC", 0x3311 => "30AE,30CB,30FC", 0x3312 => "30AD,30E5,30EA,30FC", 0x3313 => "30AE,30EB,30C0,30FC", 0x3314 => "30AD,30ED", 0x3315 => "30AD,30ED,30B0,30E9,30E0", 0x3316 => "30AD,30ED,30E1,30FC,30C8,30EB", 0x3317 => "30AD,30ED,30EF,30C3,30C8", 0x3318 => "30B0,30E9,30E0", 0x3319 => "30B0,30E9,30E0,30C8,30F3", 0x331A => "30AF,30EB,30BC,30A4,30ED", 0x331B => "30AF,30ED,30FC,30CD", 0x331C => "30B1,30FC,30B9", 0x331D => "30B3,30EB,30CA", 0x331E => "30B3,30FC,30DD", 0x331F => "30B5,30A4,30AF,30EB", 0x3320 => "30B5,30F3,30C1,30FC,30E0", 0x3321 => "30B7,30EA,30F3,30B0", 0x3322 => "30BB,30F3,30C1", 0x3323 => "30BB,30F3,30C8", 0x3324 => "30C0,30FC,30B9", 0x3325 => "30C7,30B7", 0x3326 => "30C9,30EB", 0x3327 => "30C8,30F3", 0x3328 => "30CA,30CE", 0x3329 => "30CE,30C3,30C8", 0x332A => "30CF,30A4,30C4", 0x332B => "30D1,30FC,30BB,30F3,30C8", 0x332C => "30D1,30FC,30C4", 0x332D => "30D0,30FC,30EC,30EB", 0x332E => "30D4,30A2,30B9,30C8,30EB", 0x332F => "30D4,30AF,30EB", 0x3330 => "30D4,30B3", 0x3331 => "30D3,30EB", 0x3332 => "30D5,30A1,30E9,30C3,30C9", 0x3333 => "30D5,30A3,30FC,30C8", 0x3334 => "30D6,30C3,30B7,30A7,30EB", 0x3335 => "30D5,30E9,30F3", 0x3336 => "30D8,30AF,30BF,30FC,30EB", 0x3337 => "30DA,30BD", 0x3338 => "30DA,30CB,30D2", 0x3339 => "30D8,30EB,30C4", 0x333A => "30DA,30F3,30B9", 0x333B => "30DA,30FC,30B8", 0x333C => "30D9,30FC,30BF", 0x333D => "30DD,30A4,30F3,30C8", 0x333E => "30DC,30EB,30C8", 0x333F => "30DB,30F3", 0x3340 => "30DD,30F3,30C9", 0x3341 => "30DB,30FC,30EB", 0x3342 => "30DB,30FC,30F3", 0x3343 => "30DE,30A4,30AF,30ED", 0x3344 => "30DE,30A4,30EB", 0x3345 => "30DE,30C3,30CF", 0x3346 => "30DE,30EB,30AF", 0x3347 => "30DE,30F3,30B7,30E7,30F3", 0x3348 => "30DF,30AF,30ED,30F3", 0x3349 => "30DF,30EA", 0x334A => "30DF,30EA,30D0,30FC,30EB", 0x334B => "30E1,30AC", 0x334C => "30E1,30AC,30C8,30F3", 0x334D => "30E1,30FC,30C8,30EB", 0x334E => "30E4,30FC,30C9", 0x334F => "30E4,30FC,30EB", 0x3350 => "30E6,30A2,30F3", 0x3351 => "30EA,30C3,30C8,30EB", 0x3352 => "30EA,30E9", 0x3353 => "30EB,30D4,30FC", 0x3354 => "30EB,30FC,30D6,30EB", 0x3355 => "30EC,30E0", 0x3356 => "30EC,30F3,30C8,30B2,30F3", 0x3357 => "30EF,30C3,30C8", 0x3358 => "30,70B9", 0x3359 => "31,70B9", 0x335A => "32,70B9", 0x335B => "33,70B9", 0x335C => "34,70B9", 0x335D => "35,70B9", 0x335E => "36,70B9", 0x335F => "37,70B9", 0x3360 => "38,70B9", 0x3361 => "39,70B9", 0x3362 => "31,30,70B9", 0x3363 => "31,31,70B9", 0x3364 => "31,32,70B9", 0x3365 => "31,33,70B9", 0x3366 => "31,34,70B9", 0x3367 => "31,35,70B9", 0x3368 => "31,36,70B9", 0x3369 => "31,37,70B9", 0x336A => "31,38,70B9", 0x336B => "31,39,70B9", 0x336C => "32,30,70B9", 0x336D => "32,31,70B9", 0x336E => "32,32,70B9", 0x336F => "32,33,70B9", 0x3370 => "32,34,70B9", 0x3371 => "68,70,61", 0x3372 => "64,61", 0x3373 => "61,75", 0x3374 => "62,61,72", 0x3375 => "6F,76", 0x3376 => "70,63", 0x3377 => "64,6D", 0x3378 => "64,6D,32", 0x3379 => "64,6D,33", 0x337A => "69,75", 0x337B => "5E73,6210", 0x337C => "662D,548C", 0x337D => "5927,6B63", 0x337E => "660E,6CBB", 0x337F => "682A,5F0F,4F1A,793E", 0x3380 => "70,61", 0x3381 => "6E,61", 0x3382 => "3BC,61", 0x3383 => "6D,61", 0x3384 => "6B,61", 0x3385 => "6B,62", 0x3386 => "6D,62", 0x3387 => "67,62", 0x3388 => "63,61,6C", 0x3389 => "6B,63,61,6C", 0x338A => "70,66", 0x338B => "6E,66", 0x338C => "3BC,66", 0x338D => "3BC,67", 0x338E => "6D,67", 0x338F => "6B,67", 0x3390 => "68,7A", 0x3391 => "6B,68,7A", 0x3392 => "6D,68,7A", 0x3393 => "67,68,7A", 0x3394 => "74,68,7A", 0x3395 => "3BC,6C", 0x3396 => "6D,6C", 0x3397 => "64,6C", 0x3398 => "6B,6C", 0x3399 => "66,6D", 0x339A => "6E,6D", 0x339B => "3BC,6D", 0x339C => "6D,6D", 0x339D => "63,6D", 0x339E => "6B,6D", 0x339F => "6D,6D,32", 0x33A0 => "63,6D,32", 0x33A1 => "6D,32", 0x33A2 => "6B,6D,32", 0x33A3 => "6D,6D,33", 0x33A4 => "63,6D,33", 0x33A5 => "6D,33", 0x33A6 => "6B,6D,33", 0x33A7 => "6D,2215,73", 0x33A8 => "6D,2215,73,32", 0x33A9 => "70,61", 0x33AA => "6B,70,61", 0x33AB => "6D,70,61", 0x33AC => "67,70,61", 0x33AD => "72,61,64", 0x33AE => "72,61,64,2215,73", 0x33AF => "72,61,64,2215,73,32", 0x33B0 => "70,73", 0x33B1 => "6E,73", 0x33B2 => "3BC,73", 0x33B3 => "6D,73", 0x33B4 => "70,76", 0x33B5 => "6E,76", 0x33B6 => "3BC,76", 0x33B7 => "6D,76", 0x33B8 => "6B,76", 0x33B9 => "6D,76", 0x33BA => "70,77", 0x33BB => "6E,77", 0x33BC => "3BC,77", 0x33BD => "6D,77", 0x33BE => "6B,77", 0x33BF => "6D,77", 0x33C0 => "6B,3C9", 0x33C1 => "6D,3C9", 0x33C2 => "61,2E,6D,2E", 0x33C3 => "62,71", 0x33C4 => "63,63", 0x33C5 => "63,64", 0x33C6 => "63,2215,6B,67", 0x33C7 => "63,6F,2E", 0x33C8 => "64,62", 0x33C9 => "67,79", 0x33CA => "68,61", 0x33CB => "68,70", 0x33CC => "69,6E", 0x33CD => "6B,6B", 0x33CE => "6B,6D", 0x33CF => "6B,74", 0x33D0 => "6C,6D", 0x33D1 => "6C,6E", 0x33D2 => "6C,6F,67", 0x33D3 => "6C,78", 0x33D4 => "6D,62", 0x33D5 => "6D,69,6C", 0x33D6 => "6D,6F,6C", 0x33D7 => "70,68", 0x33D8 => "70,2E,6D,2E", 0x33D9 => "70,70,6D", 0x33DA => "70,72", 0x33DB => "73,72", 0x33DC => "73,76", 0x33DD => "77,62", 0x33DE => "76,2215,6D", 0x33DF => "61,2215,6D", 0x33E0 => "31,65E5", 0x33E1 => "32,65E5", 0x33E2 => "33,65E5", 0x33E3 => "34,65E5", 0x33E4 => "35,65E5", 0x33E5 => "36,65E5", 0x33E6 => "37,65E5", 0x33E7 => "38,65E5", 0x33E8 => "39,65E5", 0x33E9 => "31,30,65E5", 0x33EA => "31,31,65E5", 0x33EB => "31,32,65E5", 0x33EC => "31,33,65E5", 0x33ED => "31,34,65E5", 0x33EE => "31,35,65E5", 0x33EF => "31,36,65E5", 0x33F0 => "31,37,65E5", 0x33F1 => "31,38,65E5", 0x33F2 => "31,39,65E5", 0x33F3 => "32,30,65E5", 0x33F4 => "32,31,65E5", 0x33F5 => "32,32,65E5", 0x33F6 => "32,33,65E5", 0x33F7 => "32,34,65E5", 0x33F8 => "32,35,65E5", 0x33F9 => "32,36,65E5", 0x33FA => "32,37,65E5", 0x33FB => "32,38,65E5", 0x33FC => "32,39,65E5", 0x33FD => "33,30,65E5", 0x33FE => "33,31,65E5", 0x33FF => "67,61,6C", 0xA640 => "A641", 0xA642 => "A643", 0xA644 => "A645", 0xA646 => "A647", 0xA648 => "A649", 0xA64A => "A64B", 0xA64C => "A64D", 0xA64E => "A64F", 0xA650 => "A651", 0xA652 => "A653", 0xA654 => "A655", 0xA656 => "A657", 0xA658 => "A659", 0xA65A => "A65B", 0xA65C => "A65D", 0xA65E => "A65F", 0xA660 => "A661", 0xA662 => "A663", 0xA664 => "A665", 0xA666 => "A667", 0xA668 => "A669", 0xA66A => "A66B", 0xA66C => "A66D", 0xA680 => "A681", 0xA682 => "A683", 0xA684 => "A685", 0xA686 => "A687", 0xA688 => "A689", 0xA68A => "A68B", 0xA68C => "A68D", 0xA68E => "A68F", 0xA690 => "A691", 0xA692 => "A693", 0xA694 => "A695", 0xA696 => "A697", 0xA698 => "A699", 0xA69A => "A69B", 0xA69C => "44A", 0xA69D => "44C", 0xA722 => "A723", 0xA724 => "A725", 0xA726 => "A727", 0xA728 => "A729", 0xA72A => "A72B", 0xA72C => "A72D", 0xA72E => "A72F", 0xA732 => "A733", 0xA734 => "A735", 0xA736 => "A737", 0xA738 => "A739", 0xA73A => "A73B", 0xA73C => "A73D", 0xA73E => "A73F", 0xA740 => "A741", 0xA742 => "A743", 0xA744 => "A745", 0xA746 => "A747", 0xA748 => "A749", 0xA74A => "A74B", 0xA74C => "A74D", 0xA74E => "A74F", 0xA750 => "A751", 0xA752 => "A753", 0xA754 => "A755", 0xA756 => "A757", 0xA758 => "A759", 0xA75A => "A75B", 0xA75C => "A75D", 0xA75E => "A75F", 0xA760 => "A761", 0xA762 => "A763", 0xA764 => "A765", 0xA766 => "A767", 0xA768 => "A769", 0xA76A => "A76B", 0xA76C => "A76D", 0xA76E => "A76F", 0xA770 => "A76F", 0xA779 => "A77A", 0xA77B => "A77C", 0xA77D => "1D79", 0xA77E => "A77F", 0xA780 => "A781", 0xA782 => "A783", 0xA784 => "A785", 0xA786 => "A787", 0xA78B => "A78C", 0xA78D => "265", 0xA790 => "A791", 0xA792 => "A793", 0xA796 => "A797", 0xA798 => "A799", 0xA79A => "A79B", 0xA79C => "A79D", 0xA79E => "A79F", 0xA7A0 => "A7A1", 0xA7A2 => "A7A3", 0xA7A4 => "A7A5", 0xA7A6 => "A7A7", 0xA7A8 => "A7A9", 0xA7AA => "266", 0xA7AB => "25C", 0xA7AC => "261", 0xA7AD => "26C", 0xA7AE => "26A", 0xA7B0 => "29E", 0xA7B1 => "287", 0xA7B2 => "29D", 0xA7B3 => "AB53", 0xA7B4 => "A7B5", 0xA7B6 => "A7B7", 0xA7B8 => "A7B9", 0xA7BA => "A7BB", 0xA7BC => "A7BD", 0xA7BE => "A7BF", 0xA7C0 => "A7C1", 0xA7C2 => "A7C3", 0xA7C4 => "A794", 0xA7C5 => "282", 0xA7C6 => "1D8E", 0xA7C7 => "A7C8", 0xA7C9 => "A7CA", 0xA7D0 => "A7D1", 0xA7D6 => "A7D7", 0xA7D8 => "A7D9", 0xA7F2 => "63", 0xA7F3 => "66", 0xA7F4 => "71", 0xA7F5 => "A7F6", 0xA7F8 => "127", 0xA7F9 => "153", 0xAB5C => "A727", 0xAB5D => "AB37", 0xAB5E => "26B", 0xAB5F => "AB52", 0xAB69 => "28D", 0xAB70 => "13A0", 0xAB71 => "13A1", 0xAB72 => "13A2", 0xAB73 => "13A3", 0xAB74 => "13A4", 0xAB75 => "13A5", 0xAB76 => "13A6", 0xAB77 => "13A7", 0xAB78 => "13A8", 0xAB79 => "13A9", 0xAB7A => "13AA", 0xAB7B => "13AB", 0xAB7C => "13AC", 0xAB7D => "13AD", 0xAB7E => "13AE", 0xAB7F => "13AF", 0xAB80 => "13B0", 0xAB81 => "13B1", 0xAB82 => "13B2", 0xAB83 => "13B3", 0xAB84 => "13B4", 0xAB85 => "13B5", 0xAB86 => "13B6", 0xAB87 => "13B7", 0xAB88 => "13B8", 0xAB89 => "13B9", 0xAB8A => "13BA", 0xAB8B => "13BB", 0xAB8C => "13BC", 0xAB8D => "13BD", 0xAB8E => "13BE", 0xAB8F => "13BF", 0xAB90 => "13C0", 0xAB91 => "13C1", 0xAB92 => "13C2", 0xAB93 => "13C3", 0xAB94 => "13C4", 0xAB95 => "13C5", 0xAB96 => "13C6", 0xAB97 => "13C7", 0xAB98 => "13C8", 0xAB99 => "13C9", 0xAB9A => "13CA", 0xAB9B => "13CB", 0xAB9C => "13CC", 0xAB9D => "13CD", 0xAB9E => "13CE", 0xAB9F => "13CF", 0xABA0 => "13D0", 0xABA1 => "13D1", 0xABA2 => "13D2", 0xABA3 => "13D3", 0xABA4 => "13D4", 0xABA5 => "13D5", 0xABA6 => "13D6", 0xABA7 => "13D7", 0xABA8 => "13D8", 0xABA9 => "13D9", 0xABAA => "13DA", 0xABAB => "13DB", 0xABAC => "13DC", 0xABAD => "13DD", 0xABAE => "13DE", 0xABAF => "13DF", 0xABB0 => "13E0", 0xABB1 => "13E1", 0xABB2 => "13E2", 0xABB3 => "13E3", 0xABB4 => "13E4", 0xABB5 => "13E5", 0xABB6 => "13E6", 0xABB7 => "13E7", 0xABB8 => "13E8", 0xABB9 => "13E9", 0xABBA => "13EA", 0xABBB => "13EB", 0xABBC => "13EC", 0xABBD => "13ED", 0xABBE => "13EE", 0xABBF => "13EF", 0xF900 => "8C48", 0xF901 => "66F4", 0xF902 => "8ECA", 0xF903 => "8CC8", 0xF904 => "6ED1", 0xF905 => "4E32", 0xF906 => "53E5", 0xF907...0xF908 => "9F9C", 0xF909 => "5951", 0xF90A => "91D1", 0xF90B => "5587", 0xF90C => "5948", 0xF90D => "61F6", 0xF90E => "7669", 0xF90F => "7F85", 0xF910 => "863F", 0xF911 => "87BA", 0xF912 => "88F8", 0xF913 => "908F", 0xF914 => "6A02", 0xF915 => "6D1B", 0xF916 => "70D9", 0xF917 => "73DE", 0xF918 => "843D", 0xF919 => "916A", 0xF91A => "99F1", 0xF91B => "4E82", 0xF91C => "5375", 0xF91D => "6B04", 0xF91E => "721B", 0xF91F => "862D", 0xF920 => "9E1E", 0xF921 => "5D50", 0xF922 => "6FEB", 0xF923 => "85CD", 0xF924 => "8964", 0xF925 => "62C9", 0xF926 => "81D8", 0xF927 => "881F", 0xF928 => "5ECA", 0xF929 => "6717", 0xF92A => "6D6A", 0xF92B => "72FC", 0xF92C => "90CE", 0xF92D => "4F86", 0xF92E => "51B7", 0xF92F => "52DE", 0xF930 => "64C4", 0xF931 => "6AD3", 0xF932 => "7210", 0xF933 => "76E7", 0xF934 => "8001", 0xF935 => "8606", 0xF936 => "865C", 0xF937 => "8DEF", 0xF938 => "9732", 0xF939 => "9B6F", 0xF93A => "9DFA", 0xF93B => "788C", 0xF93C => "797F", 0xF93D => "7DA0", 0xF93E => "83C9", 0xF93F => "9304", 0xF940 => "9E7F", 0xF941 => "8AD6", 0xF942 => "58DF", 0xF943 => "5F04", 0xF944 => "7C60", 0xF945 => "807E", 0xF946 => "7262", 0xF947 => "78CA", 0xF948 => "8CC2", 0xF949 => "96F7", 0xF94A => "58D8", 0xF94B => "5C62", 0xF94C => "6A13", 0xF94D => "6DDA", 0xF94E => "6F0F", 0xF94F => "7D2F", 0xF950 => "7E37", 0xF951 => "964B", 0xF952 => "52D2", 0xF953 => "808B", 0xF954 => "51DC", 0xF955 => "51CC", 0xF956 => "7A1C", 0xF957 => "7DBE", 0xF958 => "83F1", 0xF959 => "9675", 0xF95A => "8B80", 0xF95B => "62CF", 0xF95C => "6A02", 0xF95D => "8AFE", 0xF95E => "4E39", 0xF95F => "5BE7", 0xF960 => "6012", 0xF961 => "7387", 0xF962 => "7570", 0xF963 => "5317", 0xF964 => "78FB", 0xF965 => "4FBF", 0xF966 => "5FA9", 0xF967 => "4E0D", 0xF968 => "6CCC", 0xF969 => "6578", 0xF96A => "7D22", 0xF96B => "53C3", 0xF96C => "585E", 0xF96D => "7701", 0xF96E => "8449", 0xF96F => "8AAA", 0xF970 => "6BBA", 0xF971 => "8FB0", 0xF972 => "6C88", 0xF973 => "62FE", 0xF974 => "82E5", 0xF975 => "63A0", 0xF976 => "7565", 0xF977 => "4EAE", 0xF978 => "5169", 0xF979 => "51C9", 0xF97A => "6881", 0xF97B => "7CE7", 0xF97C => "826F", 0xF97D => "8AD2", 0xF97E => "91CF", 0xF97F => "52F5", 0xF980 => "5442", 0xF981 => "5973", 0xF982 => "5EEC", 0xF983 => "65C5", 0xF984 => "6FFE", 0xF985 => "792A", 0xF986 => "95AD", 0xF987 => "9A6A", 0xF988 => "9E97", 0xF989 => "9ECE", 0xF98A => "529B", 0xF98B => "66C6", 0xF98C => "6B77", 0xF98D => "8F62", 0xF98E => "5E74", 0xF98F => "6190", 0xF990 => "6200", 0xF991 => "649A", 0xF992 => "6F23", 0xF993 => "7149", 0xF994 => "7489", 0xF995 => "79CA", 0xF996 => "7DF4", 0xF997 => "806F", 0xF998 => "8F26", 0xF999 => "84EE", 0xF99A => "9023", 0xF99B => "934A", 0xF99C => "5217", 0xF99D => "52A3", 0xF99E => "54BD", 0xF99F => "70C8", 0xF9A0 => "88C2", 0xF9A1 => "8AAA", 0xF9A2 => "5EC9", 0xF9A3 => "5FF5", 0xF9A4 => "637B", 0xF9A5 => "6BAE", 0xF9A6 => "7C3E", 0xF9A7 => "7375", 0xF9A8 => "4EE4", 0xF9A9 => "56F9", 0xF9AA => "5BE7", 0xF9AB => "5DBA", 0xF9AC => "601C", 0xF9AD => "73B2", 0xF9AE => "7469", 0xF9AF => "7F9A", 0xF9B0 => "8046", 0xF9B1 => "9234", 0xF9B2 => "96F6", 0xF9B3 => "9748", 0xF9B4 => "9818", 0xF9B5 => "4F8B", 0xF9B6 => "79AE", 0xF9B7 => "91B4", 0xF9B8 => "96B8", 0xF9B9 => "60E1", 0xF9BA => "4E86", 0xF9BB => "50DA", 0xF9BC => "5BEE", 0xF9BD => "5C3F", 0xF9BE => "6599", 0xF9BF => "6A02", 0xF9C0 => "71CE", 0xF9C1 => "7642", 0xF9C2 => "84FC", 0xF9C3 => "907C", 0xF9C4 => "9F8D", 0xF9C5 => "6688", 0xF9C6 => "962E", 0xF9C7 => "5289", 0xF9C8 => "677B", 0xF9C9 => "67F3", 0xF9CA => "6D41", 0xF9CB => "6E9C", 0xF9CC => "7409", 0xF9CD => "7559", 0xF9CE => "786B", 0xF9CF => "7D10", 0xF9D0 => "985E", 0xF9D1 => "516D", 0xF9D2 => "622E", 0xF9D3 => "9678", 0xF9D4 => "502B", 0xF9D5 => "5D19", 0xF9D6 => "6DEA", 0xF9D7 => "8F2A", 0xF9D8 => "5F8B", 0xF9D9 => "6144", 0xF9DA => "6817", 0xF9DB => "7387", 0xF9DC => "9686", 0xF9DD => "5229", 0xF9DE => "540F", 0xF9DF => "5C65", 0xF9E0 => "6613", 0xF9E1 => "674E", 0xF9E2 => "68A8", 0xF9E3 => "6CE5", 0xF9E4 => "7406", 0xF9E5 => "75E2", 0xF9E6 => "7F79", 0xF9E7 => "88CF", 0xF9E8 => "88E1", 0xF9E9 => "91CC", 0xF9EA => "96E2", 0xF9EB => "533F", 0xF9EC => "6EBA", 0xF9ED => "541D", 0xF9EE => "71D0", 0xF9EF => "7498", 0xF9F0 => "85FA", 0xF9F1 => "96A3", 0xF9F2 => "9C57", 0xF9F3 => "9E9F", 0xF9F4 => "6797", 0xF9F5 => "6DCB", 0xF9F6 => "81E8", 0xF9F7 => "7ACB", 0xF9F8 => "7B20", 0xF9F9 => "7C92", 0xF9FA => "72C0", 0xF9FB => "7099", 0xF9FC => "8B58", 0xF9FD => "4EC0", 0xF9FE => "8336", 0xF9FF => "523A", 0xFA00 => "5207", 0xFA01 => "5EA6", 0xFA02 => "62D3", 0xFA03 => "7CD6", 0xFA04 => "5B85", 0xFA05 => "6D1E", 0xFA06 => "66B4", 0xFA07 => "8F3B", 0xFA08 => "884C", 0xFA09 => "964D", 0xFA0A => "898B", 0xFA0B => "5ED3", 0xFA0C => "5140", 0xFA0D => "55C0", 0xFA10 => "585A", 0xFA12 => "6674", 0xFA15 => "51DE", 0xFA16 => "732A", 0xFA17 => "76CA", 0xFA18 => "793C", 0xFA19 => "795E", 0xFA1A => "7965", 0xFA1B => "798F", 0xFA1C => "9756", 0xFA1D => "7CBE", 0xFA1E => "7FBD", 0xFA20 => "8612", 0xFA22 => "8AF8", 0xFA25 => "9038", 0xFA26 => "90FD", 0xFA2A => "98EF", 0xFA2B => "98FC", 0xFA2C => "9928", 0xFA2D => "9DB4", 0xFA2E => "90DE", 0xFA2F => "96B7", 0xFA30 => "4FAE", 0xFA31 => "50E7", 0xFA32 => "514D", 0xFA33 => "52C9", 0xFA34 => "52E4", 0xFA35 => "5351", 0xFA36 => "559D", 0xFA37 => "5606", 0xFA38 => "5668", 0xFA39 => "5840", 0xFA3A => "58A8", 0xFA3B => "5C64", 0xFA3C => "5C6E", 0xFA3D => "6094", 0xFA3E => "6168", 0xFA3F => "618E", 0xFA40 => "61F2", 0xFA41 => "654F", 0xFA42 => "65E2", 0xFA43 => "6691", 0xFA44 => "6885", 0xFA45 => "6D77", 0xFA46 => "6E1A", 0xFA47 => "6F22", 0xFA48 => "716E", 0xFA49 => "722B", 0xFA4A => "7422", 0xFA4B => "7891", 0xFA4C => "793E", 0xFA4D => "7949", 0xFA4E => "7948", 0xFA4F => "7950", 0xFA50 => "7956", 0xFA51 => "795D", 0xFA52 => "798D", 0xFA53 => "798E", 0xFA54 => "7A40", 0xFA55 => "7A81", 0xFA56 => "7BC0", 0xFA57 => "7DF4", 0xFA58 => "7E09", 0xFA59 => "7E41", 0xFA5A => "7F72", 0xFA5B => "8005", 0xFA5C => "81ED", 0xFA5D...0xFA5E => "8279", 0xFA5F => "8457", 0xFA60 => "8910", 0xFA61 => "8996", 0xFA62 => "8B01", 0xFA63 => "8B39", 0xFA64 => "8CD3", 0xFA65 => "8D08", 0xFA66 => "8FB6", 0xFA67 => "9038", 0xFA68 => "96E3", 0xFA69 => "97FF", 0xFA6A => "983B", 0xFA6B => "6075", 0xFA6C => "242EE", 0xFA6D => "8218", 0xFA70 => "4E26", 0xFA71 => "51B5", 0xFA72 => "5168", 0xFA73 => "4F80", 0xFA74 => "5145", 0xFA75 => "5180", 0xFA76 => "52C7", 0xFA77 => "52FA", 0xFA78 => "559D", 0xFA79 => "5555", 0xFA7A => "5599", 0xFA7B => "55E2", 0xFA7C => "585A", 0xFA7D => "58B3", 0xFA7E => "5944", 0xFA7F => "5954", 0xFA80 => "5A62", 0xFA81 => "5B28", 0xFA82 => "5ED2", 0xFA83 => "5ED9", 0xFA84 => "5F69", 0xFA85 => "5FAD", 0xFA86 => "60D8", 0xFA87 => "614E", 0xFA88 => "6108", 0xFA89 => "618E", 0xFA8A => "6160", 0xFA8B => "61F2", 0xFA8C => "6234", 0xFA8D => "63C4", 0xFA8E => "641C", 0xFA8F => "6452", 0xFA90 => "6556", 0xFA91 => "6674", 0xFA92 => "6717", 0xFA93 => "671B", 0xFA94 => "6756", 0xFA95 => "6B79", 0xFA96 => "6BBA", 0xFA97 => "6D41", 0xFA98 => "6EDB", 0xFA99 => "6ECB", 0xFA9A => "6F22", 0xFA9B => "701E", 0xFA9C => "716E", 0xFA9D => "77A7", 0xFA9E => "7235", 0xFA9F => "72AF", 0xFAA0 => "732A", 0xFAA1 => "7471", 0xFAA2 => "7506", 0xFAA3 => "753B", 0xFAA4 => "761D", 0xFAA5 => "761F", 0xFAA6 => "76CA", 0xFAA7 => "76DB", 0xFAA8 => "76F4", 0xFAA9 => "774A", 0xFAAA => "7740", 0xFAAB => "78CC", 0xFAAC => "7AB1", 0xFAAD => "7BC0", 0xFAAE => "7C7B", 0xFAAF => "7D5B", 0xFAB0 => "7DF4", 0xFAB1 => "7F3E", 0xFAB2 => "8005", 0xFAB3 => "8352", 0xFAB4 => "83EF", 0xFAB5 => "8779", 0xFAB6 => "8941", 0xFAB7 => "8986", 0xFAB8 => "8996", 0xFAB9 => "8ABF", 0xFABA => "8AF8", 0xFABB => "8ACB", 0xFABC => "8B01", 0xFABD => "8AFE", 0xFABE => "8AED", 0xFABF => "8B39", 0xFAC0 => "8B8A", 0xFAC1 => "8D08", 0xFAC2 => "8F38", 0xFAC3 => "9072", 0xFAC4 => "9199", 0xFAC5 => "9276", 0xFAC6 => "967C", 0xFAC7 => "96E3", 0xFAC8 => "9756", 0xFAC9 => "97DB", 0xFACA => "97FF", 0xFACB => "980B", 0xFACC => "983B", 0xFACD => "9B12", 0xFACE => "9F9C", 0xFACF => "2284A", 0xFAD0 => "22844", 0xFAD1 => "233D5", 0xFAD2 => "3B9D", 0xFAD3 => "4018", 0xFAD4 => "4039", 0xFAD5 => "25249", 0xFAD6 => "25CD0", 0xFAD7 => "27ED3", 0xFAD8 => "9F43", 0xFAD9 => "9F8E", 0xFB00 => "66,66", 0xFB01 => "66,69", 0xFB02 => "66,6C", 0xFB03 => "66,66,69", 0xFB04 => "66,66,6C", 0xFB05...0xFB06 => "73,74", 0xFB13 => "574,576", 0xFB14 => "574,565", 0xFB15 => "574,56B", 0xFB16 => "57E,576", 0xFB17 => "574,56D", 0xFB1D => "5D9,5B4", 0xFB1F => "5F2,5B7", 0xFB20 => "5E2", 0xFB21 => "5D0", 0xFB22 => "5D3", 0xFB23 => "5D4", 0xFB24 => "5DB", 0xFB25 => "5DC", 0xFB26 => "5DD", 0xFB27 => "5E8", 0xFB28 => "5EA", 0xFB29 => "2B", 0xFB2A => "5E9,5C1", 0xFB2B => "5E9,5C2", 0xFB2C => "5E9,5BC,5C1", 0xFB2D => "5E9,5BC,5C2", 0xFB2E => "5D0,5B7", 0xFB2F => "5D0,5B8", 0xFB30 => "5D0,5BC", 0xFB31 => "5D1,5BC", 0xFB32 => "5D2,5BC", 0xFB33 => "5D3,5BC", 0xFB34 => "5D4,5BC", 0xFB35 => "5D5,5BC", 0xFB36 => "5D6,5BC", 0xFB38 => "5D8,5BC", 0xFB39 => "5D9,5BC", 0xFB3A => "5DA,5BC", 0xFB3B => "5DB,5BC", 0xFB3C => "5DC,5BC", 0xFB3E => "5DE,5BC", 0xFB40 => "5E0,5BC", 0xFB41 => "5E1,5BC", 0xFB43 => "5E3,5BC", 0xFB44 => "5E4,5BC", 0xFB46 => "5E6,5BC", 0xFB47 => "5E7,5BC", 0xFB48 => "5E8,5BC", 0xFB49 => "5E9,5BC", 0xFB4A => "5EA,5BC", 0xFB4B => "5D5,5B9", 0xFB4C => "5D1,5BF", 0xFB4D => "5DB,5BF", 0xFB4E => "5E4,5BF", 0xFB4F => "5D0,5DC", 0xFB50...0xFB51 => "671", 0xFB52...0xFB55 => "67B", 0xFB56...0xFB59 => "67E", 0xFB5A...0xFB5D => "680", 0xFB5E...0xFB61 => "67A", 0xFB62...0xFB65 => "67F", 0xFB66...0xFB69 => "679", 0xFB6A...0xFB6D => "6A4", 0xFB6E...0xFB71 => "6A6", 0xFB72...0xFB75 => "684", 0xFB76...0xFB79 => "683", 0xFB7A...0xFB7D => "686", 0xFB7E...0xFB81 => "687", 0xFB82...0xFB83 => "68D", 0xFB84...0xFB85 => "68C", 0xFB86...0xFB87 => "68E", 0xFB88...0xFB89 => "688", 0xFB8A...0xFB8B => "698", 0xFB8C...0xFB8D => "691", 0xFB8E...0xFB91 => "6A9", 0xFB92...0xFB95 => "6AF", 0xFB96...0xFB99 => "6B3", 0xFB9A...0xFB9D => "6B1", 0xFB9E...0xFB9F => "6BA", 0xFBA0...0xFBA3 => "6BB", 0xFBA4...0xFBA5 => "6C0", 0xFBA6...0xFBA9 => "6C1", 0xFBAA...0xFBAD => "6BE", 0xFBAE...0xFBAF => "6D2", 0xFBB0...0xFBB1 => "6D3", 0xFBD3...0xFBD6 => "6AD", 0xFBD7...0xFBD8 => "6C7", 0xFBD9...0xFBDA => "6C6", 0xFBDB...0xFBDC => "6C8", 0xFBDD => "6C7,674", 0xFBDE...0xFBDF => "6CB", 0xFBE0...0xFBE1 => "6C5", 0xFBE2...0xFBE3 => "6C9", 0xFBE4...0xFBE7 => "6D0", 0xFBE8...0xFBE9 => "649", 0xFBEA...0xFBEB => "626,627", 0xFBEC...0xFBED => "626,6D5", 0xFBEE...0xFBEF => "626,648", 0xFBF0...0xFBF1 => "626,6C7", 0xFBF2...0xFBF3 => "626,6C6", 0xFBF4...0xFBF5 => "626,6C8", 0xFBF6...0xFBF8 => "626,6D0", 0xFBF9...0xFBFB => "626,649", 0xFBFC...0xFBFF => "6CC", 0xFC00 => "626,62C", 0xFC01 => "626,62D", 0xFC02 => "626,645", 0xFC03 => "626,649", 0xFC04 => "626,64A", 0xFC05 => "628,62C", 0xFC06 => "628,62D", 0xFC07 => "628,62E", 0xFC08 => "628,645", 0xFC09 => "628,649", 0xFC0A => "628,64A", 0xFC0B => "62A,62C", 0xFC0C => "62A,62D", 0xFC0D => "62A,62E", 0xFC0E => "62A,645", 0xFC0F => "62A,649", 0xFC10 => "62A,64A", 0xFC11 => "62B,62C", 0xFC12 => "62B,645", 0xFC13 => "62B,649", 0xFC14 => "62B,64A", 0xFC15 => "62C,62D", 0xFC16 => "62C,645", 0xFC17 => "62D,62C", 0xFC18 => "62D,645", 0xFC19 => "62E,62C", 0xFC1A => "62E,62D", 0xFC1B => "62E,645", 0xFC1C => "633,62C", 0xFC1D => "633,62D", 0xFC1E => "633,62E", 0xFC1F => "633,645", 0xFC20 => "635,62D", 0xFC21 => "635,645", 0xFC22 => "636,62C", 0xFC23 => "636,62D", 0xFC24 => "636,62E", 0xFC25 => "636,645", 0xFC26 => "637,62D", 0xFC27 => "637,645", 0xFC28 => "638,645", 0xFC29 => "639,62C", 0xFC2A => "639,645", 0xFC2B => "63A,62C", 0xFC2C => "63A,645", 0xFC2D => "641,62C", 0xFC2E => "641,62D", 0xFC2F => "641,62E", 0xFC30 => "641,645", 0xFC31 => "641,649", 0xFC32 => "641,64A", 0xFC33 => "642,62D", 0xFC34 => "642,645", 0xFC35 => "642,649", 0xFC36 => "642,64A", 0xFC37 => "643,627", 0xFC38 => "643,62C", 0xFC39 => "643,62D", 0xFC3A => "643,62E", 0xFC3B => "643,644", 0xFC3C => "643,645", 0xFC3D => "643,649", 0xFC3E => "643,64A", 0xFC3F => "644,62C", 0xFC40 => "644,62D", 0xFC41 => "644,62E", 0xFC42 => "644,645", 0xFC43 => "644,649", 0xFC44 => "644,64A", 0xFC45 => "645,62C", 0xFC46 => "645,62D", 0xFC47 => "645,62E", 0xFC48 => "645,645", 0xFC49 => "645,649", 0xFC4A => "645,64A", 0xFC4B => "646,62C", 0xFC4C => "646,62D", 0xFC4D => "646,62E", 0xFC4E => "646,645", 0xFC4F => "646,649", 0xFC50 => "646,64A", 0xFC51 => "647,62C", 0xFC52 => "647,645", 0xFC53 => "647,649", 0xFC54 => "647,64A", 0xFC55 => "64A,62C", 0xFC56 => "64A,62D", 0xFC57 => "64A,62E", 0xFC58 => "64A,645", 0xFC59 => "64A,649", 0xFC5A => "64A,64A", 0xFC5B => "630,670", 0xFC5C => "631,670", 0xFC5D => "649,670", 0xFC5E => "20,64C,651", 0xFC5F => "20,64D,651", 0xFC60 => "20,64E,651", 0xFC61 => "20,64F,651", 0xFC62 => "20,650,651", 0xFC63 => "20,651,670", 0xFC64 => "626,631", 0xFC65 => "626,632", 0xFC66 => "626,645", 0xFC67 => "626,646", 0xFC68 => "626,649", 0xFC69 => "626,64A", 0xFC6A => "628,631", 0xFC6B => "628,632", 0xFC6C => "628,645", 0xFC6D => "628,646", 0xFC6E => "628,649", 0xFC6F => "628,64A", 0xFC70 => "62A,631", 0xFC71 => "62A,632", 0xFC72 => "62A,645", 0xFC73 => "62A,646", 0xFC74 => "62A,649", 0xFC75 => "62A,64A", 0xFC76 => "62B,631", 0xFC77 => "62B,632", 0xFC78 => "62B,645", 0xFC79 => "62B,646", 0xFC7A => "62B,649", 0xFC7B => "62B,64A", 0xFC7C => "641,649", 0xFC7D => "641,64A", 0xFC7E => "642,649", 0xFC7F => "642,64A", 0xFC80 => "643,627", 0xFC81 => "643,644", 0xFC82 => "643,645", 0xFC83 => "643,649", 0xFC84 => "643,64A", 0xFC85 => "644,645", 0xFC86 => "644,649", 0xFC87 => "644,64A", 0xFC88 => "645,627", 0xFC89 => "645,645", 0xFC8A => "646,631", 0xFC8B => "646,632", 0xFC8C => "646,645", 0xFC8D => "646,646", 0xFC8E => "646,649", 0xFC8F => "646,64A", 0xFC90 => "649,670", 0xFC91 => "64A,631", 0xFC92 => "64A,632", 0xFC93 => "64A,645", 0xFC94 => "64A,646", 0xFC95 => "64A,649", 0xFC96 => "64A,64A", 0xFC97 => "626,62C", 0xFC98 => "626,62D", 0xFC99 => "626,62E", 0xFC9A => "626,645", 0xFC9B => "626,647", 0xFC9C => "628,62C", 0xFC9D => "628,62D", 0xFC9E => "628,62E", 0xFC9F => "628,645", 0xFCA0 => "628,647", 0xFCA1 => "62A,62C", 0xFCA2 => "62A,62D", 0xFCA3 => "62A,62E", 0xFCA4 => "62A,645", 0xFCA5 => "62A,647", 0xFCA6 => "62B,645", 0xFCA7 => "62C,62D", 0xFCA8 => "62C,645", 0xFCA9 => "62D,62C", 0xFCAA => "62D,645", 0xFCAB => "62E,62C", 0xFCAC => "62E,645", 0xFCAD => "633,62C", 0xFCAE => "633,62D", 0xFCAF => "633,62E", 0xFCB0 => "633,645", 0xFCB1 => "635,62D", 0xFCB2 => "635,62E", 0xFCB3 => "635,645", 0xFCB4 => "636,62C", 0xFCB5 => "636,62D", 0xFCB6 => "636,62E", 0xFCB7 => "636,645", 0xFCB8 => "637,62D", 0xFCB9 => "638,645", 0xFCBA => "639,62C", 0xFCBB => "639,645", 0xFCBC => "63A,62C", 0xFCBD => "63A,645", 0xFCBE => "641,62C", 0xFCBF => "641,62D", 0xFCC0 => "641,62E", 0xFCC1 => "641,645", 0xFCC2 => "642,62D", 0xFCC3 => "642,645", 0xFCC4 => "643,62C", 0xFCC5 => "643,62D", 0xFCC6 => "643,62E", 0xFCC7 => "643,644", 0xFCC8 => "643,645", 0xFCC9 => "644,62C", 0xFCCA => "644,62D", 0xFCCB => "644,62E", 0xFCCC => "644,645", 0xFCCD => "644,647", 0xFCCE => "645,62C", 0xFCCF => "645,62D", 0xFCD0 => "645,62E", 0xFCD1 => "645,645", 0xFCD2 => "646,62C", 0xFCD3 => "646,62D", 0xFCD4 => "646,62E", 0xFCD5 => "646,645", 0xFCD6 => "646,647", 0xFCD7 => "647,62C", 0xFCD8 => "647,645", 0xFCD9 => "647,670", 0xFCDA => "64A,62C", 0xFCDB => "64A,62D", 0xFCDC => "64A,62E", 0xFCDD => "64A,645", 0xFCDE => "64A,647", 0xFCDF => "626,645", 0xFCE0 => "626,647", 0xFCE1 => "628,645", 0xFCE2 => "628,647", 0xFCE3 => "62A,645", 0xFCE4 => "62A,647", 0xFCE5 => "62B,645", 0xFCE6 => "62B,647", 0xFCE7 => "633,645", 0xFCE8 => "633,647", 0xFCE9 => "634,645", 0xFCEA => "634,647", 0xFCEB => "643,644", 0xFCEC => "643,645", 0xFCED => "644,645", 0xFCEE => "646,645", 0xFCEF => "646,647", 0xFCF0 => "64A,645", 0xFCF1 => "64A,647", 0xFCF2 => "640,64E,651", 0xFCF3 => "640,64F,651", 0xFCF4 => "640,650,651", 0xFCF5 => "637,649", 0xFCF6 => "637,64A", 0xFCF7 => "639,649", 0xFCF8 => "639,64A", 0xFCF9 => "63A,649", 0xFCFA => "63A,64A", 0xFCFB => "633,649", 0xFCFC => "633,64A", 0xFCFD => "634,649", 0xFCFE => "634,64A", 0xFCFF => "62D,649", 0xFD00 => "62D,64A", 0xFD01 => "62C,649", 0xFD02 => "62C,64A", 0xFD03 => "62E,649", 0xFD04 => "62E,64A", 0xFD05 => "635,649", 0xFD06 => "635,64A", 0xFD07 => "636,649", 0xFD08 => "636,64A", 0xFD09 => "634,62C", 0xFD0A => "634,62D", 0xFD0B => "634,62E", 0xFD0C => "634,645", 0xFD0D => "634,631", 0xFD0E => "633,631", 0xFD0F => "635,631", 0xFD10 => "636,631", 0xFD11 => "637,649", 0xFD12 => "637,64A", 0xFD13 => "639,649", 0xFD14 => "639,64A", 0xFD15 => "63A,649", 0xFD16 => "63A,64A", 0xFD17 => "633,649", 0xFD18 => "633,64A", 0xFD19 => "634,649", 0xFD1A => "634,64A", 0xFD1B => "62D,649", 0xFD1C => "62D,64A", 0xFD1D => "62C,649", 0xFD1E => "62C,64A", 0xFD1F => "62E,649", 0xFD20 => "62E,64A", 0xFD21 => "635,649", 0xFD22 => "635,64A", 0xFD23 => "636,649", 0xFD24 => "636,64A", 0xFD25 => "634,62C", 0xFD26 => "634,62D", 0xFD27 => "634,62E", 0xFD28 => "634,645", 0xFD29 => "634,631", 0xFD2A => "633,631", 0xFD2B => "635,631", 0xFD2C => "636,631", 0xFD2D => "634,62C", 0xFD2E => "634,62D", 0xFD2F => "634,62E", 0xFD30 => "634,645", 0xFD31 => "633,647", 0xFD32 => "634,647", 0xFD33 => "637,645", 0xFD34 => "633,62C", 0xFD35 => "633,62D", 0xFD36 => "633,62E", 0xFD37 => "634,62C", 0xFD38 => "634,62D", 0xFD39 => "634,62E", 0xFD3A => "637,645", 0xFD3B => "638,645", 0xFD3C...0xFD3D => "627,64B", 0xFD50 => "62A,62C,645", 0xFD51...0xFD52 => "62A,62D,62C", 0xFD53 => "62A,62D,645", 0xFD54 => "62A,62E,645", 0xFD55 => "62A,645,62C", 0xFD56 => "62A,645,62D", 0xFD57 => "62A,645,62E", 0xFD58...0xFD59 => "62C,645,62D", 0xFD5A => "62D,645,64A", 0xFD5B => "62D,645,649", 0xFD5C => "633,62D,62C", 0xFD5D => "633,62C,62D", 0xFD5E => "633,62C,649", 0xFD5F...0xFD60 => "633,645,62D", 0xFD61 => "633,645,62C", 0xFD62...0xFD63 => "633,645,645", 0xFD64...0xFD65 => "635,62D,62D", 0xFD66 => "635,645,645", 0xFD67...0xFD68 => "634,62D,645", 0xFD69 => "634,62C,64A", 0xFD6A...0xFD6B => "634,645,62E", 0xFD6C...0xFD6D => "634,645,645", 0xFD6E => "636,62D,649", 0xFD6F...0xFD70 => "636,62E,645", 0xFD71...0xFD72 => "637,645,62D", 0xFD73 => "637,645,645", 0xFD74 => "637,645,64A", 0xFD75 => "639,62C,645", 0xFD76...0xFD77 => "639,645,645", 0xFD78 => "639,645,649", 0xFD79 => "63A,645,645", 0xFD7A => "63A,645,64A", 0xFD7B => "63A,645,649", 0xFD7C...0xFD7D => "641,62E,645", 0xFD7E => "642,645,62D", 0xFD7F => "642,645,645", 0xFD80 => "644,62D,645", 0xFD81 => "644,62D,64A", 0xFD82 => "644,62D,649", 0xFD83...0xFD84 => "644,62C,62C", 0xFD85...0xFD86 => "644,62E,645", 0xFD87...0xFD88 => "644,645,62D", 0xFD89 => "645,62D,62C", 0xFD8A => "645,62D,645", 0xFD8B => "645,62D,64A", 0xFD8C => "645,62C,62D", 0xFD8D => "645,62C,645", 0xFD8E => "645,62E,62C", 0xFD8F => "645,62E,645", 0xFD92 => "645,62C,62E", 0xFD93 => "647,645,62C", 0xFD94 => "647,645,645", 0xFD95 => "646,62D,645", 0xFD96 => "646,62D,649", 0xFD97...0xFD98 => "646,62C,645", 0xFD99 => "646,62C,649", 0xFD9A => "646,645,64A", 0xFD9B => "646,645,649", 0xFD9C...0xFD9D => "64A,645,645", 0xFD9E => "628,62E,64A", 0xFD9F => "62A,62C,64A", 0xFDA0 => "62A,62C,649", 0xFDA1 => "62A,62E,64A", 0xFDA2 => "62A,62E,649", 0xFDA3 => "62A,645,64A", 0xFDA4 => "62A,645,649", 0xFDA5 => "62C,645,64A", 0xFDA6 => "62C,62D,649", 0xFDA7 => "62C,645,649", 0xFDA8 => "633,62E,649", 0xFDA9 => "635,62D,64A", 0xFDAA => "634,62D,64A", 0xFDAB => "636,62D,64A", 0xFDAC => "644,62C,64A", 0xFDAD => "644,645,64A", 0xFDAE => "64A,62D,64A", 0xFDAF => "64A,62C,64A", 0xFDB0 => "64A,645,64A", 0xFDB1 => "645,645,64A", 0xFDB2 => "642,645,64A", 0xFDB3 => "646,62D,64A", 0xFDB4 => "642,645,62D", 0xFDB5 => "644,62D,645", 0xFDB6 => "639,645,64A", 0xFDB7 => "643,645,64A", 0xFDB8 => "646,62C,62D", 0xFDB9 => "645,62E,64A", 0xFDBA => "644,62C,645", 0xFDBB => "643,645,645", 0xFDBC => "644,62C,645", 0xFDBD => "646,62C,62D", 0xFDBE => "62C,62D,64A", 0xFDBF => "62D,62C,64A", 0xFDC0 => "645,62C,64A", 0xFDC1 => "641,645,64A", 0xFDC2 => "628,62D,64A", 0xFDC3 => "643,645,645", 0xFDC4 => "639,62C,645", 0xFDC5 => "635,645,645", 0xFDC6 => "633,62E,64A", 0xFDC7 => "646,62C,64A", 0xFDF0 => "635,644,6D2", 0xFDF1 => "642,644,6D2", 0xFDF2 => "627,644,644,647", 0xFDF3 => "627,643,628,631", 0xFDF4 => "645,62D,645,62F", 0xFDF5 => "635,644,639,645", 0xFDF6 => "631,633,648,644", 0xFDF7 => "639,644,64A,647", 0xFDF8 => "648,633,644,645", 0xFDF9 => "635,644,649", 0xFDFA => "635,644,649,20,627,644,644,647,20,639,644,64A,647,20,648,633,644,645", 0xFDFB => "62C,644,20,62C,644,627,644,647", 0xFDFC => "631,6CC,627,644", 0xFE00...0xFE0F => "0", 0xFE10 => "2C", 0xFE11 => "3001", 0xFE12 => "3002", 0xFE13 => "3A", 0xFE14 => "3B", 0xFE15 => "21", 0xFE16 => "3F", 0xFE17 => "3016", 0xFE18 => "3017", 0xFE19 => "2E,2E,2E", 0xFE30 => "2E,2E", 0xFE31 => "2014", 0xFE32 => "2013", 0xFE33...0xFE34 => "5F", 0xFE35 => "28", 0xFE36 => "29", 0xFE37 => "7B", 0xFE38 => "7D", 0xFE39 => "3014", 0xFE3A => "3015", 0xFE3B => "3010", 0xFE3C => "3011", 0xFE3D => "300A", 0xFE3E => "300B", 0xFE3F => "3008", 0xFE40 => "3009", 0xFE41 => "300C", 0xFE42 => "300D", 0xFE43 => "300E", 0xFE44 => "300F", 0xFE47 => "5B", 0xFE48 => "5D", 0xFE49...0xFE4C => "20,305", 0xFE4D...0xFE4F => "5F", 0xFE50 => "2C", 0xFE51 => "3001", 0xFE52 => "2E", 0xFE54 => "3B", 0xFE55 => "3A", 0xFE56 => "3F", 0xFE57 => "21", 0xFE58 => "2014", 0xFE59 => "28", 0xFE5A => "29", 0xFE5B => "7B", 0xFE5C => "7D", 0xFE5D => "3014", 0xFE5E => "3015", 0xFE5F => "23", 0xFE60 => "26", 0xFE61 => "2A", 0xFE62 => "2B", 0xFE63 => "2D", 0xFE64 => "3C", 0xFE65 => "3E", 0xFE66 => "3D", 0xFE68 => "5C", 0xFE69 => "24", 0xFE6A => "25", 0xFE6B => "40", 0xFE70 => "20,64B", 0xFE71 => "640,64B", 0xFE72 => "20,64C", 0xFE74 => "20,64D", 0xFE76 => "20,64E", 0xFE77 => "640,64E", 0xFE78 => "20,64F", 0xFE79 => "640,64F", 0xFE7A => "20,650", 0xFE7B => "640,650", 0xFE7C => "20,651", 0xFE7D => "640,651", 0xFE7E => "20,652", 0xFE7F => "640,652", 0xFE80 => "621", 0xFE81...0xFE82 => "622", 0xFE83...0xFE84 => "623", 0xFE85...0xFE86 => "624", 0xFE87...0xFE88 => "625", 0xFE89...0xFE8C => "626", 0xFE8D...0xFE8E => "627", 0xFE8F...0xFE92 => "628", 0xFE93...0xFE94 => "629", 0xFE95...0xFE98 => "62A", 0xFE99...0xFE9C => "62B", 0xFE9D...0xFEA0 => "62C", 0xFEA1...0xFEA4 => "62D", 0xFEA5...0xFEA8 => "62E", 0xFEA9...0xFEAA => "62F", 0xFEAB...0xFEAC => "630", 0xFEAD...0xFEAE => "631", 0xFEAF...0xFEB0 => "632", 0xFEB1...0xFEB4 => "633", 0xFEB5...0xFEB8 => "634", 0xFEB9...0xFEBC => "635", 0xFEBD...0xFEC0 => "636", 0xFEC1...0xFEC4 => "637", 0xFEC5...0xFEC8 => "638", 0xFEC9...0xFECC => "639", 0xFECD...0xFED0 => "63A", 0xFED1...0xFED4 => "641", 0xFED5...0xFED8 => "642", 0xFED9...0xFEDC => "643", 0xFEDD...0xFEE0 => "644", 0xFEE1...0xFEE4 => "645", 0xFEE5...0xFEE8 => "646", 0xFEE9...0xFEEC => "647", 0xFEED...0xFEEE => "648", 0xFEEF...0xFEF0 => "649", 0xFEF1...0xFEF4 => "64A", 0xFEF5...0xFEF6 => "644,622", 0xFEF7...0xFEF8 => "644,623", 0xFEF9...0xFEFA => "644,625", 0xFEFB...0xFEFC => "644,627", 0xFEFF => "0", 0xFF01 => "21", 0xFF02 => "22", 0xFF03 => "23", 0xFF04 => "24", 0xFF05 => "25", 0xFF06 => "26", 0xFF07 => "27", 0xFF08 => "28", 0xFF09 => "29", 0xFF0A => "2A", 0xFF0B => "2B", 0xFF0C => "2C", 0xFF0D => "2D", 0xFF0E => "2E", 0xFF0F => "2F", 0xFF10 => "30", 0xFF11 => "31", 0xFF12 => "32", 0xFF13 => "33", 0xFF14 => "34", 0xFF15 => "35", 0xFF16 => "36", 0xFF17 => "37", 0xFF18 => "38", 0xFF19 => "39", 0xFF1A => "3A", 0xFF1B => "3B", 0xFF1C => "3C", 0xFF1D => "3D", 0xFF1E => "3E", 0xFF1F => "3F", 0xFF20 => "40", 0xFF21 => "61", 0xFF22 => "62", 0xFF23 => "63", 0xFF24 => "64", 0xFF25 => "65", 0xFF26 => "66", 0xFF27 => "67", 0xFF28 => "68", 0xFF29 => "69", 0xFF2A => "6A", 0xFF2B => "6B", 0xFF2C => "6C", 0xFF2D => "6D", 0xFF2E => "6E", 0xFF2F => "6F", 0xFF30 => "70", 0xFF31 => "71", 0xFF32 => "72", 0xFF33 => "73", 0xFF34 => "74", 0xFF35 => "75", 0xFF36 => "76", 0xFF37 => "77", 0xFF38 => "78", 0xFF39 => "79", 0xFF3A => "7A", 0xFF3B => "5B", 0xFF3C => "5C", 0xFF3D => "5D", 0xFF3E => "5E", 0xFF3F => "5F", 0xFF40 => "60", 0xFF41 => "61", 0xFF42 => "62", 0xFF43 => "63", 0xFF44 => "64", 0xFF45 => "65", 0xFF46 => "66", 0xFF47 => "67", 0xFF48 => "68", 0xFF49 => "69", 0xFF4A => "6A", 0xFF4B => "6B", 0xFF4C => "6C", 0xFF4D => "6D", 0xFF4E => "6E", 0xFF4F => "6F", 0xFF50 => "70", 0xFF51 => "71", 0xFF52 => "72", 0xFF53 => "73", 0xFF54 => "74", 0xFF55 => "75", 0xFF56 => "76", 0xFF57 => "77", 0xFF58 => "78", 0xFF59 => "79", 0xFF5A => "7A", 0xFF5B => "7B", 0xFF5C => "7C", 0xFF5D => "7D", 0xFF5E => "7E", 0xFF5F => "2985", 0xFF60 => "2986", 0xFF61 => "3002", 0xFF62 => "300C", 0xFF63 => "300D", 0xFF64 => "3001", 0xFF65 => "30FB", 0xFF66 => "30F2", 0xFF67 => "30A1", 0xFF68 => "30A3", 0xFF69 => "30A5", 0xFF6A => "30A7", 0xFF6B => "30A9", 0xFF6C => "30E3", 0xFF6D => "30E5", 0xFF6E => "30E7", 0xFF6F => "30C3", 0xFF70 => "30FC", 0xFF71 => "30A2", 0xFF72 => "30A4", 0xFF73 => "30A6", 0xFF74 => "30A8", 0xFF75 => "30AA", 0xFF76 => "30AB", 0xFF77 => "30AD", 0xFF78 => "30AF", 0xFF79 => "30B1", 0xFF7A => "30B3", 0xFF7B => "30B5", 0xFF7C => "30B7", 0xFF7D => "30B9", 0xFF7E => "30BB", 0xFF7F => "30BD", 0xFF80 => "30BF", 0xFF81 => "30C1", 0xFF82 => "30C4", 0xFF83 => "30C6", 0xFF84 => "30C8", 0xFF85 => "30CA", 0xFF86 => "30CB", 0xFF87 => "30CC", 0xFF88 => "30CD", 0xFF89 => "30CE", 0xFF8A => "30CF", 0xFF8B => "30D2", 0xFF8C => "30D5", 0xFF8D => "30D8", 0xFF8E => "30DB", 0xFF8F => "30DE", 0xFF90 => "30DF", 0xFF91 => "30E0", 0xFF92 => "30E1", 0xFF93 => "30E2", 0xFF94 => "30E4", 0xFF95 => "30E6", 0xFF96 => "30E8", 0xFF97 => "30E9", 0xFF98 => "30EA", 0xFF99 => "30EB", 0xFF9A => "30EC", 0xFF9B => "30ED", 0xFF9C => "30EF", 0xFF9D => "30F3", 0xFF9E => "3099", 0xFF9F => "309A", 0xFFA0 => "0", 0xFFA1 => "1100", 0xFFA2 => "1101", 0xFFA3 => "11AA", 0xFFA4 => "1102", 0xFFA5 => "11AC", 0xFFA6 => "11AD", 0xFFA7 => "1103", 0xFFA8 => "1104", 0xFFA9 => "1105", 0xFFAA => "11B0", 0xFFAB => "11B1", 0xFFAC => "11B2", 0xFFAD => "11B3", 0xFFAE => "11B4", 0xFFAF => "11B5", 0xFFB0 => "111A", 0xFFB1 => "1106", 0xFFB2 => "1107", 0xFFB3 => "1108", 0xFFB4 => "1121", 0xFFB5 => "1109", 0xFFB6 => "110A", 0xFFB7 => "110B", 0xFFB8 => "110C", 0xFFB9 => "110D", 0xFFBA => "110E", 0xFFBB => "110F", 0xFFBC => "1110", 0xFFBD => "1111", 0xFFBE => "1112", 0xFFC2 => "1161", 0xFFC3 => "1162", 0xFFC4 => "1163", 0xFFC5 => "1164", 0xFFC6 => "1165", 0xFFC7 => "1166", 0xFFCA => "1167", 0xFFCB => "1168", 0xFFCC => "1169", 0xFFCD => "116A", 0xFFCE => "116B", 0xFFCF => "116C", 0xFFD2 => "116D", 0xFFD3 => "116E", 0xFFD4 => "116F", 0xFFD5 => "1170", 0xFFD6 => "1171", 0xFFD7 => "1172", 0xFFDA => "1173", 0xFFDB => "1174", 0xFFDC => "1175", 0xFFE0 => "A2", 0xFFE1 => "A3", 0xFFE2 => "AC", 0xFFE3 => "20,304", 0xFFE4 => "A6", 0xFFE5 => "A5", 0xFFE6 => "20A9", 0xFFE8 => "2502", 0xFFE9 => "2190", 0xFFEA => "2191", 0xFFEB => "2192", 0xFFEC => "2193", 0xFFED => "25A0", 0xFFEE => "25CB", 0xFFF0...0xFFF8 => "0", 0x10400 => "10428", 0x10401 => "10429", 0x10402 => "1042A", 0x10403 => "1042B", 0x10404 => "1042C", 0x10405 => "1042D", 0x10406 => "1042E", 0x10407 => "1042F", 0x10408 => "10430", 0x10409 => "10431", 0x1040A => "10432", 0x1040B => "10433", 0x1040C => "10434", 0x1040D => "10435", 0x1040E => "10436", 0x1040F => "10437", 0x10410 => "10438", 0x10411 => "10439", 0x10412 => "1043A", 0x10413 => "1043B", 0x10414 => "1043C", 0x10415 => "1043D", 0x10416 => "1043E", 0x10417 => "1043F", 0x10418 => "10440", 0x10419 => "10441", 0x1041A => "10442", 0x1041B => "10443", 0x1041C => "10444", 0x1041D => "10445", 0x1041E => "10446", 0x1041F => "10447", 0x10420 => "10448", 0x10421 => "10449", 0x10422 => "1044A", 0x10423 => "1044B", 0x10424 => "1044C", 0x10425 => "1044D", 0x10426 => "1044E", 0x10427 => "1044F", 0x104B0 => "104D8", 0x104B1 => "104D9", 0x104B2 => "104DA", 0x104B3 => "104DB", 0x104B4 => "104DC", 0x104B5 => "104DD", 0x104B6 => "104DE", 0x104B7 => "104DF", 0x104B8 => "104E0", 0x104B9 => "104E1", 0x104BA => "104E2", 0x104BB => "104E3", 0x104BC => "104E4", 0x104BD => "104E5", 0x104BE => "104E6", 0x104BF => "104E7", 0x104C0 => "104E8", 0x104C1 => "104E9", 0x104C2 => "104EA", 0x104C3 => "104EB", 0x104C4 => "104EC", 0x104C5 => "104ED", 0x104C6 => "104EE", 0x104C7 => "104EF", 0x104C8 => "104F0", 0x104C9 => "104F1", 0x104CA => "104F2", 0x104CB => "104F3", 0x104CC => "104F4", 0x104CD => "104F5", 0x104CE => "104F6", 0x104CF => "104F7", 0x104D0 => "104F8", 0x104D1 => "104F9", 0x104D2 => "104FA", 0x104D3 => "104FB", 0x10570 => "10597", 0x10571 => "10598", 0x10572 => "10599", 0x10573 => "1059A", 0x10574 => "1059B", 0x10575 => "1059C", 0x10576 => "1059D", 0x10577 => "1059E", 0x10578 => "1059F", 0x10579 => "105A0", 0x1057A => "105A1", 0x1057C => "105A3", 0x1057D => "105A4", 0x1057E => "105A5", 0x1057F => "105A6", 0x10580 => "105A7", 0x10581 => "105A8", 0x10582 => "105A9", 0x10583 => "105AA", 0x10584 => "105AB", 0x10585 => "105AC", 0x10586 => "105AD", 0x10587 => "105AE", 0x10588 => "105AF", 0x10589 => "105B0", 0x1058A => "105B1", 0x1058C => "105B3", 0x1058D => "105B4", 0x1058E => "105B5", 0x1058F => "105B6", 0x10590 => "105B7", 0x10591 => "105B8", 0x10592 => "105B9", 0x10594 => "105BB", 0x10595 => "105BC", 0x10781 => "2D0", 0x10782 => "2D1", 0x10783 => "E6", 0x10784 => "299", 0x10785 => "253", 0x10787 => "2A3", 0x10788 => "AB66", 0x10789 => "2A5", 0x1078A => "2A4", 0x1078B => "256", 0x1078C => "257", 0x1078D => "1D91", 0x1078E => "258", 0x1078F => "25E", 0x10790 => "2A9", 0x10791 => "264", 0x10792 => "262", 0x10793 => "260", 0x10794 => "29B", 0x10795 => "127", 0x10796 => "29C", 0x10797 => "267", 0x10798 => "284", 0x10799 => "2AA", 0x1079A => "2AB", 0x1079B => "26C", 0x1079C => "1DF04", 0x1079D => "A78E", 0x1079E => "26E", 0x1079F => "1DF05", 0x107A0 => "28E", 0x107A1 => "1DF06", 0x107A2 => "F8", 0x107A3 => "276", 0x107A4 => "277", 0x107A5 => "71", 0x107A6 => "27A", 0x107A7 => "1DF08", 0x107A8 => "27D", 0x107A9 => "27E", 0x107AA => "280", 0x107AB => "2A8", 0x107AC => "2A6", 0x107AD => "AB67", 0x107AE => "2A7", 0x107AF => "288", 0x107B0 => "2C71", 0x107B2 => "28F", 0x107B3 => "2A1", 0x107B4 => "2A2", 0x107B5 => "298", 0x107B6 => "1C0", 0x107B7 => "1C1", 0x107B8 => "1C2", 0x107B9 => "1DF0A", 0x107BA => "1DF1E", 0x10C80 => "10CC0", 0x10C81 => "10CC1", 0x10C82 => "10CC2", 0x10C83 => "10CC3", 0x10C84 => "10CC4", 0x10C85 => "10CC5", 0x10C86 => "10CC6", 0x10C87 => "10CC7", 0x10C88 => "10CC8", 0x10C89 => "10CC9", 0x10C8A => "10CCA", 0x10C8B => "10CCB", 0x10C8C => "10CCC", 0x10C8D => "10CCD", 0x10C8E => "10CCE", 0x10C8F => "10CCF", 0x10C90 => "10CD0", 0x10C91 => "10CD1", 0x10C92 => "10CD2", 0x10C93 => "10CD3", 0x10C94 => "10CD4", 0x10C95 => "10CD5", 0x10C96 => "10CD6", 0x10C97 => "10CD7", 0x10C98 => "10CD8", 0x10C99 => "10CD9", 0x10C9A => "10CDA", 0x10C9B => "10CDB", 0x10C9C => "10CDC", 0x10C9D => "10CDD", 0x10C9E => "10CDE", 0x10C9F => "10CDF", 0x10CA0 => "10CE0", 0x10CA1 => "10CE1", 0x10CA2 => "10CE2", 0x10CA3 => "10CE3", 0x10CA4 => "10CE4", 0x10CA5 => "10CE5", 0x10CA6 => "10CE6", 0x10CA7 => "10CE7", 0x10CA8 => "10CE8", 0x10CA9 => "10CE9", 0x10CAA => "10CEA", 0x10CAB => "10CEB", 0x10CAC => "10CEC", 0x10CAD => "10CED", 0x10CAE => "10CEE", 0x10CAF => "10CEF", 0x10CB0 => "10CF0", 0x10CB1 => "10CF1", 0x10CB2 => "10CF2", 0x118A0 => "118C0", 0x118A1 => "118C1", 0x118A2 => "118C2", 0x118A3 => "118C3", 0x118A4 => "118C4", 0x118A5 => "118C5", 0x118A6 => "118C6", 0x118A7 => "118C7", 0x118A8 => "118C8", 0x118A9 => "118C9", 0x118AA => "118CA", 0x118AB => "118CB", 0x118AC => "118CC", 0x118AD => "118CD", 0x118AE => "118CE", 0x118AF => "118CF", 0x118B0 => "118D0", 0x118B1 => "118D1", 0x118B2 => "118D2", 0x118B3 => "118D3", 0x118B4 => "118D4", 0x118B5 => "118D5", 0x118B6 => "118D6", 0x118B7 => "118D7", 0x118B8 => "118D8", 0x118B9 => "118D9", 0x118BA => "118DA", 0x118BB => "118DB", 0x118BC => "118DC", 0x118BD => "118DD", 0x118BE => "118DE", 0x118BF => "118DF", 0x16E40 => "16E60", 0x16E41 => "16E61", 0x16E42 => "16E62", 0x16E43 => "16E63", 0x16E44 => "16E64", 0x16E45 => "16E65", 0x16E46 => "16E66", 0x16E47 => "16E67", 0x16E48 => "16E68", 0x16E49 => "16E69", 0x16E4A => "16E6A", 0x16E4B => "16E6B", 0x16E4C => "16E6C", 0x16E4D => "16E6D", 0x16E4E => "16E6E", 0x16E4F => "16E6F", 0x16E50 => "16E70", 0x16E51 => "16E71", 0x16E52 => "16E72", 0x16E53 => "16E73", 0x16E54 => "16E74", 0x16E55 => "16E75", 0x16E56 => "16E76", 0x16E57 => "16E77", 0x16E58 => "16E78", 0x16E59 => "16E79", 0x16E5A => "16E7A", 0x16E5B => "16E7B", 0x16E5C => "16E7C", 0x16E5D => "16E7D", 0x16E5E => "16E7E", 0x16E5F => "16E7F", 0x1BCA0...0x1BCA3 => "0", 0x1D15E => "1D157,1D165", 0x1D15F => "1D158,1D165", 0x1D160 => "1D158,1D165,1D16E", 0x1D161 => "1D158,1D165,1D16F", 0x1D162 => "1D158,1D165,1D170", 0x1D163 => "1D158,1D165,1D171", 0x1D164 => "1D158,1D165,1D172", 0x1D173...0x1D17A => "0", 0x1D1BB => "1D1B9,1D165", 0x1D1BC => "1D1BA,1D165", 0x1D1BD => "1D1B9,1D165,1D16E", 0x1D1BE => "1D1BA,1D165,1D16E", 0x1D1BF => "1D1B9,1D165,1D16F", 0x1D1C0 => "1D1BA,1D165,1D16F", 0x1D400 => "61", 0x1D401 => "62", 0x1D402 => "63", 0x1D403 => "64", 0x1D404 => "65", 0x1D405 => "66", 0x1D406 => "67", 0x1D407 => "68", 0x1D408 => "69", 0x1D409 => "6A", 0x1D40A => "6B", 0x1D40B => "6C", 0x1D40C => "6D", 0x1D40D => "6E", 0x1D40E => "6F", 0x1D40F => "70", 0x1D410 => "71", 0x1D411 => "72", 0x1D412 => "73", 0x1D413 => "74", 0x1D414 => "75", 0x1D415 => "76", 0x1D416 => "77", 0x1D417 => "78", 0x1D418 => "79", 0x1D419 => "7A", 0x1D41A => "61", 0x1D41B => "62", 0x1D41C => "63", 0x1D41D => "64", 0x1D41E => "65", 0x1D41F => "66", 0x1D420 => "67", 0x1D421 => "68", 0x1D422 => "69", 0x1D423 => "6A", 0x1D424 => "6B", 0x1D425 => "6C", 0x1D426 => "6D", 0x1D427 => "6E", 0x1D428 => "6F", 0x1D429 => "70", 0x1D42A => "71", 0x1D42B => "72", 0x1D42C => "73", 0x1D42D => "74", 0x1D42E => "75", 0x1D42F => "76", 0x1D430 => "77", 0x1D431 => "78", 0x1D432 => "79", 0x1D433 => "7A", 0x1D434 => "61", 0x1D435 => "62", 0x1D436 => "63", 0x1D437 => "64", 0x1D438 => "65", 0x1D439 => "66", 0x1D43A => "67", 0x1D43B => "68", 0x1D43C => "69", 0x1D43D => "6A", 0x1D43E => "6B", 0x1D43F => "6C", 0x1D440 => "6D", 0x1D441 => "6E", 0x1D442 => "6F", 0x1D443 => "70", 0x1D444 => "71", 0x1D445 => "72", 0x1D446 => "73", 0x1D447 => "74", 0x1D448 => "75", 0x1D449 => "76", 0x1D44A => "77", 0x1D44B => "78", 0x1D44C => "79", 0x1D44D => "7A", 0x1D44E => "61", 0x1D44F => "62", 0x1D450 => "63", 0x1D451 => "64", 0x1D452 => "65", 0x1D453 => "66", 0x1D454 => "67", 0x1D456 => "69", 0x1D457 => "6A", 0x1D458 => "6B", 0x1D459 => "6C", 0x1D45A => "6D", 0x1D45B => "6E", 0x1D45C => "6F", 0x1D45D => "70", 0x1D45E => "71", 0x1D45F => "72", 0x1D460 => "73", 0x1D461 => "74", 0x1D462 => "75", 0x1D463 => "76", 0x1D464 => "77", 0x1D465 => "78", 0x1D466 => "79", 0x1D467 => "7A", 0x1D468 => "61", 0x1D469 => "62", 0x1D46A => "63", 0x1D46B => "64", 0x1D46C => "65", 0x1D46D => "66", 0x1D46E => "67", 0x1D46F => "68", 0x1D470 => "69", 0x1D471 => "6A", 0x1D472 => "6B", 0x1D473 => "6C", 0x1D474 => "6D", 0x1D475 => "6E", 0x1D476 => "6F", 0x1D477 => "70", 0x1D478 => "71", 0x1D479 => "72", 0x1D47A => "73", 0x1D47B => "74", 0x1D47C => "75", 0x1D47D => "76", 0x1D47E => "77", 0x1D47F => "78", 0x1D480 => "79", 0x1D481 => "7A", 0x1D482 => "61", 0x1D483 => "62", 0x1D484 => "63", 0x1D485 => "64", 0x1D486 => "65", 0x1D487 => "66", 0x1D488 => "67", 0x1D489 => "68", 0x1D48A => "69", 0x1D48B => "6A", 0x1D48C => "6B", 0x1D48D => "6C", 0x1D48E => "6D", 0x1D48F => "6E", 0x1D490 => "6F", 0x1D491 => "70", 0x1D492 => "71", 0x1D493 => "72", 0x1D494 => "73", 0x1D495 => "74", 0x1D496 => "75", 0x1D497 => "76", 0x1D498 => "77", 0x1D499 => "78", 0x1D49A => "79", 0x1D49B => "7A", 0x1D49C => "61", 0x1D49E => "63", 0x1D49F => "64", 0x1D4A2 => "67", 0x1D4A5 => "6A", 0x1D4A6 => "6B", 0x1D4A9 => "6E", 0x1D4AA => "6F", 0x1D4AB => "70", 0x1D4AC => "71", 0x1D4AE => "73", 0x1D4AF => "74", 0x1D4B0 => "75", 0x1D4B1 => "76", 0x1D4B2 => "77", 0x1D4B3 => "78", 0x1D4B4 => "79", 0x1D4B5 => "7A", 0x1D4B6 => "61", 0x1D4B7 => "62", 0x1D4B8 => "63", 0x1D4B9 => "64", 0x1D4BB => "66", 0x1D4BD => "68", 0x1D4BE => "69", 0x1D4BF => "6A", 0x1D4C0 => "6B", 0x1D4C1 => "6C", 0x1D4C2 => "6D", 0x1D4C3 => "6E", 0x1D4C5 => "70", 0x1D4C6 => "71", 0x1D4C7 => "72", 0x1D4C8 => "73", 0x1D4C9 => "74", 0x1D4CA => "75", 0x1D4CB => "76", 0x1D4CC => "77", 0x1D4CD => "78", 0x1D4CE => "79", 0x1D4CF => "7A", 0x1D4D0 => "61", 0x1D4D1 => "62", 0x1D4D2 => "63", 0x1D4D3 => "64", 0x1D4D4 => "65", 0x1D4D5 => "66", 0x1D4D6 => "67", 0x1D4D7 => "68", 0x1D4D8 => "69", 0x1D4D9 => "6A", 0x1D4DA => "6B", 0x1D4DB => "6C", 0x1D4DC => "6D", 0x1D4DD => "6E", 0x1D4DE => "6F", 0x1D4DF => "70", 0x1D4E0 => "71", 0x1D4E1 => "72", 0x1D4E2 => "73", 0x1D4E3 => "74", 0x1D4E4 => "75", 0x1D4E5 => "76", 0x1D4E6 => "77", 0x1D4E7 => "78", 0x1D4E8 => "79", 0x1D4E9 => "7A", 0x1D4EA => "61", 0x1D4EB => "62", 0x1D4EC => "63", 0x1D4ED => "64", 0x1D4EE => "65", 0x1D4EF => "66", 0x1D4F0 => "67", 0x1D4F1 => "68", 0x1D4F2 => "69", 0x1D4F3 => "6A", 0x1D4F4 => "6B", 0x1D4F5 => "6C", 0x1D4F6 => "6D", 0x1D4F7 => "6E", 0x1D4F8 => "6F", 0x1D4F9 => "70", 0x1D4FA => "71", 0x1D4FB => "72", 0x1D4FC => "73", 0x1D4FD => "74", 0x1D4FE => "75", 0x1D4FF => "76", 0x1D500 => "77", 0x1D501 => "78", 0x1D502 => "79", 0x1D503 => "7A", 0x1D504 => "61", 0x1D505 => "62", 0x1D507 => "64", 0x1D508 => "65", 0x1D509 => "66", 0x1D50A => "67", 0x1D50D => "6A", 0x1D50E => "6B", 0x1D50F => "6C", 0x1D510 => "6D", 0x1D511 => "6E", 0x1D512 => "6F", 0x1D513 => "70", 0x1D514 => "71", 0x1D516 => "73", 0x1D517 => "74", 0x1D518 => "75", 0x1D519 => "76", 0x1D51A => "77", 0x1D51B => "78", 0x1D51C => "79", 0x1D51E => "61", 0x1D51F => "62", 0x1D520 => "63", 0x1D521 => "64", 0x1D522 => "65", 0x1D523 => "66", 0x1D524 => "67", 0x1D525 => "68", 0x1D526 => "69", 0x1D527 => "6A", 0x1D528 => "6B", 0x1D529 => "6C", 0x1D52A => "6D", 0x1D52B => "6E", 0x1D52C => "6F", 0x1D52D => "70", 0x1D52E => "71", 0x1D52F => "72", 0x1D530 => "73", 0x1D531 => "74", 0x1D532 => "75", 0x1D533 => "76", 0x1D534 => "77", 0x1D535 => "78", 0x1D536 => "79", 0x1D537 => "7A", 0x1D538 => "61", 0x1D539 => "62", 0x1D53B => "64", 0x1D53C => "65", 0x1D53D => "66", 0x1D53E => "67", 0x1D540 => "69", 0x1D541 => "6A", 0x1D542 => "6B", 0x1D543 => "6C", 0x1D544 => "6D", 0x1D546 => "6F", 0x1D54A => "73", 0x1D54B => "74", 0x1D54C => "75", 0x1D54D => "76", 0x1D54E => "77", 0x1D54F => "78", 0x1D550 => "79", 0x1D552 => "61", 0x1D553 => "62", 0x1D554 => "63", 0x1D555 => "64", 0x1D556 => "65", 0x1D557 => "66", 0x1D558 => "67", 0x1D559 => "68", 0x1D55A => "69", 0x1D55B => "6A", 0x1D55C => "6B", 0x1D55D => "6C", 0x1D55E => "6D", 0x1D55F => "6E", 0x1D560 => "6F", 0x1D561 => "70", 0x1D562 => "71", 0x1D563 => "72", 0x1D564 => "73", 0x1D565 => "74", 0x1D566 => "75", 0x1D567 => "76", 0x1D568 => "77", 0x1D569 => "78", 0x1D56A => "79", 0x1D56B => "7A", 0x1D56C => "61", 0x1D56D => "62", 0x1D56E => "63", 0x1D56F => "64", 0x1D570 => "65", 0x1D571 => "66", 0x1D572 => "67", 0x1D573 => "68", 0x1D574 => "69", 0x1D575 => "6A", 0x1D576 => "6B", 0x1D577 => "6C", 0x1D578 => "6D", 0x1D579 => "6E", 0x1D57A => "6F", 0x1D57B => "70", 0x1D57C => "71", 0x1D57D => "72", 0x1D57E => "73", 0x1D57F => "74", 0x1D580 => "75", 0x1D581 => "76", 0x1D582 => "77", 0x1D583 => "78", 0x1D584 => "79", 0x1D585 => "7A", 0x1D586 => "61", 0x1D587 => "62", 0x1D588 => "63", 0x1D589 => "64", 0x1D58A => "65", 0x1D58B => "66", 0x1D58C => "67", 0x1D58D => "68", 0x1D58E => "69", 0x1D58F => "6A", 0x1D590 => "6B", 0x1D591 => "6C", 0x1D592 => "6D", 0x1D593 => "6E", 0x1D594 => "6F", 0x1D595 => "70", 0x1D596 => "71", 0x1D597 => "72", 0x1D598 => "73", 0x1D599 => "74", 0x1D59A => "75", 0x1D59B => "76", 0x1D59C => "77", 0x1D59D => "78", 0x1D59E => "79", 0x1D59F => "7A", 0x1D5A0 => "61", 0x1D5A1 => "62", 0x1D5A2 => "63", 0x1D5A3 => "64", 0x1D5A4 => "65", 0x1D5A5 => "66", 0x1D5A6 => "67", 0x1D5A7 => "68", 0x1D5A8 => "69", 0x1D5A9 => "6A", 0x1D5AA => "6B", 0x1D5AB => "6C", 0x1D5AC => "6D", 0x1D5AD => "6E", 0x1D5AE => "6F", 0x1D5AF => "70", 0x1D5B0 => "71", 0x1D5B1 => "72", 0x1D5B2 => "73", 0x1D5B3 => "74", 0x1D5B4 => "75", 0x1D5B5 => "76", 0x1D5B6 => "77", 0x1D5B7 => "78", 0x1D5B8 => "79", 0x1D5B9 => "7A", 0x1D5BA => "61", 0x1D5BB => "62", 0x1D5BC => "63", 0x1D5BD => "64", 0x1D5BE => "65", 0x1D5BF => "66", 0x1D5C0 => "67", 0x1D5C1 => "68", 0x1D5C2 => "69", 0x1D5C3 => "6A", 0x1D5C4 => "6B", 0x1D5C5 => "6C", 0x1D5C6 => "6D", 0x1D5C7 => "6E", 0x1D5C8 => "6F", 0x1D5C9 => "70", 0x1D5CA => "71", 0x1D5CB => "72", 0x1D5CC => "73", 0x1D5CD => "74", 0x1D5CE => "75", 0x1D5CF => "76", 0x1D5D0 => "77", 0x1D5D1 => "78", 0x1D5D2 => "79", 0x1D5D3 => "7A", 0x1D5D4 => "61", 0x1D5D5 => "62", 0x1D5D6 => "63", 0x1D5D7 => "64", 0x1D5D8 => "65", 0x1D5D9 => "66", 0x1D5DA => "67", 0x1D5DB => "68", 0x1D5DC => "69", 0x1D5DD => "6A", 0x1D5DE => "6B", 0x1D5DF => "6C", 0x1D5E0 => "6D", 0x1D5E1 => "6E", 0x1D5E2 => "6F", 0x1D5E3 => "70", 0x1D5E4 => "71", 0x1D5E5 => "72", 0x1D5E6 => "73", 0x1D5E7 => "74", 0x1D5E8 => "75", 0x1D5E9 => "76", 0x1D5EA => "77", 0x1D5EB => "78", 0x1D5EC => "79", 0x1D5ED => "7A", 0x1D5EE => "61", 0x1D5EF => "62", 0x1D5F0 => "63", 0x1D5F1 => "64", 0x1D5F2 => "65", 0x1D5F3 => "66", 0x1D5F4 => "67", 0x1D5F5 => "68", 0x1D5F6 => "69", 0x1D5F7 => "6A", 0x1D5F8 => "6B", 0x1D5F9 => "6C", 0x1D5FA => "6D", 0x1D5FB => "6E", 0x1D5FC => "6F", 0x1D5FD => "70", 0x1D5FE => "71", 0x1D5FF => "72", 0x1D600 => "73", 0x1D601 => "74", 0x1D602 => "75", 0x1D603 => "76", 0x1D604 => "77", 0x1D605 => "78", 0x1D606 => "79", 0x1D607 => "7A", 0x1D608 => "61", 0x1D609 => "62", 0x1D60A => "63", 0x1D60B => "64", 0x1D60C => "65", 0x1D60D => "66", 0x1D60E => "67", 0x1D60F => "68", 0x1D610 => "69", 0x1D611 => "6A", 0x1D612 => "6B", 0x1D613 => "6C", 0x1D614 => "6D", 0x1D615 => "6E", 0x1D616 => "6F", 0x1D617 => "70", 0x1D618 => "71", 0x1D619 => "72", 0x1D61A => "73", 0x1D61B => "74", 0x1D61C => "75", 0x1D61D => "76", 0x1D61E => "77", 0x1D61F => "78", 0x1D620 => "79", 0x1D621 => "7A", 0x1D622 => "61", 0x1D623 => "62", 0x1D624 => "63", 0x1D625 => "64", 0x1D626 => "65", 0x1D627 => "66", 0x1D628 => "67", 0x1D629 => "68", 0x1D62A => "69", 0x1D62B => "6A", 0x1D62C => "6B", 0x1D62D => "6C", 0x1D62E => "6D", 0x1D62F => "6E", 0x1D630 => "6F", 0x1D631 => "70", 0x1D632 => "71", 0x1D633 => "72", 0x1D634 => "73", 0x1D635 => "74", 0x1D636 => "75", 0x1D637 => "76", 0x1D638 => "77", 0x1D639 => "78", 0x1D63A => "79", 0x1D63B => "7A", 0x1D63C => "61", 0x1D63D => "62", 0x1D63E => "63", 0x1D63F => "64", 0x1D640 => "65", 0x1D641 => "66", 0x1D642 => "67", 0x1D643 => "68", 0x1D644 => "69", 0x1D645 => "6A", 0x1D646 => "6B", 0x1D647 => "6C", 0x1D648 => "6D", 0x1D649 => "6E", 0x1D64A => "6F", 0x1D64B => "70", 0x1D64C => "71", 0x1D64D => "72", 0x1D64E => "73", 0x1D64F => "74", 0x1D650 => "75", 0x1D651 => "76", 0x1D652 => "77", 0x1D653 => "78", 0x1D654 => "79", 0x1D655 => "7A", 0x1D656 => "61", 0x1D657 => "62", 0x1D658 => "63", 0x1D659 => "64", 0x1D65A => "65", 0x1D65B => "66", 0x1D65C => "67", 0x1D65D => "68", 0x1D65E => "69", 0x1D65F => "6A", 0x1D660 => "6B", 0x1D661 => "6C", 0x1D662 => "6D", 0x1D663 => "6E", 0x1D664 => "6F", 0x1D665 => "70", 0x1D666 => "71", 0x1D667 => "72", 0x1D668 => "73", 0x1D669 => "74", 0x1D66A => "75", 0x1D66B => "76", 0x1D66C => "77", 0x1D66D => "78", 0x1D66E => "79", 0x1D66F => "7A", 0x1D670 => "61", 0x1D671 => "62", 0x1D672 => "63", 0x1D673 => "64", 0x1D674 => "65", 0x1D675 => "66", 0x1D676 => "67", 0x1D677 => "68", 0x1D678 => "69", 0x1D679 => "6A", 0x1D67A => "6B", 0x1D67B => "6C", 0x1D67C => "6D", 0x1D67D => "6E", 0x1D67E => "6F", 0x1D67F => "70", 0x1D680 => "71", 0x1D681 => "72", 0x1D682 => "73", 0x1D683 => "74", 0x1D684 => "75", 0x1D685 => "76", 0x1D686 => "77", 0x1D687 => "78", 0x1D688 => "79", 0x1D689 => "7A", 0x1D68A => "61", 0x1D68B => "62", 0x1D68C => "63", 0x1D68D => "64", 0x1D68E => "65", 0x1D68F => "66", 0x1D690 => "67", 0x1D691 => "68", 0x1D692 => "69", 0x1D693 => "6A", 0x1D694 => "6B", 0x1D695 => "6C", 0x1D696 => "6D", 0x1D697 => "6E", 0x1D698 => "6F", 0x1D699 => "70", 0x1D69A => "71", 0x1D69B => "72", 0x1D69C => "73", 0x1D69D => "74", 0x1D69E => "75", 0x1D69F => "76", 0x1D6A0 => "77", 0x1D6A1 => "78", 0x1D6A2 => "79", 0x1D6A3 => "7A", 0x1D6A4 => "131", 0x1D6A5 => "237", 0x1D6A8 => "3B1", 0x1D6A9 => "3B2", 0x1D6AA => "3B3", 0x1D6AB => "3B4", 0x1D6AC => "3B5", 0x1D6AD => "3B6", 0x1D6AE => "3B7", 0x1D6AF => "3B8", 0x1D6B0 => "3B9", 0x1D6B1 => "3BA", 0x1D6B2 => "3BB", 0x1D6B3 => "3BC", 0x1D6B4 => "3BD", 0x1D6B5 => "3BE", 0x1D6B6 => "3BF", 0x1D6B7 => "3C0", 0x1D6B8 => "3C1", 0x1D6B9 => "3B8", 0x1D6BA => "3C3", 0x1D6BB => "3C4", 0x1D6BC => "3C5", 0x1D6BD => "3C6", 0x1D6BE => "3C7", 0x1D6BF => "3C8", 0x1D6C0 => "3C9", 0x1D6C1 => "2207", 0x1D6C2 => "3B1", 0x1D6C3 => "3B2", 0x1D6C4 => "3B3", 0x1D6C5 => "3B4", 0x1D6C6 => "3B5", 0x1D6C7 => "3B6", 0x1D6C8 => "3B7", 0x1D6C9 => "3B8", 0x1D6CA => "3B9", 0x1D6CB => "3BA", 0x1D6CC => "3BB", 0x1D6CD => "3BC", 0x1D6CE => "3BD", 0x1D6CF => "3BE", 0x1D6D0 => "3BF", 0x1D6D1 => "3C0", 0x1D6D2 => "3C1", 0x1D6D3...0x1D6D4 => "3C3", 0x1D6D5 => "3C4", 0x1D6D6 => "3C5", 0x1D6D7 => "3C6", 0x1D6D8 => "3C7", 0x1D6D9 => "3C8", 0x1D6DA => "3C9", 0x1D6DB => "2202", 0x1D6DC => "3B5", 0x1D6DD => "3B8", 0x1D6DE => "3BA", 0x1D6DF => "3C6", 0x1D6E0 => "3C1", 0x1D6E1 => "3C0", 0x1D6E2 => "3B1", 0x1D6E3 => "3B2", 0x1D6E4 => "3B3", 0x1D6E5 => "3B4", 0x1D6E6 => "3B5", 0x1D6E7 => "3B6", 0x1D6E8 => "3B7", 0x1D6E9 => "3B8", 0x1D6EA => "3B9", 0x1D6EB => "3BA", 0x1D6EC => "3BB", 0x1D6ED => "3BC", 0x1D6EE => "3BD", 0x1D6EF => "3BE", 0x1D6F0 => "3BF", 0x1D6F1 => "3C0", 0x1D6F2 => "3C1", 0x1D6F3 => "3B8", 0x1D6F4 => "3C3", 0x1D6F5 => "3C4", 0x1D6F6 => "3C5", 0x1D6F7 => "3C6", 0x1D6F8 => "3C7", 0x1D6F9 => "3C8", 0x1D6FA => "3C9", 0x1D6FB => "2207", 0x1D6FC => "3B1", 0x1D6FD => "3B2", 0x1D6FE => "3B3", 0x1D6FF => "3B4", 0x1D700 => "3B5", 0x1D701 => "3B6", 0x1D702 => "3B7", 0x1D703 => "3B8", 0x1D704 => "3B9", 0x1D705 => "3BA", 0x1D706 => "3BB", 0x1D707 => "3BC", 0x1D708 => "3BD", 0x1D709 => "3BE", 0x1D70A => "3BF", 0x1D70B => "3C0", 0x1D70C => "3C1", 0x1D70D...0x1D70E => "3C3", 0x1D70F => "3C4", 0x1D710 => "3C5", 0x1D711 => "3C6", 0x1D712 => "3C7", 0x1D713 => "3C8", 0x1D714 => "3C9", 0x1D715 => "2202", 0x1D716 => "3B5", 0x1D717 => "3B8", 0x1D718 => "3BA", 0x1D719 => "3C6", 0x1D71A => "3C1", 0x1D71B => "3C0", 0x1D71C => "3B1", 0x1D71D => "3B2", 0x1D71E => "3B3", 0x1D71F => "3B4", 0x1D720 => "3B5", 0x1D721 => "3B6", 0x1D722 => "3B7", 0x1D723 => "3B8", 0x1D724 => "3B9", 0x1D725 => "3BA", 0x1D726 => "3BB", 0x1D727 => "3BC", 0x1D728 => "3BD", 0x1D729 => "3BE", 0x1D72A => "3BF", 0x1D72B => "3C0", 0x1D72C => "3C1", 0x1D72D => "3B8", 0x1D72E => "3C3", 0x1D72F => "3C4", 0x1D730 => "3C5", 0x1D731 => "3C6", 0x1D732 => "3C7", 0x1D733 => "3C8", 0x1D734 => "3C9", 0x1D735 => "2207", 0x1D736 => "3B1", 0x1D737 => "3B2", 0x1D738 => "3B3", 0x1D739 => "3B4", 0x1D73A => "3B5", 0x1D73B => "3B6", 0x1D73C => "3B7", 0x1D73D => "3B8", 0x1D73E => "3B9", 0x1D73F => "3BA", 0x1D740 => "3BB", 0x1D741 => "3BC", 0x1D742 => "3BD", 0x1D743 => "3BE", 0x1D744 => "3BF", 0x1D745 => "3C0", 0x1D746 => "3C1", 0x1D747...0x1D748 => "3C3", 0x1D749 => "3C4", 0x1D74A => "3C5", 0x1D74B => "3C6", 0x1D74C => "3C7", 0x1D74D => "3C8", 0x1D74E => "3C9", 0x1D74F => "2202", 0x1D750 => "3B5", 0x1D751 => "3B8", 0x1D752 => "3BA", 0x1D753 => "3C6", 0x1D754 => "3C1", 0x1D755 => "3C0", 0x1D756 => "3B1", 0x1D757 => "3B2", 0x1D758 => "3B3", 0x1D759 => "3B4", 0x1D75A => "3B5", 0x1D75B => "3B6", 0x1D75C => "3B7", 0x1D75D => "3B8", 0x1D75E => "3B9", 0x1D75F => "3BA", 0x1D760 => "3BB", 0x1D761 => "3BC", 0x1D762 => "3BD", 0x1D763 => "3BE", 0x1D764 => "3BF", 0x1D765 => "3C0", 0x1D766 => "3C1", 0x1D767 => "3B8", 0x1D768 => "3C3", 0x1D769 => "3C4", 0x1D76A => "3C5", 0x1D76B => "3C6", 0x1D76C => "3C7", 0x1D76D => "3C8", 0x1D76E => "3C9", 0x1D76F => "2207", 0x1D770 => "3B1", 0x1D771 => "3B2", 0x1D772 => "3B3", 0x1D773 => "3B4", 0x1D774 => "3B5", 0x1D775 => "3B6", 0x1D776 => "3B7", 0x1D777 => "3B8", 0x1D778 => "3B9", 0x1D779 => "3BA", 0x1D77A => "3BB", 0x1D77B => "3BC", 0x1D77C => "3BD", 0x1D77D => "3BE", 0x1D77E => "3BF", 0x1D77F => "3C0", 0x1D780 => "3C1", 0x1D781...0x1D782 => "3C3", 0x1D783 => "3C4", 0x1D784 => "3C5", 0x1D785 => "3C6", 0x1D786 => "3C7", 0x1D787 => "3C8", 0x1D788 => "3C9", 0x1D789 => "2202", 0x1D78A => "3B5", 0x1D78B => "3B8", 0x1D78C => "3BA", 0x1D78D => "3C6", 0x1D78E => "3C1", 0x1D78F => "3C0", 0x1D790 => "3B1", 0x1D791 => "3B2", 0x1D792 => "3B3", 0x1D793 => "3B4", 0x1D794 => "3B5", 0x1D795 => "3B6", 0x1D796 => "3B7", 0x1D797 => "3B8", 0x1D798 => "3B9", 0x1D799 => "3BA", 0x1D79A => "3BB", 0x1D79B => "3BC", 0x1D79C => "3BD", 0x1D79D => "3BE", 0x1D79E => "3BF", 0x1D79F => "3C0", 0x1D7A0 => "3C1", 0x1D7A1 => "3B8", 0x1D7A2 => "3C3", 0x1D7A3 => "3C4", 0x1D7A4 => "3C5", 0x1D7A5 => "3C6", 0x1D7A6 => "3C7", 0x1D7A7 => "3C8", 0x1D7A8 => "3C9", 0x1D7A9 => "2207", 0x1D7AA => "3B1", 0x1D7AB => "3B2", 0x1D7AC => "3B3", 0x1D7AD => "3B4", 0x1D7AE => "3B5", 0x1D7AF => "3B6", 0x1D7B0 => "3B7", 0x1D7B1 => "3B8", 0x1D7B2 => "3B9", 0x1D7B3 => "3BA", 0x1D7B4 => "3BB", 0x1D7B5 => "3BC", 0x1D7B6 => "3BD", 0x1D7B7 => "3BE", 0x1D7B8 => "3BF", 0x1D7B9 => "3C0", 0x1D7BA => "3C1", 0x1D7BB...0x1D7BC => "3C3", 0x1D7BD => "3C4", 0x1D7BE => "3C5", 0x1D7BF => "3C6", 0x1D7C0 => "3C7", 0x1D7C1 => "3C8", 0x1D7C2 => "3C9", 0x1D7C3 => "2202", 0x1D7C4 => "3B5", 0x1D7C5 => "3B8", 0x1D7C6 => "3BA", 0x1D7C7 => "3C6", 0x1D7C8 => "3C1", 0x1D7C9 => "3C0", 0x1D7CA...0x1D7CB => "3DD", 0x1D7CE => "30", 0x1D7CF => "31", 0x1D7D0 => "32", 0x1D7D1 => "33", 0x1D7D2 => "34", 0x1D7D3 => "35", 0x1D7D4 => "36", 0x1D7D5 => "37", 0x1D7D6 => "38", 0x1D7D7 => "39", 0x1D7D8 => "30", 0x1D7D9 => "31", 0x1D7DA => "32", 0x1D7DB => "33", 0x1D7DC => "34", 0x1D7DD => "35", 0x1D7DE => "36", 0x1D7DF => "37", 0x1D7E0 => "38", 0x1D7E1 => "39", 0x1D7E2 => "30", 0x1D7E3 => "31", 0x1D7E4 => "32", 0x1D7E5 => "33", 0x1D7E6 => "34", 0x1D7E7 => "35", 0x1D7E8 => "36", 0x1D7E9 => "37", 0x1D7EA => "38", 0x1D7EB => "39", 0x1D7EC => "30", 0x1D7ED => "31", 0x1D7EE => "32", 0x1D7EF => "33", 0x1D7F0 => "34", 0x1D7F1 => "35", 0x1D7F2 => "36", 0x1D7F3 => "37", 0x1D7F4 => "38", 0x1D7F5 => "39", 0x1D7F6 => "30", 0x1D7F7 => "31", 0x1D7F8 => "32", 0x1D7F9 => "33", 0x1D7FA => "34", 0x1D7FB => "35", 0x1D7FC => "36", 0x1D7FD => "37", 0x1D7FE => "38", 0x1D7FF => "39", 0x1E900 => "1E922", 0x1E901 => "1E923", 0x1E902 => "1E924", 0x1E903 => "1E925", 0x1E904 => "1E926", 0x1E905 => "1E927", 0x1E906 => "1E928", 0x1E907 => "1E929", 0x1E908 => "1E92A", 0x1E909 => "1E92B", 0x1E90A => "1E92C", 0x1E90B => "1E92D", 0x1E90C => "1E92E", 0x1E90D => "1E92F", 0x1E90E => "1E930", 0x1E90F => "1E931", 0x1E910 => "1E932", 0x1E911 => "1E933", 0x1E912 => "1E934", 0x1E913 => "1E935", 0x1E914 => "1E936", 0x1E915 => "1E937", 0x1E916 => "1E938", 0x1E917 => "1E939", 0x1E918 => "1E93A", 0x1E919 => "1E93B", 0x1E91A => "1E93C", 0x1E91B => "1E93D", 0x1E91C => "1E93E", 0x1E91D => "1E93F", 0x1E91E => "1E940", 0x1E91F => "1E941", 0x1E920 => "1E942", 0x1E921 => "1E943", 0x1EE00 => "627", 0x1EE01 => "628", 0x1EE02 => "62C", 0x1EE03 => "62F", 0x1EE05 => "648", 0x1EE06 => "632", 0x1EE07 => "62D", 0x1EE08 => "637", 0x1EE09 => "64A", 0x1EE0A => "643", 0x1EE0B => "644", 0x1EE0C => "645", 0x1EE0D => "646", 0x1EE0E => "633", 0x1EE0F => "639", 0x1EE10 => "641", 0x1EE11 => "635", 0x1EE12 => "642", 0x1EE13 => "631", 0x1EE14 => "634", 0x1EE15 => "62A", 0x1EE16 => "62B", 0x1EE17 => "62E", 0x1EE18 => "630", 0x1EE19 => "636", 0x1EE1A => "638", 0x1EE1B => "63A", 0x1EE1C => "66E", 0x1EE1D => "6BA", 0x1EE1E => "6A1", 0x1EE1F => "66F", 0x1EE21 => "628", 0x1EE22 => "62C", 0x1EE24 => "647", 0x1EE27 => "62D", 0x1EE29 => "64A", 0x1EE2A => "643", 0x1EE2B => "644", 0x1EE2C => "645", 0x1EE2D => "646", 0x1EE2E => "633", 0x1EE2F => "639", 0x1EE30 => "641", 0x1EE31 => "635", 0x1EE32 => "642", 0x1EE34 => "634", 0x1EE35 => "62A", 0x1EE36 => "62B", 0x1EE37 => "62E", 0x1EE39 => "636", 0x1EE3B => "63A", 0x1EE42 => "62C", 0x1EE47 => "62D", 0x1EE49 => "64A", 0x1EE4B => "644", 0x1EE4D => "646", 0x1EE4E => "633", 0x1EE4F => "639", 0x1EE51 => "635", 0x1EE52 => "642", 0x1EE54 => "634", 0x1EE57 => "62E", 0x1EE59 => "636", 0x1EE5B => "63A", 0x1EE5D => "6BA", 0x1EE5F => "66F", 0x1EE61 => "628", 0x1EE62 => "62C", 0x1EE64 => "647", 0x1EE67 => "62D", 0x1EE68 => "637", 0x1EE69 => "64A", 0x1EE6A => "643", 0x1EE6C => "645", 0x1EE6D => "646", 0x1EE6E => "633", 0x1EE6F => "639", 0x1EE70 => "641", 0x1EE71 => "635", 0x1EE72 => "642", 0x1EE74 => "634", 0x1EE75 => "62A", 0x1EE76 => "62B", 0x1EE77 => "62E", 0x1EE79 => "636", 0x1EE7A => "638", 0x1EE7B => "63A", 0x1EE7C => "66E", 0x1EE7E => "6A1", 0x1EE80 => "627", 0x1EE81 => "628", 0x1EE82 => "62C", 0x1EE83 => "62F", 0x1EE84 => "647", 0x1EE85 => "648", 0x1EE86 => "632", 0x1EE87 => "62D", 0x1EE88 => "637", 0x1EE89 => "64A", 0x1EE8B => "644", 0x1EE8C => "645", 0x1EE8D => "646", 0x1EE8E => "633", 0x1EE8F => "639", 0x1EE90 => "641", 0x1EE91 => "635", 0x1EE92 => "642", 0x1EE93 => "631", 0x1EE94 => "634", 0x1EE95 => "62A", 0x1EE96 => "62B", 0x1EE97 => "62E", 0x1EE98 => "630", 0x1EE99 => "636", 0x1EE9A => "638", 0x1EE9B => "63A", 0x1EEA1 => "628", 0x1EEA2 => "62C", 0x1EEA3 => "62F", 0x1EEA5 => "648", 0x1EEA6 => "632", 0x1EEA7 => "62D", 0x1EEA8 => "637", 0x1EEA9 => "64A", 0x1EEAB => "644", 0x1EEAC => "645", 0x1EEAD => "646", 0x1EEAE => "633", 0x1EEAF => "639", 0x1EEB0 => "641", 0x1EEB1 => "635", 0x1EEB2 => "642", 0x1EEB3 => "631", 0x1EEB4 => "634", 0x1EEB5 => "62A", 0x1EEB6 => "62B", 0x1EEB7 => "62E", 0x1EEB8 => "630", 0x1EEB9 => "636", 0x1EEBA => "638", 0x1EEBB => "63A", 0x1F100 => "30,2E", 0x1F101 => "30,2C", 0x1F102 => "31,2C", 0x1F103 => "32,2C", 0x1F104 => "33,2C", 0x1F105 => "34,2C", 0x1F106 => "35,2C", 0x1F107 => "36,2C", 0x1F108 => "37,2C", 0x1F109 => "38,2C", 0x1F10A => "39,2C", 0x1F110 => "28,61,29", 0x1F111 => "28,62,29", 0x1F112 => "28,63,29", 0x1F113 => "28,64,29", 0x1F114 => "28,65,29", 0x1F115 => "28,66,29", 0x1F116 => "28,67,29", 0x1F117 => "28,68,29", 0x1F118 => "28,69,29", 0x1F119 => "28,6A,29", 0x1F11A => "28,6B,29", 0x1F11B => "28,6C,29", 0x1F11C => "28,6D,29", 0x1F11D => "28,6E,29", 0x1F11E => "28,6F,29", 0x1F11F => "28,70,29", 0x1F120 => "28,71,29", 0x1F121 => "28,72,29", 0x1F122 => "28,73,29", 0x1F123 => "28,74,29", 0x1F124 => "28,75,29", 0x1F125 => "28,76,29", 0x1F126 => "28,77,29", 0x1F127 => "28,78,29", 0x1F128 => "28,79,29", 0x1F129 => "28,7A,29", 0x1F12A => "3014,73,3015", 0x1F12B => "63", 0x1F12C => "72", 0x1F12D => "63,64", 0x1F12E => "77,7A", 0x1F130 => "61", 0x1F131 => "62", 0x1F132 => "63", 0x1F133 => "64", 0x1F134 => "65", 0x1F135 => "66", 0x1F136 => "67", 0x1F137 => "68", 0x1F138 => "69", 0x1F139 => "6A", 0x1F13A => "6B", 0x1F13B => "6C", 0x1F13C => "6D", 0x1F13D => "6E", 0x1F13E => "6F", 0x1F13F => "70", 0x1F140 => "71", 0x1F141 => "72", 0x1F142 => "73", 0x1F143 => "74", 0x1F144 => "75", 0x1F145 => "76", 0x1F146 => "77", 0x1F147 => "78", 0x1F148 => "79", 0x1F149 => "7A", 0x1F14A => "68,76", 0x1F14B => "6D,76", 0x1F14C => "73,64", 0x1F14D => "73,73", 0x1F14E => "70,70,76", 0x1F14F => "77,63", 0x1F16A => "6D,63", 0x1F16B => "6D,64", 0x1F16C => "6D,72", 0x1F190 => "64,6A", 0x1F200 => "307B,304B", 0x1F201 => "30B3,30B3", 0x1F202 => "30B5", 0x1F210 => "624B", 0x1F211 => "5B57", 0x1F212 => "53CC", 0x1F213 => "30C7", 0x1F214 => "4E8C", 0x1F215 => "591A", 0x1F216 => "89E3", 0x1F217 => "5929", 0x1F218 => "4EA4", 0x1F219 => "6620", 0x1F21A => "7121", 0x1F21B => "6599", 0x1F21C => "524D", 0x1F21D => "5F8C", 0x1F21E => "518D", 0x1F21F => "65B0", 0x1F220 => "521D", 0x1F221 => "7D42", 0x1F222 => "751F", 0x1F223 => "8CA9", 0x1F224 => "58F0", 0x1F225 => "5439", 0x1F226 => "6F14", 0x1F227 => "6295", 0x1F228 => "6355", 0x1F229 => "4E00", 0x1F22A => "4E09", 0x1F22B => "904A", 0x1F22C => "5DE6", 0x1F22D => "4E2D", 0x1F22E => "53F3", 0x1F22F => "6307", 0x1F230 => "8D70", 0x1F231 => "6253", 0x1F232 => "7981", 0x1F233 => "7A7A", 0x1F234 => "5408", 0x1F235 => "6E80", 0x1F236 => "6709", 0x1F237 => "6708", 0x1F238 => "7533", 0x1F239 => "5272", 0x1F23A => "55B6", 0x1F23B => "914D", 0x1F240 => "3014,672C,3015", 0x1F241 => "3014,4E09,3015", 0x1F242 => "3014,4E8C,3015", 0x1F243 => "3014,5B89,3015", 0x1F244 => "3014,70B9,3015", 0x1F245 => "3014,6253,3015", 0x1F246 => "3014,76D7,3015", 0x1F247 => "3014,52DD,3015", 0x1F248 => "3014,6557,3015", 0x1F250 => "5F97", 0x1F251 => "53EF", 0x1FBF0 => "30", 0x1FBF1 => "31", 0x1FBF2 => "32", 0x1FBF3 => "33", 0x1FBF4 => "34", 0x1FBF5 => "35", 0x1FBF6 => "36", 0x1FBF7 => "37", 0x1FBF8 => "38", 0x1FBF9 => "39", 0x2F800 => "4E3D", 0x2F801 => "4E38", 0x2F802 => "4E41", 0x2F803 => "20122", 0x2F804 => "4F60", 0x2F805 => "4FAE", 0x2F806 => "4FBB", 0x2F807 => "5002", 0x2F808 => "507A", 0x2F809 => "5099", 0x2F80A => "50E7", 0x2F80B => "50CF", 0x2F80C => "349E", 0x2F80D => "2063A", 0x2F80E => "514D", 0x2F80F => "5154", 0x2F810 => "5164", 0x2F811 => "5177", 0x2F812 => "2051C", 0x2F813 => "34B9", 0x2F814 => "5167", 0x2F815 => "518D", 0x2F816 => "2054B", 0x2F817 => "5197", 0x2F818 => "51A4", 0x2F819 => "4ECC", 0x2F81A => "51AC", 0x2F81B => "51B5", 0x2F81C => "291DF", 0x2F81D => "51F5", 0x2F81E => "5203", 0x2F81F => "34DF", 0x2F820 => "523B", 0x2F821 => "5246", 0x2F822 => "5272", 0x2F823 => "5277", 0x2F824 => "3515", 0x2F825 => "52C7", 0x2F826 => "52C9", 0x2F827 => "52E4", 0x2F828 => "52FA", 0x2F829 => "5305", 0x2F82A => "5306", 0x2F82B => "5317", 0x2F82C => "5349", 0x2F82D => "5351", 0x2F82E => "535A", 0x2F82F => "5373", 0x2F830 => "537D", 0x2F831...0x2F833 => "537F", 0x2F834 => "20A2C", 0x2F835 => "7070", 0x2F836 => "53CA", 0x2F837 => "53DF", 0x2F838 => "20B63", 0x2F839 => "53EB", 0x2F83A => "53F1", 0x2F83B => "5406", 0x2F83C => "549E", 0x2F83D => "5438", 0x2F83E => "5448", 0x2F83F => "5468", 0x2F840 => "54A2", 0x2F841 => "54F6", 0x2F842 => "5510", 0x2F843 => "5553", 0x2F844 => "5563", 0x2F845...0x2F846 => "5584", 0x2F847 => "5599", 0x2F848 => "55AB", 0x2F849 => "55B3", 0x2F84A => "55C2", 0x2F84B => "5716", 0x2F84C => "5606", 0x2F84D => "5717", 0x2F84E => "5651", 0x2F84F => "5674", 0x2F850 => "5207", 0x2F851 => "58EE", 0x2F852 => "57CE", 0x2F853 => "57F4", 0x2F854 => "580D", 0x2F855 => "578B", 0x2F856 => "5832", 0x2F857 => "5831", 0x2F858 => "58AC", 0x2F859 => "214E4", 0x2F85A => "58F2", 0x2F85B => "58F7", 0x2F85C => "5906", 0x2F85D => "591A", 0x2F85E => "5922", 0x2F85F => "5962", 0x2F860 => "216A8", 0x2F861 => "216EA", 0x2F862 => "59EC", 0x2F863 => "5A1B", 0x2F864 => "5A27", 0x2F865 => "59D8", 0x2F866 => "5A66", 0x2F867 => "36EE", 0x2F868 => "36FC", 0x2F869 => "5B08", 0x2F86A...0x2F86B => "5B3E", 0x2F86C => "219C8", 0x2F86D => "5BC3", 0x2F86E => "5BD8", 0x2F86F => "5BE7", 0x2F870 => "5BF3", 0x2F871 => "21B18", 0x2F872 => "5BFF", 0x2F873 => "5C06", 0x2F874 => "5F53", 0x2F875 => "5C22", 0x2F876 => "3781", 0x2F877 => "5C60", 0x2F878 => "5C6E", 0x2F879 => "5CC0", 0x2F87A => "5C8D", 0x2F87B => "21DE4", 0x2F87C => "5D43", 0x2F87D => "21DE6", 0x2F87E => "5D6E", 0x2F87F => "5D6B", 0x2F880 => "5D7C", 0x2F881 => "5DE1", 0x2F882 => "5DE2", 0x2F883 => "382F", 0x2F884 => "5DFD", 0x2F885 => "5E28", 0x2F886 => "5E3D", 0x2F887 => "5E69", 0x2F888 => "3862", 0x2F889 => "22183", 0x2F88A => "387C", 0x2F88B => "5EB0", 0x2F88C => "5EB3", 0x2F88D => "5EB6", 0x2F88E => "5ECA", 0x2F88F => "2A392", 0x2F890 => "5EFE", 0x2F891...0x2F892 => "22331", 0x2F893 => "8201", 0x2F894...0x2F895 => "5F22", 0x2F896 => "38C7", 0x2F897 => "232B8", 0x2F898 => "261DA", 0x2F899 => "5F62", 0x2F89A => "5F6B", 0x2F89B => "38E3", 0x2F89C => "5F9A", 0x2F89D => "5FCD", 0x2F89E => "5FD7", 0x2F89F => "5FF9", 0x2F8A0 => "6081", 0x2F8A1 => "393A", 0x2F8A2 => "391C", 0x2F8A3 => "6094", 0x2F8A4 => "226D4", 0x2F8A5 => "60C7", 0x2F8A6 => "6148", 0x2F8A7 => "614C", 0x2F8A8 => "614E", 0x2F8A9 => "614C", 0x2F8AA => "617A", 0x2F8AB => "618E", 0x2F8AC => "61B2", 0x2F8AD => "61A4", 0x2F8AE => "61AF", 0x2F8AF => "61DE", 0x2F8B0 => "61F2", 0x2F8B1 => "61F6", 0x2F8B2 => "6210", 0x2F8B3 => "621B", 0x2F8B4 => "625D", 0x2F8B5 => "62B1", 0x2F8B6 => "62D4", 0x2F8B7 => "6350", 0x2F8B8 => "22B0C", 0x2F8B9 => "633D", 0x2F8BA => "62FC", 0x2F8BB => "6368", 0x2F8BC => "6383", 0x2F8BD => "63E4", 0x2F8BE => "22BF1", 0x2F8BF => "6422", 0x2F8C0 => "63C5", 0x2F8C1 => "63A9", 0x2F8C2 => "3A2E", 0x2F8C3 => "6469", 0x2F8C4 => "647E", 0x2F8C5 => "649D", 0x2F8C6 => "6477", 0x2F8C7 => "3A6C", 0x2F8C8 => "654F", 0x2F8C9 => "656C", 0x2F8CA => "2300A", 0x2F8CB => "65E3", 0x2F8CC => "66F8", 0x2F8CD => "6649", 0x2F8CE => "3B19", 0x2F8CF => "6691", 0x2F8D0 => "3B08", 0x2F8D1 => "3AE4", 0x2F8D2 => "5192", 0x2F8D3 => "5195", 0x2F8D4 => "6700", 0x2F8D5 => "669C", 0x2F8D6 => "80AD", 0x2F8D7 => "43D9", 0x2F8D8 => "6717", 0x2F8D9 => "671B", 0x2F8DA => "6721", 0x2F8DB => "675E", 0x2F8DC => "6753", 0x2F8DD => "233C3", 0x2F8DE => "3B49", 0x2F8DF => "67FA", 0x2F8E0 => "6785", 0x2F8E1 => "6852", 0x2F8E2 => "6885", 0x2F8E3 => "2346D", 0x2F8E4 => "688E", 0x2F8E5 => "681F", 0x2F8E6 => "6914", 0x2F8E7 => "3B9D", 0x2F8E8 => "6942", 0x2F8E9 => "69A3", 0x2F8EA => "69EA", 0x2F8EB => "6AA8", 0x2F8EC => "236A3", 0x2F8ED => "6ADB", 0x2F8EE => "3C18", 0x2F8EF => "6B21", 0x2F8F0 => "238A7", 0x2F8F1 => "6B54", 0x2F8F2 => "3C4E", 0x2F8F3 => "6B72", 0x2F8F4 => "6B9F", 0x2F8F5 => "6BBA", 0x2F8F6 => "6BBB", 0x2F8F7 => "23A8D", 0x2F8F8 => "21D0B", 0x2F8F9 => "23AFA", 0x2F8FA => "6C4E", 0x2F8FB => "23CBC", 0x2F8FC => "6CBF", 0x2F8FD => "6CCD", 0x2F8FE => "6C67", 0x2F8FF => "6D16", 0x2F900 => "6D3E", 0x2F901 => "6D77", 0x2F902 => "6D41", 0x2F903 => "6D69", 0x2F904 => "6D78", 0x2F905 => "6D85", 0x2F906 => "23D1E", 0x2F907 => "6D34", 0x2F908 => "6E2F", 0x2F909 => "6E6E", 0x2F90A => "3D33", 0x2F90B => "6ECB", 0x2F90C => "6EC7", 0x2F90D => "23ED1", 0x2F90E => "6DF9", 0x2F90F => "6F6E", 0x2F910 => "23F5E", 0x2F911 => "23F8E", 0x2F912 => "6FC6", 0x2F913 => "7039", 0x2F914 => "701E", 0x2F915 => "701B", 0x2F916 => "3D96", 0x2F917 => "704A", 0x2F918 => "707D", 0x2F919 => "7077", 0x2F91A => "70AD", 0x2F91B => "20525", 0x2F91C => "7145", 0x2F91D => "24263", 0x2F91E => "719C", 0x2F91F => "243AB", 0x2F920 => "7228", 0x2F921 => "7235", 0x2F922 => "7250", 0x2F923 => "24608", 0x2F924 => "7280", 0x2F925 => "7295", 0x2F926 => "24735", 0x2F927 => "24814", 0x2F928 => "737A", 0x2F929 => "738B", 0x2F92A => "3EAC", 0x2F92B => "73A5", 0x2F92C...0x2F92D => "3EB8", 0x2F92E => "7447", 0x2F92F => "745C", 0x2F930 => "7471", 0x2F931 => "7485", 0x2F932 => "74CA", 0x2F933 => "3F1B", 0x2F934 => "7524", 0x2F935 => "24C36", 0x2F936 => "753E", 0x2F937 => "24C92", 0x2F938 => "7570", 0x2F939 => "2219F", 0x2F93A => "7610", 0x2F93B => "24FA1", 0x2F93C => "24FB8", 0x2F93D => "25044", 0x2F93E => "3FFC", 0x2F93F => "4008", 0x2F940 => "76F4", 0x2F941 => "250F3", 0x2F942 => "250F2", 0x2F943 => "25119", 0x2F944 => "25133", 0x2F945 => "771E", 0x2F946...0x2F947 => "771F", 0x2F948 => "774A", 0x2F949 => "4039", 0x2F94A => "778B", 0x2F94B => "4046", 0x2F94C => "4096", 0x2F94D => "2541D", 0x2F94E => "784E", 0x2F94F => "788C", 0x2F950 => "78CC", 0x2F951 => "40E3", 0x2F952 => "25626", 0x2F953 => "7956", 0x2F954 => "2569A", 0x2F955 => "256C5", 0x2F956 => "798F", 0x2F957 => "79EB", 0x2F958 => "412F", 0x2F959 => "7A40", 0x2F95A => "7A4A", 0x2F95B => "7A4F", 0x2F95C => "2597C", 0x2F95D...0x2F95E => "25AA7", 0x2F95F => "7AEE", 0x2F960 => "4202", 0x2F961 => "25BAB", 0x2F962 => "7BC6", 0x2F963 => "7BC9", 0x2F964 => "4227", 0x2F965 => "25C80", 0x2F966 => "7CD2", 0x2F967 => "42A0", 0x2F968 => "7CE8", 0x2F969 => "7CE3", 0x2F96A => "7D00", 0x2F96B => "25F86", 0x2F96C => "7D63", 0x2F96D => "4301", 0x2F96E => "7DC7", 0x2F96F => "7E02", 0x2F970 => "7E45", 0x2F971 => "4334", 0x2F972 => "26228", 0x2F973 => "26247", 0x2F974 => "4359", 0x2F975 => "262D9", 0x2F976 => "7F7A", 0x2F977 => "2633E", 0x2F978 => "7F95", 0x2F979 => "7FFA", 0x2F97A => "8005", 0x2F97B => "264DA", 0x2F97C => "26523", 0x2F97D => "8060", 0x2F97E => "265A8", 0x2F97F => "8070", 0x2F980 => "2335F", 0x2F981 => "43D5", 0x2F982 => "80B2", 0x2F983 => "8103", 0x2F984 => "440B", 0x2F985 => "813E", 0x2F986 => "5AB5", 0x2F987 => "267A7", 0x2F988 => "267B5", 0x2F989 => "23393", 0x2F98A => "2339C", 0x2F98B => "8201", 0x2F98C => "8204", 0x2F98D => "8F9E", 0x2F98E => "446B", 0x2F98F => "8291", 0x2F990 => "828B", 0x2F991 => "829D", 0x2F992 => "52B3", 0x2F993 => "82B1", 0x2F994 => "82B3", 0x2F995 => "82BD", 0x2F996 => "82E6", 0x2F997 => "26B3C", 0x2F998 => "82E5", 0x2F999 => "831D", 0x2F99A => "8363", 0x2F99B => "83AD", 0x2F99C => "8323", 0x2F99D => "83BD", 0x2F99E => "83E7", 0x2F99F => "8457", 0x2F9A0 => "8353", 0x2F9A1 => "83CA", 0x2F9A2 => "83CC", 0x2F9A3 => "83DC", 0x2F9A4 => "26C36", 0x2F9A5 => "26D6B", 0x2F9A6 => "26CD5", 0x2F9A7 => "452B", 0x2F9A8 => "84F1", 0x2F9A9 => "84F3", 0x2F9AA => "8516", 0x2F9AB => "273CA", 0x2F9AC => "8564", 0x2F9AD => "26F2C", 0x2F9AE => "455D", 0x2F9AF => "4561", 0x2F9B0 => "26FB1", 0x2F9B1 => "270D2", 0x2F9B2 => "456B", 0x2F9B3 => "8650", 0x2F9B4 => "865C", 0x2F9B5 => "8667", 0x2F9B6 => "8669", 0x2F9B7 => "86A9", 0x2F9B8 => "8688", 0x2F9B9 => "870E", 0x2F9BA => "86E2", 0x2F9BB => "8779", 0x2F9BC => "8728", 0x2F9BD => "876B", 0x2F9BE => "8786", 0x2F9BF => "45D7", 0x2F9C0 => "87E1", 0x2F9C1 => "8801", 0x2F9C2 => "45F9", 0x2F9C3 => "8860", 0x2F9C4 => "8863", 0x2F9C5 => "27667", 0x2F9C6 => "88D7", 0x2F9C7 => "88DE", 0x2F9C8 => "4635", 0x2F9C9 => "88FA", 0x2F9CA => "34BB", 0x2F9CB => "278AE", 0x2F9CC => "27966", 0x2F9CD => "46BE", 0x2F9CE => "46C7", 0x2F9CF => "8AA0", 0x2F9D0 => "8AED", 0x2F9D1 => "8B8A", 0x2F9D2 => "8C55", 0x2F9D3 => "27CA8", 0x2F9D4 => "8CAB", 0x2F9D5 => "8CC1", 0x2F9D6 => "8D1B", 0x2F9D7 => "8D77", 0x2F9D8 => "27F2F", 0x2F9D9 => "20804", 0x2F9DA => "8DCB", 0x2F9DB => "8DBC", 0x2F9DC => "8DF0", 0x2F9DD => "208DE", 0x2F9DE => "8ED4", 0x2F9DF => "8F38", 0x2F9E0 => "285D2", 0x2F9E1 => "285ED", 0x2F9E2 => "9094", 0x2F9E3 => "90F1", 0x2F9E4 => "9111", 0x2F9E5 => "2872E", 0x2F9E6 => "911B", 0x2F9E7 => "9238", 0x2F9E8 => "92D7", 0x2F9E9 => "92D8", 0x2F9EA => "927C", 0x2F9EB => "93F9", 0x2F9EC => "9415", 0x2F9ED => "28BFA", 0x2F9EE => "958B", 0x2F9EF => "4995", 0x2F9F0 => "95B7", 0x2F9F1 => "28D77", 0x2F9F2 => "49E6", 0x2F9F3 => "96C3", 0x2F9F4 => "5DB2", 0x2F9F5 => "9723", 0x2F9F6 => "29145", 0x2F9F7 => "2921A", 0x2F9F8 => "4A6E", 0x2F9F9 => "4A76", 0x2F9FA => "97E0", 0x2F9FB => "2940A", 0x2F9FC => "4AB2", 0x2F9FD => "29496", 0x2F9FE...0x2F9FF => "980B", 0x2FA00 => "9829", 0x2FA01 => "295B6", 0x2FA02 => "98E2", 0x2FA03 => "4B33", 0x2FA04 => "9929", 0x2FA05 => "99A7", 0x2FA06 => "99C2", 0x2FA07 => "99FE", 0x2FA08 => "4BCE", 0x2FA09 => "29B30", 0x2FA0A => "9B12", 0x2FA0B => "9C40", 0x2FA0C => "9CFD", 0x2FA0D => "4CCE", 0x2FA0E => "4CED", 0x2FA0F => "9D67", 0x2FA10 => "2A0CE", 0x2FA11 => "4CF8", 0x2FA12 => "2A105", 0x2FA13 => "2A20E", 0x2FA14 => "2A291", 0x2FA15 => "9EBB", 0x2FA16 => "4D56", 0x2FA17 => "9EF9", 0x2FA18 => "9EFE", 0x2FA19 => "9F05", 0x2FA1A => "9F0F", 0x2FA1B => "9F16", 0x2FA1C => "9F3B", 0x2FA1D => "2A600", 0xE0000 => "0", 0xE0001 => "0", 0xE0002...0xE001F => "0", 0xE0020...0xE007F => "0", 0xE0080...0xE00FF => "0", 0xE0100...0xE01EF => "0", 0xE01F0...0xE0FFF => "0", else => "", }; } /// `changesWhenNfkcCaseFold` returns true if `toNFKCCF` for `cp` results in `cp` itself. pub fn changerWhenNfkcCaseFold(cp: u21) bool { return switch(cp) { 0x41...0x5A => true, 0xA0 => true, 0xA8 => true, 0xAA => true, 0xAD => true, 0xAF => true, 0xB2...0xB3 => true, 0xB4 => true, 0xB5 => true, 0xB8 => true, 0xB9 => true, 0xBA => true, 0xBC...0xBE => true, 0xC0...0xD6 => true, 0xD8...0xDF => true, 0x100 => true, 0x102 => true, 0x104 => true, 0x106 => true, 0x108 => true, 0x10A => true, 0x10C => true, 0x10E => true, 0x110 => true, 0x112 => true, 0x114 => true, 0x116 => true, 0x118 => true, 0x11A => true, 0x11C => true, 0x11E => true, 0x120 => true, 0x122 => true, 0x124 => true, 0x126 => true, 0x128 => true, 0x12A => true, 0x12C => true, 0x12E => true, 0x130 => true, 0x132...0x134 => true, 0x136 => true, 0x139 => true, 0x13B => true, 0x13D => true, 0x13F...0x141 => true, 0x143 => true, 0x145 => true, 0x147 => true, 0x149...0x14A => true, 0x14C => true, 0x14E => true, 0x150 => true, 0x152 => true, 0x154 => true, 0x156 => true, 0x158 => true, 0x15A => true, 0x15C => true, 0x15E => true, 0x160 => true, 0x162 => true, 0x164 => true, 0x166 => true, 0x168 => true, 0x16A => true, 0x16C => true, 0x16E => true, 0x170 => true, 0x172 => true, 0x174 => true, 0x176 => true, 0x178...0x179 => true, 0x17B => true, 0x17D => true, 0x17F => true, 0x181...0x182 => true, 0x184 => true, 0x186...0x187 => true, 0x189...0x18B => true, 0x18E...0x191 => true, 0x193...0x194 => true, 0x196...0x198 => true, 0x19C...0x19D => true, 0x19F...0x1A0 => true, 0x1A2 => true, 0x1A4 => true, 0x1A6...0x1A7 => true, 0x1A9 => true, 0x1AC => true, 0x1AE...0x1AF => true, 0x1B1...0x1B3 => true, 0x1B5 => true, 0x1B7...0x1B8 => true, 0x1BC => true, 0x1C4...0x1CD => true, 0x1CF => true, 0x1D1 => true, 0x1D3 => true, 0x1D5 => true, 0x1D7 => true, 0x1D9 => true, 0x1DB => true, 0x1DE => true, 0x1E0 => true, 0x1E2 => true, 0x1E4 => true, 0x1E6 => true, 0x1E8 => true, 0x1EA => true, 0x1EC => true, 0x1EE => true, 0x1F1...0x1F4 => true, 0x1F6...0x1F8 => true, 0x1FA => true, 0x1FC => true, 0x1FE => true, 0x200 => true, 0x202 => true, 0x204 => true, 0x206 => true, 0x208 => true, 0x20A => true, 0x20C => true, 0x20E => true, 0x210 => true, 0x212 => true, 0x214 => true, 0x216 => true, 0x218 => true, 0x21A => true, 0x21C => true, 0x21E => true, 0x220 => true, 0x222 => true, 0x224 => true, 0x226 => true, 0x228 => true, 0x22A => true, 0x22C => true, 0x22E => true, 0x230 => true, 0x232 => true, 0x23A...0x23B => true, 0x23D...0x23E => true, 0x241 => true, 0x243...0x246 => true, 0x248 => true, 0x24A => true, 0x24C => true, 0x24E => true, 0x2B0...0x2B8 => true, 0x2D8...0x2DD => true, 0x2E0...0x2E4 => true, 0x340...0x341 => true, 0x343...0x345 => true, 0x34F => true, 0x370 => true, 0x372 => true, 0x374 => true, 0x376 => true, 0x37A => true, 0x37E => true, 0x37F => true, 0x384...0x385 => true, 0x386 => true, 0x387 => true, 0x388...0x38A => true, 0x38C => true, 0x38E...0x38F => true, 0x391...0x3A1 => true, 0x3A3...0x3AB => true, 0x3C2 => true, 0x3CF...0x3D6 => true, 0x3D8 => true, 0x3DA => true, 0x3DC => true, 0x3DE => true, 0x3E0 => true, 0x3E2 => true, 0x3E4 => true, 0x3E6 => true, 0x3E8 => true, 0x3EA => true, 0x3EC => true, 0x3EE => true, 0x3F0...0x3F2 => true, 0x3F4...0x3F5 => true, 0x3F7 => true, 0x3F9...0x3FA => true, 0x3FD...0x42F => true, 0x460 => true, 0x462 => true, 0x464 => true, 0x466 => true, 0x468 => true, 0x46A => true, 0x46C => true, 0x46E => true, 0x470 => true, 0x472 => true, 0x474 => true, 0x476 => true, 0x478 => true, 0x47A => true, 0x47C => true, 0x47E => true, 0x480 => true, 0x48A => true, 0x48C => true, 0x48E => true, 0x490 => true, 0x492 => true, 0x494 => true, 0x496 => true, 0x498 => true, 0x49A => true, 0x49C => true, 0x49E => true, 0x4A0 => true, 0x4A2 => true, 0x4A4 => true, 0x4A6 => true, 0x4A8 => true, 0x4AA => true, 0x4AC => true, 0x4AE => true, 0x4B0 => true, 0x4B2 => true, 0x4B4 => true, 0x4B6 => true, 0x4B8 => true, 0x4BA => true, 0x4BC => true, 0x4BE => true, 0x4C0...0x4C1 => true, 0x4C3 => true, 0x4C5 => true, 0x4C7 => true, 0x4C9 => true, 0x4CB => true, 0x4CD => true, 0x4D0 => true, 0x4D2 => true, 0x4D4 => true, 0x4D6 => true, 0x4D8 => true, 0x4DA => true, 0x4DC => true, 0x4DE => true, 0x4E0 => true, 0x4E2 => true, 0x4E4 => true, 0x4E6 => true, 0x4E8 => true, 0x4EA => true, 0x4EC => true, 0x4EE => true, 0x4F0 => true, 0x4F2 => true, 0x4F4 => true, 0x4F6 => true, 0x4F8 => true, 0x4FA => true, 0x4FC => true, 0x4FE => true, 0x500 => true, 0x502 => true, 0x504 => true, 0x506 => true, 0x508 => true, 0x50A => true, 0x50C => true, 0x50E => true, 0x510 => true, 0x512 => true, 0x514 => true, 0x516 => true, 0x518 => true, 0x51A => true, 0x51C => true, 0x51E => true, 0x520 => true, 0x522 => true, 0x524 => true, 0x526 => true, 0x528 => true, 0x52A => true, 0x52C => true, 0x52E => true, 0x531...0x556 => true, 0x587 => true, 0x61C => true, 0x675...0x678 => true, 0x958...0x95F => true, 0x9DC...0x9DD => true, 0x9DF => true, 0xA33 => true, 0xA36 => true, 0xA59...0xA5B => true, 0xA5E => true, 0xB5C...0xB5D => true, 0xE33 => true, 0xEB3 => true, 0xEDC...0xEDD => true, 0xF0C => true, 0xF43 => true, 0xF4D => true, 0xF52 => true, 0xF57 => true, 0xF5C => true, 0xF69 => true, 0xF73 => true, 0xF75...0xF79 => true, 0xF81 => true, 0xF93 => true, 0xF9D => true, 0xFA2 => true, 0xFA7 => true, 0xFAC => true, 0xFB9 => true, 0x10A0...0x10C5 => true, 0x10C7 => true, 0x10CD => true, 0x10FC => true, 0x115F...0x1160 => true, 0x13F8...0x13FD => true, 0x17B4...0x17B5 => true, 0x180B...0x180D => true, 0x180E => true, 0x180F => true, 0x1C80...0x1C88 => true, 0x1C90...0x1CBA => true, 0x1CBD...0x1CBF => true, 0x1D2C...0x1D2E => true, 0x1D30...0x1D3A => true, 0x1D3C...0x1D4D => true, 0x1D4F...0x1D6A => true, 0x1D78 => true, 0x1D9B...0x1DBF => true, 0x1E00 => true, 0x1E02 => true, 0x1E04 => true, 0x1E06 => true, 0x1E08 => true, 0x1E0A => true, 0x1E0C => true, 0x1E0E => true, 0x1E10 => true, 0x1E12 => true, 0x1E14 => true, 0x1E16 => true, 0x1E18 => true, 0x1E1A => true, 0x1E1C => true, 0x1E1E => true, 0x1E20 => true, 0x1E22 => true, 0x1E24 => true, 0x1E26 => true, 0x1E28 => true, 0x1E2A => true, 0x1E2C => true, 0x1E2E => true, 0x1E30 => true, 0x1E32 => true, 0x1E34 => true, 0x1E36 => true, 0x1E38 => true, 0x1E3A => true, 0x1E3C => true, 0x1E3E => true, 0x1E40 => true, 0x1E42 => true, 0x1E44 => true, 0x1E46 => true, 0x1E48 => true, 0x1E4A => true, 0x1E4C => true, 0x1E4E => true, 0x1E50 => true, 0x1E52 => true, 0x1E54 => true, 0x1E56 => true, 0x1E58 => true, 0x1E5A => true, 0x1E5C => true, 0x1E5E => true, 0x1E60 => true, 0x1E62 => true, 0x1E64 => true, 0x1E66 => true, 0x1E68 => true, 0x1E6A => true, 0x1E6C => true, 0x1E6E => true, 0x1E70 => true, 0x1E72 => true, 0x1E74 => true, 0x1E76 => true, 0x1E78 => true, 0x1E7A => true, 0x1E7C => true, 0x1E7E => true, 0x1E80 => true, 0x1E82 => true, 0x1E84 => true, 0x1E86 => true, 0x1E88 => true, 0x1E8A => true, 0x1E8C => true, 0x1E8E => true, 0x1E90 => true, 0x1E92 => true, 0x1E94 => true, 0x1E9A...0x1E9B => true, 0x1E9E => true, 0x1EA0 => true, 0x1EA2 => true, 0x1EA4 => true, 0x1EA6 => true, 0x1EA8 => true, 0x1EAA => true, 0x1EAC => true, 0x1EAE => true, 0x1EB0 => true, 0x1EB2 => true, 0x1EB4 => true, 0x1EB6 => true, 0x1EB8 => true, 0x1EBA => true, 0x1EBC => true, 0x1EBE => true, 0x1EC0 => true, 0x1EC2 => true, 0x1EC4 => true, 0x1EC6 => true, 0x1EC8 => true, 0x1ECA => true, 0x1ECC => true, 0x1ECE => true, 0x1ED0 => true, 0x1ED2 => true, 0x1ED4 => true, 0x1ED6 => true, 0x1ED8 => true, 0x1EDA => true, 0x1EDC => true, 0x1EDE => true, 0x1EE0 => true, 0x1EE2 => true, 0x1EE4 => true, 0x1EE6 => true, 0x1EE8 => true, 0x1EEA => true, 0x1EEC => true, 0x1EEE => true, 0x1EF0 => true, 0x1EF2 => true, 0x1EF4 => true, 0x1EF6 => true, 0x1EF8 => true, 0x1EFA => true, 0x1EFC => true, 0x1EFE => true, 0x1F08...0x1F0F => true, 0x1F18...0x1F1D => true, 0x1F28...0x1F2F => true, 0x1F38...0x1F3F => true, 0x1F48...0x1F4D => true, 0x1F59 => true, 0x1F5B => true, 0x1F5D => true, 0x1F5F => true, 0x1F68...0x1F6F => true, 0x1F71 => true, 0x1F73 => true, 0x1F75 => true, 0x1F77 => true, 0x1F79 => true, 0x1F7B => true, 0x1F7D => true, 0x1F80...0x1FAF => true, 0x1FB2...0x1FB4 => true, 0x1FB7...0x1FBC => true, 0x1FBD => true, 0x1FBE => true, 0x1FBF...0x1FC1 => true, 0x1FC2...0x1FC4 => true, 0x1FC7...0x1FCC => true, 0x1FCD...0x1FCF => true, 0x1FD3 => true, 0x1FD8...0x1FDB => true, 0x1FDD...0x1FDF => true, 0x1FE3 => true, 0x1FE8...0x1FEC => true, 0x1FED...0x1FEF => true, 0x1FF2...0x1FF4 => true, 0x1FF7...0x1FFC => true, 0x1FFD...0x1FFE => true, 0x2000...0x200A => true, 0x200B...0x200F => true, 0x2011 => true, 0x2017 => true, 0x2024...0x2026 => true, 0x202A...0x202E => true, 0x202F => true, 0x2033...0x2034 => true, 0x2036...0x2037 => true, 0x203C => true, 0x203E => true, 0x2047...0x2049 => true, 0x2057 => true, 0x205F => true, 0x2060...0x2064 => true, 0x2065 => true, 0x2066...0x206F => true, 0x2070 => true, 0x2071 => true, 0x2074...0x2079 => true, 0x207A...0x207C => true, 0x207D => true, 0x207E => true, 0x207F => true, 0x2080...0x2089 => true, 0x208A...0x208C => true, 0x208D => true, 0x208E => true, 0x2090...0x209C => true, 0x20A8 => true, 0x2100...0x2101 => true, 0x2102 => true, 0x2103 => true, 0x2105...0x2106 => true, 0x2107 => true, 0x2109 => true, 0x210A...0x2113 => true, 0x2115 => true, 0x2116 => true, 0x2119...0x211D => true, 0x2120...0x2122 => true, 0x2124 => true, 0x2126 => true, 0x2128 => true, 0x212A...0x212D => true, 0x212F...0x2134 => true, 0x2135...0x2138 => true, 0x2139 => true, 0x213B => true, 0x213C...0x213F => true, 0x2140 => true, 0x2145...0x2149 => true, 0x2150...0x215F => true, 0x2160...0x217F => true, 0x2183 => true, 0x2189 => true, 0x222C...0x222D => true, 0x222F...0x2230 => true, 0x2329 => true, 0x232A => true, 0x2460...0x249B => true, 0x249C...0x24E9 => true, 0x24EA => true, 0x2A0C => true, 0x2A74...0x2A76 => true, 0x2ADC => true, 0x2C00...0x2C2F => true, 0x2C60 => true, 0x2C62...0x2C64 => true, 0x2C67 => true, 0x2C69 => true, 0x2C6B => true, 0x2C6D...0x2C70 => true, 0x2C72 => true, 0x2C75 => true, 0x2C7C...0x2C7D => true, 0x2C7E...0x2C80 => true, 0x2C82 => true, 0x2C84 => true, 0x2C86 => true, 0x2C88 => true, 0x2C8A => true, 0x2C8C => true, 0x2C8E => true, 0x2C90 => true, 0x2C92 => true, 0x2C94 => true, 0x2C96 => true, 0x2C98 => true, 0x2C9A => true, 0x2C9C => true, 0x2C9E => true, 0x2CA0 => true, 0x2CA2 => true, 0x2CA4 => true, 0x2CA6 => true, 0x2CA8 => true, 0x2CAA => true, 0x2CAC => true, 0x2CAE => true, 0x2CB0 => true, 0x2CB2 => true, 0x2CB4 => true, 0x2CB6 => true, 0x2CB8 => true, 0x2CBA => true, 0x2CBC => true, 0x2CBE => true, 0x2CC0 => true, 0x2CC2 => true, 0x2CC4 => true, 0x2CC6 => true, 0x2CC8 => true, 0x2CCA => true, 0x2CCC => true, 0x2CCE => true, 0x2CD0 => true, 0x2CD2 => true, 0x2CD4 => true, 0x2CD6 => true, 0x2CD8 => true, 0x2CDA => true, 0x2CDC => true, 0x2CDE => true, 0x2CE0 => true, 0x2CE2 => true, 0x2CEB => true, 0x2CED => true, 0x2CF2 => true, 0x2D6F => true, 0x2E9F => true, 0x2EF3 => true, 0x2F00...0x2FD5 => true, 0x3000 => true, 0x3036 => true, 0x3038...0x303A => true, 0x309B...0x309C => true, 0x309F => true, 0x30FF => true, 0x3131...0x318E => true, 0x3192...0x3195 => true, 0x3196...0x319F => true, 0x3200...0x321E => true, 0x3220...0x3229 => true, 0x322A...0x3247 => true, 0x3250 => true, 0x3251...0x325F => true, 0x3260...0x327E => true, 0x3280...0x3289 => true, 0x328A...0x32B0 => true, 0x32B1...0x32BF => true, 0x32C0...0x33FF => true, 0xA640 => true, 0xA642 => true, 0xA644 => true, 0xA646 => true, 0xA648 => true, 0xA64A => true, 0xA64C => true, 0xA64E => true, 0xA650 => true, 0xA652 => true, 0xA654 => true, 0xA656 => true, 0xA658 => true, 0xA65A => true, 0xA65C => true, 0xA65E => true, 0xA660 => true, 0xA662 => true, 0xA664 => true, 0xA666 => true, 0xA668 => true, 0xA66A => true, 0xA66C => true, 0xA680 => true, 0xA682 => true, 0xA684 => true, 0xA686 => true, 0xA688 => true, 0xA68A => true, 0xA68C => true, 0xA68E => true, 0xA690 => true, 0xA692 => true, 0xA694 => true, 0xA696 => true, 0xA698 => true, 0xA69A => true, 0xA69C...0xA69D => true, 0xA722 => true, 0xA724 => true, 0xA726 => true, 0xA728 => true, 0xA72A => true, 0xA72C => true, 0xA72E => true, 0xA732 => true, 0xA734 => true, 0xA736 => true, 0xA738 => true, 0xA73A => true, 0xA73C => true, 0xA73E => true, 0xA740 => true, 0xA742 => true, 0xA744 => true, 0xA746 => true, 0xA748 => true, 0xA74A => true, 0xA74C => true, 0xA74E => true, 0xA750 => true, 0xA752 => true, 0xA754 => true, 0xA756 => true, 0xA758 => true, 0xA75A => true, 0xA75C => true, 0xA75E => true, 0xA760 => true, 0xA762 => true, 0xA764 => true, 0xA766 => true, 0xA768 => true, 0xA76A => true, 0xA76C => true, 0xA76E => true, 0xA770 => true, 0xA779 => true, 0xA77B => true, 0xA77D...0xA77E => true, 0xA780 => true, 0xA782 => true, 0xA784 => true, 0xA786 => true, 0xA78B => true, 0xA78D => true, 0xA790 => true, 0xA792 => true, 0xA796 => true, 0xA798 => true, 0xA79A => true, 0xA79C => true, 0xA79E => true, 0xA7A0 => true, 0xA7A2 => true, 0xA7A4 => true, 0xA7A6 => true, 0xA7A8 => true, 0xA7AA...0xA7AE => true, 0xA7B0...0xA7B4 => true, 0xA7B6 => true, 0xA7B8 => true, 0xA7BA => true, 0xA7BC => true, 0xA7BE => true, 0xA7C0 => true, 0xA7C2 => true, 0xA7C4...0xA7C7 => true, 0xA7C9 => true, 0xA7D0 => true, 0xA7D6 => true, 0xA7D8 => true, 0xA7F2...0xA7F4 => true, 0xA7F5 => true, 0xA7F8...0xA7F9 => true, 0xAB5C...0xAB5F => true, 0xAB69 => true, 0xAB70...0xABBF => true, 0xF900...0xFA0D => true, 0xFA10 => true, 0xFA12 => true, 0xFA15...0xFA1E => true, 0xFA20 => true, 0xFA22 => true, 0xFA25...0xFA26 => true, 0xFA2A...0xFA6D => true, 0xFA70...0xFAD9 => true, 0xFB00...0xFB06 => true, 0xFB13...0xFB17 => true, 0xFB1D => true, 0xFB1F...0xFB28 => true, 0xFB29 => true, 0xFB2A...0xFB36 => true, 0xFB38...0xFB3C => true, 0xFB3E => true, 0xFB40...0xFB41 => true, 0xFB43...0xFB44 => true, 0xFB46...0xFBB1 => true, 0xFBD3...0xFD3D => true, 0xFD50...0xFD8F => true, 0xFD92...0xFDC7 => true, 0xFDF0...0xFDFB => true, 0xFDFC => true, 0xFE00...0xFE0F => true, 0xFE10...0xFE16 => true, 0xFE17 => true, 0xFE18 => true, 0xFE19 => true, 0xFE30 => true, 0xFE31...0xFE32 => true, 0xFE33...0xFE34 => true, 0xFE35 => true, 0xFE36 => true, 0xFE37 => true, 0xFE38 => true, 0xFE39 => true, 0xFE3A => true, 0xFE3B => true, 0xFE3C => true, 0xFE3D => true, 0xFE3E => true, 0xFE3F => true, 0xFE40 => true, 0xFE41 => true, 0xFE42 => true, 0xFE43 => true, 0xFE44 => true, 0xFE47 => true, 0xFE48 => true, 0xFE49...0xFE4C => true, 0xFE4D...0xFE4F => true, 0xFE50...0xFE52 => true, 0xFE54...0xFE57 => true, 0xFE58 => true, 0xFE59 => true, 0xFE5A => true, 0xFE5B => true, 0xFE5C => true, 0xFE5D => true, 0xFE5E => true, 0xFE5F...0xFE61 => true, 0xFE62 => true, 0xFE63 => true, 0xFE64...0xFE66 => true, 0xFE68 => true, 0xFE69 => true, 0xFE6A...0xFE6B => true, 0xFE70...0xFE72 => true, 0xFE74 => true, 0xFE76...0xFEFC => true, 0xFEFF => true, 0xFF01...0xFF03 => true, 0xFF04 => true, 0xFF05...0xFF07 => true, 0xFF08 => true, 0xFF09 => true, 0xFF0A => true, 0xFF0B => true, 0xFF0C => true, 0xFF0D => true, 0xFF0E...0xFF0F => true, 0xFF10...0xFF19 => true, 0xFF1A...0xFF1B => true, 0xFF1C...0xFF1E => true, 0xFF1F...0xFF20 => true, 0xFF21...0xFF3A => true, 0xFF3B => true, 0xFF3C => true, 0xFF3D => true, 0xFF3E => true, 0xFF3F => true, 0xFF40 => true, 0xFF41...0xFF5A => true, 0xFF5B => true, 0xFF5C => true, 0xFF5D => true, 0xFF5E => true, 0xFF5F => true, 0xFF60 => true, 0xFF61 => true, 0xFF62 => true, 0xFF63 => true, 0xFF64...0xFF65 => true, 0xFF66...0xFF6F => true, 0xFF70 => true, 0xFF71...0xFF9D => true, 0xFF9E...0xFF9F => true, 0xFFA0...0xFFBE => true, 0xFFC2...0xFFC7 => true, 0xFFCA...0xFFCF => true, 0xFFD2...0xFFD7 => true, 0xFFDA...0xFFDC => true, 0xFFE0...0xFFE1 => true, 0xFFE2 => true, 0xFFE3 => true, 0xFFE4 => true, 0xFFE5...0xFFE6 => true, 0xFFE8 => true, 0xFFE9...0xFFEC => true, 0xFFED...0xFFEE => true, 0xFFF0...0xFFF8 => true, 0x10400...0x10427 => true, 0x104B0...0x104D3 => true, 0x10570...0x1057A => true, 0x1057C...0x1058A => true, 0x1058C...0x10592 => true, 0x10594...0x10595 => true, 0x10781...0x10785 => true, 0x10787...0x107B0 => true, 0x107B2...0x107BA => true, 0x10C80...0x10CB2 => true, 0x118A0...0x118BF => true, 0x16E40...0x16E5F => true, 0x1BCA0...0x1BCA3 => true, 0x1D15E...0x1D164 => true, 0x1D173...0x1D17A => true, 0x1D1BB...0x1D1C0 => 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, 0x1D6C1 => true, 0x1D6C2...0x1D6DA => true, 0x1D6DB => true, 0x1D6DC...0x1D6FA => true, 0x1D6FB => true, 0x1D6FC...0x1D714 => true, 0x1D715 => true, 0x1D716...0x1D734 => true, 0x1D735 => true, 0x1D736...0x1D74E => true, 0x1D74F => true, 0x1D750...0x1D76E => true, 0x1D76F => true, 0x1D770...0x1D788 => true, 0x1D789 => true, 0x1D78A...0x1D7A8 => true, 0x1D7A9 => true, 0x1D7AA...0x1D7C2 => true, 0x1D7C3 => true, 0x1D7C4...0x1D7CB => true, 0x1D7CE...0x1D7FF => true, 0x1E900...0x1E921 => 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, 0x1F100...0x1F10A => true, 0x1F110...0x1F12E => true, 0x1F130...0x1F14F => true, 0x1F16A...0x1F16C => true, 0x1F190 => true, 0x1F200...0x1F202 => true, 0x1F210...0x1F23B => true, 0x1F240...0x1F248 => true, 0x1F250...0x1F251 => true, 0x1FBF0...0x1FBF9 => true, 0x2F800...0x2FA1D => true, 0xE0000 => true, 0xE0001 => true, 0xE0002...0xE001F => true, 0xE0020...0xE007F => true, 0xE0080...0xE00FF => true, 0xE0100...0xE01EF => true, 0xE01F0...0xE0FFF => true, else => false, }; }
.gyro/ziglyph-jecolon-github.com-c37d93b6/pkg/src/autogen/derived_normalization_props.zig
const std = @import("std"); const print = std.debug.print; const aro = @import("aro"); const Codegen = aro.Codegen; const Tree = aro.Tree; const Token = Tree.Token; const NodeIndex = Tree.NodeIndex; const AllocatorError = std.mem.Allocator.Error; var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; pub fn main() !void { const gpa = general_purpose_allocator.allocator(); defer if (general_purpose_allocator.deinit()) std.process.exit(1); var args = try std.process.argsAlloc(gpa); defer std.process.argsFree(gpa, args); if (args.len != 3) { print("expected test case directory and zig executable as only arguments\n", .{}); return error.InvalidArguments; } var buf = std.ArrayList(u8).init(gpa); var cases = std.ArrayList([]const u8).init(gpa); defer { for (cases.items) |path| gpa.free(path); cases.deinit(); buf.deinit(); } // collect all cases { var cases_dir = try std.fs.cwd().openDir(args[1], .{ .iterate = true }); defer cases_dir.close(); var it = cases_dir.iterate(); while (try it.next()) |entry| { if (entry.kind == .Directory) continue; if (entry.kind != .File) { print("skipping non file entry '{s}'\n", .{entry.name}); continue; } defer buf.items.len = 0; try buf.writer().print("{s}{c}{s}", .{ args[1], std.fs.path.sep, entry.name }); try cases.append(try gpa.dupe(u8, buf.items)); } } var progress = std.Progress{}; const root_node = try progress.start("Test", cases.items.len); // prepare compiler var initial_comp = aro.Compilation.init(gpa); defer initial_comp.deinit(); try initial_comp.addDefaultPragmaHandlers(); try initial_comp.defineSystemIncludes(); // apparently we can't use setAstCwd without libc on windows yet const win = @import("builtin").os.tag == .windows; var tmp_dir = if (!win) std.testing.tmpDir(.{}); defer if (!win) tmp_dir.cleanup(); if (!win) try tmp_dir.dir.setAsCwd(); // iterate over all cases var ok_count: u32 = 0; var fail_count: u32 = 0; var skip_count: u32 = 0; next_test: for (cases.items) |path| { var comp = initial_comp; defer { // preserve some values comp.system_include_dirs = @TypeOf(comp.system_include_dirs).init(gpa); comp.pragma_handlers = @TypeOf(comp.pragma_handlers).init(gpa); comp.builtin_header_path = null; // reset everything else comp.deinit(); } const case = std.mem.sliceTo(std.fs.path.basename(path), '.'); var case_node = root_node.start(case, 0); case_node.activate(); defer case_node.end(); progress.refresh(); const file = comp.addSource(path) catch |err| { fail_count += 1; progress.log("could not add source '{s}': {s}\n", .{ path, @errorName(err) }); continue; }; if (std.mem.startsWith(u8, file.buf, "//aro-args")) { var test_args = std.ArrayList([]const u8).init(gpa); defer test_args.deinit(); var it = std.mem.tokenize(u8, std.mem.sliceTo(file.buf, '\n'), " "); while (it.next()) |some| try test_args.append(some); var source_files = std.ArrayList(aro.Source).init(std.testing.failing_allocator); _ = try aro.parseArgs(&comp, std.io.null_writer, &source_files, std.io.null_writer, test_args.items); } const builtin_macros = try comp.generateBuiltinMacros(); comp.diag.errors = 0; var pp = aro.Preprocessor.init(&comp); defer pp.deinit(); try pp.addBuiltinMacros(); _ = try pp.preprocess(builtin_macros); const eof = pp.preprocess(file) catch |err| { if (!std.unicode.utf8ValidateSlice(file.buf)) { // non-utf8 files are not preprocessed, so we can't use EXPECTED_ERRORS; instead we // check that the most recent error is .invalid_utf8 if (comp.diag.list.items.len > 0 and comp.diag.list.items[comp.diag.list.items.len - 1].tag == .invalid_utf8) { _ = comp.diag.list.pop(); continue; } } fail_count += 1; progress.log("could not preprocess file '{s}': {s}\n", .{ path, @errorName(err) }); continue; }; try pp.tokens.append(gpa, eof); if (pp.defines.get("TESTS_SKIPPED")) |macro| { if (macro.is_func or macro.tokens.len != 1 or macro.tokens[0].id != .integer_literal) { fail_count += 1; progress.log("invalid TESTS_SKIPPED, definition should contain exactly one integer literal {}\n", .{macro}); continue; } const tok_slice = pp.tokSlice(macro.tokens[0]); const tests_skipped = try std.fmt.parseInt(u32, tok_slice, 0); progress.log("{d} test{s} skipped\n", .{ tests_skipped, if (tests_skipped == 1) @as([]const u8, "") else "s" }); skip_count += tests_skipped; } if (comp.only_preprocess) { if (try checkExpectedErrors(&pp, &progress, &buf)) |some| { if (!some) { fail_count += 1; continue; } } else { comp.renderErrors(); if (comp.diag.errors != 0) { fail_count += 1; continue; } } const expected_output = blk: { const expaned_path = try std.fs.path.join(gpa, &.{ args[1], "expanded", std.fs.path.basename(path) }); defer gpa.free(expaned_path); break :blk try std.fs.cwd().readFileAlloc(gpa, expaned_path, std.math.maxInt(u32)); }; defer gpa.free(expected_output); var output = std.ArrayList(u8).init(gpa); defer output.deinit(); try pp.prettyPrintTokens(output.writer()); if (std.testing.expectEqualStrings(expected_output, output.items)) ok_count += 1 else |_| fail_count += 1; continue; } const expected_types = pp.defines.get("EXPECTED_TYPES"); var tree = try aro.Parser.parse(&pp); defer tree.deinit(); tree.dump(std.io.null_writer) catch {}; if (expected_types) |types| { const test_fn = for (tree.root_decls) |decl| { if (tree.nodes.items(.tag)[@enumToInt(decl)] == .fn_def) break tree.nodes.items(.data)[@enumToInt(decl)]; } else { fail_count += 1; progress.log("EXPECTED_TYPES requires a function to be defined\n", .{}); break; }; var actual = StmtTypeDumper.init(gpa); defer actual.deinit(gpa); try actual.dump(&tree, test_fn.decl.node, gpa); var i: usize = 0; for (types.tokens) |str| { if (str.id == .macro_ws) continue; if (str.id != .string_literal) { fail_count += 1; progress.log("EXPECTED_TYPES tokens must be string literals (found {s})\n", .{@tagName(str.id)}); continue :next_test; } defer i += 1; if (i >= actual.types.items.len) continue; const expected_type = std.mem.trim(u8, pp.tokSlice(str), "\""); const actual_type = actual.types.items[i]; if (!std.mem.eql(u8, expected_type, actual_type)) { fail_count += 1; progress.log("expected type '{s}' did not match actual type '{s}'\n", .{ expected_type, actual_type, }); continue :next_test; } } if (i != actual.types.items.len) { fail_count += 1; progress.log( "EXPECTED_TYPES count differs: expected {d} found {d}\n", .{ i, actual.types.items.len }, ); continue; } } if (try checkExpectedErrors(&pp, &progress, &buf)) |some| { if (some) ok_count += 1 else fail_count += 1; continue; } comp.renderErrors(); if (pp.defines.get("EXPECTED_OUTPUT")) |macro| blk: { if (comp.diag.errors != 0) break :blk; if (macro.is_func) { fail_count += 1; progress.log("invalid EXPECTED_OUTPUT {}\n", .{macro}); continue; } if (macro.tokens.len != 1 or macro.tokens[0].id != .string_literal) { fail_count += 1; progress.log("EXPECTED_OUTPUT takes exactly one string", .{}); continue; } defer buf.items.len = 0; // realistically the strings will only contain \" if any escapes so we can use Zig's string parsing std.debug.assert((try std.zig.string_literal.parseAppend(&buf, pp.tokSlice(macro.tokens[0]))) == .success); const expected_output = buf.items; const obj_name = "test_object.o"; { const obj = try Codegen.generateTree(&comp, tree); defer obj.deinit(); const out_file = try std.fs.cwd().createFile(obj_name, .{}); defer out_file.close(); try obj.finish(out_file); } var child = try std.ChildProcess.init(&.{ args[2], "run", "-lc", obj_name }, gpa); defer child.deinit(); child.stdout_behavior = .Pipe; try child.spawn(); const stdout = try child.stdout.?.reader().readAllAlloc(gpa, std.math.maxInt(u16)); defer gpa.free(stdout); switch (try child.wait()) { .Exited => |code| if (code != 0) { fail_count += 1; continue; }, else => { fail_count += 1; continue; }, } if (!std.mem.eql(u8, expected_output, stdout)) { fail_count += 1; progress.log( \\ \\======= expected output ======= \\{s} \\ \\=== but output does not contain it === \\{s} \\ \\ , .{ expected_output, stdout }); break; } ok_count += 1; continue; } if (comp.diag.errors != 0) fail_count += 1 else ok_count += 1; } root_node.end(); if (ok_count == cases.items.len and skip_count == 0) { print("All {d} tests passed.\n", .{ok_count}); } else if (fail_count == 0) { print("{d} passed; {d} skipped.\n", .{ ok_count, skip_count }); } else { print("{d} passed; {d} failed.\n\n", .{ ok_count, fail_count }); std.process.exit(1); } } // returns true if passed fn checkExpectedErrors(pp: *aro.Preprocessor, progress: *std.Progress, buf: *std.ArrayList(u8)) !?bool { const macro = pp.defines.get("EXPECTED_ERRORS") orelse return null; const expected_count = pp.comp.diag.list.items.len; var m = MsgWriter.init(pp.comp.gpa); defer m.deinit(); aro.Diagnostics.renderExtra(pp.comp, &m); if (macro.is_func) { progress.log("invalid EXPECTED_ERRORS {}\n", .{macro}); return false; } var count: usize = 0; for (macro.tokens) |str| { if (str.id == .macro_ws) continue; if (str.id != .string_literal) { progress.log("EXPECTED_ERRORS tokens must be string literals (found {s})\n", .{@tagName(str.id)}); return false; } defer count += 1; if (count >= expected_count) continue; defer buf.items.len = 0; // realistically the strings will only contain \" if any escapes so we can use Zig's string parsing std.debug.assert((try std.zig.string_literal.parseAppend(buf, pp.tokSlice(str))) == .success); try buf.append('\n'); const expected_error = buf.items; const index = std.mem.indexOf(u8, m.buf.items, expected_error); if (index == null) { progress.log( \\ \\======= expected to find error ======= \\{s} \\ \\=== but output does not contain it === \\{s} \\ \\ , .{ expected_error, m.buf.items }); return false; } } if (count != expected_count) { progress.log( \\EXPECTED_ERRORS missing errors, expected {d} found {d}, \\=== actual output === \\{s} \\ \\ , .{ count, expected_count, m.buf.items }); return false; } return true; } const MsgWriter = struct { buf: std.ArrayList(u8), fn init(gpa: std.mem.Allocator) MsgWriter { return .{ .buf = std.ArrayList(u8).init(gpa), }; } fn deinit(m: *MsgWriter) void { m.buf.deinit(); } pub fn print(m: *MsgWriter, comptime fmt: []const u8, args: anytype) void { m.buf.writer().print(fmt, args) catch {}; } pub fn write(m: *MsgWriter, msg: []const u8) void { m.buf.writer().writeAll(msg) catch {}; } pub fn location(m: *MsgWriter, path: []const u8, line: u32, col: u32) void { m.print("{s}:{d}:{d}: ", .{ path, line, col }); } pub fn start(m: *MsgWriter, kind: aro.Diagnostics.Kind) void { m.print("{s}: ", .{@tagName(kind)}); } pub fn end(m: *MsgWriter, maybe_line: ?[]const u8, col: u32) void { const line = maybe_line orelse { m.write("\n"); return; }; m.print("\n{s}\n", .{line}); m.print("{s: >[1]}^\n", .{ "", col }); } }; const StmtTypeDumper = struct { types: std.ArrayList([]const u8), fn deinit(self: *StmtTypeDumper, allocator: std.mem.Allocator) void { for (self.types.items) |t| { allocator.free(t); } self.types.deinit(); } fn init(allocator: std.mem.Allocator) StmtTypeDumper { return .{ .types = std.ArrayList([]const u8).init(allocator), }; } fn dumpNode(self: *StmtTypeDumper, tree: *const aro.Tree, node: NodeIndex, m: *MsgWriter) AllocatorError!void { if (node == .none) return; const tag = tree.nodes.items(.tag)[@enumToInt(node)]; if (tag == .implicit_return) return; const ty = tree.nodes.items(.ty)[@enumToInt(node)]; ty.dump(m.buf.writer()) catch {}; try self.types.append(m.buf.toOwnedSlice()); } fn dump(self: *StmtTypeDumper, tree: *const aro.Tree, decl_idx: NodeIndex, allocator: std.mem.Allocator) AllocatorError!void { var m = MsgWriter.init(allocator); defer m.deinit(); const idx = @enumToInt(decl_idx); const tag = tree.nodes.items(.tag)[idx]; const data = tree.nodes.items(.data)[idx]; switch (tag) { .compound_stmt_two => { try self.dumpNode(tree, data.bin.lhs, &m); try self.dumpNode(tree, data.bin.rhs, &m); }, .compound_stmt => { for (tree.data[data.range.start..data.range.end]) |stmt| { try self.dumpNode(tree, stmt, &m); } }, else => unreachable, } } };
test/runner.zig
const std = @import("std"); const PixelBuffer = @import("../video.zig").PixelBuffer; const console_ = @import("../console.zig"); const Config = console_.Config; const Console = console_.Console; const Cart = @import("../cart.zig").Cart; const Cpu = @import("../cpu.zig").Cpu; const common = @import("common.zig"); const Address = common.Address; const flags_ = @import("../flags.zig"); const FieldFlags = flags_.FieldFlags; const setMask = flags_.setMask; const getMaskBool = flags_.getMaskBool; pub fn Ppu(comptime config: Config) type { return struct { const Self = @This(); cart: *Cart(config), cpu: *Cpu(config), reg: Registers(config), mem: Memory(config), oam: Oam, scanline: u9 = 0, cycle: u9 = 0, odd_frame: bool = false, // internal registers vram_addr: Address = .{ .value = 0 }, vram_temp: Address = .{ .value = 0 }, fine_x: u3 = 0, current_nametable_byte: u8 = 0, pattern_sr1: BgPatternShiftRegister = .{}, pattern_sr2: BgPatternShiftRegister = .{}, attribute_sr1: AttributeShiftRegister = .{}, attribute_sr2: AttributeShiftRegister = .{}, pixel_buffer: *PixelBuffer(config.method), present_frame: bool = false, pub fn init(console: *Console(config), pixel_buffer: *PixelBuffer(config.method)) Self { return Self{ .cart = &console.cart, .cpu = &console.cpu, .reg = Registers(config).init(&console.ppu), .mem = Memory(config).init(&console.cart), .oam = std.mem.zeroes(Oam), .pixel_buffer = pixel_buffer, }; } pub fn deinit(_: Self) void {} fn incCoarseX(self: *Self) void { if ((self.vram_addr.value & @as(u15, 0x1f)) == 0x1f) { self.vram_addr.value = (self.vram_addr.value & ~@as(u15, 0x1f)) ^ 0x400; } else { self.vram_addr.value +%= 1; } } fn incCoarseY(self: *Self) void { if ((self.vram_addr.value & 0x7000) != 0x7000) { self.vram_addr.value += 0x1000; } else { self.vram_addr.value &= ~@as(u15, 0x7000); var y = (self.vram_addr.value & @as(u15, 0x03e0)) >> 5; if (y == 29) { y = 0; self.vram_addr.value ^= 0x0800; } else if (y == 31) { y = 0; } else { y += 1; } setMask(u15, &self.vram_addr.value, y << 5, 0x03e0); } } fn renderingEnabled(self: Self) bool { return self.reg.getFlags(.{ .flags = "sb" }) != 0; } fn onRenderScanline(self: Self) bool { return self.scanline < 240 or self.scanline == 261; } fn feedShiftRegisters(self: *Self) void { self.pattern_sr1.feed(); self.pattern_sr2.feed(); self.attribute_sr1.feed(); self.attribute_sr2.feed(); } fn loadShiftRegisters(self: *Self) void { self.pattern_sr1.load(); self.pattern_sr2.load(); self.attribute_sr1.load(); self.attribute_sr2.load(); } fn fetchNametableByte(self: *Self) void { self.current_nametable_byte = self.mem.read(0x2000 | @truncate(u14, self.vram_addr.value & 0xfff)); } fn fetchAttributeByte(self: *Self) void { const attribute_table_byte: u8 = self.mem.read(@as(u14, 0x23c0) | (@as(u14, self.vram_addr.nametableSelect()) << 10) | ((@as(u14, self.vram_addr.coarseY()) << 1) & 0x38) | ((self.vram_addr.coarseX() >> 2) & 7)); const x_quadrant = self.vram_addr.value & 2; const y_quadrant = (self.vram_addr.value >> 4) & 4; const shift = @truncate(u3, x_quadrant | y_quadrant); self.attribute_sr1.prepare(@truncate(u1, attribute_table_byte >> shift)); self.attribute_sr2.prepare(@truncate(u1, attribute_table_byte >> (shift + 1))); } fn fetchLowBgTile(self: *Self) void { const addr = (@as(u14, self.current_nametable_byte) << 4) | self.vram_addr.fineY(); const offset = if (self.reg.getFlag(.{ .field = "ppu_ctrl", .flags = "B" })) @as(u14, 0x1000) else 0; const pattern_table_byte = self.mem.read(addr | offset); self.pattern_sr1.prepare(pattern_table_byte); } fn fetchHighBgTile(self: *Self) void { const addr = (@as(u14, self.current_nametable_byte) << 4) | self.vram_addr.fineY(); const offset = if (self.reg.getFlag(.{ .field = "ppu_ctrl", .flags = "B" })) @as(u14, 0x1000) else 0; const pattern_table_byte = self.mem.read(addr | offset | 8); self.pattern_sr2.prepare(pattern_table_byte); } fn fetchNextByte(self: *Self) void { if (!((self.cycle >= 1 and self.cycle <= 256) or (self.cycle >= 321 and self.cycle <= 336))) { return; } self.feedShiftRegisters(); switch (@truncate(u2, self.cycle >> 1)) { 0 => { self.loadShiftRegisters(); self.fetchNametableByte(); // cycle % 8 == 0 }, 1 => self.fetchAttributeByte(), // cycle % 8 == 2 2 => self.fetchLowBgTile(), // cycle % 8 == 4 3 => self.fetchHighBgTile(), // cycle % 8 == 6 } } fn spriteEvaluation(self: *Self) void { switch (self.cycle) { 1...64 => if (self.cycle & 1 == 0) { self.oam.secondary[(self.cycle >> 1) - 1] = 0xff; }, 65...256 => { if (self.oam.search_finished) { return; } if (self.cycle & 1 == 1) { // read cycle self.oam.readForSecondary(); return; } else if (self.oam.primary_index & 3 == 0) { const sprite_height = if (self.reg.getFlag(.{ .flags = "H" })) @as(u5, 16) else 8; // check if y is in range const sprite_y = self.oam.temp_read_byte; if (sprite_y <= self.scanline and @as(u9, sprite_y) + sprite_height > self.scanline) { if (self.oam.primary_index == 0) { self.oam.next_has_sprite_0 = true; } self.oam.storeSecondary(); } else { self.oam.primary_index +%= 4; } } else { // copy the rest of bytes 1 <= n <= 3 self.oam.storeSecondary(); if (self.oam.primary_index & 3 == 0) { self.oam.sprites_found += 1; } } if (self.oam.primary_index == 0 or self.oam.sprites_found == 8) { self.oam.search_finished = true; } }, 257...320 => { // not exactly cycle accurate if (self.cycle & 1 != 0 or self.oam.sprite_index == self.oam.sprites_found or self.oam.sprite_index == 8) { return; } const y = self.oam.secondary[self.oam.sprite_index * 4]; const tile_index = self.oam.secondary[self.oam.sprite_index * 4 + 1]; const attributes = self.oam.secondary[self.oam.sprite_index * 4 + 2]; const x = self.oam.secondary[self.oam.sprite_index * 4 + 3]; const y_offset_16 = if (getMaskBool(u8, attributes, 0x80)) @truncate(u4, ~(self.scanline - y)) else @truncate(u4, self.scanline - y); const y_offset = @truncate(u3, y_offset_16); const tile_offset = @as(u14, tile_index) << 4; const pattern_offset = blk: { if (self.reg.getFlag(.{ .flags = "H" })) { const bank = @as(u14, tile_index & 1) << 12; const tile_offset_16 = tile_offset & ~@as(u14, 0x10); if (y_offset_16 < 8) { break :blk bank | tile_offset_16; } else { break :blk bank | tile_offset_16 | 0x10; } } else if (self.reg.getFlag(.{ .field = "ppu_ctrl", .flags = "S" })) { break :blk 0x1000 | tile_offset; } else { break :blk tile_offset; } }; switch (@truncate(u2, self.cycle >> 1)) { 0 => {}, 1 => { self.oam.sprite_x_counters[self.oam.sprite_index] = x; self.oam.sprite_attributes[self.oam.sprite_index] = attributes; }, 2 => { const pattern_byte = blk: { var byte = self.mem.read(pattern_offset | y_offset); if (attributes & 0x40 != 0) { byte = @bitReverse(u8, byte); } break :blk byte; }; self.oam.sprite_pattern_srs1[self.oam.sprite_index].load(pattern_byte); }, 3 => { const pattern_byte = blk: { var byte = self.mem.read(pattern_offset | y_offset | 8); if (attributes & 0x40 != 0) { byte = @bitReverse(u8, byte); } break :blk byte; }; self.oam.sprite_pattern_srs2[self.oam.sprite_index].load(pattern_byte); self.oam.sprite_index += 1; }, } }, else => {}, } } pub fn runCycle(self: *Self) void { defer self.runPostCycle(); if (!(self.onRenderScanline() and self.renderingEnabled())) { return; } self.fetchNextByte(); if (self.scanline < 240) { self.spriteEvaluation(); if (self.cycle < 256) { self.drawPixel(); } } if (self.cycle > 0) { if (self.cycle > 257 and self.cycle < 321) { self.reg.oam_addr = 0; if (self.scanline == 261 and self.cycle >= 280 and self.cycle <= 304) { // set coarse and fine y as well as 0x800 (high nametable select bit) setMask(u15, &self.vram_addr.value, self.vram_temp.value, 0x7be0); } } else if (self.cycle == 256) { self.incCoarseY(); } else if ((self.cycle & 7) == 0) { self.incCoarseX(); } else if (self.cycle == 257) { // set coarse x and 0x400 (low nametable select bit) setMask(u15, &self.vram_addr.value, self.vram_temp.value, 0x41f); } } } fn runPostCycle(self: *Self) void { if (self.scanline == 261 and self.cycle == 339 and self.odd_frame) { self.cycle += 1; } self.cycle += 1; if (self.cycle == 341) { self.cycle = 0; self.scanline = (self.scanline + 1) % 262; self.oam.resetSecondaryTemps(); } if (self.scanline == 241 and self.cycle == 1) { self.reg.setFlag(.{ .field = "ppu_status", .flags = "V" }, true); if (self.reg.getFlag(.{ .field = "ppu_ctrl", .flags = "V" })) { self.cpu.setNmi(); } self.present_frame = true; } else if (self.scanline == 261 and self.cycle == 1) { self.reg.setFlags(.{ .field = "ppu_status", .flags = "VS" }, 0); self.odd_frame = !self.odd_frame; } } fn drawPixel(self: *Self) void { const bg_pattern_index: u2 = blk: { if (self.reg.getFlag(.{ .flags = "b" })) { const p1 = self.pattern_sr1.get(self.fine_x); const p2 = self.pattern_sr2.get(self.fine_x); break :blk p1 | (@as(u2, p2) << 1); } else { break :blk 0; } }; var sprite_pattern_index: u2 = 0; var sprite_attribute_index: u2 = 0; var sprite_behind: bool = false; if (self.reg.getFlag(.{ .flags = "s" })) { var i: usize = 0; while (i < self.oam.active_sprites) : (i += 1) { if (sprite_pattern_index == 0 and self.oam.sprite_x_counters[i] == 0) { const p1 = self.oam.sprite_pattern_srs1[i].get(); const p2 = self.oam.sprite_pattern_srs2[i].get(); const pattern_index = p1 | (@as(u2, p2) << 1); if (pattern_index != 0) { sprite_pattern_index = pattern_index; sprite_attribute_index = @truncate(u2, self.oam.sprite_attributes[i]); sprite_behind = getMaskBool(u8, self.oam.sprite_attributes[i], 0x20); if (i == 0 and self.oam.has_sprite_0 and bg_pattern_index != 0) { self.reg.setFlag(.{ .field = "ppu_status", .flags = "S" }, true); } } } else if (self.oam.sprite_x_counters[i] > 0) { self.oam.sprite_x_counters[i] -= 1; continue; } if (self.oam.sprite_x_counters[i] == 0) { self.oam.sprite_pattern_srs1[i].feed(); self.oam.sprite_pattern_srs2[i].feed(); } } } const addr = blk: { if (bg_pattern_index == 0 and sprite_pattern_index == 0) { break :blk 0x3f00; } else { var pattern_index: u2 = undefined; var attribute_index: u14 = undefined; var palette_base: u14 = undefined; if (sprite_pattern_index != 0 and !(sprite_behind and bg_pattern_index != 0)) { pattern_index = sprite_pattern_index; attribute_index = sprite_attribute_index; palette_base = 0x3f10; } else { pattern_index = bg_pattern_index; const a1 = self.attribute_sr1.get(self.fine_x); const a2 = self.attribute_sr2.get(self.fine_x); attribute_index = a1 | (@as(u2, a2) << 1); palette_base = 0x3f00; } break :blk palette_base | (attribute_index << 2) | pattern_index; } }; const palette_byte = self.mem.read(addr) & 0x3f; self.pixel_buffer.putPixel(self.cycle, self.scanline, common.palette[palette_byte]); } }; } const BgPatternShiftRegister = struct { bits: u16 = 0, next_byte: u8 = 0, fn feed(self: *BgPatternShiftRegister) void { self.bits <<= 1; } fn prepare(self: *BgPatternShiftRegister, byte: u8) void { self.next_byte = byte; } fn load(self: *BgPatternShiftRegister) void { self.bits |= self.next_byte; self.next_byte = 0; } fn get(self: BgPatternShiftRegister, offset: u3) u1 { return @truncate(u1, ((self.bits << offset) & 0x8000) >> 15); } }; const SpritePatternShiftRegister = struct { bits: u8 = 0, fn feed(self: *SpritePatternShiftRegister) void { self.bits <<= 1; } fn load(self: *SpritePatternShiftRegister, byte: u8) void { self.bits = byte; } fn get(self: SpritePatternShiftRegister) u1 { return @truncate(u1, (self.bits & 0x80) >> 7); } }; const AttributeShiftRegister = struct { bits: u8 = 0, latch: u1 = 0, next_latch: u1 = 0, fn feed(self: *AttributeShiftRegister) void { self.bits = (self.bits << 1) | self.latch; } fn prepare(self: *AttributeShiftRegister, bit: u1) void { self.next_latch = bit; } fn load(self: *AttributeShiftRegister) void { self.latch = self.next_latch; } fn get(self: AttributeShiftRegister, offset: u3) u1 { return @truncate(u1, ((self.bits << offset) & 0x80) >> 7); } }; pub fn Registers(comptime config: Config) type { return struct { const Self = @This(); ppu: *Ppu(config), ppu_ctrl: u8 = 0, ppu_mask: u8 = 0, ppu_status: u8 = 0, oam_addr: u8 = 0, oam_data: u8 = 0, ppu_scroll: u8 = 0, ppu_addr: u8 = 0, ppu_data: u8 = 0, write_toggle: bool = false, io_bus: u8 = 0, vram_data_buffer: u8 = 0, const ff_masks = common.RegisterMasks(Self){}; fn init(ppu: *Ppu(config)) Self { return Self{ .ppu = ppu }; } // flag functions do not have side effects even when they should fn getFlag(self: Self, comptime flags: FieldFlags) bool { return ff_masks.getFlag(self, flags); } fn getFlags(self: Self, comptime flags: FieldFlags) u8 { return ff_masks.getFlags(self, flags); } fn setFlag(self: *Self, comptime flags: FieldFlags, val: bool) void { return ff_masks.setFlag(self, flags, val); } fn setFlags(self: *Self, comptime flags: FieldFlags, val: u8) void { return ff_masks.setFlags(self, flags, val); } pub fn peek(self: Self, i: u3) u8 { return switch (i) { 0 => self.ppu_ctrl, 1 => self.ppu_mask, 2 => self.ppu_status, 3 => self.oam_addr, 4 => self.oam_data, 5 => self.ppu_scroll, 6 => self.ppu_addr, 7 => self.ppu_data, }; } pub fn read(self: *Self, i: u3) u8 { switch (i) { 0, 1, 3, 5, 6 => return self.io_bus, 2 => { const prev = self.ppu_status; self.ppu.reg.setFlag(.{ .field = "ppu_status", .flags = "V" }, false); self.write_toggle = false; return prev | (self.io_bus & 0x1f); }, 4 => { return self.ppu.oam.primary[self.oam_addr]; }, 7 => { const val = blk: { const mem_val = self.ppu.mem.read(@truncate(u14, self.ppu.vram_addr.value)); if (self.ppu.vram_addr.value < 0x3f00) { const prev = self.vram_data_buffer; self.vram_data_buffer = mem_val; break :blk prev; } else { // quirk const nametable_addr = @truncate(u14, self.ppu.vram_addr.value) & 0x2fff; self.vram_data_buffer = self.ppu.mem.read(nametable_addr); break :blk mem_val; } }; self.ppu.vram_addr.value +%= if (self.getFlag(.{ .flags = "I" })) @as(u8, 32) else 1; return val; }, } } pub fn write(self: *Self, i: u3, val: u8) void { self.io_bus = val; var val_u15 = @as(u15, val); switch (i) { 0 => { setMask(u15, &self.ppu.vram_temp.value, (val_u15 & 3) << 10, 0b000_1100_0000_0000); self.ppu_ctrl = val; }, 1 => self.ppu_mask = val, 2 => {}, 3 => self.oam_addr = val, 4 => { self.ppu.oam.primary[self.oam_addr] = val; self.oam_addr +%= 1; }, 5 => if (!self.write_toggle) { setMask(u15, &self.ppu.vram_temp.value, val >> 3, 0x1f); self.ppu.fine_x = @truncate(u3, val); self.write_toggle = true; } else { setMask( u15, &self.ppu.vram_temp.value, ((val_u15 & 0xf8) << 2) | ((val_u15 & 7) << 12), 0b111_0011_1110_0000, ); self.write_toggle = false; }, 6 => if (!self.write_toggle) { setMask(u15, &self.ppu.vram_temp.value, (val_u15 & 0x3f) << 8, 0b0111_1111_0000_0000); self.write_toggle = true; } else { setMask(u15, &self.ppu.vram_temp.value, val_u15, 0xff); self.ppu.vram_addr.value = self.ppu.vram_temp.value; self.write_toggle = false; }, 7 => { self.ppu.mem.write(@truncate(u14, self.ppu.vram_addr.value), val); self.ppu.vram_addr.value +%= if (self.getFlag(.{ .flags = "I" })) @as(u8, 32) else 1; }, } } }; } pub fn Memory(comptime config: Config) type { return struct { const Self = @This(); cart: *Cart(config), nametables: [0x1000]u8, palettes: [0x20]u8, address_bus: u14 = 0, fn init(cart: *Cart(config)) Self { return Self{ .cart = cart, .nametables = std.mem.zeroes([0x1000]u8), .palettes = std.mem.zeroes([0x20]u8), }; } pub fn peek(self: Self, addr: u14) u8 { return switch (addr) { 0x0000...0x1fff => self.cart.peekChr(addr), 0x2000...0x3eff => self.nametables[self.cart.mirrorNametable(addr)], 0x3f00...0x3fff => if (addr & 3 == 0) self.palettes[addr & 0x0c] else self.palettes[addr & 0x1f], }; } pub fn read(self: *Self, addr: u14) u8 { self.address_bus = addr; return switch (addr) { 0x0000...0x1fff => self.cart.readChr(addr), 0x2000...0x3eff => self.nametables[self.cart.mirrorNametable(addr)], 0x3f00...0x3fff => if (addr & 3 == 0) self.palettes[addr & 0x0c] else self.palettes[addr & 0x1f], }; } pub fn write(self: *Self, addr: u14, val: u8) void { self.address_bus = addr; switch (addr) { 0x0000...0x1fff => self.cart.writeChr(addr, val), 0x2000...0x3eff => self.nametables[self.cart.mirrorNametable(addr)] = val, 0x3f00...0x3fff => if (addr & 3 == 0) { self.palettes[addr & 0x0c] = val; } else { self.palettes[addr & 0x1f] = val; }, } } }; } const Oam = struct { primary: [0x100]u8, secondary: [0x20]u8, // information needed to draw current scanline sprite_pattern_srs1: [8]SpritePatternShiftRegister, sprite_pattern_srs2: [8]SpritePatternShiftRegister, sprite_attributes: [8]u8, sprite_x_counters: [8]u8, active_sprites: u8, has_sprite_0: bool, // for sprite evaluation step 2 temp_read_byte: u8, primary_index: u8, sprites_found: u8, search_finished: bool, next_has_sprite_0: bool, // for sprite evaluation step 3 sprite_index: u8, fn resetSecondaryTemps(self: *Oam) void { self.primary_index = 0; self.sprites_found = 0; self.search_finished = false; self.active_sprites = self.sprite_index; self.has_sprite_0 = self.next_has_sprite_0; self.next_has_sprite_0 = false; self.sprite_index = 0; } fn readForSecondary(self: *Oam) void { self.temp_read_byte = self.primary[self.primary_index]; } fn storeSecondary(self: *Oam) void { self.secondary[self.sprites_found * 4 + (self.primary_index & 3)] = self.temp_read_byte; self.primary_index +%= 1; } };
src/ppu/accurate.zig
const std = @import("std"); const c = @import("internal/c.zig"); const internal = @import("internal/internal.zig"); const log = std.log.scoped(.git); const git = @import("git.zig"); pub const GitError = error{ /// Generic error GenericError, /// Requested object could not be found NotFound, /// Object exists preventing operation Exists, /// More than one object matches Ambiguous, /// Output buffer too short to hold data BufferTooShort, /// A special error that is never generated by libgit2 code. You can return it from a callback (e.g to stop an iteration) /// to know that it was generated by the callback and not by libgit2. User, /// Operation not allowed on bare repository BareRepo, /// HEAD refers to branch with no commits UnbornBranch, /// Merge in progress prevented operation Unmerged, /// Reference was not fast-forwardable NonFastForwardable, /// Name/ref spec was not in a valid format InvalidSpec, /// Checkout conflicts prevented operation Conflict, /// Lock file prevented operation Locked, /// Reference value does not match expected Modifed, /// Authentication error Auth, /// Server certificate is invalid Certificate, /// Patch/merge has already been applied Applied, /// The requested peel operation is not possible Peel, /// Unexpected EOF EndOfFile, /// Invalid operation or input Invalid, /// Uncommitted changes in index prevented operation Uncommited, /// The operation is not valid for a directory Directory, /// A merge conflict exists and cannot continue MergeConflict, /// A user-configured callback refused to act Passthrough, /// Signals end of iteration with iterator IterOver, /// Internal only Retry, /// Hashsum mismatch in object Mismatch, /// Unsaved changes in the index would be overwritten IndexDirty, /// Patch application failed ApplyFail, }; /// Get detailed information regarding the last error that occured on *this* thread. pub fn getDetailedLastError() ?*const DetailedError { return @ptrCast(?*const DetailedError, c.git_error_last()); } /// Clear the last error that occured on *this* thread. pub fn clearLastError() void { c.git_error_clear(); } pub const DetailedError = extern struct { raw_message: [*:0]const u8, class: ErrorClass, pub const ErrorClass = enum(c_int) { NONE = 0, NOMEMORY, OS, INVALID, REFERENCE, ZLIB, REPOSITORY, CONFIG, REGEX, ODB, INDEX, OBJECT, NET, TAG, TREE, INDEXER, SSL, SUBMODULE, THREAD, STASH, CHECKOUT, FETCHHEAD, MERGE, SSH, FILTER, REVERT, CALLBACK, CHERRYPICK, DESCRIBE, REBASE, FILESYSTEM, PATCH, WORKTREE, SHA1, HTTP, INTERNAL, }; pub fn message(self: DetailedError) [:0]const u8 { return std.mem.sliceTo(self.raw_message, 0); } test { try std.testing.expectEqual(@sizeOf(c.git_error), @sizeOf(DetailedError)); try std.testing.expectEqual(@bitSizeOf(c.git_error), @bitSizeOf(DetailedError)); } comptime { std.testing.refAllDecls(@This()); } }; comptime { std.testing.refAllDecls(@This()); }
src/errors.zig
const std = @import("std"); const with_trace = true; const assert = std.debug.assert; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } pub fn main() anyerror!void { 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, "day8.txt", limit); var size_doubleescpaed: u32 = 0; var size_escaped: u32 = 0; var size_final: u32 = 0; var it = std.mem.split(u8, text, "\n"); while (it.next()) |line_full| { const line_quoted = std.mem.trim(u8, line_full, " \n\r\t"); if (line_quoted.len < 2) continue; assert(line_quoted[0] == '"' and line_quoted[line_quoted.len - 1] == '"'); const line = line_quoted[1 .. line_quoted.len - 1]; size_escaped += 2; size_doubleescpaed += 6; var i: u32 = 0; while (i < line.len) : (i += 1) { const c = line[i]; if (c == '\\') { size_doubleescpaed += 2; const c1 = line[i + 1]; if (c1 == '\\' or c1 == '"') { size_doubleescpaed += 2; size_escaped += 2; size_final += 1; i += 1; } else if (c1 == 'x') { size_doubleescpaed += 3; size_escaped += 4; size_final += 1; i += 3; } else { unreachable; } } else { size_doubleescpaed += 1; size_escaped += 1; size_final += 1; } } } const out = std.io.getStdOut().writer(); try out.print("chars {}-{} = {}\n", size_escaped, size_final, size_escaped - size_final); try out.print("chars {}-{} = {}\n", size_doubleescpaed, size_escaped, size_doubleescpaed - size_escaped); // return error.SolutionNotFound; }
2015/day8.zig
const std = @import("std"); const c = @import("../../c_global.zig").c_imp; // dross-zig const Vector2 = @import("../../core/vector2.zig").Vector2; const Renderer = @import("../renderer.zig").Renderer; const PackingMode = @import("../renderer.zig").PackingMode; const ByteAlignment = @import("../renderer.zig").ByteAlignment; const fs = @import("../../utils/file_loader.zig"); const gly = @import("glyph.zig"); const Glyph = gly.Glyph; // ----------------------------------------------------------------------------- // ----------------------------------------- // - Font - // ----------------------------------------- /// pub const Font = struct { glyphs: std.AutoHashMap(u32, *Glyph), // FreeType library: ?*c.FT_Library, face: ?*c.FT_Face, const Self = @This(); /// Creates a new Font instance /// Comments: The caller should only be going through the Resource Handler. /// The Resource Handler will automatically handle de-allocating. pub fn new(allocator: *std.mem.Allocator, path: [*c]const u8) !*Self { var self = try allocator.create(Font); // Allocate the memory block for the Font Library self.library = allocator.create(c.FT_Library) catch |err| { std.debug.print("[Font]: Error occurred while creating font library for {s}! {s}\n", .{ path, err }); @panic("[Font]: Error occurred while creating font!\n"); }; // Initialize the Font Library const library_error = c.FT_Init_FreeType(self.library.?); if (library_error != 0) @panic("[Font]: Error occurred when initializing FreeType Library!"); // Allocate the memory block for the Font Face self.face = allocator.create(c.FT_Face) catch |err| { std.debug.print("[Font]: Error occurred while creating font face for {s}! {s}\n", .{ path, err }); @panic("[Font]: Error occurred while creating font!\n"); }; // Initialize the Font Face const face_error = c.FT_New_Face(self.library.?.*, path, 0, self.face.?); if (face_error != 0) @panic("[Font]: Error occurred when initializing FreeType Face!"); // Set the font's pixel size // NOTE(devon): Giving it a pixel width of 0 will force it to be dynamically calculated. const pixel_size_error = c.FT_Set_Pixel_Sizes(self.face.?.*, 0, 24); // face, pixel_width, pixel_height if (pixel_size_error != 0) @panic("[Font]: Error occurred when setting the pixel size!"); // Set the unpack byte alignment to 1 byte Renderer.setByteAlignment(PackingMode.Unpack, ByteAlignment.One); // Initialize the glyph hashmap self.glyphs = std.AutoHashMap(u32, *Glyph).init(allocator); // Loop through and setup the glyphs const number_of_glyphs = 128; const start_offset = 32; var character: u32 = start_offset; while (character < start_offset + number_of_glyphs) : (character += 1) { // Load the glyph const char_load_error = c.FT_Load_Char(self.face.?.*, @intCast(c_ulong, character), c.FT_LOAD_RENDER); if (char_load_error != 0) @panic("[Font]: Error occurred when loading glyph!"); const glyph_width = @intCast(u32, self.face.?.*.*.glyph.*.bitmap.width); const glyph_rows = @intCast(u32, self.face.?.*.*.glyph.*.bitmap.rows); const glyph_offset_x = @intCast(i32, self.face.?.*.*.glyph.*.bitmap_left); const glyph_offset_y = @intCast(i32, self.face.?.*.*.glyph.*.bitmap_top); const glyph_x_advance = @intCast(u32, self.face.?.*.*.glyph.*.advance.x); const buffer_data = self.face.?.*.*.glyph.*.bitmap.buffer; // Generate Texture var new_glyph = try Glyph.new(allocator, buffer_data, glyph_width, glyph_rows, glyph_offset_x, glyph_offset_y, glyph_x_advance); //// Add glyph to the list try self.glyphs.put(character, new_glyph); } Renderer.clearBoundTexture(); return self; } /// Cleans up and de-allocates any memory in regards to the Font instance. pub fn free(allocator: *std.mem.Allocator, self: *Self) void { _ = c.FT_Done_Face(self.face.?.*); _ = c.FT_Done_FreeType(self.library.?.*); var glyph_iter = self.glyphs.iterator(); while (glyph_iter.next()) |entry| { var glyph_entry = self.glyphs.remove(entry.key); Glyph.free(allocator, glyph_entry.?.value); } self.glyphs.deinit(); allocator.destroy(self.face.?); allocator.destroy(self.library.?); allocator.destroy(self); } /// Returns a pointer to the glyph pub fn glyph(self: *Self, character: u8) !*Glyph { return self.glyphs.get(@intCast(c_ulong, character)).?; } };
src/renderer/font/font.zig
pub const FD_EVENTID_PRIVATE = @as(u32, 100); pub const FD_EVENTID = @as(u32, 1000); pub const FD_EVENTID_SEARCHCOMPLETE = @as(u32, 1000); pub const FD_EVENTID_ASYNCTHREADEXIT = @as(u32, 1001); pub const FD_EVENTID_SEARCHSTART = @as(u32, 1002); pub const FD_EVENTID_IPADDRESSCHANGE = @as(u32, 1003); pub const FD_EVENTID_QUERYREFRESH = @as(u32, 1004); pub const SID_PnpProvider = Guid.initString("8101368e-cabb-4426-acff-96c410812000"); pub const SID_UPnPActivator = Guid.initString("0d0d66eb-cf74-4164-b52f-08344672dd46"); pub const SID_EnumInterface = Guid.initString("40eab0b9-4d7f-4b53-a334-1581dd9041f4"); pub const SID_PNPXPropertyStore = Guid.initString("a86530b1-542f-439f-b71c-b0756b13677a"); pub const SID_PNPXAssociation = Guid.initString("cee8ccc9-4f6b-4469-a235-5a22869eef03"); pub const SID_PNPXServiceCollection = Guid.initString("439e80ee-a217-4712-9fa6-deabd9c2a727"); pub const SID_FDPairingHandler = Guid.initString("383b69fa-5486-49da-91f5-d63c24c8e9d0"); pub const SID_EnumDeviceFunction = Guid.initString("13e0e9e2-c3fa-4e3c-906e-64502fa4dc95"); pub const SID_UnpairProvider = Guid.initString("89a502fc-857b-4698-a0b7-027192002f9e"); pub const SID_DeviceDisplayStatusManager = Guid.initString("f59aa553-8309-46ca-9736-1ac3c62d6031"); pub const SID_FunctionDiscoveryProviderRefresh = Guid.initString("2b4cbdc9-31c4-40d4-a62d-772aa174ed52"); pub const SID_UninstallDeviceFunction = Guid.initString("c920566e-5671-4496-8025-bf0b89bd44cd"); pub const FMTID_FD = Guid.initString("904b03a2-471d-423c-a584-f3483238a146"); pub const FD_Visibility_Default = @as(u32, 0); pub const FD_Visibility_Hidden = @as(u32, 1); pub const FMTID_Device = Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"); pub const FMTID_DeviceInterface = Guid.initString("53808008-07bb-4661-bc3c-b5953e708560"); pub const FMTID_Pairing = Guid.initString("8807cae6-7db6-4f10-8ee4-435eaa1392bc"); pub const FMTID_WSD = Guid.initString("92506491-ff95-4724-a05a-5b81885a7c92"); pub const FMTID_PNPX = Guid.initString("656a3bb3-ecc0-43fd-8477-4ae0404a96cd"); pub const FMTID_PNPXDynamicProperty = Guid.initString("4fc5077e-b686-44be-93e3-86cafe368ccd"); pub const PNPX_INSTALLSTATE_NOTINSTALLED = @as(u32, 0); pub const PNPX_INSTALLSTATE_INSTALLED = @as(u32, 1); pub const PNPX_INSTALLSTATE_INSTALLING = @as(u32, 2); pub const PNPX_INSTALLSTATE_FAILED = @as(u32, 3); pub const FD_LONGHORN = @as(u32, 1); pub const MAX_FDCONSTRAINTNAME_LENGTH = @as(u32, 100); pub const MAX_FDCONSTRAINTVALUE_LENGTH = @as(u32, 1000); pub const E_FDPAIRING_NOCONNECTION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1882193919)); pub const E_FDPAIRING_HWFAILURE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1882193918)); pub const E_FDPAIRING_AUTHFAILURE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1882193917)); pub const E_FDPAIRING_CONNECTTIMEOUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1882193916)); pub const E_FDPAIRING_TOOMANYCONNECTIONS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1882193915)); pub const E_FDPAIRING_AUTHNOTALLOWED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1882193914)); pub const E_FDPAIRING_IPBUSDISABLED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1882193913)); pub const E_FDPAIRING_NOPROFILES = @import("../zig.zig").typedConst(HRESULT, @as(i32, -1882193912)); //-------------------------------------------------------------------------------- // Section: Types (27) //-------------------------------------------------------------------------------- pub const PropertyConstraint = enum(i32) { EQUALS = 0, NOTEQUAL = 1, LESSTHAN = 2, LESSTHANOREQUAL = 3, GREATERTHAN = 4, GREATERTHANOREQUAL = 5, STARTSWITH = 6, EXISTS = 7, DOESNOTEXIST = 8, CONTAINS = 9, }; pub const QC_EQUALS = PropertyConstraint.EQUALS; pub const QC_NOTEQUAL = PropertyConstraint.NOTEQUAL; pub const QC_LESSTHAN = PropertyConstraint.LESSTHAN; pub const QC_LESSTHANOREQUAL = PropertyConstraint.LESSTHANOREQUAL; pub const QC_GREATERTHAN = PropertyConstraint.GREATERTHAN; pub const QC_GREATERTHANOREQUAL = PropertyConstraint.GREATERTHANOREQUAL; pub const QC_STARTSWITH = PropertyConstraint.STARTSWITH; pub const QC_EXISTS = PropertyConstraint.EXISTS; pub const QC_DOESNOTEXIST = PropertyConstraint.DOESNOTEXIST; pub const QC_CONTAINS = PropertyConstraint.CONTAINS; pub const SystemVisibilityFlags = enum(i32) { SYSTEM = 0, USER = 1, }; pub const SVF_SYSTEM = SystemVisibilityFlags.SYSTEM; pub const SVF_USER = SystemVisibilityFlags.USER; pub const QueryUpdateAction = enum(i32) { ADD = 0, REMOVE = 1, CHANGE = 2, }; pub const QUA_ADD = QueryUpdateAction.ADD; pub const QUA_REMOVE = QueryUpdateAction.REMOVE; pub const QUA_CHANGE = QueryUpdateAction.CHANGE; pub const QueryCategoryType = enum(i32) { PROVIDER = 0, LAYERED = 1, }; pub const QCT_PROVIDER = QueryCategoryType.PROVIDER; pub const QCT_LAYERED = QueryCategoryType.LAYERED; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IFunctionDiscoveryNotification_Value = @import("../zig.zig").Guid.initString("5f6c1ba8-5330-422e-a368-572b244d3f87"); pub const IID_IFunctionDiscoveryNotification = &IID_IFunctionDiscoveryNotification_Value; pub const IFunctionDiscoveryNotification = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnUpdate: fn( self: *const IFunctionDiscoveryNotification, enumQueryUpdateAction: QueryUpdateAction, fdqcQueryContext: u64, pIFunctionInstance: ?*IFunctionInstance, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnError: fn( self: *const IFunctionDiscoveryNotification, hr: HRESULT, fdqcQueryContext: u64, pszProvider: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnEvent: fn( self: *const IFunctionDiscoveryNotification, dwEventID: u32, fdqcQueryContext: u64, pszProvider: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscoveryNotification_OnUpdate(self: *const T, enumQueryUpdateAction: QueryUpdateAction, fdqcQueryContext: u64, pIFunctionInstance: ?*IFunctionInstance) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryNotification.VTable, self.vtable).OnUpdate(@ptrCast(*const IFunctionDiscoveryNotification, self), enumQueryUpdateAction, fdqcQueryContext, pIFunctionInstance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscoveryNotification_OnError(self: *const T, hr: HRESULT, fdqcQueryContext: u64, pszProvider: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryNotification.VTable, self.vtable).OnError(@ptrCast(*const IFunctionDiscoveryNotification, self), hr, fdqcQueryContext, pszProvider); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscoveryNotification_OnEvent(self: *const T, dwEventID: u32, fdqcQueryContext: u64, pszProvider: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryNotification.VTable, self.vtable).OnEvent(@ptrCast(*const IFunctionDiscoveryNotification, self), dwEventID, fdqcQueryContext, pszProvider); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IFunctionDiscovery_Value = @import("../zig.zig").Guid.initString("4df99b70-e148-4432-b004-4c9eeb535a5e"); pub const IID_IFunctionDiscovery = &IID_IFunctionDiscovery_Value; pub const IFunctionDiscovery = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetInstanceCollection: fn( self: *const IFunctionDiscovery, pszCategory: ?[*:0]const u16, pszSubCategory: ?[*:0]const u16, fIncludeAllSubCategories: BOOL, ppIFunctionInstanceCollection: ?*?*IFunctionInstanceCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInstance: fn( self: *const IFunctionDiscovery, pszFunctionInstanceIdentity: ?[*:0]const u16, ppIFunctionInstance: ?*?*IFunctionInstance, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateInstanceCollectionQuery: fn( self: *const IFunctionDiscovery, pszCategory: ?[*:0]const u16, pszSubCategory: ?[*:0]const u16, fIncludeAllSubCategories: BOOL, pIFunctionDiscoveryNotification: ?*IFunctionDiscoveryNotification, pfdqcQueryContext: ?*u64, ppIFunctionInstanceCollectionQuery: ?*?*IFunctionInstanceCollectionQuery, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateInstanceQuery: fn( self: *const IFunctionDiscovery, pszFunctionInstanceIdentity: ?[*:0]const u16, pIFunctionDiscoveryNotification: ?*IFunctionDiscoveryNotification, pfdqcQueryContext: ?*u64, ppIFunctionInstanceQuery: ?*?*IFunctionInstanceQuery, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddInstance: fn( self: *const IFunctionDiscovery, enumSystemVisibility: SystemVisibilityFlags, pszCategory: ?[*:0]const u16, pszSubCategory: ?[*:0]const u16, pszCategoryIdentity: ?[*:0]const u16, ppIFunctionInstance: ?*?*IFunctionInstance, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveInstance: fn( self: *const IFunctionDiscovery, enumSystemVisibility: SystemVisibilityFlags, pszCategory: ?[*:0]const u16, pszSubCategory: ?[*:0]const u16, pszCategoryIdentity: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscovery_GetInstanceCollection(self: *const T, pszCategory: ?[*:0]const u16, pszSubCategory: ?[*:0]const u16, fIncludeAllSubCategories: BOOL, ppIFunctionInstanceCollection: ?*?*IFunctionInstanceCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscovery.VTable, self.vtable).GetInstanceCollection(@ptrCast(*const IFunctionDiscovery, self), pszCategory, pszSubCategory, fIncludeAllSubCategories, ppIFunctionInstanceCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscovery_GetInstance(self: *const T, pszFunctionInstanceIdentity: ?[*:0]const u16, ppIFunctionInstance: ?*?*IFunctionInstance) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscovery.VTable, self.vtable).GetInstance(@ptrCast(*const IFunctionDiscovery, self), pszFunctionInstanceIdentity, ppIFunctionInstance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscovery_CreateInstanceCollectionQuery(self: *const T, pszCategory: ?[*:0]const u16, pszSubCategory: ?[*:0]const u16, fIncludeAllSubCategories: BOOL, pIFunctionDiscoveryNotification: ?*IFunctionDiscoveryNotification, pfdqcQueryContext: ?*u64, ppIFunctionInstanceCollectionQuery: ?*?*IFunctionInstanceCollectionQuery) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscovery.VTable, self.vtable).CreateInstanceCollectionQuery(@ptrCast(*const IFunctionDiscovery, self), pszCategory, pszSubCategory, fIncludeAllSubCategories, pIFunctionDiscoveryNotification, pfdqcQueryContext, ppIFunctionInstanceCollectionQuery); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscovery_CreateInstanceQuery(self: *const T, pszFunctionInstanceIdentity: ?[*:0]const u16, pIFunctionDiscoveryNotification: ?*IFunctionDiscoveryNotification, pfdqcQueryContext: ?*u64, ppIFunctionInstanceQuery: ?*?*IFunctionInstanceQuery) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscovery.VTable, self.vtable).CreateInstanceQuery(@ptrCast(*const IFunctionDiscovery, self), pszFunctionInstanceIdentity, pIFunctionDiscoveryNotification, pfdqcQueryContext, ppIFunctionInstanceQuery); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscovery_AddInstance(self: *const T, enumSystemVisibility: SystemVisibilityFlags, pszCategory: ?[*:0]const u16, pszSubCategory: ?[*:0]const u16, pszCategoryIdentity: ?[*:0]const u16, ppIFunctionInstance: ?*?*IFunctionInstance) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscovery.VTable, self.vtable).AddInstance(@ptrCast(*const IFunctionDiscovery, self), enumSystemVisibility, pszCategory, pszSubCategory, pszCategoryIdentity, ppIFunctionInstance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscovery_RemoveInstance(self: *const T, enumSystemVisibility: SystemVisibilityFlags, pszCategory: ?[*:0]const u16, pszSubCategory: ?[*:0]const u16, pszCategoryIdentity: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscovery.VTable, self.vtable).RemoveInstance(@ptrCast(*const IFunctionDiscovery, self), enumSystemVisibility, pszCategory, pszSubCategory, pszCategoryIdentity); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IFunctionInstance_Value = @import("../zig.zig").Guid.initString("33591c10-0bed-4f02-b0ab-1530d5533ee9"); pub const IID_IFunctionInstance = &IID_IFunctionInstance_Value; pub const IFunctionInstance = extern struct { pub const VTable = extern struct { base: IServiceProvider.VTable, GetID: fn( self: *const IFunctionInstance, ppszCoMemIdentity: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProviderInstanceID: fn( self: *const IFunctionInstance, ppszCoMemProviderInstanceIdentity: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenPropertyStore: fn( self: *const IFunctionInstance, dwStgAccess: u32, ppIPropertyStore: ?*?*IPropertyStore, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCategory: fn( self: *const IFunctionInstance, ppszCoMemCategory: ?*?*u16, ppszCoMemSubCategory: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IServiceProvider.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionInstance_GetID(self: *const T, ppszCoMemIdentity: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionInstance.VTable, self.vtable).GetID(@ptrCast(*const IFunctionInstance, self), ppszCoMemIdentity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionInstance_GetProviderInstanceID(self: *const T, ppszCoMemProviderInstanceIdentity: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionInstance.VTable, self.vtable).GetProviderInstanceID(@ptrCast(*const IFunctionInstance, self), ppszCoMemProviderInstanceIdentity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionInstance_OpenPropertyStore(self: *const T, dwStgAccess: u32, ppIPropertyStore: ?*?*IPropertyStore) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionInstance.VTable, self.vtable).OpenPropertyStore(@ptrCast(*const IFunctionInstance, self), dwStgAccess, ppIPropertyStore); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionInstance_GetCategory(self: *const T, ppszCoMemCategory: ?*?*u16, ppszCoMemSubCategory: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionInstance.VTable, self.vtable).GetCategory(@ptrCast(*const IFunctionInstance, self), ppszCoMemCategory, ppszCoMemSubCategory); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IFunctionInstanceCollection_Value = @import("../zig.zig").Guid.initString("f0a3d895-855c-42a2-948d-2f97d450ecb1"); pub const IID_IFunctionInstanceCollection = &IID_IFunctionInstanceCollection_Value; pub const IFunctionInstanceCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IFunctionInstanceCollection, pdwCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Get: fn( self: *const IFunctionInstanceCollection, pszInstanceIdentity: ?[*:0]const u16, pdwIndex: ?*u32, ppIFunctionInstance: ?*?*IFunctionInstance, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Item: fn( self: *const IFunctionInstanceCollection, dwIndex: u32, ppIFunctionInstance: ?*?*IFunctionInstance, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const IFunctionInstanceCollection, pIFunctionInstance: ?*IFunctionInstance, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const IFunctionInstanceCollection, dwIndex: u32, ppIFunctionInstance: ?*?*IFunctionInstance, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Delete: fn( self: *const IFunctionInstanceCollection, dwIndex: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAll: fn( self: *const IFunctionInstanceCollection, ) 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 IFunctionInstanceCollection_GetCount(self: *const T, pdwCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionInstanceCollection.VTable, self.vtable).GetCount(@ptrCast(*const IFunctionInstanceCollection, self), pdwCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionInstanceCollection_Get(self: *const T, pszInstanceIdentity: ?[*:0]const u16, pdwIndex: ?*u32, ppIFunctionInstance: ?*?*IFunctionInstance) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionInstanceCollection.VTable, self.vtable).Get(@ptrCast(*const IFunctionInstanceCollection, self), pszInstanceIdentity, pdwIndex, ppIFunctionInstance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionInstanceCollection_Item(self: *const T, dwIndex: u32, ppIFunctionInstance: ?*?*IFunctionInstance) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionInstanceCollection.VTable, self.vtable).Item(@ptrCast(*const IFunctionInstanceCollection, self), dwIndex, ppIFunctionInstance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionInstanceCollection_Add(self: *const T, pIFunctionInstance: ?*IFunctionInstance) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionInstanceCollection.VTable, self.vtable).Add(@ptrCast(*const IFunctionInstanceCollection, self), pIFunctionInstance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionInstanceCollection_Remove(self: *const T, dwIndex: u32, ppIFunctionInstance: ?*?*IFunctionInstance) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionInstanceCollection.VTable, self.vtable).Remove(@ptrCast(*const IFunctionInstanceCollection, self), dwIndex, ppIFunctionInstance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionInstanceCollection_Delete(self: *const T, dwIndex: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionInstanceCollection.VTable, self.vtable).Delete(@ptrCast(*const IFunctionInstanceCollection, self), dwIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionInstanceCollection_DeleteAll(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionInstanceCollection.VTable, self.vtable).DeleteAll(@ptrCast(*const IFunctionInstanceCollection, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPropertyStoreCollection_Value = @import("../zig.zig").Guid.initString("d14d9c30-12d2-42d8-bce4-c60c2bb226fa"); pub const IID_IPropertyStoreCollection = &IID_IPropertyStoreCollection_Value; pub const IPropertyStoreCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IPropertyStoreCollection, pdwCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Get: fn( self: *const IPropertyStoreCollection, pszInstanceIdentity: ?[*:0]const u16, pdwIndex: ?*u32, ppIPropertyStore: ?*?*IPropertyStore, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Item: fn( self: *const IPropertyStoreCollection, dwIndex: u32, ppIPropertyStore: ?*?*IPropertyStore, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const IPropertyStoreCollection, pIPropertyStore: ?*IPropertyStore, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const IPropertyStoreCollection, dwIndex: u32, pIPropertyStore: ?*?*IPropertyStore, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Delete: fn( self: *const IPropertyStoreCollection, dwIndex: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAll: fn( self: *const IPropertyStoreCollection, ) 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 IPropertyStoreCollection_GetCount(self: *const T, pdwCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertyStoreCollection.VTable, self.vtable).GetCount(@ptrCast(*const IPropertyStoreCollection, self), pdwCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropertyStoreCollection_Get(self: *const T, pszInstanceIdentity: ?[*:0]const u16, pdwIndex: ?*u32, ppIPropertyStore: ?*?*IPropertyStore) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertyStoreCollection.VTable, self.vtable).Get(@ptrCast(*const IPropertyStoreCollection, self), pszInstanceIdentity, pdwIndex, ppIPropertyStore); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropertyStoreCollection_Item(self: *const T, dwIndex: u32, ppIPropertyStore: ?*?*IPropertyStore) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertyStoreCollection.VTable, self.vtable).Item(@ptrCast(*const IPropertyStoreCollection, self), dwIndex, ppIPropertyStore); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropertyStoreCollection_Add(self: *const T, pIPropertyStore: ?*IPropertyStore) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertyStoreCollection.VTable, self.vtable).Add(@ptrCast(*const IPropertyStoreCollection, self), pIPropertyStore); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropertyStoreCollection_Remove(self: *const T, dwIndex: u32, pIPropertyStore: ?*?*IPropertyStore) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertyStoreCollection.VTable, self.vtable).Remove(@ptrCast(*const IPropertyStoreCollection, self), dwIndex, pIPropertyStore); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropertyStoreCollection_Delete(self: *const T, dwIndex: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertyStoreCollection.VTable, self.vtable).Delete(@ptrCast(*const IPropertyStoreCollection, self), dwIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropertyStoreCollection_DeleteAll(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertyStoreCollection.VTable, self.vtable).DeleteAll(@ptrCast(*const IPropertyStoreCollection, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IFunctionInstanceQuery_Value = @import("../zig.zig").Guid.initString("6242bc6b-90ec-4b37-bb46-e229fd84ed95"); pub const IID_IFunctionInstanceQuery = &IID_IFunctionInstanceQuery_Value; pub const IFunctionInstanceQuery = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Execute: fn( self: *const IFunctionInstanceQuery, ppIFunctionInstance: ?*?*IFunctionInstance, ) 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 IFunctionInstanceQuery_Execute(self: *const T, ppIFunctionInstance: ?*?*IFunctionInstance) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionInstanceQuery.VTable, self.vtable).Execute(@ptrCast(*const IFunctionInstanceQuery, self), ppIFunctionInstance); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IFunctionInstanceCollectionQuery_Value = @import("../zig.zig").Guid.initString("57cc6fd2-c09a-4289-bb72-25f04142058e"); pub const IID_IFunctionInstanceCollectionQuery = &IID_IFunctionInstanceCollectionQuery_Value; pub const IFunctionInstanceCollectionQuery = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddQueryConstraint: fn( self: *const IFunctionInstanceCollectionQuery, pszConstraintName: ?[*:0]const u16, pszConstraintValue: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPropertyConstraint: fn( self: *const IFunctionInstanceCollectionQuery, Key: ?*const PROPERTYKEY, pv: ?*const PROPVARIANT, enumPropertyConstraint: PropertyConstraint, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Execute: fn( self: *const IFunctionInstanceCollectionQuery, ppIFunctionInstanceCollection: ?*?*IFunctionInstanceCollection, ) 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 IFunctionInstanceCollectionQuery_AddQueryConstraint(self: *const T, pszConstraintName: ?[*:0]const u16, pszConstraintValue: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionInstanceCollectionQuery.VTable, self.vtable).AddQueryConstraint(@ptrCast(*const IFunctionInstanceCollectionQuery, self), pszConstraintName, pszConstraintValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionInstanceCollectionQuery_AddPropertyConstraint(self: *const T, Key: ?*const PROPERTYKEY, pv: ?*const PROPVARIANT, enumPropertyConstraint: PropertyConstraint) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionInstanceCollectionQuery.VTable, self.vtable).AddPropertyConstraint(@ptrCast(*const IFunctionInstanceCollectionQuery, self), Key, pv, enumPropertyConstraint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionInstanceCollectionQuery_Execute(self: *const T, ppIFunctionInstanceCollection: ?*?*IFunctionInstanceCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionInstanceCollectionQuery.VTable, self.vtable).Execute(@ptrCast(*const IFunctionInstanceCollectionQuery, self), ppIFunctionInstanceCollection); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IFunctionDiscoveryProvider_Value = @import("../zig.zig").Guid.initString("dcde394f-1478-4813-a402-f6fb10657222"); pub const IID_IFunctionDiscoveryProvider = &IID_IFunctionDiscoveryProvider_Value; pub const IFunctionDiscoveryProvider = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IFunctionDiscoveryProvider, pIFunctionDiscoveryProviderFactory: ?*IFunctionDiscoveryProviderFactory, pIFunctionDiscoveryNotification: ?*IFunctionDiscoveryNotification, lcidUserDefault: u32, pdwStgAccessCapabilities: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Query: fn( self: *const IFunctionDiscoveryProvider, pIFunctionDiscoveryProviderQuery: ?*IFunctionDiscoveryProviderQuery, ppIFunctionInstanceCollection: ?*?*IFunctionInstanceCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EndQuery: fn( self: *const IFunctionDiscoveryProvider, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InstancePropertyStoreValidateAccess: fn( self: *const IFunctionDiscoveryProvider, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, dwStgAccess: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InstancePropertyStoreOpen: fn( self: *const IFunctionDiscoveryProvider, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, dwStgAccess: u32, ppIPropertyStore: ?*?*IPropertyStore, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InstancePropertyStoreFlush: fn( self: *const IFunctionDiscoveryProvider, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InstanceQueryService: fn( self: *const IFunctionDiscoveryProvider, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, guidService: ?*const Guid, riid: ?*const Guid, ppIUnknown: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InstanceReleased: fn( self: *const IFunctionDiscoveryProvider, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, ) 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 IFunctionDiscoveryProvider_Initialize(self: *const T, pIFunctionDiscoveryProviderFactory: ?*IFunctionDiscoveryProviderFactory, pIFunctionDiscoveryNotification: ?*IFunctionDiscoveryNotification, lcidUserDefault: u32, pdwStgAccessCapabilities: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryProvider.VTable, self.vtable).Initialize(@ptrCast(*const IFunctionDiscoveryProvider, self), pIFunctionDiscoveryProviderFactory, pIFunctionDiscoveryNotification, lcidUserDefault, pdwStgAccessCapabilities); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscoveryProvider_Query(self: *const T, pIFunctionDiscoveryProviderQuery: ?*IFunctionDiscoveryProviderQuery, ppIFunctionInstanceCollection: ?*?*IFunctionInstanceCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryProvider.VTable, self.vtable).Query(@ptrCast(*const IFunctionDiscoveryProvider, self), pIFunctionDiscoveryProviderQuery, ppIFunctionInstanceCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscoveryProvider_EndQuery(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryProvider.VTable, self.vtable).EndQuery(@ptrCast(*const IFunctionDiscoveryProvider, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscoveryProvider_InstancePropertyStoreValidateAccess(self: *const T, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, dwStgAccess: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryProvider.VTable, self.vtable).InstancePropertyStoreValidateAccess(@ptrCast(*const IFunctionDiscoveryProvider, self), pIFunctionInstance, iProviderInstanceContext, dwStgAccess); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscoveryProvider_InstancePropertyStoreOpen(self: *const T, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, dwStgAccess: u32, ppIPropertyStore: ?*?*IPropertyStore) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryProvider.VTable, self.vtable).InstancePropertyStoreOpen(@ptrCast(*const IFunctionDiscoveryProvider, self), pIFunctionInstance, iProviderInstanceContext, dwStgAccess, ppIPropertyStore); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscoveryProvider_InstancePropertyStoreFlush(self: *const T, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryProvider.VTable, self.vtable).InstancePropertyStoreFlush(@ptrCast(*const IFunctionDiscoveryProvider, self), pIFunctionInstance, iProviderInstanceContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscoveryProvider_InstanceQueryService(self: *const T, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, guidService: ?*const Guid, riid: ?*const Guid, ppIUnknown: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryProvider.VTable, self.vtable).InstanceQueryService(@ptrCast(*const IFunctionDiscoveryProvider, self), pIFunctionInstance, iProviderInstanceContext, guidService, riid, ppIUnknown); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscoveryProvider_InstanceReleased(self: *const T, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryProvider.VTable, self.vtable).InstanceReleased(@ptrCast(*const IFunctionDiscoveryProvider, self), pIFunctionInstance, iProviderInstanceContext); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IProviderProperties_Value = @import("../zig.zig").Guid.initString("cf986ea6-3b5f-4c5f-b88a-2f8b20ceef17"); pub const IID_IProviderProperties = &IID_IProviderProperties_Value; pub const IProviderProperties = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IProviderProperties, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, pdwCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IProviderProperties, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, dwIndex: u32, pKey: ?*PROPERTYKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetValue: fn( self: *const IProviderProperties, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, Key: ?*const PROPERTYKEY, ppropVar: ?*PROPVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetValue: fn( self: *const IProviderProperties, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, Key: ?*const PROPERTYKEY, ppropVar: ?*const PROPVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderProperties_GetCount(self: *const T, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, pdwCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderProperties.VTable, self.vtable).GetCount(@ptrCast(*const IProviderProperties, self), pIFunctionInstance, iProviderInstanceContext, pdwCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderProperties_GetAt(self: *const T, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, dwIndex: u32, pKey: ?*PROPERTYKEY) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderProperties.VTable, self.vtable).GetAt(@ptrCast(*const IProviderProperties, self), pIFunctionInstance, iProviderInstanceContext, dwIndex, pKey); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderProperties_GetValue(self: *const T, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, Key: ?*const PROPERTYKEY, ppropVar: ?*PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderProperties.VTable, self.vtable).GetValue(@ptrCast(*const IProviderProperties, self), pIFunctionInstance, iProviderInstanceContext, Key, ppropVar); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderProperties_SetValue(self: *const T, pIFunctionInstance: ?*IFunctionInstance, iProviderInstanceContext: isize, Key: ?*const PROPERTYKEY, ppropVar: ?*const PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderProperties.VTable, self.vtable).SetValue(@ptrCast(*const IProviderProperties, self), pIFunctionInstance, iProviderInstanceContext, Key, ppropVar); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IProviderPublishing_Value = @import("../zig.zig").Guid.initString("cd1b9a04-206c-4a05-a0c8-1635a21a2b7c"); pub const IID_IProviderPublishing = &IID_IProviderPublishing_Value; pub const IProviderPublishing = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateInstance: fn( self: *const IProviderPublishing, enumVisibilityFlags: SystemVisibilityFlags, pszSubCategory: ?[*:0]const u16, pszProviderInstanceIdentity: ?[*:0]const u16, ppIFunctionInstance: ?*?*IFunctionInstance, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveInstance: fn( self: *const IProviderPublishing, enumVisibilityFlags: SystemVisibilityFlags, pszSubCategory: ?[*:0]const u16, pszProviderInstanceIdentity: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderPublishing_CreateInstance(self: *const T, enumVisibilityFlags: SystemVisibilityFlags, pszSubCategory: ?[*:0]const u16, pszProviderInstanceIdentity: ?[*:0]const u16, ppIFunctionInstance: ?*?*IFunctionInstance) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderPublishing.VTable, self.vtable).CreateInstance(@ptrCast(*const IProviderPublishing, self), enumVisibilityFlags, pszSubCategory, pszProviderInstanceIdentity, ppIFunctionInstance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderPublishing_RemoveInstance(self: *const T, enumVisibilityFlags: SystemVisibilityFlags, pszSubCategory: ?[*:0]const u16, pszProviderInstanceIdentity: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderPublishing.VTable, self.vtable).RemoveInstance(@ptrCast(*const IProviderPublishing, self), enumVisibilityFlags, pszSubCategory, pszProviderInstanceIdentity); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IFunctionDiscoveryProviderFactory_Value = @import("../zig.zig").Guid.initString("86443ff0-1ad5-4e68-a45a-40c2c329de3b"); pub const IID_IFunctionDiscoveryProviderFactory = &IID_IFunctionDiscoveryProviderFactory_Value; pub const IFunctionDiscoveryProviderFactory = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreatePropertyStore: fn( self: *const IFunctionDiscoveryProviderFactory, ppIPropertyStore: ?*?*IPropertyStore, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateInstance: fn( self: *const IFunctionDiscoveryProviderFactory, pszSubCategory: ?[*:0]const u16, pszProviderInstanceIdentity: ?[*:0]const u16, iProviderInstanceContext: isize, pIPropertyStore: ?*IPropertyStore, pIFunctionDiscoveryProvider: ?*IFunctionDiscoveryProvider, ppIFunctionInstance: ?*?*IFunctionInstance, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateFunctionInstanceCollection: fn( self: *const IFunctionDiscoveryProviderFactory, ppIFunctionInstanceCollection: ?*?*IFunctionInstanceCollection, ) 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 IFunctionDiscoveryProviderFactory_CreatePropertyStore(self: *const T, ppIPropertyStore: ?*?*IPropertyStore) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryProviderFactory.VTable, self.vtable).CreatePropertyStore(@ptrCast(*const IFunctionDiscoveryProviderFactory, self), ppIPropertyStore); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscoveryProviderFactory_CreateInstance(self: *const T, pszSubCategory: ?[*:0]const u16, pszProviderInstanceIdentity: ?[*:0]const u16, iProviderInstanceContext: isize, pIPropertyStore: ?*IPropertyStore, pIFunctionDiscoveryProvider: ?*IFunctionDiscoveryProvider, ppIFunctionInstance: ?*?*IFunctionInstance) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryProviderFactory.VTable, self.vtable).CreateInstance(@ptrCast(*const IFunctionDiscoveryProviderFactory, self), pszSubCategory, pszProviderInstanceIdentity, iProviderInstanceContext, pIPropertyStore, pIFunctionDiscoveryProvider, ppIFunctionInstance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscoveryProviderFactory_CreateFunctionInstanceCollection(self: *const T, ppIFunctionInstanceCollection: ?*?*IFunctionInstanceCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryProviderFactory.VTable, self.vtable).CreateFunctionInstanceCollection(@ptrCast(*const IFunctionDiscoveryProviderFactory, self), ppIFunctionInstanceCollection); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IFunctionDiscoveryProviderQuery_Value = @import("../zig.zig").Guid.initString("6876ea98-baec-46db-bc20-75a76e267a3a"); pub const IID_IFunctionDiscoveryProviderQuery = &IID_IFunctionDiscoveryProviderQuery_Value; pub const IFunctionDiscoveryProviderQuery = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, IsInstanceQuery: fn( self: *const IFunctionDiscoveryProviderQuery, pisInstanceQuery: ?*BOOL, ppszConstraintValue: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsSubcategoryQuery: fn( self: *const IFunctionDiscoveryProviderQuery, pisSubcategoryQuery: ?*BOOL, ppszConstraintValue: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetQueryConstraints: fn( self: *const IFunctionDiscoveryProviderQuery, ppIProviderQueryConstraints: ?*?*IProviderQueryConstraintCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPropertyConstraints: fn( self: *const IFunctionDiscoveryProviderQuery, ppIProviderPropertyConstraints: ?*?*IProviderPropertyConstraintCollection, ) 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 IFunctionDiscoveryProviderQuery_IsInstanceQuery(self: *const T, pisInstanceQuery: ?*BOOL, ppszConstraintValue: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryProviderQuery.VTable, self.vtable).IsInstanceQuery(@ptrCast(*const IFunctionDiscoveryProviderQuery, self), pisInstanceQuery, ppszConstraintValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscoveryProviderQuery_IsSubcategoryQuery(self: *const T, pisSubcategoryQuery: ?*BOOL, ppszConstraintValue: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryProviderQuery.VTable, self.vtable).IsSubcategoryQuery(@ptrCast(*const IFunctionDiscoveryProviderQuery, self), pisSubcategoryQuery, ppszConstraintValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscoveryProviderQuery_GetQueryConstraints(self: *const T, ppIProviderQueryConstraints: ?*?*IProviderQueryConstraintCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryProviderQuery.VTable, self.vtable).GetQueryConstraints(@ptrCast(*const IFunctionDiscoveryProviderQuery, self), ppIProviderQueryConstraints); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFunctionDiscoveryProviderQuery_GetPropertyConstraints(self: *const T, ppIProviderPropertyConstraints: ?*?*IProviderPropertyConstraintCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryProviderQuery.VTable, self.vtable).GetPropertyConstraints(@ptrCast(*const IFunctionDiscoveryProviderQuery, self), ppIProviderPropertyConstraints); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IProviderQueryConstraintCollection_Value = @import("../zig.zig").Guid.initString("9c243e11-3261-4bcd-b922-84a873d460ae"); pub const IID_IProviderQueryConstraintCollection = &IID_IProviderQueryConstraintCollection_Value; pub const IProviderQueryConstraintCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IProviderQueryConstraintCollection, pdwCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Get: fn( self: *const IProviderQueryConstraintCollection, pszConstraintName: ?[*:0]const u16, ppszConstraintValue: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Item: fn( self: *const IProviderQueryConstraintCollection, dwIndex: u32, ppszConstraintName: ?*?*u16, ppszConstraintValue: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IProviderQueryConstraintCollection, ppszConstraintName: ?*?*u16, ppszConstraintValue: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IProviderQueryConstraintCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IProviderQueryConstraintCollection, ) 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 IProviderQueryConstraintCollection_GetCount(self: *const T, pdwCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderQueryConstraintCollection.VTable, self.vtable).GetCount(@ptrCast(*const IProviderQueryConstraintCollection, self), pdwCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderQueryConstraintCollection_Get(self: *const T, pszConstraintName: ?[*:0]const u16, ppszConstraintValue: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderQueryConstraintCollection.VTable, self.vtable).Get(@ptrCast(*const IProviderQueryConstraintCollection, self), pszConstraintName, ppszConstraintValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderQueryConstraintCollection_Item(self: *const T, dwIndex: u32, ppszConstraintName: ?*?*u16, ppszConstraintValue: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderQueryConstraintCollection.VTable, self.vtable).Item(@ptrCast(*const IProviderQueryConstraintCollection, self), dwIndex, ppszConstraintName, ppszConstraintValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderQueryConstraintCollection_Next(self: *const T, ppszConstraintName: ?*?*u16, ppszConstraintValue: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderQueryConstraintCollection.VTable, self.vtable).Next(@ptrCast(*const IProviderQueryConstraintCollection, self), ppszConstraintName, ppszConstraintValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderQueryConstraintCollection_Skip(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderQueryConstraintCollection.VTable, self.vtable).Skip(@ptrCast(*const IProviderQueryConstraintCollection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderQueryConstraintCollection_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderQueryConstraintCollection.VTable, self.vtable).Reset(@ptrCast(*const IProviderQueryConstraintCollection, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IProviderPropertyConstraintCollection_Value = @import("../zig.zig").Guid.initString("f4fae42f-5778-4a13-8540-b5fd8c1398dd"); pub const IID_IProviderPropertyConstraintCollection = &IID_IProviderPropertyConstraintCollection_Value; pub const IProviderPropertyConstraintCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IProviderPropertyConstraintCollection, pdwCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Get: fn( self: *const IProviderPropertyConstraintCollection, Key: ?*const PROPERTYKEY, pPropVar: ?*PROPVARIANT, pdwPropertyConstraint: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Item: fn( self: *const IProviderPropertyConstraintCollection, dwIndex: u32, pKey: ?*PROPERTYKEY, pPropVar: ?*PROPVARIANT, pdwPropertyConstraint: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IProviderPropertyConstraintCollection, pKey: ?*PROPERTYKEY, pPropVar: ?*PROPVARIANT, pdwPropertyConstraint: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IProviderPropertyConstraintCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IProviderPropertyConstraintCollection, ) 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 IProviderPropertyConstraintCollection_GetCount(self: *const T, pdwCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderPropertyConstraintCollection.VTable, self.vtable).GetCount(@ptrCast(*const IProviderPropertyConstraintCollection, self), pdwCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderPropertyConstraintCollection_Get(self: *const T, Key: ?*const PROPERTYKEY, pPropVar: ?*PROPVARIANT, pdwPropertyConstraint: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderPropertyConstraintCollection.VTable, self.vtable).Get(@ptrCast(*const IProviderPropertyConstraintCollection, self), Key, pPropVar, pdwPropertyConstraint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderPropertyConstraintCollection_Item(self: *const T, dwIndex: u32, pKey: ?*PROPERTYKEY, pPropVar: ?*PROPVARIANT, pdwPropertyConstraint: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderPropertyConstraintCollection.VTable, self.vtable).Item(@ptrCast(*const IProviderPropertyConstraintCollection, self), dwIndex, pKey, pPropVar, pdwPropertyConstraint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderPropertyConstraintCollection_Next(self: *const T, pKey: ?*PROPERTYKEY, pPropVar: ?*PROPVARIANT, pdwPropertyConstraint: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderPropertyConstraintCollection.VTable, self.vtable).Next(@ptrCast(*const IProviderPropertyConstraintCollection, self), pKey, pPropVar, pdwPropertyConstraint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderPropertyConstraintCollection_Skip(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderPropertyConstraintCollection.VTable, self.vtable).Skip(@ptrCast(*const IProviderPropertyConstraintCollection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProviderPropertyConstraintCollection_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IProviderPropertyConstraintCollection.VTable, self.vtable).Reset(@ptrCast(*const IProviderPropertyConstraintCollection, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IFunctionDiscoveryServiceProvider_Value = @import("../zig.zig").Guid.initString("4c81ed02-1b04-43f2-a451-69966cbcd1c2"); pub const IID_IFunctionDiscoveryServiceProvider = &IID_IFunctionDiscoveryServiceProvider_Value; pub const IFunctionDiscoveryServiceProvider = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IFunctionDiscoveryServiceProvider, pIFunctionInstance: ?*IFunctionInstance, riid: ?*const Guid, ppv: ?*?*anyopaque, ) 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 IFunctionDiscoveryServiceProvider_Initialize(self: *const T, pIFunctionInstance: ?*IFunctionInstance, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IFunctionDiscoveryServiceProvider.VTable, self.vtable).Initialize(@ptrCast(*const IFunctionDiscoveryServiceProvider, self), pIFunctionInstance, riid, ppv); } };} pub usingnamespace MethodMixin(@This()); }; const CLSID_PNPXAssociation_Value = @import("../zig.zig").Guid.initString("cee8ccc9-4f6b-4469-a235-5a22869eef03"); pub const CLSID_PNPXAssociation = &CLSID_PNPXAssociation_Value; const CLSID_PNPXPairingHandler_Value = @import("../zig.zig").Guid.initString("b8a27942-ade7-4085-aa6e-4fadc7ada1ef"); pub const CLSID_PNPXPairingHandler = &CLSID_PNPXPairingHandler_Value; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IPNPXAssociation_Value = @import("../zig.zig").Guid.initString("0bd7e521-4da6-42d5-81ba-1981b6b94075"); pub const IID_IPNPXAssociation = &IID_IPNPXAssociation_Value; pub const IPNPXAssociation = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Associate: fn( self: *const IPNPXAssociation, pszSubcategory: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unassociate: fn( self: *const IPNPXAssociation, pszSubcategory: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Delete: fn( self: *const IPNPXAssociation, pszSubcategory: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPNPXAssociation_Associate(self: *const T, pszSubcategory: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IPNPXAssociation.VTable, self.vtable).Associate(@ptrCast(*const IPNPXAssociation, self), pszSubcategory); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPNPXAssociation_Unassociate(self: *const T, pszSubcategory: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IPNPXAssociation.VTable, self.vtable).Unassociate(@ptrCast(*const IPNPXAssociation, self), pszSubcategory); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPNPXAssociation_Delete(self: *const T, pszSubcategory: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IPNPXAssociation.VTable, self.vtable).Delete(@ptrCast(*const IPNPXAssociation, self), pszSubcategory); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IPNPXDeviceAssociation_Value = @import("../zig.zig").Guid.initString("eed366d0-35b8-4fc5-8d20-7e5bd31f6ded"); pub const IID_IPNPXDeviceAssociation = &IID_IPNPXDeviceAssociation_Value; pub const IPNPXDeviceAssociation = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Associate: fn( self: *const IPNPXDeviceAssociation, pszSubCategory: ?[*:0]const u16, pIFunctionDiscoveryNotification: ?*IFunctionDiscoveryNotification, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unassociate: fn( self: *const IPNPXDeviceAssociation, pszSubCategory: ?[*:0]const u16, pIFunctionDiscoveryNotification: ?*IFunctionDiscoveryNotification, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Delete: fn( self: *const IPNPXDeviceAssociation, pszSubcategory: ?[*:0]const u16, pIFunctionDiscoveryNotification: ?*IFunctionDiscoveryNotification, ) 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 IPNPXDeviceAssociation_Associate(self: *const T, pszSubCategory: ?[*:0]const u16, pIFunctionDiscoveryNotification: ?*IFunctionDiscoveryNotification) callconv(.Inline) HRESULT { return @ptrCast(*const IPNPXDeviceAssociation.VTable, self.vtable).Associate(@ptrCast(*const IPNPXDeviceAssociation, self), pszSubCategory, pIFunctionDiscoveryNotification); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPNPXDeviceAssociation_Unassociate(self: *const T, pszSubCategory: ?[*:0]const u16, pIFunctionDiscoveryNotification: ?*IFunctionDiscoveryNotification) callconv(.Inline) HRESULT { return @ptrCast(*const IPNPXDeviceAssociation.VTable, self.vtable).Unassociate(@ptrCast(*const IPNPXDeviceAssociation, self), pszSubCategory, pIFunctionDiscoveryNotification); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPNPXDeviceAssociation_Delete(self: *const T, pszSubcategory: ?[*:0]const u16, pIFunctionDiscoveryNotification: ?*IFunctionDiscoveryNotification) callconv(.Inline) HRESULT { return @ptrCast(*const IPNPXDeviceAssociation.VTable, self.vtable).Delete(@ptrCast(*const IPNPXDeviceAssociation, self), pszSubcategory, pIFunctionDiscoveryNotification); } };} pub usingnamespace MethodMixin(@This()); }; const CLSID_FunctionDiscovery_Value = @import("../zig.zig").Guid.initString("c72be2ec-8e90-452c-b29a-ab8ff1c071fc"); pub const CLSID_FunctionDiscovery = &CLSID_FunctionDiscovery_Value; const CLSID_PropertyStore_Value = @import("../zig.zig").Guid.initString("e4796550-df61-448b-9193-13fc1341b163"); pub const CLSID_PropertyStore = &CLSID_PropertyStore_Value; const CLSID_FunctionInstanceCollection_Value = @import("../zig.zig").Guid.initString("ba818ce5-b55f-443f-ad39-2fe89be6191f"); pub const CLSID_FunctionInstanceCollection = &CLSID_FunctionInstanceCollection_Value; const CLSID_PropertyStoreCollection_Value = @import("../zig.zig").Guid.initString("edd36029-d753-4862-aa5b-5bccad2a4d29"); pub const CLSID_PropertyStoreCollection = &CLSID_PropertyStoreCollection_Value; //-------------------------------------------------------------------------------- // Section: Functions (0) //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (9) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const HRESULT = @import("../foundation.zig").HRESULT; const IPropertyStore = @import("../ui/shell/properties_system.zig").IPropertyStore; const IServiceProvider = @import("../system/com.zig").IServiceProvider; const IUnknown = @import("../system/com.zig").IUnknown; const PROPERTYKEY = @import("../ui/shell/properties_system.zig").PROPERTYKEY; const PROPVARIANT = @import("../system/com/structured_storage.zig").PROPVARIANT; const PWSTR = @import("../foundation.zig").PWSTR; test { @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/devices/function_discovery.zig
// Ported from the ISAAC64 C Source written by <NAME>, 1996, Public Domain // https://burtleburtle.net/bob/c/isaac64.h // https://burtleburtle.net/bob/c/standard.h // https://burtleburtle.net/bob/c/isaac64.c // // USAGE: // // var isaac = Isaac64 {}; // isaac.seed(c"CHAR_DATA_UP_TO_RANDSIZ_TIMES_8_BYTES", 37); // isaac.randInit(true); // isaac.isaac64(); // const random_64bit_unsigned_integer: u64 = isaac.rand(); // const random_number_from_one_to_ten: u64 = isaac.randInRange(1, 10)); // // NOTES: // // You are free to run another round of ISAAC64 and reset the result counter // at any time; rand()/randInRange() will do this automatically when the // random number buffer is exhausted. // // EXAMPLE: // // isaac.isaac64(); // isaac.randcnt = RANDSIZ; // // // NOTE ABOUT SEEDING: // // It is not recommended to seed the CSPRNG with a C string, as they cannot // contain nulls, which is a perfectly acceptable byte value in the seed. // The C string was used in the example above for brevity. The seed() method // actually takes up to 2048 bytes as input. // const Isaac64Octet = packed struct { a: u64, b: u64, c: u64, d: u64, e: u64, f: u64, g: u64, h: u64, fn mix(self: *Isaac64Octet) void { self.a -%= self.e; self.f ^= (self.h >> 9); self.h +%= self.a; self.b -%= self.f; self.g ^= (self.a << 9); self.a +%= self.b; self.c -%= self.g; self.h ^= (self.b >> 23); self.b +%= self.c; self.d -%= self.h; self.a ^= (self.c << 15); self.c +%= self.d; self.e -%= self.a; self.b ^= (self.d >> 14); self.d +%= self.e; self.f -%= self.b; self.c ^= (self.e << 20); self.e +%= self.f; self.g -%= self.c; self.d ^= (self.f >> 17); self.f +%= self.g; self.h -%= self.d; self.e ^= (self.g << 14); self.g +%= self.h; } }; pub const Isaac64 = struct { pub const RANDSIZL = 8; pub const RANDSIZ = 1<<RANDSIZL; pub const GOLDEN_RATIO = 0x9e3779b97f4a7c13; randrsl: [RANDSIZ]u64 = [_]u64{0} ** RANDSIZ, mm: [RANDSIZ]u64 = [_]u64{0} ** RANDSIZ, randcnt: u64 = 0, aa: u64 = 0, bb: u64 = 0, cc: u64 = 0, pub fn randInit(self: *Isaac64, flag: bool) void { var i: usize = 0; var octet = Isaac64Octet { .a = GOLDEN_RATIO, .b = GOLDEN_RATIO, .c = GOLDEN_RATIO, .d = GOLDEN_RATIO, .e = GOLDEN_RATIO, .f = GOLDEN_RATIO, .g = GOLDEN_RATIO, .h = GOLDEN_RATIO, }; while (i < 4) : (i += 1) { octet.mix(); } i = 0; while (i < RANDSIZ) : (i += 8) { if (flag) { octet.a +%= self.randrsl[i ]; octet.b +%= self.randrsl[i+1]; octet.c +%= self.randrsl[i+2]; octet.d +%= self.randrsl[i+3]; octet.e +%= self.randrsl[i+4]; octet.f +%= self.randrsl[i+5]; octet.g +%= self.randrsl[i+6]; octet.h +%= self.randrsl[i+7]; } octet.mix(); self.mm[i ] = octet.a; self.mm[i+1] = octet.b; self.mm[i+2] = octet.c; self.mm[i+3] = octet.d; self.mm[i+4] = octet.e; self.mm[i+5] = octet.f; self.mm[i+6] = octet.g; self.mm[i+7] = octet.h; } if (flag) { i = 0; while (i < RANDSIZ) : (i += 8) { octet.a +%= self.mm[i ]; octet.b +%= self.mm[i+1]; octet.c +%= self.mm[i+2]; octet.d +%= self.mm[i+3]; octet.e +%= self.mm[i+4]; octet.f +%= self.mm[i+5]; octet.g +%= self.mm[i+6]; octet.h +%= self.mm[i+7]; octet.mix(); self.mm[i ] = octet.a; self.mm[i+1] = octet.b; self.mm[i+2] = octet.c; self.mm[i+3] = octet.d; self.mm[i+4] = octet.e; self.mm[i+5] = octet.f; self.mm[i+6] = octet.g; self.mm[i+7] = octet.h; } } self.isaac64(); self.randcnt = RANDSIZ; } pub fn isaac64(self: *Isaac64) void { var a: u64 = 0; var b: u64 = 0; var x: u64 = 0; var y: u64 = 0; var z: usize = 0; var m: *u64 = &self.mm[0]; var m2: *u64 = &self.mm[RANDSIZ/2]; var r: *u64 = &self.randrsl[0]; var mend: *u64 = m2; a = self.aa; self.cc += 1; b = self.bb + self.cc; while (@ptrToInt(m) < @ptrToInt(mend)) { z = 0; while (z < 4) : (z += 1) { x = m.*; a = switch (z) { 0 => (~(a ^ (a << 21)) +% m2.*), 1 => (a ^ (a >> 5)) +% m2.*, 2 => (a ^ (a << 12)) +% m2.*, 3 => (a ^ (a >> 33)) +% m2.*, else => unreachable, }; m2 = @intToPtr(*u64, @ptrToInt(m2) + 8); y = @intToPtr(*u64, @ptrToInt(&self.mm[0]) + (x & ((RANDSIZ - 1) << 3))).* +% a +% b; m.* = y; m = @intToPtr(*u64, @ptrToInt(m) + 8); b = @intToPtr(*u64, @ptrToInt(&self.mm[0]) + ((y >> RANDSIZL) & ((RANDSIZ - 1) << 3))).* +% x; r.* = b; r = @intToPtr(*u64, @ptrToInt(r) + 8); } } m2 = &self.mm[0]; while (@ptrToInt(m2) < @ptrToInt(mend)) { z = 0; while (z < 4) : (z += 1) { x = m.*; a = switch (z) { 0 => (~(a ^ (a << 21)) +% m2.*), 1 => (a ^ (a >> 5)) +% m2.*, 2 => (a ^ (a << 12)) +% m2.*, 3 => (a ^ (a >> 33)) +% m2.*, else => unreachable, }; m2 = @intToPtr(*u64, @ptrToInt(m2) + 8); y = @intToPtr(*u64, @ptrToInt(&self.mm[0]) + (x & ((RANDSIZ - 1) << 3))).* +% a +% b; m.* = y; m = @intToPtr(*u64, @ptrToInt(m) + 8); b = @intToPtr(*u64, @ptrToInt(&self.mm[0]) + ((y >> RANDSIZL) & ((RANDSIZ - 1) << 3))).* +% x; r.* = b; r = @intToPtr(*u64, @ptrToInt(r) + 8); } } self.bb = b; self.aa = a; } pub fn rand(self: *Isaac64) u64 { if (self.randcnt > 0) { self.randcnt -= 1; return self.randrsl[self.randcnt]; } else { self.isaac64(); self.randcnt = RANDSIZ; return self.rand(); } } pub fn randInRange(self: *Isaac64, minimum: u64, maximum: u64) u64 { return ((self.rand() % (maximum - minimum + 1)) + minimum); } pub fn seed(self: *Isaac64, seedptr: [*]const u8, seedsize: usize) void { var i: usize = 0; var rslptr: [*]u8 = @ptrCast([*]u8, &self.randrsl[0]); if (seedsize > (RANDIZ * 8)) { @panic("Maximum byte count exceeded for Isaac64 seed"); } while (i < seedsize and i < (RANDSIZ * 8)) { rslptr[i] = seedptr[i]; i += 1; } } };
isaac64.zig
const Response = @This(); const std = @import("std"); const net = std.net; const MimeType = @import("MimeType.zig"); /// The status representing this response. /// By default set to "20 - SUCCESS" status: Status = .success, /// Buffered writer for writing to the client. /// By buffering we limit the amount of syscalls and improve /// the performance. /// /// NOTE: It is allowed to directly call this instead of using `flush` and `body`. /// When calling this directly, ensure to set `is_flushed` to `true` to prevent /// sending multiple responses. buffered_writer: std.io.BufferedWriter(4096, net.Stream.Writer), /// Determines if the response has been flushed or not /// This prevents double writes to the client. /// /// NOTE: Setting this to `true` without actually sending a response, /// will cause the connection to be closed without the client receiving any response. /// Therefore it's recommended to not manually set this, unless ensuring a response was sent. is_flushed: bool = false, /// A writer for writing to the response body. /// All content is flushed at once. body: std.ArrayList(u8).Writer, /// Possible errors when sending a response /// to the client. (This excludes writing to `body`) pub const Error = net.Stream.WriteError; /// The maximum amount of bytes a header will entail /// <STATUS><SPACE><META><CR><LF> pub const max_header_size: usize = 2 + 1 + 1024 + 1 + 1; /// Represents a status code as described by the Gemini spec. pub const Status = enum(u6) { /// Ask the client to send a new request with input as query parameters input = 10, /// Like `input` but for sensitive input such as passwords. sensitive_input = 11, /// Success, provides a response body to the client with plain text/binary data. success = 20, /// Temporary redirect. Client may attempt to retry the same URI at a later point. redirect_temporary = 30, /// Permanently redirected. The client should use the URI provided in the header's META. redirect_permanent = 31, /// Temporary failure, client may attempt to retry at a later point. temporary_failure = 40, /// Server is currently unavailable for maintence, etc. server_unavailable = 41, /// A CGI process or similar system died unexpectedly or timed out. cgi_error = 42, /// A proxy request failed because the server was unable to complete a transaction with the remote host. proxy_error = 43, /// Rate limiting is in effect. META must contain an integer representing the number of seconds the client must wait. slow_down = 44, /// Permanent failure. Client must not attempt to reconnect to this URI. permanent_failure = 50, /// The provided URI represents an unknown source. Much like HTTP's 404 code. not_found = 51, /// The requested resource is no longer available. Clients must no longer connect with this resource. gone = 52, /// The request was for a resource at a domain not served by the server and the server /// does not accept proxy requests. proxy_request_refused = 53, /// The server was unable to parse the client's request. Presumably due to a malformed request. bad_request = 59, /// Client was unable to provide a certificate. client_certificate_required = 60, /// The provided certificate is not authorised for this server. certificate_not_authorised = 61, /// The provided certificate is invalid. certificate_not_valid = 62, /// Returns the integer value representing the `Status` pub fn int(self: Status) u6 { return @enumToInt(self); } }; /// Sends a response to the client with only a header and an empty body. /// The response will be written instantly and is_flushed will be set to `true`. /// Any writes after are illegal. pub fn writeHeader(self: *Response, status: Status, meta: []const u8) Error!void { std.debug.assert(meta.len <= 1024); // max META size is 1024 bytes std.debug.assert(status != .success); // success status code requires a body // We may have written a partial response later on. Since trying to resubmit a response // on error, wouldn't be parsable, ensure users cannot call `flush` again. self.is_flushed = true; try self.buffered_writer.writer().print("{d} {s}\r\n", .{ status.int(), meta }); try self.buffered_writer.flush(); } /// Flushes and writes the entire contents of `body` to the client. /// It is valid to call this by the user. However, it is illegal /// to call this more than once during a request. /// /// It can provide benefits to call this instead of relying on the server, as /// work can be done by the user within the same request handle after calling flush, /// such as writing to a log, database or cleaning up data. /// /// This also allows the user to provide a specific mime type for the content. pub fn flush(self: *Response, mime_type: MimeType) Error!void { std.debug.assert(!self.is_flushed); // it is illegal to call `flush` more than once. std.debug.assert(self.buffered_writer.fifo.count == 0); // It's illegal to use both the writer and `flush`. try self.buffered_writer.writer().print("{d} {s}\r\n", .{ self.status.int(), mime_type }); // We may have written a partial response later on. Since trying to resubmit a response // on error, wouldn't be parsable, ensure users cannot call `flush` again. self.is_flushed = true; // write the contents of the body if (self.body.context.items.len != 0) { try self.buffered_writer.writer().writeAll(self.body.context.items); } // ensure all bytes are sent try self.buffered_writer.flush(); }
src/Response.zig
const mmio = @import("io/mmio.zig"); const mbox = @import("io/mbox.zig"); const gpio = @import("io/gpio.zig"); const uart = @import("io/uart.zig"); const regs = @import("types/regs.zig"); const Register = regs.Register; // Embedded version number pub const Version = "0.1.1"; /// Hang the system with an infinite while loop. pub fn hang() noreturn { while (true) {} } const PM_RSTC = Register{ .ReadOnly = mmio.MMIO_BASE + 0x0010001C}; const PM_RSTS = Register{ .ReadWrite = mmio.MMIO_BASE + 0x00100020 }; const PM_WDOG = Register{ .ReadOnly = mmio.MMIO_BASE + 0x00100024 }; const PM_WDOG_MAGIC = u32(0x5A000000); const PM_RSTC_FULLRST = u32(0x00000020); /// Power the SoC down into a very low power state. pub fn powerOff() void { var r: u32 = 0; while (r < 16) : (r += 1) { // Setup a mailbox call to power off each device mbox.mbox[0] = 8*4; mbox.mbox[1] = mbox.MBOX_REQUEST; mbox.mbox[2] = mbox.MBOX_TAG_SETPOWER; mbox.mbox[3] = 8; mbox.mbox[4] = 8; mbox.mbox[5] = r; mbox.mbox[6] = 0; mbox.mbox[7] = mbox.MBOX_TAG_LAST; _ = mbox.mboxCall(mbox.MBOX_CH_PROP); } // Power off GPIO pins mmio.write(gpio.GPFSEL0, 0); mmio.write(gpio.GPFSEL1, 0); mmio.write(gpio.GPFSEL2, 0); mmio.write(gpio.GPFSEL3, 0); mmio.write(gpio.GPFSEL4, 0); mmio.write(gpio.GPFSEL5, 0); mmio.write(gpio.GPPUD, 0); mmio.wait(150); mmio.write(gpio.GPPUDCLK0, 0xFFFFFFFF); mmio.write(gpio.GPPUDCLK1, 0xFFFFFFFF); mmio.wait(150); mmio.write(gpio.GPPUDCLK0, 0); mmio.write(gpio.GPPUDCLK1, 0); // Power off SoC r = mmio.read(PM_RSTS); r &= ~u32(0xfffffaaa); // Indicate halt r |= 0x555; mmio.write(PM_RSTS, PM_WDOG_MAGIC | r); mmio.write(PM_RSTS, PM_WDOG_MAGIC | 10); mmio.write(PM_RSTS, PM_WDOG_MAGIC | PM_RSTC_FULLRST); } /// Reset the SoC pub fn reset() void { var r: u32 = 0; r = mmio.read(PM_RSTS); r &= ~u32(0xfffffaaa); mmio.write(PM_RSTS, PM_WDOG_MAGIC | r); mmio.write(PM_RSTS, PM_WDOG_MAGIC | 10); mmio.write(PM_RSTS, PM_WDOG_MAGIC | PM_RSTC_FULLRST); } // Constants for random number generator const RNG_CTRL = Register{ .ReadOnly = mmio.MMIO_BASE + 0x00104000 }; const RNG_STATUS = Register{ .ReadWrite = mmio.MMIO_BASE + 0x00104004 }; const RNG_DATA = Register{ .ReadOnly = mmio.MMIO_BASE + 0x00104008 }; const RNG_INT_MASK = Register{ .WriteOnly = mmio.MMIO_BASE + 0x00104010 }; /// Initialize the random number generator /// NOTE: Currently just assuming this works until I can test on real hardware. pub fn randInit() void { mmio.write(RNG_STATUS, 0x40000).?; var r = mmio.read(RNG_INT_MASK).?; r |= 1; mmio.write(RNG_INT_MASK, r).?; r = mmio.read(RNG_CTRL).?; r |= 1; mmio.write(RNG_CTRL, r); while ((mmio.read(RNG_STATUS).? >> 24) != 0) { mmio.wait(1); } } /// Get a random number between min and max. pub fn getRand(min: usize, max: usize) usize { if (min > max) return 0; return ((mmio.read(RNG_DATA).?) % (max-min)) + min; } const SYSTMR_HI = Register{ .ReadOnly = mmio.MMIO_BASE + 0x00003004 }; const SYSTMR_LO = Register{ .ReadOnly = mmio.MMIO_BASE + 0x00003008 }; /// Get system timer counter from the BCM chip. fn getSystemTimer() c_ulong { var h = c_ulong(0); var l = c_ulong(0); var res = u32(0); // read MMIO area as two separate c_ulong h = @intCast(c_ulong, mmio.read(SYSTMR_HI).?); l = @intCast(c_ulong, mmio.read(SYSTMR_LO).?); // re-read if high changed during first read if (h != mmio.read(SYSTMR_HI).?) { h = @intCast(c_ulong, mmio.read(SYSTMR_HI).?); l = @intCast(c_ulong, mmio.read(SYSTMR_LO).?); } return res; } /// Wait a given number of milliseconds. /// NOTE: This does NOT work on QEMU, as QEMU doesn't emulate the system timer. pub fn waitMsec(secs: u32) void { var n = @intCast(c_ulong, secs); var t = getSystemTimer(); if (t != 0) { while (getSystemTimer() < t + n) {} } }
kernel/src/arch/aarch64/util.zig
const inputFile = @embedFile("./input/day06.txt"); const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const assert = std.debug.assert; // Returns a list of ages // The input is a comma separated list of ages fn parseInput(input: []const u8, allocator: Allocator) !ArrayList(u8) { var result = ArrayList(u8).init(allocator); var start: usize = 0; while (std.mem.indexOfAnyPos(u8, input, start, &.{ ',', '\n' })) |end| : (start = end + 1) { const age = try std.fmt.parseInt(u8, input[start..end], 10); if (age < 0 or age > 8) return error.InputError; try result.append(age); } return result; } const maxLaternfishAge = 8; // 0, 1, ... 8; // Given a list of initial lanternfish ages, fn numLaternfishAfter(noofDays: u32, initialAges: []const u8) u64 { var ages = [_]u64{0} ** (maxLaternfishAge + 1); // partition for (initialAges) |age| { ages[age] += 1; } var day: u32 = 0; while (day < noofDays) : (day += 1) { std.mem.rotate(u64, &ages, 1); // all those from day 0 go to day 6 too ages[6] += ages[8]; } // sum var result: u64 = 0; for (ages) |numInAge, age| { std.debug.print("For age {d}, there are {d} lanternfish\n", .{ age, numInAge }); result += numInAge; } return result; } pub fn main() !void { const stdout = std.io.getStdOut().writer(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = &gpa.allocator; defer std.debug.assert(!gpa.deinit()); // no leaks const ages = try parseInput(inputFile, allocator); defer ages.deinit(); try stdout.print("Part 1 Num lantern fish: {d}\nPart 2: {d}\n", .{ numLaternfishAfter(80, ages.items), numLaternfishAfter(256, ages.items) }); } test "Part 1" { const input = \\3,4,3,1,2 \\ ; const ages = try parseInput(input, std.testing.allocator); defer ages.deinit(); try std.testing.expectEqual(@as(u64, 26), numLaternfishAfter(18, ages.items)); try std.testing.expectEqual(@as(u64, 5934), numLaternfishAfter(80, ages.items)); try std.testing.expectEqual(@as(u64, 26984457539), numLaternfishAfter(256, ages.items)); }
src/day06.zig
const std = @import("std"); const ArrayList = std.ArrayList; const StringHashMap = std.StringHashMap; const StrMap = std.StringHashMap; const Token = @import("./token.zig").Token; const hash = std.hash; const Kind = Token.Kind; const Lexer = @import("./lexer.zig").Lexer; const LexerError = @import("./lexer.zig").LexerError; const @"Type" = @import("./token/type.zig").@"Type"; const Op = @import("./token/op.zig").Op; const Block = @import("./token/block.zig").Block; const Kw = @import("./token/kw.zig").Kw; pub const AstError = error{ MemoryLimit, }; pub const Ast = struct { root: ?*Ast.Node = null, input: []const u8, arena: std.heap.ArenaAllocator, allocator: std.mem.Allocator, sym_map: std.StringHashMap([]const u8), const Self = @This(); pub fn init(a: std.mem.Allocator, arena: std.heap.ArenaAllocator, i: []const u8) Self { var hm = StringHashMap([]const u8).init(a); defer hm.deinit(); return Self{ .arena = arena, .allocator = a, .root = null, .sym_map = hm, .input = i }; } pub fn deinit(self: *Self) void { self.sym_map.deinit(); _ = self.arena.state.promote(self.allocator); self.arena.deinit(); self.* = undefined; } pub fn push(self: *Self, data: Token) void { var node = self.newLeaf(data); if (self.root) |root| { node.next = root; self.root = node; } else self.root = node; } pub fn create(a: std.mem.Allocator, input: []const u8) !void { var lx = Lexer.init(input, a); const tok_str = try lx.tokenListToString(); std.debug.print("{s}", .{tok_str}); var arena = std.heap.ArenaAllocator.init(a); defer arena.deinit(); var ast = Self.init(a, arena, input); defer ast.deinit(); // var stack = Stack.init(a, @intCast(i32, input.len)); } /// Tokenize input without use of Lexer struct pub fn tokenize(a: std.mem.Allocator, input: []const u8) *Self { var ln_instr = std.mem.tokenize(u8, input, '\n'); while (ln_instr.next()) |instr| { var ws_strip = std.mem.tokenize(u8, instr, " "); for (ws_strip) |w| { std.debug.print("Got {s}\n", w); } } return Self.init(a, std.heap.ArenaAllocator.init(a)); } pub fn pop(self: *Self) ?*Node { const node = self.root; self.root = self.root.?.next; return node; } pub fn newLeaf(self: *Self, data: Token) !Ast.Node { const new = self.allocator.create(Ast.Node); var node: Ast.Node = Node.init(data); node = Ast.Node{ .idx = 0, .data = data, .lhs = null, .rhs = null }; try return new; } pub fn newNode(self: *Self, data: Token, lhs: ?*Ast.Node, rhs: ?*Ast.Node) !Ast.Node { const new = self.allocator.create(Ast.Node); new.* = Ast.Node{ .idx = 0, .data = data, .lhs = lhs, .rhs = rhs }; try return new; } pub fn printJson(self: *Self) !void { try std.json.stringify(self, .{}, std.io.getStdOut().writer()); } pub fn build(self: *Self, tkl: ArrayList(Token)) AstError!?Self { // var curr_st = ":"; if (!self.root) self.withRoot(tkl.next()); for (tkl) |token| { switch (token.kind) { .type => |ty| switch (ty) { .ident => |_| continue, //store in sym table else => continue, }, .op => |o| switch (o) { .newline, .semicolon => continue, }, .kw => |kwd| switch (kwd) { .is => continue, else => continue, }, .block => |bl| switch (bl) { .lpar => continue, else => continue, }, } } return self; } pub fn withRoot(self: Self, data: Token) void { self.root = Node.init(data); } pub fn len(self: Self) usize { return self.len; } pub const Node = struct { idx: usize, data: Token, lhs: ?*Ast.Node = null, rhs: ?*Ast.Node = null, const AstNode = @This(); pub fn init(data: Token) Ast.Node { return Ast.Node{ .idx = 0, .data = data, .lhs = null, .rhs = null, }; } pub fn inOrder(self: ?Ast.Node, a: std.mem.Allocator) void { if (self) |root| { root.inOrder(a); std.debug.print("{s}", .{&root.toStr(a)}); root.inOrder(a); } } pub fn undef() Ast.Node { return Ast.Node{ .idx = 0, .lhs = null, .rhs = null, .data = Token.initKind(.unknown, null) }; } pub fn initExpr(idx: usize, data: Token, lhs: ?*Ast.Node, rhs: ?*Ast.Node) Node { return Ast.Node{ .idx = idx, .data = data, .lhs = lhs, .rhs = rhs }; } pub fn addNode() void {} pub fn setLhs(self: Ast.Node, data: Token) void { self.lhs = Ast.Node.init(data); } pub fn setRhs(self: Ast.Node, data: Token) void { self.lhs = Ast.Node.init(data); } pub fn eval(self: Ast.Node, a: std.mem.Allocator) void { if (self.lhs) |lhs| if (self.rhs) |rhs| { const args = .{ lhs.toStr(a), self.toStr(a), rhs.toStr(a) }; std.debug.print("Ast.Node.Eval {s} {s} {s}", args); switch (self.data.kind) { Kind.op => |op| switch (op) { .mul => Eval.mul(0, 0), else => {}, }, Kind.@"Type" => |_| {}, else => {}, } }; } pub fn toStr(self: *Ast.Node, a: std.mem.Allocator) []const u8 { const args = .{ self.idx, self.data.kind.toStr(), if (self.lhs) |l| Ast.Node.toStr(l, a) else "", if (self.rhs) |r| Ast.Node.toStr(r, a) else "", }; const pfmt = "AST NODE: {s} with data:\n{s}\nlhs: {s}\trhs: {s}"; std.debug.print("AST NODE: {s} with data:\n{s}\nlhs: {s}\trhs: {s}", args); return std.fmt.allocPrint(a, comptime pfmt, comptime args) catch { return " "; }; } }; pub const Eval = struct { op: ?Token.Kind.Op, lhs: []const u8, lhs: []const u8, pub fn add(a: i32, b: i32) i32 { return a + b; } pub fn sub(a: i32, b: i32) i32 { return a - b; } pub fn mul(a: i32, b: i32) i32 { return a * b; } pub fn div(a: i32, b: i32) f32 { return a / b; } }; pub const Symbols = struct { const Sym = @This(); sym: StringHashMap(Symbol), pub fn init(a: std.mem.Allocator) Symbols { return Self{ .sym = StringHashMap(Symbol).init(a) }; } pub fn print(self: Symbols) void { std.debug.print("IDLANG SYMBOL TABLE: ", .{}); for (self.sym) |sy| { sy.print(); } } }; pub const Symbol = struct { key: []const u8, val: []const u8, scope: Scope, context: []const u8, line: usize, next: ?Symbol, pub fn print(self: Symbol) void { const args = .{ self.key, self.val, self.scope, self.line, self.context }; std.debug.print("SYM: {s} = {s} :: SCOPE {s}, LINE {s} :: CTX {s}", args); } pub fn init(ident: []const u8, val: []const u8, scope: []const u8, ln: usize) Symbol { return Self{ .key = ident, .val = val, .scope = scope, .line = ln, .next = null }; } pub const Scope = union(enum(u8)) { local, public, block: ?[]const u8, pub fn fromStr(st: []const u8) ?Scope { if (std.mem.eql(u8, "loc", st) or std.mem.eql(u8, "local", st)) { return Scope.local; } else if (std.mem.eql(u8, "pub", st) or std.mem.eql(u8, "public", st)) { return Scope.public; } else if (st[0] == ':') { return Scope{ .block = st[1..] }; } return null; } }; }; pub fn toStr(self: *Ast, a: std.mem.Allocator) []const u8 { std.debug.print("AST: ROOT {s}", .{self.root.?.toStr(a)}); return ""; } }; pub const Stack = struct { const Self = @This(); capacity: i32, top: i32 = -1, alloc: std.mem.Allocator, nodes: std.ArrayList(Token), pub fn init(a: std.mem.Allocator, cap: i32) Stack { const nodes = std.ArrayList(Token).init(a); return Stack{ .top = -1, .capacity = cap, .nodes = nodes, .alloc = a }; } pub fn isFull(self: *Self) bool { return self.top == self.capacity - 1; } pub fn isEmpty(self: *Self) bool { return self.top == -1; } pub fn push(self: *Self, data: Token) StackError!void { if (self.isFull()) return StackError.MaxCapacity; self.nodes.items[@intCast(usize, self.top) + 1] = data; } pub fn pop(self: *Self) StackError!Token { if (@intCast(usize, self.top) == -1) return StackError.Empty; return self.nodes.items[@intCast(usize, self.top) - 1]; } pub fn peek(self: *Self) Token { return self.nodes.items[@intCast(usize, self.top)]; } pub fn fromArrayList(self: *Self, sl: ArrayList(Ast.Node)) !?Ast { self.nodes = sl; self.capacity = std.mem.len(sl.items); self.top = self.capacity - 1; } }; pub const StackError = error{ MaxCapacity, Empty };
src/lang/ast.zig
const std = @import("std"); const trait = std.meta.trait; const ctregex = @import("ctregex"); /// A collection of utilities that are likely to be used on a fairly common /// basis and would therefore cause repetitive, avoidable boilerplate. pub const Utils = struct { arena: *std.mem.Allocator, gpa: *std.mem.Allocator, out: std.fs.File.Writer, }; /// An alias for ArrayListUnmanaged because unmanaged is the best default. pub const List = std.ArrayListUnmanaged; /// Automatically chooses StringArrayHashMapUnmanaged(V) if K is []const u8, /// otherwise chooses AutoArrayHashMapUnmanaged(K, V). Saves a lot of typing. pub fn Map(comptime K: type, comptime V: type) type { return switch(K) { []const u8 => std.StringArrayHashMapUnmanaged(V), else => std.AutoArrayHashMapUnmanaged(K, V), }; } /// Convenience constructor for List(T){}. pub fn list(comptime T: type) List(T) { return List(T){}; } /// Convenience constructor for Map(K, V){}. pub fn map(comptime K: type, comptime V: type) Map(K, V) { return Map(K, V){}; } /// Transforms an input of bytes in a rectangular grid (a series of equal length /// rows separated by newlines; a common form of input) pub fn gridRows(comptime input: []const u8) GridRows(input) { @setEvalBranchQuota(input.len * 10); comptime { var buf: GridRows(input) = undefined; for (buf) |*bytes, y| { const width = bytes.len; const index = y * (width + 1); bytes.* = input[index..][0..width].*; } return buf; } } fn GridRows(comptime input: []const u8) type { const width = comptime std.mem.indexOfScalar(u8, input, '\n').?; const height = @divExact(input.len, width + 1); return [height][width]u8; } /// Transforms an input of characters separated by newlines into an array of lines. /// This is done more efficiently than `std.mem.tokenize` to optimize comptime eval. pub fn lines(comptime input: []const u8) []const []const u8 { @setEvalBranchQuota(input.len * 5); comptime { var buf: []const []const u8 = &[_][]const u8{}; var slice = input; while (slice.len > 0) { for (slice) |c, i| { if (c == '\n') { buf = buf ++ [_][]const u8{slice[0..i]}; slice = slice[(i + 1)..]; break; } } } return buf; } } /// Convenience wrapper over std.fmt.parseUnsigned for T radix 10. pub fn parseUint(comptime T: type, str: []const u8) !T { return std.fmt.parseUnsigned(T, str, 10); } /// Convenience wrapper over std.fmt.parseInt for T radix 10. pub fn parseInt(comptime T: type, str: []const u8) !T { return std.fmt.parseInt(T, str, 10); } /// Wrapper over ctregex.MatchResult that compile errors instead of silently /// returning `void` when the regex fails to parse. pub fn MatchResult(comptime regex: []const u8) type { const T = ctregex.MatchResult(regex, .{}); if (T == void) @compileError("Failed to parse regex: " ++ regex); return T; } /// Wrapper over ctregex.match that is UTF-8 always and compile errors if the /// regex is invalid instead of silently returning `void`. pub fn match(comptime regex: []const u8, str: []const u8) ?MatchResult(regex) { return ctregex.match(regex, .{}, str) catch null; } /// Wrapper over `(match(regex, str) catch null) != null`. pub fn isMatch(comptime regex: []const u8, str: []const u8) bool { return match(regex, str) != null; } /// Return an error if the provided condition is false. pub fn expect(condition: bool) !void { if (!condition) return error.AssertionFailed; } /// Return an error if the provided values are inequal. pub fn expectEq(a: anytype, b: anytype) !void { if (a != b) return error.AssertionFailed; } /// Return an error if the provided values are equal. pub fn expectNe(a: anytype, b: anytype) !void { if (a == b) return error.AssertionFailed; } /// Return an error if the number is outside of the provided bounds. /// Otherwise, return the number to use in another expression. pub fn expectRange(num: anytype, lower: anytype, upper: anytype) !@TypeOf(num) { if (lower <= num and upper >= num) return num; return error.AssertionFailed; // num < lower or num > upper } /// Can take an optional, array of optionals, or tuple of optionals. /// Return an error if any of these optional values are null. pub fn expectNonNull(values: anytype) !void { const T = @TypeOf(values); if (comptime trait.isTuple(T)) { comptime var i = 0; inline while (i < values.len) : (i += 1) { if (values[i] == null) return error.AssertionFailed; } } else if (comptime trait.isIndexable(T)) { for (values) |value| { if (value == null) return error.AssertionFailed; } } else if (@typeInfo(T) == .Optional) { if (values == null) return error.AssertionFailed; } else { @compileError("expectNonNull unimplemented for " ++ @typeName(T)); } } /// Takes an optional value and unwraps it, returning an error if the value was null. pub fn unwrap(value: anytype) !std.meta.Child(@TypeOf(value)) { return if (value == null) error.AssertionFailed else value.?; }
util.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const mem = std.mem; const fmt = std.fmt; pub const rdata = @import("dns/rdata.zig"); pub const RData = rdata.DNSRData; pub const QuestionList = std.ArrayList(Question); pub const ResourceList = std.ArrayList(Resource); pub const FixedStream = std.io.FixedBufferStream([]const u8); pub const DNSDeserializer = std.io.Deserializer(.Big, .Bit, FixedStream.Reader); pub const Error = error{ UnknownType, RDATANotSupported, DeserialFail, ParseFail, }; /// The response code of a packet. pub const ResponseCode = enum(u4) { NoError = 0, FmtError = 1, ServFail = 2, NameErr = 3, NotImpl = 4, Refused = 5, }; /// Represents a DNS type. /// Keep in mind this enum does not declare all possible DNS types. pub const Type = enum(u16) { A = 1, NS = 2, MD = 3, MF = 4, CNAME = 5, SOA = 6, MB = 7, MG = 8, MR = 9, NULL = 10, WKS = 11, PTR = 12, HINFO = 13, MINFO = 14, MX = 15, TXT = 16, AAAA = 28, // TODO LOC = 29, (check if it's worth it. https://tools.ietf.org/html/rfc1876) SRV = 33, // those types are only valid in request packets. they may be wanted // later on for completeness, but for now, it's more hassle than it's worth. // AXFR = 252, // MAILB = 253, // MAILA = 254, // ANY = 255, // should this enum be non-exhaustive? // trying to get it non-exhaustive gives "TODO @tagName on non-exhaustive enum https://github.com/ziglang/zig/issues/3991" //_, /// Convert a given string to an integer representing a Type. pub fn fromStr(str: []const u8) !@This() { if (str.len > 10) return error.Overflow; var uppercased: [10]u8 = undefined; toUpper(str, uppercased[0..]); const type_info = @typeInfo(@This()).Enum; inline for (type_info.fields) |field| { if (mem.eql(u8, uppercased[0..str.len], field.name)) { return @intToEnum(@This(), field.value); } } return error.InvalidDnsType; } }; pub const Class = enum(u16) { IN = 1, CS = 2, CH = 3, HS = 4, WILDCARD = 255, }; fn toUpper(str: []const u8, out: []u8) void { for (str) |c, i| { out[i] = std.ascii.toUpper(c); } } /// Describes the header of a DNS packet. pub const Header = packed struct { id: u16 = 0, qr_flag: bool = false, opcode: i4 = 0, aa_flag: bool = false, tc: bool = false, rd: bool = false, ra: bool = false, z: u3 = 0, rcode: ResponseCode = .NoError, /// Amount of questions in the packet. qdcount: u16 = 0, /// Amount of answers in the packet. ancount: u16 = 0, /// Amount of nameservers in the packet. nscount: u16 = 0, /// Amount of additional recordsin the packet. arcount: u16 = 0, }; /// Represents a single DNS domain-name, which is a slice of strings. /// /// The "www.google.com" friendly domain name can be represented in DNS as a /// sequence of labels: first "www", then "google", then "com", with a length /// prefix for all of them, ending in a null byte. /// /// Keep in mind Name's are not singularly deserializeable, as the names /// could be pointers to different bytes in the packet. /// (RFC1035, section 4.1.4 Message Compression) pub const Name = struct { /// The name's labels. labels: [][]const u8, /// Returns the total size in bytes of the Name as if it was sent /// over a socket. pub fn size(self: @This()) usize { // by default, add the null octet at the end of it var total_size: usize = 1; for (self.labels) |label| { // length octet + the actual label octets total_size += @sizeOf(u8); total_size += label.len * @sizeOf(u8); } return total_size; } /// Convert a Name to a human-friendly domain name. /// Does not add a period to the end of it. pub fn toStr(self: @This(), allocator: *Allocator) ![]u8 { return try std.mem.join(allocator, ".", self.labels); } /// Get a Name out of a domain name ("www.google.com", for example). pub fn fromString(allocator: *Allocator, domain: []const u8) !@This() { if (domain.len > 255) return error.Overflow; const period_count = blk: { var it = std.mem.split(domain, "."); var count: usize = 0; while (it.next()) |_| count += 1; break :blk count; }; var it = std.mem.split(domain, "."); var labels: [][]const u8 = try allocator.alloc([]u8, period_count); var labels_idx: usize = 0; while (labels_idx < period_count) : (labels_idx += 1) { var label = it.next().?; labels[labels_idx] = label; } return Name{ .labels = labels[0..] }; } pub fn serialize(self: @This(), serializer: anytype) !void { for (self.labels) |label| { std.debug.assert(label.len < 255); try serializer.serialize(@intCast(u8, label.len)); for (label) |byte| { try serializer.serialize(byte); } } // null-octet for the end of labels for this name try serializer.serialize(@as(u8, 0)); } /// Format the given DNS name. pub fn format(self: @This(), comptime f: []const u8, options: fmt.FormatOptions, writer: anytype) !void { if (f.len != 0) { @compileError("Unknown format character: '" ++ f ++ "'"); } for (self.labels) |label| { try fmt.format(writer, "{}.", .{label}); } } }; /// Represents a DNS question sent on the packet's question list. pub const Question = struct { qname: Name, qtype: Type, qclass: Class, }; /// Represents a single DNS resource. Appears on the answer, authority, /// and additional lists of the packet. pub const Resource = struct { name: Name, rr_type: Type, class: Class, ttl: i32, /// Use the dns.rdata module to interprete a resource's RDATA. opaque_rdata: []u8, /// Give the size, in bytes, of the binary representation of a resource. pub fn size(resource: @This()) usize { var res_size: usize = 0; // name for the resource res_size += resource.name.size(); // rr_type, class, ttl, rdlength are 3 u16's and one u32. res_size += @sizeOf(u16) * 3; res_size += @sizeOf(u32); res_size += resource.opaque_rdata.len * @sizeOf(u8); return res_size; } pub fn serialize(self: @This(), serializer: anytype) !void { try serializer.serialize(self.name); try serializer.serialize(self.rr_type); try serializer.serialize(self.class); try serializer.serialize(self.ttl); try serializer.serialize(@intCast(u16, self.opaque_rdata.len)); try serializer.serialize(self.opaque_rdata); } }; /// Represents a Label if it is a pointer to a set of labels OR a single label. /// Name's, by RFC1035 can appear in three ways (in binary form): /// - As a set of labels, ending with a null byte. /// - As a set of labels, with a pointer to another set of labels, /// ending with null. /// - As a pointer to another set of labels. /// /// Recursive parsing is used to convert all pointers into proper labels. const LabelComponent = union(enum) { Pointer: [][]const u8, Label: []u8, }; /// Deserialize a type, but turn any error caused by it into Error.DeserialFail. /// /// This is required because of the following facts: /// - nonasync stack-allocated recursive functions must have explicit error sets. /// - std.io.Deserializer's error set is not stable. fn inDeserial(deserializer: anytype, comptime T: type) Error!T { return deserializer.deserialize(T) catch |_| { return Error.DeserialFail; }; } /// Represents a full DNS packet, including all conversion to and from binary. /// This struct supports the io.Serializer and io.Deserializer interfaces. /// The serialization of DNS packets only serializes the question list. Be /// careful with adding things other than questions, as the header will be /// modified, but the lists won't appear in the final result. pub const Packet = struct { const Self = @This(); allocator: *Allocator, raw_bytes: []const u8, header: Header, questions: QuestionList, answers: ResourceList, authority: ResourceList, additional: ResourceList, /// Initialize a Packet with an allocator (for internal parsing) /// and a raw_bytes slice for pointer deserialization purposes (as they /// point to an offset *inside* the existing DNS packet's binary) /// Caller owns the memory. pub fn init(allocator: *Allocator, raw_bytes: []const u8) Packet { var self = Packet{ .header = Header{}, // keeping the original packet bytes // for compression purposes .raw_bytes = raw_bytes, .allocator = allocator, .questions = QuestionList.init(allocator), .answers = ResourceList.init(allocator), .authority = ResourceList.init(allocator), .additional = ResourceList.init(allocator), }; return self; } pub fn deinit(self: *Self) void { self.questions.deinit(); self.answers.deinit(); self.authority.deinit(); self.additional.deinit(); } /// Return if this packet makes sense, if the headers' provided lengths /// match the lengths of the given packets. This is not checked when /// serializing. pub fn is_valid(self: *Self) bool { return (self.questions.len == self.header.qdcount and self.answers.len == self.header.ancount and self.authority.len == self.header.nscount and self.additional.len == self.header.arcount); } /// Serialize a ResourceList. fn serializeRList( self: Packet, serializer: anytype, rlist: ResourceList, ) !void { for (rlist.items) |resource| { try serializer.serialize(resource); } } pub fn serialize(self: Packet, serializer: anytype) !void { std.debug.assert(self.header.qdcount == self.questions.items.len); std.debug.assert(self.header.ancount == self.answers.items.len); std.debug.assert(self.header.nscount == self.authority.items.len); std.debug.assert(self.header.arcount == self.additional.items.len); try serializer.serialize(self.header); for (self.questions.items) |question| { try serializer.serialize(question.qname); try serializer.serialize(question.qtype); try serializer.serialize(@enumToInt(question.qclass)); } try self.serializeRList(serializer, self.answers); try self.serializeRList(serializer, self.authority); try self.serializeRList(serializer, self.additional); } fn deserializePointer( self: *Self, ptr_offset_1: u8, deserializer: anytype, ) (Error || Allocator.Error)![][]const u8 { // we need to read another u8 and merge both ptr_prefix_1 and the // u8 we read into an u16 // the final offset is u14, but we keep it as u16 to prevent having // to do too many complicated things in regards to deserializer state. const ptr_offset_2 = try inDeserial(deserializer, u8); // merge them together var ptr_offset: u16 = (ptr_offset_1 << 7) | ptr_offset_2; // set first two bits of ptr_offset to zero as they're the // pointer prefix bits (which are always 1, which brings problems) ptr_offset &= ~@as(u16, 1 << 15); ptr_offset &= ~@as(u16, 1 << 14); // we need to make a proper [][]const u8 which means // re-deserializing labels but using start_slice instead var offset_size_opt = std.mem.indexOf(u8, self.raw_bytes[ptr_offset..], "\x00"); if (offset_size_opt) |offset_size| { var start_slice = self.raw_bytes[ptr_offset .. ptr_offset + (offset_size + 1)]; var in = FixedStream{ .buffer = start_slice, .pos = 0 }; var new_deserializer = DNSDeserializer.init(in.reader()); // the old (nonfunctional approach) a simpleDeserializeName // to counteract the problems with just slapping deserializeName // in and doing recursion. however that's problematic as pointers // could be pointing to other pointers. // because of https://github.com/ziglang/zig/issues/1006 // and the disallowance of recursive async fns, we heap-allocate this call var frame = try self.allocator.create(@Frame(Packet.deserializeName)); defer self.allocator.destroy(frame); frame.* = async self.deserializeName(&new_deserializer); var name = try await frame; return name.labels; } else { return Error.ParseFail; } } /// Deserialize the given label into a LabelComponent, which can be either /// A Pointer or a full Label. fn deserializeLabel( self: *Self, deserializer: anytype, ) (Error || Allocator.Error)!?LabelComponent { // check if label is a pointer, this byte will contain 11 as the starting // point of it var ptr_prefix = try inDeserial(deserializer, u8); if (ptr_prefix == 0) return null; var bit1 = (ptr_prefix & (1 << 7)) != 0; var bit2 = (ptr_prefix & (1 << 6)) != 0; if (bit1 and bit2) { var labels = try self.deserializePointer(ptr_prefix, deserializer); return LabelComponent{ .Pointer = labels }; } else { // the ptr_prefix is currently encoding the label's size var label = try self.allocator.alloc(u8, ptr_prefix); // properly deserialize the slice var label_idx: usize = 0; while (label_idx < ptr_prefix) : (label_idx += 1) { label[label_idx] = try inDeserial(deserializer, u8); } return LabelComponent{ .Label = label }; } return null; } /// Deserializes a Name, which represents a slice of slice of u8 ([][]u8) pub fn deserializeName( self: *Self, deserial: *DNSDeserializer, ) (Error || Allocator.Error)!Name { // Removing this causes the compiler to send a // 'error: recursive function cannot be async' if (std.io.mode == .evented) { _ = @frame(); } // allocate empty label slice var deserializer = deserial; var labels: [][]const u8 = try self.allocator.alloc([]u8, 0); var labels_idx: usize = 0; while (true) { var label = try self.deserializeLabel(deserializer); if (label) |denulled_label| { labels = try self.allocator.realloc(labels, (labels_idx + 1)); switch (denulled_label) { .Pointer => |label_ptr| { if (labels_idx == 0) { return Name{ .labels = label_ptr }; } else { // in here we have an existing label in the labels slice, e.g "leah", // and then label_ptr points to a [][]const u8, e.g // [][]const u8{"ns", "cloudflare", "com"}. we // need to copy that, as a suffix, to the existing // labels slice for (label_ptr) |label_ptr_label, idx| { labels[labels_idx] = label_ptr_label; labels_idx += 1; // reallocate to account for the next incoming label if (idx != label_ptr.len - 1) { labels = try self.allocator.realloc(labels, (labels_idx + 1)); } } return Name{ .labels = labels }; } }, .Label => |label_val| labels[labels_idx] = label_val, } } else { break; } labels_idx += 1; } return Name{ .labels = labels }; } /// (almost) Deserialize an RDATA section. This only deserializes to a slice of u8. /// Parsing of RDATA sections are in their own dns.rdata module. fn deserializeRData(self: *Self, deserializer: anytype) ![]u8 { var rdata_length = try deserializer.deserialize(u16); var opaque_rdata = try self.allocator.alloc(u8, rdata_length); var i: u16 = 0; while (i < rdata_length) : (i += 1) { opaque_rdata[i] = try deserializer.deserialize(u8); } return opaque_rdata; } /// Deserialize a list of Resource which sizes are controlled by the /// header's given count. fn deserialResourceList( self: *Self, deserializer: anytype, comptime header_field: []const u8, rs_list: *ResourceList, ) !void { const total = @field(self.*.header, header_field); var i: usize = 0; while (i < total) : (i += 1) { var name = try self.deserializeName(deserializer); var rr_type = try deserializer.deserialize(u16); var class = try deserializer.deserialize(u16); var ttl = try deserializer.deserialize(i32); // rdlength and rdata are under deserializeRData var opaque_rdata = try self.deserializeRData(deserializer); var resource = Resource{ .name = name, .rr_type = @intToEnum(Type, rr_type), .class = @intToEnum(Class, class), .ttl = ttl, .opaque_rdata = opaque_rdata, }; try rs_list.append(resource); } } pub fn deserialize(self: *Self, deserializer: anytype) !void { self.header = try deserializer.deserialize(Header); // deserialize our questions, but since they contain Name, // the deserialization is messier than what it should be.. var i: usize = 0; while (i < self.header.qdcount) { // question contains {name, qtype, qclass} var name = try self.deserializeName(deserializer); var qtype = try deserializer.deserialize(u16); var qclass = try deserializer.deserialize(u16); var question = Question{ .qname = name, .qtype = @intToEnum(Type, qtype), .qclass = @intToEnum(Class, qclass), }; try self.questions.append(question); i += 1; } try self.deserialResourceList(deserializer, "ancount", &self.answers); try self.deserialResourceList(deserializer, "nscount", &self.authority); try self.deserialResourceList(deserializer, "arcount", &self.additional); } pub fn addQuestion(self: *Self, question: Question) !void { self.header.qdcount += 1; try self.questions.append(question); } pub fn addAnswer(self: *Self, resource: Resource) !void { self.header.ancount += 1; try self.answers.append(resource); } pub fn addAuthority(self: *Self, resource: Resource) !void { self.header.nscount += 1; try self.authority.append(resource); } pub fn addAdditional(self: *Self, resource: Resource) !void { self.header.arcount += 1; try self.additional.append(resource); } fn sliceSizes(self: Self) usize { var pkt_size: usize = 0; for (self.questions.items) |question| { pkt_size += question.qname.size(); // add both qtype and qclass (both u16's) pkt_size += @sizeOf(u16); pkt_size += @sizeOf(u16); } for (self.answers.items) |resource| { pkt_size += resource.size(); } for (self.authority.items) |resource| { pkt_size += resource.size(); } for (self.additional.items) |resource| { pkt_size += resource.size(); } return pkt_size; } /// Returns the size in bytes of the binary representation of the packet. pub fn size(self: Self) usize { return @sizeOf(Header) + self.sliceSizes(); } };
src/pkg/dns.zig
const midi = @import("midi"); const std = @import("std"); pub fn main() !void { const stdin = std.io.getStdIn().reader(); const header = try midi.decode.fileHeader(stdin); std.debug.warn("file_header:\n", .{}); std.debug.warn(" chunk_type: {s}\n", .{header.chunk.kind}); std.debug.warn(" chunk_len: {}\n", .{header.chunk.len}); std.debug.warn(" format: {}\n", .{header.format}); std.debug.warn(" tracks: {}\n", .{header.tracks}); std.debug.warn(" division: {}\n", .{header.division}); // The midi standard says that we should respect the headers size, even if it // is bigger than nessesary. We therefor need to figure out what to do with the // extra bytes in the header. This example will just skip them. try stdin.skipBytes(header.chunk.len - midi.file.Header.size, .{}); while (true) { const chunk = midi.decode.chunk(stdin) catch |err| switch (err) { error.EndOfStream => break, else => |e| return e, }; std.debug.warn("chunk:\n", .{}); std.debug.warn(" type: {s}\n", .{chunk.kind}); std.debug.warn(" len: {}\n", .{chunk.len}); // If our chunk isn't a track header, we just skip it. if (!std.mem.eql(u8, &chunk.kind, midi.file.Chunk.track_header)) { try stdin.skipBytes(chunk.len, .{}); continue; } // To be decode midi correctly, we have to keep track of the last // event. Midi can compress midi event if the same kind of event // is repeated. var last_event: ?midi.file.TrackEvent = null; while (true) { const event = try midi.decode.trackEvent(stdin, last_event); last_event = event; std.debug.warn(" {:>6}", .{event.delta_time}); switch (event.kind) { .MetaEvent => |meta_event| { var buf: [1024]u8 = undefined; const data = buf[0..meta_event.len]; try stdin.readNoEof(data); std.debug.warn(" {s:>20} {:>6}", .{ metaEventKindToStr(meta_event.kind()), meta_event.len }); switch (meta_event.kind()) { .Luric, .InstrumentName, .TrackName => std.debug.warn(" {s}\n", .{data}), .EndOfTrack => { std.debug.warn("\n", .{}); break; }, else => std.debug.warn("\n", .{}), } }, .MidiEvent => |midi_event| { std.debug.warn(" {s:>20}", .{midiEventKindToStr(midi_event.kind())}); if (midi_event.channel()) |channel| std.debug.warn(" {:>6}", .{channel}); std.debug.warn(" {:>3} {:>3}\n", .{ midi_event.values[0], midi_event.values[1] }); if (midi_event.kind() == .ExclusiveStart) { while ((try stdin.readByte()) != 0xF7) {} } }, } } } } fn metaEventKindToStr(kind: midi.file.MetaEvent.Kind) []const u8 { return switch (kind) { .Undefined => "undef", .SequenceNumber => "seqnum", .TextEvent => "text", .CopyrightNotice => "copyright", .TrackName => "track_name", .InstrumentName => "instr_name", .Luric => "luric", .Marker => "marker", .CuePoint => "cue_point", .MidiChannelPrefix => "channel_prefix", .EndOfTrack => "eot", .SetTempo => "tempo", .SmpteOffset => "smpte_offset", .TimeSignature => "time_sig", .KeySignature => "key_sig", .SequencerSpecificMetaEvent => "seq_spec_meta_event", }; } fn midiEventKindToStr(kind: midi.Message.Kind) []const u8 { return switch (kind) { // Channel events .NoteOff => "note_off", .NoteOn => "note_on", .PolyphonicKeyPressure => "polykey_pressure", .ControlChange => "cntrl_change", .ProgramChange => "program_change", .ChannelPressure => "chnl_pressure", .PitchBendChange => "pitch_bend_change", // System events .ExclusiveStart => "excl_start", .MidiTimeCodeQuarterFrame => "midi_timecode_quater_frame", .SongPositionPointer => "song_pos_pointer", .SongSelect => "song_select", .TuneRequest => "tune_request", .ExclusiveEnd => "excl_end", .TimingClock => "timing_clock", .Start => "start", .Continue => "continue", .Stop => "stop", .ActiveSensing => "active_sens", .Reset => "reset", .Undefined => "undef", }; }
example/midi_file_to_text_stream.zig
const std = @import("std"); const testing = std.testing; const utils = @import("utils.zig"); const config = @import("config.zig"); const initBoundedArray = utils.initBoundedArray; /// The main definition of a test to perform pub const Entry = struct { name: std.BoundedArray(u8, 1024) = initBoundedArray(u8, 1024), method: HttpMethod = undefined, url: std.BoundedArray(u8, config.MAX_URL_LEN) = initBoundedArray(u8, config.MAX_URL_LEN), headers: std.BoundedArray(HttpHeader, 32) = initBoundedArray(HttpHeader, 32), payload: std.BoundedArray(u8, config.MAX_PAYLOAD_SIZE) = initBoundedArray(u8, config.MAX_PAYLOAD_SIZE), expected_http_code: u64 = 0, // 0 == don't care expected_response_substring: std.BoundedArray(u8, 1024) = initBoundedArray(u8, 1024), extraction_entries: std.BoundedArray(ExtractionEntry, 32) = initBoundedArray(ExtractionEntry, 32), repeats: usize = 1, }; /// Container for the results after executing an Entry pub const EntryResult = struct { num_fails: usize = 0, // Will increase for each failed attempt, relates to "repeats" conclusion: bool = false, response_content_type: std.BoundedArray(u8, HttpHeader.MAX_VALUE_LEN) = initBoundedArray(u8, HttpHeader.MAX_VALUE_LEN), response_http_code: u64 = 0, response_match: bool = false, response_first_1mb: std.BoundedArray(u8, 1024 * 1024) = initBoundedArray(u8, 1024 * 1024), response_headers_first_1mb: std.BoundedArray(u8, 1024 * 1024) = initBoundedArray(u8, 1024 * 1024), }; pub const TestContext = struct { entry: Entry = .{}, result: EntryResult = .{} }; pub const HttpMethod = enum { CONNECT, DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, TRACE, pub fn string(self: HttpMethod) [:0]const u8 { return @tagName(self); } pub fn create(raw: []const u8) !HttpMethod { return std.meta.stringToEnum(HttpMethod, raw) orelse error.NoSuchHttpMethod; } }; test "HttpMethod.create()" { try testing.expect((try HttpMethod.create("OPTIONS")) == HttpMethod.OPTIONS); try testing.expect((try HttpMethod.create("HEAD")) == HttpMethod.HEAD); try testing.expect((try HttpMethod.create("CONNECT")) == HttpMethod.CONNECT); try testing.expect((try HttpMethod.create("TRACE")) == HttpMethod.TRACE); try testing.expect((try HttpMethod.create("GET")) == HttpMethod.GET); try testing.expect((try HttpMethod.create("POST")) == HttpMethod.POST); try testing.expect((try HttpMethod.create("PUT")) == HttpMethod.PUT); try testing.expect((try HttpMethod.create("PATCH")) == HttpMethod.PATCH); try testing.expect((try HttpMethod.create("DELETE")) == HttpMethod.DELETE); try testing.expectError(error.NoSuchHttpMethod, HttpMethod.create("BLAH")); try testing.expectError(error.NoSuchHttpMethod, HttpMethod.create("")); try testing.expectError(error.NoSuchHttpMethod, HttpMethod.create(" GET")); } pub const HttpHeader = struct { pub const MAX_VALUE_LEN = 8*1024; name: std.BoundedArray(u8,256), value: std.BoundedArray(u8,MAX_VALUE_LEN), pub fn create(name: []const u8, value: []const u8) !HttpHeader { return HttpHeader { .name = std.BoundedArray(u8,256).fromSlice(std.mem.trim(u8, name, " ")) catch { return error.ParseError; }, .value = std.BoundedArray(u8,MAX_VALUE_LEN).fromSlice(std.mem.trim(u8, value, " ")) catch { return error.ParseError; }, }; } pub fn render(self: *HttpHeader, comptime capacity: usize, out: *std.BoundedArray(u8, capacity)) !void { try out.appendSlice(self.name.slice()); try out.appendSlice(": "); try out.appendSlice(self.value.slice()); } }; test "HttpHeader.render" { var mybuf = initBoundedArray(u8, 2048); var header = try HttpHeader.create("Accept", "application/xml"); try header.render(mybuf.buffer.len, &mybuf); try testing.expectEqualStrings("Accept: application/xml", mybuf.slice()); } pub const ExtractionEntry = struct { name: std.BoundedArray(u8,256), expression: std.BoundedArray(u8,1024), pub fn create(name: []const u8, value: []const u8) !ExtractionEntry { return ExtractionEntry { .name = std.BoundedArray(u8,256).fromSlice(std.mem.trim(u8, name, " ")) catch { return error.ParseError; }, .expression = std.BoundedArray(u8,1024).fromSlice(std.mem.trim(u8, value, " ")) catch { return error.ParseError; }, }; } };
src/types.zig
const std = @import("std"); const bytecode = @import("bytecode.zig"); const compiler = @import("compiler.zig"); const debug = @import("debug.zig"); const gc = @import("gc.zig"); const Value = @import("value.zig").Value; const Heap = gc.Heap; const DEBUG_TRACE_EXECUTION = true; pub const InterpreterError = error{ ScanError, CompileError, RuntimeError, CastError, CannotCompareValuesError, NonsensicalComparisonError, NonsensicalOperationError, StackOverflowError, StackUnderflowError, InvalidOperationError, UndefinedVariableError, }; var the_vm: VM = undefined; pub fn vm() *VM { return &the_vm; } pub const VM = struct { chunk: *bytecode.Chunk = undefined, ip: usize = 0, allocator: std.mem.Allocator, // FIXME: Not sure about wether we should use a stack or // heap allocated array here. stack: std.ArrayList(Value), heap: Heap, // Keep this list of roots to avoid allocating / deallocating a list on every garbage collection root_list: std.ArrayList(*const Value), running: bool = false, globals: std.StringHashMap(Value), const Self = @This(); pub fn init(allocator: std.mem.Allocator) *Self { the_vm = VM{ .allocator = allocator, .stack = std.ArrayList(Value).init(allocator), .heap = Heap.init(allocator), .root_list = std.ArrayList(*const Value).init(allocator), .globals = std.StringHashMap(Value).init(allocator), }; return vm(); } pub fn deinit(self: *Self) void { self.globals.deinit(); self.root_list.deinit(); self.heap.deinit(); self.stack.deinit(); } pub fn interpret(self: *Self, buf: []const u8) InterpreterError!void { const t0 = std.time.nanoTimestamp(); var chunk = bytecode.Chunk.init(self.allocator); defer chunk.deinit(); if (!compiler.compile(buf, &chunk, &self.heap)) { return InterpreterError.CompileError; } const t1 = std.time.nanoTimestamp(); self.chunk = &chunk; self.ip = 0; const t2 = std.time.nanoTimestamp(); try self.run(); const t3 = std.time.nanoTimestamp(); const t_compile_ms = @intToFloat(f64, t1 - t0) * 1e-6; const t_execute_ms = @intToFloat(f64, t3 - t2) * 1e-6; std.debug.print("Compilation took {d}ms, execution took {d}ms\n", .{ t_compile_ms, t_execute_ms }); } fn run(self: *Self) InterpreterError!void { self.running = true; defer self.running = false; while (true) : (self.ip += 1) { var inst = @intToEnum(bytecode.Op, self.chunk.code.items[self.ip]); if (DEBUG_TRACE_EXECUTION) { _ = debug.disassembleInst(self.chunk.*, self.ip); } switch (inst) { .Return => { break; }, .Constant => { const value = self.getNextConstant(); self.push(value); }, .True => self.push(Value.fromBoolean(true)), .False => self.push(Value.fromBoolean(false)), .Nil => self.push(Value.fromNil()), .Add => try self.binaryOp(opAdd), .Sub => try self.binaryOp(opSub), .Mul => try self.binaryOp(opMul), .Div => try self.binaryOp(opDiv), .And => try self.binaryOp(opAnd), .Or => try self.binaryOp(opOr), .Xor => try self.binaryOp(opXor), .Equal => try self.binaryOp(opEq), .NotEqual => try self.binaryOp(opNeq), .Greater => try self.binaryOp(opGt), .GreaterEqual => try self.binaryOp(opGEq), .Less => try self.binaryOp(opLt), .LessEqual => try self.binaryOp(opLEq), .Neg => { const value = try (self.pop()).asNumber(); self.push(Value.fromNumber(-value)); }, .Not => { const value = try (self.pop()).asBoolean(); self.push(Value.fromBoolean(!value)); }, .Print => { const value = self.pop(); std.debug.print("{}\n", .{value}); }, .Pop => _ = self.pop(), .DefineGlobal => { const name = try self.getNextConstant().asString(); self.globals.put(name.str(), self.pop()) catch unreachable; }, .GetGlobal => { const name = try self.getNextConstant().asString(); const value = self.globals.get(name.str()); if (value == null) { return InterpreterError.UndefinedVariableError; } self.push(value.?); }, .SetGlobal => { const name = try self.getNextConstant().asString(); const value = self.globals.getPtr(name.str()); if (value == null) { return InterpreterError.UndefinedVariableError; } const new_value = self.peek(0); if (!value.?.sharesType(new_value)) { return InterpreterError.CastError; } value.?.* = new_value; }, } } } fn getNextConstant(self: *Self) Value { const value = self.chunk.getConstant(self.ip + 1); self.ip += 2; return value; } fn pushReplace(self: *Self, value: Value) void { _ = self.pop(); _ = self.pop(); self.push(value); } fn push(self: *Self, value: Value) void { self.stack.append(value) catch unreachable; } fn pop(self: *Self) Value { var result = self.stack.popOrNull() orelse unreachable; return result; } fn peek(self: Self, distance: usize) Value { return self.stack.items[self.stack.items.len - 1 - distance]; } pub fn gatherRoots(self: *Self) []*const Value { self.root_list.clearRetainingCapacity(); // Chunk constants are roots for (self.chunk.constants.items) |*v| { self.root_list.append(v) catch unreachable; } // Stack data are roots for (self.stack.items) |*v| { self.root_list.append(v) catch unreachable; } return self.root_list.items; } fn binaryOp(self: *Self, op: BinaryFn) InterpreterError!void { self.pushReplace(try op(self.peek(1), self.peek(0))); } }; const BinaryFn = fn (lhs: Value, rhs: Value) InterpreterError!Value; fn opAdd(lhs: Value, rhs: Value) InterpreterError!Value { if (!Value.sharesType(lhs, rhs)) { return InterpreterError.CannotCompareValuesError; } switch (lhs) { .number => { const n1 = lhs.asNumber() catch unreachable; const n2 = rhs.asNumber() catch unreachable; return Value.fromNumber(n1 + n2); }, .string => { const s1 = lhs.asString() catch unreachable; const s2 = rhs.asString() catch unreachable; const str = vm().heap.makeString(); str.concat(.{ s1.str(), s2.str() }) catch return InterpreterError.RuntimeError; return Value.fromString(str); }, else => return InterpreterError.NonsensicalOperationError, } } fn opSub(lhs: Value, rhs: Value) InterpreterError!Value { if (!Value.sharesType(lhs, rhs)) { return InterpreterError.CannotCompareValuesError; } switch (lhs) { .number => { const n1 = lhs.asNumber() catch unreachable; const n2 = rhs.asNumber() catch unreachable; return Value.fromNumber(n1 - n2); }, else => return InterpreterError.NonsensicalOperationError, } } fn opMul(lhs: Value, rhs: Value) InterpreterError!Value { if (lhs.isString() and rhs.isNumber()) { const s = lhs.asString() catch unreachable; const n = @floatToInt(usize, rhs.asNumber() catch unreachable); const str = vm().heap.makeString(); str.concatNTimes(s.str(), n) catch return InterpreterError.RuntimeError; return Value.fromString(str); } else { if (!Value.sharesType(lhs, rhs)) { return InterpreterError.CannotCompareValuesError; } switch (lhs) { .number => { const n1 = lhs.asNumber() catch unreachable; const n2 = rhs.asNumber() catch unreachable; return Value.fromNumber(n1 * n2); }, else => return InterpreterError.NonsensicalOperationError, } } } fn opDiv(lhs: Value, rhs: Value) InterpreterError!Value { if (!Value.sharesType(lhs, rhs)) { return InterpreterError.CannotCompareValuesError; } switch (lhs) { .number => { const n1 = lhs.asNumber() catch unreachable; const n2 = rhs.asNumber() catch unreachable; return Value.fromNumber(n1 / n2); }, else => return InterpreterError.NonsensicalOperationError, } } fn opAnd(lhs: Value, rhs: Value) InterpreterError!Value { var lhs_bool = try lhs.asBoolean(); var rhs_bool = try rhs.asBoolean(); return Value.fromBoolean(lhs_bool and rhs_bool); } fn opOr(lhs: Value, rhs: Value) InterpreterError!Value { var lhs_bool = try lhs.asBoolean(); var rhs_bool = try rhs.asBoolean(); return Value.fromBoolean(lhs_bool or rhs_bool); } fn opXor(lhs: Value, rhs: Value) InterpreterError!Value { var lhs_bool = try lhs.asBoolean(); var rhs_bool = try rhs.asBoolean(); return Value.fromBoolean((lhs_bool and !rhs_bool) or (rhs_bool and !lhs_bool)); } fn opEq(lhs: Value, rhs: Value) InterpreterError!Value { return Value.fromBoolean(try Value.equals(lhs, rhs)); } fn opNeq(lhs: Value, rhs: Value) InterpreterError!Value { return Value.fromBoolean(!try Value.equals(lhs, rhs)); } fn opGt(lhs: Value, rhs: Value) InterpreterError!Value { return Value.fromBoolean(try Value.greaterThan(lhs, rhs)); } fn opGEq(lhs: Value, rhs: Value) InterpreterError!Value { return Value.fromBoolean(try lhs.greaterThanOrEqual(rhs)); } fn opLt(lhs: Value, rhs: Value) InterpreterError!Value { return Value.fromBoolean(try lhs.lessThan(rhs)); } fn opLEq(lhs: Value, rhs: Value) InterpreterError!Value { return Value.fromBoolean(try lhs.lessThanOrEqual(rhs)); }
src/vm.zig
const std = @import("std"); const input = @import("input.zig"); pub fn run(stdout: anytype) anyerror!void { { var input_ = try input.readFile("inputs/day10"); defer input_.deinit(); const result = try part1(&input_); try stdout.print("10a: {}\n", .{ result }); std.debug.assert(result == 294195); } { var input_ = try input.readFile("inputs/day10"); defer input_.deinit(); const result = try part2(&input_); try stdout.print("10b: {}\n", .{ result }); std.debug.assert(result == 3490802734); } } const Answer = u64; fn part1(input_: anytype) !Answer { var result: Answer = 0; while (try input_.next()) |line| { const line_validation_result = try validateLine(line); switch (line_validation_result) { .invalid_char => |invalid_char| result += @as(Answer, switch (invalid_char) { .@")" => 3, .@"]" => 57, .@"}" => 1197, .@">" => 25137, else => unreachable, }), else => {}, } } return result; } fn part2(input_: anytype) !Answer { var all_scores = std.BoundedArray(Answer, max_line_len).init(0) catch unreachable; while (try input_.next()) |line| { var line_validation_result = try validateLine(line); switch (line_validation_result) { .remaining_closing_chars => |*remaining_closing_chars| { var score: Answer = 0; while (remaining_closing_chars.popOrNull()) |c| { score = score * 5 + @as(Answer, switch (c) { .@")" => 1, .@"]" => 2, .@"}" => 3, .@">" => 4, else => unreachable, }); } try all_scores.append(score); }, else => {}, } } std.sort.sort(Answer, all_scores.slice(), {}, comptime std.sort.asc(Answer)); return all_scores.constSlice()[all_scores.len / 2]; } const max_line_len = 100; const Char = enum { @"(", @"[", @"{", @"<", @")", @"]", @"}", @">", }; const LineValidationResult = union (enum) { ok, invalid_char: Char, remaining_closing_chars: std.BoundedArray(Char, max_line_len), }; fn validateLine(line: []const u8) !LineValidationResult { var remaining_closing_chars = std.BoundedArray(Char, max_line_len).init(0) catch unreachable; for (line) |c| { const char = std.meta.stringToEnum(Char, &[_]u8 { c }) orelse return error.InvalidInput; switch (char) { .@"(" => { try remaining_closing_chars.append(.@")"); }, .@"[" => { try remaining_closing_chars.append(.@"]"); }, .@"{" => { try remaining_closing_chars.append(.@"}"); }, .@"<" => { try remaining_closing_chars.append(.@">"); }, else => { if (remaining_closing_chars.popOrNull()) |remaining_closing_chars_closing_char| { if (remaining_closing_chars_closing_char == char) { continue; } try remaining_closing_chars.append(remaining_closing_chars_closing_char); } return LineValidationResult { .invalid_char = char, }; }, } } return if (remaining_closing_chars.len > 0) LineValidationResult { .remaining_closing_chars = remaining_closing_chars } else LineValidationResult { .ok = {} }; } test "day 10 example 1" { const input_ = \\[({(<(())[]>[[{[]{<()<>> \\[(()[<>])]({[<{<<[]>>( \\{([(<{}[<>[]}>{[]{[(<()> \\(((({<>}<{<{<>}{[]{[]{} \\[[<[([]))<([[{}[[()]]] \\[{[{({}]{}}([{[{{{}}([] \\{<[[]]>}<{[{[{[]{()[[[] \\[<(<(<(<{}))><([]([]() \\<{([([[(<>()){}]>(<<{{ \\<{([{{}}[<[[[<>{}]]]>[]] ; try std.testing.expectEqual(@as(Answer, 2 * 3 + 1 * 57 + 1 * 1197 + 1 * 25137), try part1(&input.readString(input_))); try std.testing.expectEqual(@as(Answer, 288957), try part2(&input.readString(input_))); }
src/day10.zig
const std = @import("std"); const ArrayList = std.ArrayList; const print = std.debug.print; const panic = std.debug.panic; const TailQueue = std.TailQueue; const graph = @import("graph.zig"); const Allocator = std.mem.Allocator; const AutoHashMap = std.AutoHashMap; const LinearFifo = std.fifo.LinearFifo; pub fn bfs( allocator: Allocator, initial: anytype, // a node pointer type context: anytype, // anytype goalTest: fn (context: @TypeOf(context), node: @TypeOf(initial)) bool, ) ?@TypeOf(initial) { const Node = @TypeOf(initial); const frontier = LinearFifo(u8, .Dynamic).init(allocator); defer frontier.deinit(); var explored = AutoHashMap(*Node, void).init(allocator); defer explored.deinit(); var node = initial; while (!goalTest(context, frontier.read())) { //for try frontier.write(node.edges.keys()); } return node; } // Uses a `TailQueue` as a FIFO data structure. // pub fn dfs( // allocator: Allocator, // initial: anytype, // a node pointer type // context: anytype, // anytype // goalTest: fn (context: @TypeOf(context), node: @TypeOf(initial)) bool, // ) ?@TypeOf(initial) { // const Node = @TypeOf(initial); // // Initially, the frontier consists of just the start node. // const frontier = TailQueue(Node).init(allocator); // defer frontier.deinit(); // _ = goalTest; // var node = initial; // while (!goalTest(context, node)) { // frontier.popFirst(); // // for // try fifo.write("HELLO"); // } // return node; // } test "bfs depth 0" { const NodeType = graph.Node([]const u8, u32); const allocator = std.testing.allocator; const node1 = try NodeType.init(allocator, "n1"); defer node1.deinit(allocator); if (bfs(allocator, node1, node1, struct { pub fn pred(initial: *NodeType, node: *NodeType) bool { return node == initial; } }.pred)) |goal| { if (goal != node1) // Shouldn't be possible panic("Incorrect goal found", .{}); } else { panic("Node not found", .{}); } } test "dfs depth 1" { const allocator = std.testing.allocator; var node1 = try graph.Node([]const u8, u32).init(allocator, "n1"); defer node1.destroy(); var node2 = try graph.Node([]const u8, u32).initWithEdges(allocator, "n2", &.{}); defer node2.destroy(); var node3 = try graph.Node([]const u8, u32).initWithEdges(allocator, "n3", &.{}); defer node3.destroy(); const node4 = try graph.Node([]const u8, u32).initWithEdges( allocator, "n4", // Segfaults if an anon struct is used instead &[_]graph.Node([]const u8, u32).Edge{ .{ .that = node1, .weight = 41, }, }, ); defer node4.destroy(); }
src/uninformed.zig
const std = @import("std"); const zfetch = @import("zfetch"); const tar = @import("tar"); const uri = @import("uri"); const Options = @import("main.zig").Options; const Hasher = std.crypto.hash.blake2.Blake2b128; pub fn gz( allocator: *std.mem.Allocator, cache_root: []const u8, url: []const u8, opts: Options, ) ![]const u8 { try zfetch.init(); defer zfetch.deinit(); var digest: [Hasher.digest_length]u8 = undefined; var subpath: [2 * Hasher.digest_length]u8 = undefined; Hasher.hash(url, &digest, .{}); var fixed_buffer = std.io.fixedBufferStream(&subpath); for (digest) |i| try std.fmt.format(fixed_buffer.writer(), "{x:0>2}", .{i}); const base = try std.fs.path.join(allocator, &[_][]const u8{ cache_root, "downloads", if (opts.name) |n| n else &subpath, }); defer allocator.free(base); var ret = try std.fs.path.join(allocator, &[_][]const u8{ base, "content", }); errdefer allocator.free(ret); var base_dir = try std.fs.cwd().makeOpenPath(base, .{}); defer base_dir.close(); var found = true; base_dir.access("ok", .{ .read = true }) catch |err| { if (err == error.FileNotFound) found = false else return err; }; if (found) return ret; var dir = try std.fs.cwd().makeOpenPath(ret, .{}); defer dir.close(); try getTarGz(allocator, url, dir, opts.sha256); (try base_dir.createFile("ok", .{ .read = true })).close(); return ret; } fn getTarGz( allocator: *std.mem.Allocator, url: []const u8, dir: std.fs.Dir, sha256: ?[]const u8, ) !void { var headers = zfetch.Headers.init(allocator); defer headers.deinit(); std.log.info("fetching tarball: {s}", .{url}); try headers.set("Accept", "*/*"); try headers.set("User-Agent", "zig"); var real_url = try allocator.dupe(u8, url); defer allocator.free(real_url); var redirects: usize = 0; var req = while (redirects < 128) { var ret = try zfetch.Request.init(allocator, real_url, null); const link = try uri.parse(real_url); try headers.set("Host", link.host orelse return error.NoHost); try ret.commit(.GET, headers, null); try ret.fulfill(); switch (ret.status.code) { 200 => break ret, 302 => { // tmp needed for memory safety const tmp = real_url; const location = ret.headers.get("location") orelse return error.NoLocation; real_url = try allocator.dupe(u8, location); allocator.free(tmp); ret.deinit(); }, else => { return error.FailedRequest; }, } } else return error.TooManyRedirects; defer req.deinit(); var checker = try integrityChecker(sha256, req.reader()); var gzip = try std.compress.gzip.gzipStream(allocator, checker.reader()); defer gzip.deinit(); try tar.instantiate(allocator, dir, gzip.reader(), 1); if (!try checker.valid()) return error.InvalidHash; } fn integrityChecker(sha256: ?[]const u8, reader: anytype) !IntegrityChecker(@TypeOf(reader)) { return IntegrityChecker(@TypeOf(reader)).init(sha256, reader); } fn IntegrityChecker(comptime ReaderType: type) type { return struct { internal: ReaderType, hasher: std.crypto.hash.sha2.Sha256, expected: ?[]const u8, const Self = @This(); pub const Reader = std.io.Reader(*Self, ReaderType.Error, read); pub fn init(sha256: ?[]const u8, internal: ReaderType) !Self { if (sha256) |hash| if (hash.len != 64) return error.BadHashLen; return Self{ .internal = internal, .hasher = std.crypto.hash.sha2.Sha256.init(.{}), .expected = sha256, }; } fn read(self: *Self, buffer: []u8) ReaderType.Error!usize { const n = try self.internal.read(buffer); if (self.expected != null) self.hasher.update(buffer[0..n]); return n; } pub fn valid(self: *Self) !bool { return if (self.expected) |expected| blk: { const digest_len = std.crypto.hash.sha2.Sha256.digest_length; var out: [digest_len]u8 = undefined; self.hasher.final(&out); var fmted: [2 * digest_len]u8 = undefined; var fixed_buffer = std.io.fixedBufferStream(&fmted); for (out) |i| try std.fmt.format(fixed_buffer.writer(), "{x:0>2}", .{i}); break :blk std.mem.eql(u8, expected, &fmted); } else true; } pub fn reader(self: *Self) Reader { return .{ .context = self }; } }; }
src/tar.zig
const std = @import("std"); /// Modulated lapped transform window function pub fn window(comptime T: type, index: T, len: T) T { return @sin((std.math.pi / len) * (index + 0.5)); } // TODO: Naive; factor, vectorize /// Modified discrete cosine transform /// Returns useful data from 0 <= index < data.len/2 pub fn mdct(comptime T: type, data: []const T, index: usize) T { const len_cast = std.math.lossyCast(T, data.len); var n: usize = 0; var sum: T = 0; while (n < data.len) : (n += 1) { const n_cast = std.math.lossyCast(T, n); sum += window(T, n_cast, len_cast) * data[n] * @cos(((2.0 * std.math.pi) / len_cast) * (n_cast + 0.5 + len_cast / 4.0) * (std.math.lossyCast(T, index) + 0.5)); } return sum; } // TODO: Naive; factor, vectorize /// Inverse modified discrete cosine transform /// Returns useful data from 0 <= index < 2*data.len pub fn imdct(comptime T: type, data: []const T, index: usize) T { const index_cast = std.math.lossyCast(T, index); const len_cast = std.math.lossyCast(T, data.len); var k: usize = 0; var sum: T = 0; while (k < data.len) : (k += 1) { const k_cast = std.math.lossyCast(T, k); sum += data[k] * @cos((std.math.pi / len_cast) * (index_cast + 0.5 + len_cast / 2.0) * (k_cast + 0.5)); } return window(T, index_cast, 2 * len_cast) * (2.0 / len_cast) * sum; } /// Works for both mdct and its inverse pub fn calcBlockMdctOutputSize(block_size: usize, len: usize) usize { return len - block_size / 2; } pub fn naiveBlockMdct(comptime T: type, comptime block_size: usize, data: []const T, out: []T) void { std.debug.assert(data.len % block_size == 0); std.debug.assert(out.len == calcBlockMdctOutputSize(block_size, data.len)); var block: usize = 0; while (block < out.len / 2) : (block += 1) { var outdex: usize = 0; while (outdex < block_size / 2) : (outdex += 1) { out[block * (block_size / 2) + outdex] = mdct(T, data[block * block_size / 2 ..][0..block_size], outdex); } } } pub fn naiveBlockImdct(comptime T: type, comptime block_size: usize, data: []const T, out: []T) void { std.debug.assert(data.len % (block_size / 2) == 0); std.debug.assert(out.len == calcBlockMdctOutputSize(block_size, data.len)); var i: usize = 0; var block: usize = 0; while (block <= out.len / (block_size / 2) - (block_size / 2)) : (block += 1) { var s: usize = 0; while (s < block_size / 2) : (s += 1) { out[i] = imdct(f32, data[(block_size / 2) * block .. (block_size / 2) * (block + 1)], block_size / 2 + s) + imdct(f32, data[(block_size / 2) * (block + 1) .. (block_size / 2) * (block + 2)], s); i += 1; } } }
src/mdct.zig
usingnamespace @import("c.zig"); const Texture = @import("texture.zig").Texture; /// Options for the display such as width, height and title pub const Options = struct { /// Sets the initial window width width: c_int, /// Sets the initial window height height: c_int, /// Sets the title of the window title: [*c]const u8, }; /// our window var window: *GLFWwindow = undefined; /// the texture to render each frame var texture: Texture = undefined; /// Creates a new window, can fail initialization /// Currently uses opengl version 3.3 for most compatibility pub fn init(options: Options, comptime callback: anytype) !void { if (glfwInit() == 0) { return error.FailedToInitialize; } errdefer glfwTerminate(); // using opengl 3.3 we support pretty much anything glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); window = glfwCreateWindow(options.width, options.height, options.title, null, null) orelse return error.WindowCreationFailed; glfwMakeContextCurrent(window); errdefer glfwDestroyWindow(window); _ = glfwSetKeyCallback(window, callback); texture = try Texture.init(); glClearColor(0.2, 0.3, 0.3, 1); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } /// Keeps the window open until Shutdown is called pub fn run() void { while (glfwWindowShouldClose(window) == GL_FALSE) { var w: c_int = 0; var h: c_int = 0; glfwGetFramebufferSize(window, &w, &h); glViewport(0, 0, w, h); glClear(GL_COLOR_BUFFER_BIT); texture.draw(); glfwSwapBuffers(window); glfwPollEvents(); } } /// Updates the texture using the given frames /// Make sure init() is called before using update pub fn update(frame: []u1) void { texture.update(frame); } /// Destroys Opengl buffers and the window pub fn deinit() void { texture.deinit(); glfwDestroyWindow(window); } /// Shuts down the GLFW window pub fn shutdown() void { glfwSetWindowShouldClose(window, GL_TRUE); }
src/window.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const int = i64; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day25.txt"); const Rec = struct { val: int, }; pub fn main() !void { var width: usize = 0; var height: usize = 0; // Load the map with a border of 9 values var grid = blk: { var height_map = List(u8).init(gpa); errdefer height_map.deinit(); var lines = tokenize(u8, data, "\r\n"); while (lines.next()) |line| { if (line.len == 0) { continue; } if (width == 0) { width = line.len; try height_map.appendNTimes('-', width + 2); } else { assert(width == line.len); } try height_map.append('-'); for (line) |c| { try height_map.append(c); } height += 1; try height_map.append('-'); } try height_map.appendNTimes('-', width + 2); break :blk height_map.toOwnedSlice(); }; defer gpa.free(grid); const pitch = width + 2; const start = pitch + 1; var next_grid = try gpa.dupe(u8, grid); defer gpa.free(next_grid); var is_moving = true; var part1: usize = 0; while (is_moving) { is_moving = false; { var i: usize = 0; while (i < height) : (i += 1) { @memset(next_grid.ptr + start + i*pitch, '.', width); } } part1 += 1; for (grid) |c, i| { if (c == '>') { if (grid[i+1] == '.') { next_grid[i+1] = '>'; is_moving = true; } else if (grid[i+1] == '-' and grid[i+1-width] == '.') { next_grid[i+1-width] = '>'; is_moving = true; } else { next_grid[i] = '>'; } } if (c == 'v') { next_grid[i] = 'v'; } } { const tmp = next_grid; next_grid = grid; grid = tmp; var i: usize = 0; while (i < height) : (i += 1) { @memset(next_grid.ptr + start + i*pitch, '.', width); } } for (grid) |c, i| { if (c == '>') { next_grid[i] = '>'; } if (c == 'v') { if (grid[i+pitch] == '.') { next_grid[i+pitch] = 'v'; is_moving = true; } else if (grid[i+pitch] == '-' and grid[i+pitch-(pitch*height)] == '.') { next_grid[i+pitch-(pitch*height)] = 'v'; is_moving = true; } else { next_grid[i] = 'v'; } } } { const tmp = next_grid; next_grid = grid; grid = tmp; } } print("part1={}\n", .{part1}); } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const eql = std.mem.eql; const parseEnum = std.meta.stringToEnum; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc;
src/day25.zig
const std = @import("std"); const zt = @import("zt"); const main = @import("../main.zig"); const ig = @import("imgui"); const zg = zt.custom_components; const Hash = zt.game.SpatialHash.Generate(usize, .{ .bucketSize = 80 }); var rng: std.rand.Random = undefined; const blip = struct { aabb: zt.math.Rect = .{}, color: zt.math.Vec4 = .{}, pub fn generate(within: zt.math.Rect) blip { // This is slow, but I'm lazy and this is just a demo, soooooo... var self: blip = .{}; self.aabb.size.x = std.math.clamp(rng.float(f32) * 100.0, 5.0, within.size.x); self.aabb.size.y = std.math.clamp(rng.float(f32) * 100.0, 5.0, within.size.y); self.aabb.position.x = std.math.clamp(rng.float(f32) * within.size.x, 0, within.size.x - self.aabb.size.x) + within.position.x; self.aabb.position.y = std.math.clamp(rng.float(f32) * within.size.y, 0, within.size.y - self.aabb.size.y) + within.position.y; // Little bit of transparency! Incase they overlap. self.color = zt.math.vec4(rng.float(f32), rng.float(f32), rng.float(f32), 0.33); return self; } }; var rotation: f32 = 0.0; var scale: f32 = 1.0; var pos: zt.math.Vec2 = .{}; // I'm avoiding allocations here, in your application you probably want an `std.ArrayList(blip)` var array: std.ArrayList(blip) = undefined; var hash: Hash = undefined; var bounds: zt.math.Rect = zt.math.rect(-400, -400, 800, 800); var inited = false; var spawned: i32 = 0; // This is the storage for when the user is querying with a rectangle. var rect_Q: zt.math.Rect = .{}; // This is the storage for when the user is querying with a line. var line_Q: zt.math.Vec2 = .{}; const queryStyle = enum { point, line, rect }; var currentStyle: queryStyle = .point; pub fn update(ctx: *main.SampleApplication.Context) void { // Basic scene initialization: var io = ig.igGetIO(); sceneSetup(ctx); var render = ctx.data.render; render.updateRenderSize(io.*.DisplaySize); render.updateCamera(pos, scale, rotation); for (array.items) |*b| { render.sprite(ctx.data.sheet, b.aabb.position, 0.0, b.aabb.size, b.color, null, zt.math.rect(131, 84, 2, 2)); } // Generate the query based on the user input! switch (currentStyle) { // For a point, we just use the mouse position. .point => { var mouse = render.screenToWorld(io.*.MousePos); render.sprite(ctx.data.sheet, mouse.sub(zt.math.vec2(-1, 1)), 0.0, zt.math.vec2(2, 2), zt.math.Vec4.white, null, zt.math.rect(131, 84, 2, 2)); var query = hash.queryPoint(mouse); for (query) |i| { var b: blip = array.items[i]; if (zt.game.Physics.isPointInRect(mouse, b.aabb)) { render.sprite(ctx.data.sheet, b.aabb.position, 0.0, b.aabb.size, zt.math.vec4(0.0, 1.0, 0.0, 0.5), null, zt.math.rect(131, 84, 2, 2)); } else { render.sprite(ctx.data.sheet, b.aabb.position, 0.0, b.aabb.size, zt.math.vec4(1.0, 1.0, 0.0, 0.5), null, zt.math.rect(131, 84, 2, 2)); } } }, // We simulate a line drawing by not dragging the start node when holding lmb, and querying the 2. .line => { const lineCol = zt.math.vec4(0.0, 0.0, 0.0, 1.0); var mouse = render.screenToWorld(io.*.MousePos); if (!io.*.MouseDown[ig.ImGuiMouseButton_Left]) { line_Q = mouse; } else {} var query = hash.queryLine(line_Q, mouse); for (query) |i| { var b: blip = array.items[i]; if (zt.game.Physics.isLineInRect(line_Q, mouse, b.aabb.position, b.aabb.size)) { render.sprite(ctx.data.sheet, b.aabb.position, 0.0, b.aabb.size, zt.math.vec4(0.0, 1.0, 0.0, 0.5), null, zt.math.rect(131, 84, 2, 2)); } else { render.sprite(ctx.data.sheet, b.aabb.position, 0.0, b.aabb.size, zt.math.vec4(1.0, 1.0, 0.0, 0.5), null, zt.math.rect(131, 84, 2, 2)); } } render.line(ctx.data.sheet, zt.math.rect(131, 84, 2, 2), line_Q, mouse, 0, 5.0, lineCol, lineCol); }, .rect => { const lineCol = zt.math.vec4(0.0, 0.0, 0.0, 1.0); var mouse = render.screenToWorld(io.*.MousePos); if (!io.*.MouseDown[ig.ImGuiMouseButton_Left]) { rect_Q.position = mouse; } else { rect_Q.size = mouse.sub(rect_Q.position); } var query = hash.queryAABB(rect_Q.position, rect_Q.size); for (query) |i| { var b: blip = array.items[i]; if (zt.game.Physics.isRectInRect(rect_Q.position, rect_Q.size, b.aabb.position, b.aabb.size)) { render.sprite(ctx.data.sheet, b.aabb.position, 0.0, b.aabb.size, zt.math.vec4(0.0, 1.0, 0.0, 0.5), null, zt.math.rect(131, 84, 2, 2)); } else { render.sprite(ctx.data.sheet, b.aabb.position, 0.0, b.aabb.size, zt.math.vec4(1.0, 1.0, 0.0, 0.5), null, zt.math.rect(131, 84, 2, 2)); } } render.rectangleHollow(ctx.data.sheet, zt.math.rect(131, 84, 2, 2), rect_Q, 0, 2.0, lineCol); }, } render.rectangleHollow(ctx.data.sheet, zt.math.rect(131, 84, 2, 2), bounds, 0, 2.0, zt.math.vec4(0.2, 1.0, 0.2, 0.8)); render.flush(); } fn control() void { var io = ig.igGetIO(); ig.igSetNextWindowPos(io.*.DisplaySize, ig.ImGuiCond_Appearing, .{ .x = 1, .y = 1 }); if (ig.igBegin("Spatial Hash Demo", null, ig.ImGuiWindowFlags_None)) { ig.igPushItemWidth(ig.igGetWindowWidth() * 0.5); _ = ig.igDragFloat("Camera Rotation", &rotation, 0.02, zt.math.toRadians(-360.0), zt.math.toRadians(360.0), "%.3f", ig.ImGuiSliderFlags_None); _ = ig.igDragFloat("Camera Zoom", &scale, 0.02, 0.1, 16, "%.3f", ig.ImGuiSliderFlags_None); ig.igSeparator(); _ = zg.editDrag("Within Bounds", 2, &bounds); var generation: ?usize = null; if (ig.igButton("Spawn 10 items", .{})) { generation = 10; } if (ig.igButton("Spawn 100 items", .{})) { generation = 100; } if (ig.igButton("Spawn 1000 items", .{})) { generation = 1000; } if (generation) |len| { var i: usize = 0; while (i < len) : (i += 1) { var new = blip.generate(bounds); var index = array.items.len; array.append(new) catch unreachable; hash.addAABB(index, array.items[index].aabb.position, array.items[index].aabb.size); } spawned += @intCast(i32, len); } if (ig.igBeginListBox("## INPUT STYLE", .{})) { if (ig.igSelectable_Bool("Point", currentStyle == .point, ig.ImGuiSelectableFlags_SpanAvailWidth, .{})) { currentStyle = .point; } if (ig.igSelectable_Bool("Line", currentStyle == .line, ig.ImGuiSelectableFlags_SpanAvailWidth, .{})) { currentStyle = .line; } if (ig.igSelectable_Bool("Rect", currentStyle == .rect, ig.ImGuiSelectableFlags_SpanAvailWidth, .{})) { currentStyle = .rect; } ig.igEndListBox(); } zg.textWrap("You've spawned {any} squares.", .{spawned}); ig.igTextWrapped("Use middle mouse to scroll, and mousewheel to zoom"); ig.igPopItemWidth(); } ig.igEnd(); } fn sceneSetup(ctx: *main.SampleApplication.Context) void { var io = ig.igGetIO(); if (!inited) { var prng = std.rand.DefaultPrng.init(blk: { var seed: u64 = undefined; std.os.getrandom(std.mem.asBytes(&seed)) catch { std.debug.print("OS getRandom failed.", .{}); std.process.exit(1); }; break :blk seed; }); rng = prng.random(); array = std.ArrayList(blip).init(ctx.allocator); hash = Hash.init(ctx.allocator); inited = true; } // Mouse Controls for this scene, pretty convenient considering the aabb size. if (io.*.MouseDown[ig.ImGuiMouseButton_Middle]) { pos = pos.add(io.*.MouseDelta.scaleDiv(scale)); } if (io.*.MouseWheel != 0) { scale = std.math.clamp(scale + (io.*.MouseWheel * 0.5), 0.5, 16); } control(); }
example/src/scenes/spatialhash_squares.zig
const std = @import("std"); const builtin = @import("builtin"); const assert = std.debug.assert; const ast = std.zig.ast; const Token = std.zig.Token; usingnamespace @import("clang.zig"); pub const Mode = enum { import, translate, }; // TODO merge with Type.Fn.CallingConvention const CallingConvention = builtin.TypeInfo.CallingConvention; pub const ClangErrMsg = Stage2ErrorMsg; pub const Error = error{OutOfMemory}; const TypeError = Error || error{UnsupportedType}; const TransError = TypeError || error{UnsupportedTranslation}; const DeclTable = std.HashMap(usize, void, addrHash, addrEql); fn addrHash(x: usize) u32 { switch (@typeInfo(usize).Int.bits) { 32 => return x, // pointers are usually aligned so we ignore the bits that are probably all 0 anyway // usually the larger bits of addr space are unused so we just chop em off 64 => return @truncate(u32, x >> 4), else => @compileError("unreachable"), } } fn addrEql(a: usize, b: usize) bool { return a == b; } const Scope = struct { id: Id, parent: ?*Scope, const Id = enum { Switch, Var, Block, Root, While, }; const Switch = struct { base: Scope, }; const Var = struct { base: Scope, c_name: []const u8, zig_name: []const u8, }; const Block = struct { base: Scope, block_node: *ast.Node.Block, /// Don't forget to set rbrace token later fn create(c: *Context, parent: *Scope, lbrace_tok: ast.TokenIndex) !*Block { const block = try c.a().create(Block); block.* = Block{ .base = Scope{ .id = Id.Block, .parent = parent, }, .block_node = try c.a().create(ast.Node.Block), }; block.block_node.* = ast.Node.Block{ .base = ast.Node{ .id = ast.Node.Id.Block }, .label = null, .lbrace = lbrace_tok, .statements = ast.Node.Block.StatementList.init(c.a()), .rbrace = undefined, }; return block; } }; const Root = struct { base: Scope, }; const While = struct { base: Scope, }; }; const TransResult = struct { node: *ast.Node, node_scope: *Scope, child_scope: *Scope, }; const Context = struct { tree: *ast.Tree, source_buffer: *std.Buffer, err: Error, source_manager: *ZigClangSourceManager, decl_table: DeclTable, global_scope: *Scope.Root, mode: Mode, ptr_params: std.BufSet, clang_context: *ZigClangASTContext, fn a(c: *Context) *std.mem.Allocator { return &c.tree.arena_allocator.allocator; } /// Convert a null-terminated C string to a slice allocated in the arena fn str(c: *Context, s: [*]const u8) ![]u8 { return std.mem.dupe(c.a(), u8, std.mem.toSliceConst(u8, s)); } /// Convert a clang source location to a file:line:column string fn locStr(c: *Context, loc: ZigClangSourceLocation) ![]u8 { const spelling_loc = ZigClangSourceManager_getSpellingLoc(c.source_manager, loc); const filename_c = ZigClangSourceManager_getFilename(c.source_manager, spelling_loc); const filename = if (filename_c) |s| try c.str(s) else ([]const u8)("(no file)"); const line = ZigClangSourceManager_getSpellingLineNumber(c.source_manager, spelling_loc); const column = ZigClangSourceManager_getSpellingColumnNumber(c.source_manager, spelling_loc); return std.fmt.allocPrint(c.a(), "{}:{}:{}", filename, line, column); } }; pub fn translate( backing_allocator: *std.mem.Allocator, args_begin: [*]?[*]const u8, args_end: [*]?[*]const u8, mode: Mode, errors: *[]ClangErrMsg, resources_path: [*]const u8, ) !*ast.Tree { const ast_unit = ZigClangLoadFromCommandLine( args_begin, args_end, &errors.ptr, &errors.len, resources_path, ) orelse { if (errors.len == 0) return error.OutOfMemory; return error.SemanticAnalyzeFail; }; defer ZigClangASTUnit_delete(ast_unit); const tree = blk: { var tree_arena = std.heap.ArenaAllocator.init(backing_allocator); errdefer tree_arena.deinit(); const tree = try tree_arena.allocator.create(ast.Tree); tree.* = ast.Tree{ .source = undefined, // need to use Buffer.toOwnedSlice later .root_node = undefined, .arena_allocator = tree_arena, .tokens = undefined, // can't reference the allocator yet .errors = undefined, // can't reference the allocator yet }; break :blk tree; }; const arena = &tree.arena_allocator.allocator; // now we can reference the allocator errdefer tree.arena_allocator.deinit(); tree.tokens = ast.Tree.TokenList.init(arena); tree.errors = ast.Tree.ErrorList.init(arena); tree.root_node = try arena.create(ast.Node.Root); tree.root_node.* = ast.Node.Root{ .base = ast.Node{ .id = ast.Node.Id.Root }, .decls = ast.Node.Root.DeclList.init(arena), .doc_comments = null, // initialized with the eof token at the end .eof_token = undefined, }; var source_buffer = try std.Buffer.initSize(arena, 0); var context = Context{ .tree = tree, .source_buffer = &source_buffer, .source_manager = ZigClangASTUnit_getSourceManager(ast_unit), .err = undefined, .decl_table = DeclTable.init(arena), .global_scope = try arena.create(Scope.Root), .mode = mode, .ptr_params = std.BufSet.init(arena), .clang_context = ZigClangASTUnit_getASTContext(ast_unit).?, }; context.global_scope.* = Scope.Root{ .base = Scope{ .id = Scope.Id.Root, .parent = null, }, }; if (!ZigClangASTUnit_visitLocalTopLevelDecls(ast_unit, &context, declVisitorC)) { return context.err; } tree.root_node.eof_token = try appendToken(&context, .Eof, ""); tree.source = source_buffer.toOwnedSlice(); if (false) { std.debug.warn("debug source:\n{}\n==EOF==\ntokens:\n", tree.source); var i: usize = 0; while (i < tree.tokens.len) : (i += 1) { const token = tree.tokens.at(i); std.debug.warn("{}\n", token); } } return tree; } extern fn declVisitorC(context: ?*c_void, decl: *const ZigClangDecl) bool { const c = @ptrCast(*Context, @alignCast(@alignOf(Context), context)); declVisitor(c, decl) catch |err| { c.err = err; return false; }; return true; } fn declVisitor(c: *Context, decl: *const ZigClangDecl) Error!void { switch (ZigClangDecl_getKind(decl)) { .Function => { return visitFnDecl(c, @ptrCast(*const ZigClangFunctionDecl, decl)); }, .Typedef => { try emitWarning(c, ZigClangDecl_getLocation(decl), "TODO implement translate-c for typedefs"); }, .Enum => { try emitWarning(c, ZigClangDecl_getLocation(decl), "TODO implement translate-c for enums"); }, .Record => { try emitWarning(c, ZigClangDecl_getLocation(decl), "TODO implement translate-c for structs"); }, .Var => { try emitWarning(c, ZigClangDecl_getLocation(decl), "TODO implement translate-c for variables"); }, else => { const decl_name = try c.str(ZigClangDecl_getDeclKindName(decl)); try emitWarning(c, ZigClangDecl_getLocation(decl), "ignoring {} declaration", decl_name); }, } } fn visitFnDecl(c: *Context, fn_decl: *const ZigClangFunctionDecl) Error!void { if (try c.decl_table.put(@ptrToInt(fn_decl), {})) |_| return; // Avoid processing this decl twice const rp = makeRestorePoint(c); const fn_name = try c.str(ZigClangDecl_getName_bytes_begin(@ptrCast(*const ZigClangDecl, fn_decl))); const fn_decl_loc = ZigClangFunctionDecl_getLocation(fn_decl); const fn_qt = ZigClangFunctionDecl_getType(fn_decl); const fn_type = ZigClangQualType_getTypePtr(fn_qt); var scope = &c.global_scope.base; const has_body = ZigClangFunctionDecl_hasBody(fn_decl); const storage_class = ZigClangFunctionDecl_getStorageClass(fn_decl); const decl_ctx = FnDeclContext{ .fn_name = fn_name, .has_body = has_body, .storage_class = storage_class, .scope = &scope, .is_export = switch (storage_class) { .None => has_body and c.mode != .import, .Extern, .Static => false, .PrivateExtern => return failDecl(c, fn_decl_loc, fn_name, "unsupported storage class: private extern"), .Auto => unreachable, // Not legal on functions .Register => unreachable, // Not legal on functions }, }; const proto_node = switch (ZigClangType_getTypeClass(fn_type)) { .FunctionProto => blk: { const fn_proto_type = @ptrCast(*const ZigClangFunctionProtoType, fn_type); break :blk transFnProto(rp, fn_proto_type, fn_decl_loc, decl_ctx, true) catch |err| switch (err) { error.UnsupportedType => { return failDecl(c, fn_decl_loc, fn_name, "unable to resolve prototype of function"); }, error.OutOfMemory => |e| return e, }; }, .FunctionNoProto => blk: { const fn_no_proto_type = @ptrCast(*const ZigClangFunctionType, fn_type); break :blk transFnNoProto(rp, fn_no_proto_type, fn_decl_loc, decl_ctx, true) catch |err| switch (err) { error.UnsupportedType => { return failDecl(c, fn_decl_loc, fn_name, "unable to resolve prototype of function"); }, error.OutOfMemory => |e| return e, }; }, else => unreachable, }; if (!decl_ctx.has_body) { const semi_tok = try appendToken(c, .Semicolon, ";"); return addTopLevelDecl(c, fn_name, &proto_node.base); } // actual function definition with body const body_stmt = ZigClangFunctionDecl_getBody(fn_decl); const result = transStmt(rp, scope, body_stmt, .unused, .r_value) catch |err| switch (err) { error.OutOfMemory => |e| return e, error.UnsupportedTranslation, error.UnsupportedType, => return failDecl(c, fn_decl_loc, fn_name, "unable to translate function"), }; assert(result.node.id == ast.Node.Id.Block); proto_node.body_node = result.node; return addTopLevelDecl(c, fn_name, &proto_node.base); } const ResultUsed = enum { used, unused, }; const LRValue = enum { l_value, r_value, }; fn transStmt( rp: RestorePoint, scope: *Scope, stmt: *const ZigClangStmt, result_used: ResultUsed, lrvalue: LRValue, ) !TransResult { const sc = ZigClangStmt_getStmtClass(stmt); switch (sc) { .BinaryOperatorClass => return transBinaryOperator(rp, scope, @ptrCast(*const ZigClangBinaryOperator, stmt), result_used), .CompoundStmtClass => return transCompoundStmt(rp, scope, @ptrCast(*const ZigClangCompoundStmt, stmt)), .CStyleCastExprClass => return transCStyleCastExprClass(rp, scope, @ptrCast(*const ZigClangCStyleCastExpr, stmt), result_used, lrvalue), .DeclStmtClass => return transDeclStmt(rp, scope, @ptrCast(*const ZigClangDeclStmt, stmt)), .DeclRefExprClass => return transDeclRefExpr(rp, scope, @ptrCast(*const ZigClangDeclRefExpr, stmt), lrvalue), .ImplicitCastExprClass => return transImplicitCastExpr(rp, scope, @ptrCast(*const ZigClangImplicitCastExpr, stmt), result_used), .IntegerLiteralClass => return transIntegerLiteral(rp, scope, @ptrCast(*const ZigClangIntegerLiteral, stmt), result_used), .ReturnStmtClass => return transReturnStmt(rp, scope, @ptrCast(*const ZigClangReturnStmt, stmt)), .StringLiteralClass => return transStringLiteral(rp, scope, @ptrCast(*const ZigClangStringLiteral, stmt), result_used), else => { return revertAndWarn( rp, error.UnsupportedTranslation, ZigClangStmt_getBeginLoc(stmt), "TODO implement translation of stmt class {}", @tagName(sc), ); }, } } fn transBinaryOperator( rp: RestorePoint, scope: *Scope, stmt: *const ZigClangBinaryOperator, result_used: ResultUsed, ) TransError!TransResult { const op = ZigClangBinaryOperator_getOpcode(stmt); const qt = ZigClangBinaryOperator_getType(stmt); switch (op) { .PtrMemD, .PtrMemI, .Cmp => return revertAndWarn( rp, error.UnsupportedTranslation, ZigClangBinaryOperator_getBeginLoc(stmt), "TODO: handle more C binary operators: {}", op, ), .Assign => return TransResult{ .node = &(try transCreateNodeAssign(rp, scope, result_used, ZigClangBinaryOperator_getLHS(stmt), ZigClangBinaryOperator_getRHS(stmt))).base, .child_scope = scope, .node_scope = scope, }, .Add => { const node = if (cIsUnsignedInteger(qt)) try transCreateNodeInfixOp(rp, scope, stmt, .AddWrap, .PlusPercent, "+%", true) else try transCreateNodeInfixOp(rp, scope, stmt, .Add, .Plus, "+", true); return maybeSuppressResult(rp, scope, result_used, TransResult{ .node = node, .child_scope = scope, .node_scope = scope, }); }, .Sub => { const node = if (cIsUnsignedInteger(qt)) try transCreateNodeInfixOp(rp, scope, stmt, .SubWrap, .MinusPercent, "-%", true) else try transCreateNodeInfixOp(rp, scope, stmt, .Sub, .Minus, "-", true); return maybeSuppressResult(rp, scope, result_used, TransResult{ .node = node, .child_scope = scope, .node_scope = scope, }); }, .Mul, .Div, .Rem, .Shl, .Shr, .LT, .GT, .LE, .GE, .EQ, .NE, .And, .Xor, .Or, .LAnd, .LOr, .Comma, => return revertAndWarn( rp, error.UnsupportedTranslation, ZigClangBinaryOperator_getBeginLoc(stmt), "TODO: handle more C binary operators: {}", op, ), .MulAssign, .DivAssign, .RemAssign, .AddAssign, .SubAssign, .ShlAssign, .ShrAssign, .AndAssign, .XorAssign, .OrAssign, => unreachable, } } fn transCompoundStmtInline( rp: RestorePoint, parent_scope: *Scope, stmt: *const ZigClangCompoundStmt, block_node: *ast.Node.Block, ) TransError!TransResult { var it = ZigClangCompoundStmt_body_begin(stmt); const end_it = ZigClangCompoundStmt_body_end(stmt); var scope = parent_scope; while (it != end_it) : (it += 1) { const result = try transStmt(rp, parent_scope, it.*, .unused, .r_value); scope = result.child_scope; if (result.node != &block_node.base) try block_node.statements.push(result.node); } return TransResult{ .node = &block_node.base, .child_scope = scope, .node_scope = scope, }; } fn transCompoundStmt(rp: RestorePoint, scope: *Scope, stmt: *const ZigClangCompoundStmt) !TransResult { const lbrace_tok = try appendToken(rp.c, .LBrace, "{"); const block_scope = try Scope.Block.create(rp.c, scope, lbrace_tok); const inline_result = try transCompoundStmtInline(rp, &block_scope.base, stmt, block_scope.block_node); block_scope.block_node.rbrace = try appendToken(rp.c, .RBrace, "}"); return TransResult{ .node = &block_scope.block_node.base, .node_scope = inline_result.node_scope, .child_scope = inline_result.child_scope, }; } fn transCStyleCastExprClass( rp: RestorePoint, scope: *Scope, stmt: *const ZigClangCStyleCastExpr, result_used: ResultUsed, lrvalue: LRValue, ) !TransResult { const sub_expr = ZigClangCStyleCastExpr_getSubExpr(stmt); const cast_node = (try transCCast( rp, scope, ZigClangCStyleCastExpr_getBeginLoc(stmt), ZigClangCStyleCastExpr_getType(stmt), ZigClangExpr_getType(sub_expr), (try transExpr(rp, scope, sub_expr, .used, lrvalue)).node, )); const cast_res = TransResult{ .node = cast_node, .child_scope = scope, .node_scope = scope, }; return maybeSuppressResult(rp, scope, result_used, cast_res); } fn transDeclStmt(rp: RestorePoint, parent_scope: *Scope, stmt: *const ZigClangDeclStmt) !TransResult { const c = rp.c; const block_scope = findBlockScope(parent_scope); var scope = parent_scope; var it = ZigClangDeclStmt_decl_begin(stmt); const end_it = ZigClangDeclStmt_decl_end(stmt); while (it != end_it) : (it += 1) { switch (ZigClangDecl_getKind(it.*)) { .Var => { const var_decl = @ptrCast(*const ZigClangVarDecl, it.*); const thread_local_token = if (ZigClangVarDecl_getTLSKind(var_decl) == .None) null else try appendToken(c, .Keyword_threadlocal, "threadlocal"); const qual_type = ZigClangVarDecl_getType(var_decl); const mut_token = if (ZigClangQualType_isConstQualified(qual_type)) try appendToken(c, .Keyword_const, "const") else try appendToken(c, .Keyword_var, "var"); const c_name = try c.str(ZigClangDecl_getName_bytes_begin( @ptrCast(*const ZigClangDecl, var_decl), )); const name_token = try appendToken(c, .Identifier, c_name); const var_scope = try c.a().create(Scope.Var); var_scope.* = Scope.Var{ .base = Scope{ .id = .Var, .parent = scope }, .c_name = c_name, .zig_name = c_name, // TODO: getWantedName }; scope = &var_scope.base; const colon_token = try appendToken(c, .Colon, ":"); const loc = ZigClangStmt_getBeginLoc(@ptrCast(*const ZigClangStmt, stmt)); const type_node = try transQualType(rp, qual_type, loc); const eq_token = try appendToken(c, .Equal, "="); const init_node = if (ZigClangVarDecl_getInit(var_decl)) |expr| (try transExpr(rp, scope, expr, .used, .r_value)).node else blk: { const undefined_token = try appendToken(c, .Keyword_undefined, "undefined"); const undefined_node = try rp.c.a().create(ast.Node.UndefinedLiteral); undefined_node.* = ast.Node.UndefinedLiteral{ .base = ast.Node{ .id = .UndefinedLiteral }, .token = undefined_token, }; break :blk &undefined_node.base; }; const semicolon_token = try appendToken(c, .Semicolon, ";"); const node = try c.a().create(ast.Node.VarDecl); node.* = ast.Node.VarDecl{ .base = ast.Node{ .id = .VarDecl }, .doc_comments = null, .visib_token = null, .thread_local_token = thread_local_token, .name_token = name_token, .eq_token = eq_token, .mut_token = mut_token, .comptime_token = null, .extern_export_token = null, .lib_name = null, .type_node = type_node, .align_node = null, // TODO ?*Node, .section_node = null, .init_node = init_node, .semicolon_token = semicolon_token, }; try block_scope.block_node.statements.push(&node.base); }, else => |kind| return revertAndWarn( rp, error.UnsupportedTranslation, ZigClangStmt_getBeginLoc(@ptrCast(*const ZigClangStmt, stmt)), "TODO implement translation of DeclStmt kind {}", @tagName(kind), ), } } return TransResult{ .node = &block_scope.block_node.base, .node_scope = scope, .child_scope = scope, }; } fn transDeclRefExpr( rp: RestorePoint, scope: *Scope, expr: *const ZigClangDeclRefExpr, lrvalue: LRValue, ) !TransResult { const value_decl = ZigClangDeclRefExpr_getDecl(expr); const c_name = try rp.c.str(ZigClangDecl_getName_bytes_begin(@ptrCast(*const ZigClangDecl, value_decl))); const zig_name = transLookupZigIdentifier(scope, c_name); if (lrvalue == .l_value) try rp.c.ptr_params.put(zig_name); const node = try appendIdentifier(rp.c, zig_name); return TransResult{ .node = node, .node_scope = scope, .child_scope = scope, }; } fn transImplicitCastExpr( rp: RestorePoint, scope: *Scope, expr: *const ZigClangImplicitCastExpr, result_used: ResultUsed, ) !TransResult { const c = rp.c; const sub_expr = ZigClangImplicitCastExpr_getSubExpr(expr); const sub_expr_node = try transExpr(rp, scope, @ptrCast(*const ZigClangExpr, sub_expr), .used, .r_value); switch (ZigClangImplicitCastExpr_getCastKind(expr)) { .BitCast => { const dest_type = getExprQualType(c, @ptrCast(*const ZigClangExpr, expr)); const src_type = getExprQualType(c, sub_expr); return TransResult{ .node = try transCCast(rp, scope, ZigClangImplicitCastExpr_getBeginLoc(expr), dest_type, src_type, sub_expr_node.node), .node_scope = scope, .child_scope = scope, }; }, .IntegralCast => { const dest_type = ZigClangExpr_getType(@ptrCast(*const ZigClangExpr, expr)); const src_type = ZigClangExpr_getType(sub_expr); return TransResult{ .node = try transCCast(rp, scope, ZigClangImplicitCastExpr_getBeginLoc(expr), dest_type, src_type, sub_expr_node.node), .node_scope = scope, .child_scope = scope, }; }, .FunctionToPointerDecay, .ArrayToPointerDecay => { return maybeSuppressResult(rp, scope, result_used, sub_expr_node); }, .LValueToRValue => { return transExpr(rp, scope, sub_expr, .used, .r_value); }, else => |kind| return revertAndWarn( rp, error.UnsupportedTranslation, ZigClangStmt_getBeginLoc(@ptrCast(*const ZigClangStmt, expr)), "TODO implement translation of CastKind {}", @tagName(kind), ), } } fn transIntegerLiteral( rp: RestorePoint, scope: *Scope, expr: *const ZigClangIntegerLiteral, result_used: ResultUsed, ) !TransResult { var eval_result: ZigClangExprEvalResult = undefined; if (!ZigClangIntegerLiteral_EvaluateAsInt(expr, &eval_result, rp.c.clang_context)) { const loc = ZigClangIntegerLiteral_getBeginLoc(expr); return revertAndWarn(rp, error.UnsupportedTranslation, loc, "invalid integer literal"); } const node = try transCreateNodeAPInt(rp.c, ZigClangAPValue_getInt(&eval_result.Val)); const res = TransResult{ .node = node, .child_scope = scope, .node_scope = scope, }; return maybeSuppressResult(rp, scope, result_used, res); } fn transReturnStmt( rp: RestorePoint, scope: *Scope, expr: *const ZigClangReturnStmt, ) !TransResult { const node = try transCreateNodeReturnExpr(rp.c); if (ZigClangReturnStmt_getRetValue(expr)) |val_expr| { const ret_node = node.cast(ast.Node.ControlFlowExpression).?; ret_node.rhs = (try transExpr(rp, scope, val_expr, .used, .r_value)).node; } _ = try appendToken(rp.c, .Semicolon, ";"); return TransResult{ .node = node, .child_scope = scope, .node_scope = scope, }; } fn transStringLiteral( rp: RestorePoint, scope: *Scope, stmt: *const ZigClangStringLiteral, result_used: ResultUsed, ) !TransResult { const kind = ZigClangStringLiteral_getKind(stmt); switch (kind) { .Ascii, .UTF8 => { var len: usize = undefined; const bytes_ptr = ZigClangStringLiteral_getString_bytes_begin_size(stmt, &len); const str = bytes_ptr[0..len]; var char_buf: [4]u8 = undefined; len = 0; for (str) |c| len += escapeChar(c, &char_buf).len; const buf = try rp.c.a().alloc(u8, len + "c\"\"".len); buf[0] = 'c'; buf[1] = '"'; writeEscapedString(buf[2..], str); buf[buf.len - 1] = '"'; const token = try appendToken(rp.c, .StringLiteral, buf); const node = try rp.c.a().create(ast.Node.StringLiteral); node.* = ast.Node.StringLiteral{ .base = ast.Node{ .id = .StringLiteral }, .token = token, }; const res = TransResult{ .node = &node.base, .child_scope = scope, .node_scope = scope, }; return maybeSuppressResult(rp, scope, result_used, res); }, .UTF16, .UTF32, .Wide => return revertAndWarn( rp, error.UnsupportedTranslation, ZigClangStmt_getBeginLoc(@ptrCast(*const ZigClangStmt, stmt)), "TODO: support string literal kind {}", kind, ), } } fn escapedStringLen(s: []const u8) usize { var len: usize = 0; var char_buf: [4]u8 = undefined; for (s) |c| len += escapeChar(c, &char_buf).len; return len; } fn writeEscapedString(buf: []u8, s: []const u8) void { var char_buf: [4]u8 = undefined; var i: usize = 0; for (s) |c| { const escaped = escapeChar(c, &char_buf); std.mem.copy(u8, buf[i..], escaped); i += escaped.len; } } // Returns either a string literal or a slice of `buf`. fn escapeChar(c: u8, char_buf: *[4]u8) []const u8 { // TODO: https://github.com/ziglang/zig/issues/2749 const escaped = switch (c) { // Printable ASCII except for ' " \ ' ', '!', '#'...'&', '('...'[', ']'...'~' => ([_]u8{c})[0..], '\'', '\"', '\\' => ([_]u8{ '\\', c })[0..], '\n' => return "\\n"[0..], '\r' => return "\\r"[0..], '\t' => return "\\t"[0..], else => return std.fmt.bufPrint(char_buf[0..], "\\x{x:2}", c) catch unreachable, }; std.mem.copy(u8, char_buf, escaped); return char_buf[0..escaped.len]; } fn transCCast( rp: RestorePoint, scope: *Scope, loc: ZigClangSourceLocation, dst_type: ZigClangQualType, src_type: ZigClangQualType, expr: *ast.Node, ) !*ast.Node { if (ZigClangType_isVoidType(qualTypeCanon(dst_type))) return expr; if (ZigClangQualType_eq(dst_type, src_type)) return expr; if (qualTypeIsPtr(dst_type) and qualTypeIsPtr(src_type)) return transCPtrCast(rp, loc, dst_type, src_type, expr); if (cIsUnsignedInteger(dst_type) and qualTypeIsPtr(src_type)) { const cast_node = try transCreateNodeFnCall(rp.c, try transQualType(rp, dst_type, loc)); const builtin_node = try transCreateNodeBuiltinFnCall(rp.c, "@ptrToInt"); try builtin_node.params.push(expr); builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); try cast_node.op.Call.params.push(&builtin_node.base); cast_node.rtoken = try appendToken(rp.c, .RParen, ")"); return &cast_node.base; } if (cIsUnsignedInteger(src_type) and qualTypeIsPtr(dst_type)) { const builtin_node = try transCreateNodeBuiltinFnCall(rp.c, "@intToPtr"); try builtin_node.params.push(try transQualType(rp, dst_type, loc)); _ = try appendToken(rp.c, .Comma, ","); try builtin_node.params.push(expr); builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return &builtin_node.base; } // TODO: maybe widen to increase size // TODO: maybe bitcast to change sign // TODO: maybe truncate to reduce size const cast_node = try transCreateNodeFnCall(rp.c, try transQualType(rp, dst_type, loc)); try cast_node.op.Call.params.push(expr); cast_node.rtoken = try appendToken(rp.c, .RParen, ")"); return &cast_node.base; } fn transExpr( rp: RestorePoint, scope: *Scope, expr: *const ZigClangExpr, used: ResultUsed, lrvalue: LRValue, ) TransError!TransResult { return transStmt(rp, scope, @ptrCast(*const ZigClangStmt, expr), used, lrvalue); } fn findBlockScope(inner: *Scope) *Scope.Block { var scope = inner; while (true) : (scope = scope.parent orelse unreachable) { if (scope.id == .Block) return @fieldParentPtr(Scope.Block, "base", scope); } } fn transLookupZigIdentifier(inner: *Scope, c_name: []const u8) []const u8 { var scope = inner; while (true) : (scope = scope.parent orelse return c_name) { if (scope.id == .Var) { const var_scope = @ptrCast(*const Scope.Var, scope); if (std.mem.eql(u8, var_scope.c_name, c_name)) return var_scope.zig_name; } } } fn transCPtrCast( rp: RestorePoint, loc: ZigClangSourceLocation, dst_type: ZigClangQualType, src_type: ZigClangQualType, expr: *ast.Node, ) !*ast.Node { const ty = ZigClangQualType_getTypePtr(dst_type); const child_type = ZigClangType_getPointeeType(ty); // Implicit downcasting from higher to lower alignment values is forbidden, // use @alignCast to side-step this problem const ptrcast_node = try transCreateNodeBuiltinFnCall(rp.c, "@ptrCast"); const dst_type_node = try transType(rp, ty, loc); try ptrcast_node.params.push(dst_type_node); _ = try appendToken(rp.c, .Comma, ","); if (ZigClangType_isVoidType(qualTypeCanon(child_type))) { // void has 1-byte alignment, so @alignCast is not needed try ptrcast_node.params.push(expr); } else { const aligncast_node = try transCreateNodeBuiltinFnCall(rp.c, "@alignCast"); const alignof_node = try transCreateNodeBuiltinFnCall(rp.c, "@alignOf"); const child_type_node = try transQualType(rp, child_type, loc); try alignof_node.params.push(child_type_node); alignof_node.rparen_token = try appendToken(rp.c, .RParen, ")"); try aligncast_node.params.push(&alignof_node.base); _ = try appendToken(rp.c, .Comma, ","); try aligncast_node.params.push(expr); aligncast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); try ptrcast_node.params.push(&aligncast_node.base); } ptrcast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return &ptrcast_node.base; } fn maybeSuppressResult( rp: RestorePoint, scope: *Scope, used: ResultUsed, result: TransResult, ) !TransResult { if (used == .used) return result; // NOTE: This is backwards, but the semicolon must immediately follow the node. _ = try appendToken(rp.c, .Semicolon, ";"); const lhs = try appendIdentifier(rp.c, "_"); const op_token = try appendToken(rp.c, .Equal, "="); const op_node = try rp.c.a().create(ast.Node.InfixOp); op_node.* = ast.Node.InfixOp{ .base = ast.Node{ .id = .InfixOp }, .op_token = op_token, .lhs = lhs, .op = .Assign, .rhs = result.node, }; return TransResult{ .node = &op_node.base, .child_scope = scope, .node_scope = scope, }; } fn addTopLevelDecl(c: *Context, name: []const u8, decl_node: *ast.Node) !void { try c.tree.root_node.decls.push(decl_node); } fn transQualType(rp: RestorePoint, qt: ZigClangQualType, source_loc: ZigClangSourceLocation) TypeError!*ast.Node { return transType(rp, ZigClangQualType_getTypePtr(qt), source_loc); } fn qualTypeIsPtr(qt: ZigClangQualType) bool { return ZigClangType_getTypeClass(qualTypeCanon(qt)) == .Pointer; } fn qualTypeChildIsFnProto(qt: ZigClangQualType) bool { const ty = ZigClangQualType_getTypePtr(qt); if (ZigClangType_getTypeClass(ty) == .Paren) { const paren_type = @ptrCast(*const ZigClangParenType, ty); const inner_type = ZigClangParenType_getInnerType(paren_type); return ZigClangQualType_getTypeClass(inner_type) == .FunctionProto; } if (ZigClangType_getTypeClass(ty) == .Attributed) { const attr_type = @ptrCast(*const ZigClangAttributedType, ty); return qualTypeChildIsFnProto(ZigClangAttributedType_getEquivalentType(attr_type)); } return false; } fn qualTypeCanon(qt: ZigClangQualType) *const ZigClangType { const canon = ZigClangQualType_getCanonicalType(qt); return ZigClangQualType_getTypePtr(canon); } fn getExprQualType(c: *Context, expr: *const ZigClangExpr) ZigClangQualType { blk: { // If this is a C `char *`, turn it into a `const char *` if (ZigClangExpr_getStmtClass(expr) != .ImplicitCastExprClass) break :blk; const cast_expr = @ptrCast(*const ZigClangImplicitCastExpr, expr); if (ZigClangImplicitCastExpr_getCastKind(cast_expr) != .ArrayToPointerDecay) break :blk; const sub_expr = ZigClangImplicitCastExpr_getSubExpr(cast_expr); if (ZigClangExpr_getStmtClass(sub_expr) != .StringLiteralClass) break :blk; const array_qt = ZigClangExpr_getType(sub_expr); const array_type = @ptrCast(*const ZigClangArrayType, ZigClangQualType_getTypePtr(array_qt)); var pointee_qt = ZigClangArrayType_getElementType(array_type); ZigClangQualType_addConst(&pointee_qt); return ZigClangASTContext_getPointerType(c.clang_context, pointee_qt); } return ZigClangExpr_getType(expr); } fn typeIsOpaque(c: *Context, ty: *const ZigClangType, loc: ZigClangSourceLocation) bool { switch (ZigClangType_getTypeClass(ty)) { .Builtin => { const builtin_ty = @ptrCast(*const ZigClangBuiltinType, ty); return ZigClangBuiltinType_getKind(builtin_ty) == .Void; }, .Record => { const record_ty = @ptrCast(*const ZigClangRecordType, ty); const record_decl = ZigClangRecordType_getDecl(record_ty); return (ZigClangRecordDecl_getDefinition(record_decl) == null); }, .Elaborated => { const elaborated_ty = @ptrCast(*const ZigClangElaboratedType, ty); const qt = ZigClangElaboratedType_getNamedType(elaborated_ty); return typeIsOpaque(c, ZigClangQualType_getTypePtr(qt), loc); }, .Typedef => { const typedef_ty = @ptrCast(*const ZigClangTypedefType, ty); const typedef_decl = ZigClangTypedefType_getDecl(typedef_ty); const underlying_type = ZigClangTypedefNameDecl_getUnderlyingType(typedef_decl); return typeIsOpaque(c, ZigClangQualType_getTypePtr(underlying_type), loc); }, else => return false, } } fn cIsUnsignedInteger(qt: ZigClangQualType) bool { const c_type = qualTypeCanon(qt); if (ZigClangType_getTypeClass(c_type) != .Builtin) return false; const builtin_ty = @ptrCast(*const ZigClangBuiltinType, c_type); return switch (ZigClangBuiltinType_getKind(builtin_ty)) { .Char_U, .UChar, .Char_S, .UShort, .UInt, .ULong, .ULongLong, .UInt128, .WChar_U, => true, else => false, }; } fn transCreateNodeAssign( rp: RestorePoint, scope: *Scope, result_used: ResultUsed, lhs: *const ZigClangExpr, rhs: *const ZigClangExpr, ) !*ast.Node.InfixOp { // common case // c: lhs = rhs // zig: lhs = rhs if (result_used == .unused) { const lhs_node = try transExpr(rp, scope, lhs, .used, .l_value); const eq_token = try appendToken(rp.c, .Equal, "="); const rhs_node = try transExpr(rp, scope, rhs, .used, .r_value); _ = try appendToken(rp.c, .Semicolon, ";"); const node = try rp.c.a().create(ast.Node.InfixOp); node.* = ast.Node.InfixOp{ .base = ast.Node{ .id = .InfixOp }, .op_token = eq_token, .lhs = lhs_node.node, .op = .Assign, .rhs = rhs_node.node, }; return node; } // worst case // c: lhs = rhs // zig: (x: { // zig: const _tmp = rhs; // zig: lhs = _tmp; // zig: break :x _tmp // zig: }) return revertAndWarn(rp, error.UnsupportedTranslation, ZigClangExpr_getBeginLoc(lhs), "TODO: worst case assign op expr"); } fn transCreateNodeBuiltinFnCall(c: *Context, name: []const u8) !*ast.Node.BuiltinCall { const builtin_token = try appendToken(c, .Builtin, name); _ = try appendToken(c, .LParen, "("); const node = try c.a().create(ast.Node.BuiltinCall); node.* = ast.Node.BuiltinCall{ .base = ast.Node{ .id = .BuiltinCall }, .builtin_token = builtin_token, .params = ast.Node.BuiltinCall.ParamList.init(c.a()), .rparen_token = undefined, // set after appending args }; return node; } fn transCreateNodeFnCall(c: *Context, fn_expr: *ast.Node) !*ast.Node.SuffixOp { _ = try appendToken(c, .LParen, "("); const node = try c.a().create(ast.Node.SuffixOp); node.* = ast.Node.SuffixOp{ .base = ast.Node{ .id = .SuffixOp }, .lhs = fn_expr, .op = ast.Node.SuffixOp.Op{ .Call = ast.Node.SuffixOp.Op.Call{ .params = ast.Node.SuffixOp.Op.Call.ParamList.init(c.a()), .async_token = null, }, }, .rtoken = undefined, // set after appending args }; return node; } fn transCreateNodePrefixOp( c: *Context, op: ast.Node.PrefixOp.Op, op_tok_id: std.zig.Token.Id, bytes: []const u8, ) !*ast.Node.PrefixOp { const node = try c.a().create(ast.Node.PrefixOp); node.* = ast.Node.PrefixOp{ .base = ast.Node{ .id = .PrefixOp }, .op_token = try appendToken(c, op_tok_id, bytes), .op = op, .rhs = undefined, // translate and set afterward }; return node; } fn transCreateNodeInfixOp( rp: RestorePoint, scope: *Scope, stmt: *const ZigClangBinaryOperator, op: ast.Node.InfixOp.Op, op_tok_id: std.zig.Token.Id, bytes: []const u8, grouped: bool, ) !*ast.Node { const lparen = if (grouped) try appendToken(rp.c, .LParen, "(") else undefined; const lhs = try transExpr(rp, scope, ZigClangBinaryOperator_getLHS(stmt), .used, .l_value); const op_token = try appendToken(rp.c, op_tok_id, bytes); const rhs = try transExpr(rp, scope, ZigClangBinaryOperator_getRHS(stmt), .used, .r_value); const node = try rp.c.a().create(ast.Node.InfixOp); node.* = ast.Node.InfixOp{ .base = ast.Node{ .id = .InfixOp }, .op_token = op_token, .lhs = lhs.node, .op = op, .rhs = rhs.node, }; if (!grouped) return &node.base; const rparen = try appendToken(rp.c, .RParen, ")"); const grouped_expr = try rp.c.a().create(ast.Node.GroupedExpression); grouped_expr.* = ast.Node.GroupedExpression{ .base = ast.Node{ .id = .GroupedExpression }, .lparen = lparen, .expr = &node.base, .rparen = rparen, }; return &grouped_expr.base; } fn transCreateNodePtrType( c: *Context, is_const: bool, is_volatile: bool, op_tok_id: std.zig.Token.Id, bytes: []const u8, ) !*ast.Node.PrefixOp { const node = try c.a().create(ast.Node.PrefixOp); node.* = ast.Node.PrefixOp{ .base = ast.Node{ .id = .PrefixOp }, .op_token = try appendToken(c, op_tok_id, bytes), .op = ast.Node.PrefixOp.Op{ .PtrType = ast.Node.PrefixOp.PtrInfo{ .allowzero_token = null, .align_info = null, .const_token = if (is_const) try appendToken(c, .Keyword_const, "const") else null, .volatile_token = if (is_volatile) try appendToken(c, .Keyword_volatile, "volatile") else null, }, }, .rhs = undefined, // translate and set afterward }; return node; } fn transCreateNodeAPInt(c: *Context, int: ?*const ZigClangAPSInt) !*ast.Node { const num_limbs = ZigClangAPSInt_getNumWords(int.?); var big = try std.math.big.Int.initCapacity(c.a(), num_limbs); defer big.deinit(); const data = ZigClangAPSInt_getRawData(int.?); var i: @typeOf(num_limbs) = 0; while (i < num_limbs) : (i += 1) big.limbs[i] = data[i]; const str = big.toString(c.a(), 10) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => unreachable, }; const token = try appendToken(c, .IntegerLiteral, str); const node = try c.a().create(ast.Node.IntegerLiteral); node.* = ast.Node.IntegerLiteral{ .base = ast.Node{ .id = .IntegerLiteral }, .token = token, }; return &node.base; } fn transCreateNodeReturnExpr(c: *Context) !*ast.Node { const ltoken = try appendToken(c, .Keyword_return, "return"); const node = try c.a().create(ast.Node.ControlFlowExpression); node.* = ast.Node.ControlFlowExpression{ .base = ast.Node{ .id = .ControlFlowExpression }, .ltoken = ltoken, .kind = .Return, .rhs = null, }; return &node.base; } const RestorePoint = struct { c: *Context, token_index: ast.TokenIndex, src_buf_index: usize, fn activate(self: RestorePoint) void { self.c.tree.tokens.shrink(self.token_index); self.c.source_buffer.shrink(self.src_buf_index); } }; fn makeRestorePoint(c: *Context) RestorePoint { return RestorePoint{ .c = c, .token_index = c.tree.tokens.len, .src_buf_index = c.source_buffer.len(), }; } fn transType(rp: RestorePoint, ty: *const ZigClangType, source_loc: ZigClangSourceLocation) TypeError!*ast.Node { switch (ZigClangType_getTypeClass(ty)) { .Builtin => { const builtin_ty = @ptrCast(*const ZigClangBuiltinType, ty); switch (ZigClangBuiltinType_getKind(builtin_ty)) { .Void => return appendIdentifier(rp.c, "c_void"), .Bool => return appendIdentifier(rp.c, "bool"), .Char_U, .UChar, .Char_S, .Char8 => return appendIdentifier(rp.c, "u8"), .SChar => return appendIdentifier(rp.c, "i8"), .UShort => return appendIdentifier(rp.c, "c_ushort"), .UInt => return appendIdentifier(rp.c, "c_uint"), .ULong => return appendIdentifier(rp.c, "c_ulong"), .ULongLong => return appendIdentifier(rp.c, "c_ulonglong"), .Short => return appendIdentifier(rp.c, "c_short"), .Int => return appendIdentifier(rp.c, "c_int"), .Long => return appendIdentifier(rp.c, "c_long"), .LongLong => return appendIdentifier(rp.c, "c_longlong"), .UInt128 => return appendIdentifier(rp.c, "u128"), .Int128 => return appendIdentifier(rp.c, "i128"), .Float => return appendIdentifier(rp.c, "f32"), .Double => return appendIdentifier(rp.c, "f64"), .Float128 => return appendIdentifier(rp.c, "f128"), .Float16 => return appendIdentifier(rp.c, "f16"), .LongDouble => return appendIdentifier(rp.c, "c_longdouble"), else => return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported builtin type"), } }, .FunctionProto => { const fn_proto_ty = @ptrCast(*const ZigClangFunctionProtoType, ty); const fn_proto = try transFnProto(rp, fn_proto_ty, source_loc, null, false); return &fn_proto.base; }, .Paren => { const paren_ty = @ptrCast(*const ZigClangParenType, ty); return transQualType(rp, ZigClangParenType_getInnerType(paren_ty), source_loc); }, .Pointer => { const child_qt = ZigClangType_getPointeeType(ty); if (qualTypeChildIsFnProto(child_qt)) { const optional_node = try transCreateNodePrefixOp(rp.c, .OptionalType, .QuestionMark, "?"); optional_node.rhs = try transQualType(rp, child_qt, source_loc); return &optional_node.base; } if (typeIsOpaque(rp.c, ZigClangQualType_getTypePtr(child_qt), source_loc)) { const optional_node = try transCreateNodePrefixOp(rp.c, .OptionalType, .QuestionMark, "?"); const pointer_node = try transCreateNodePtrType( rp.c, ZigClangQualType_isConstQualified(child_qt), ZigClangQualType_isVolatileQualified(child_qt), .Asterisk, "*", ); optional_node.rhs = &pointer_node.base; pointer_node.rhs = try transQualType(rp, child_qt, source_loc); return &optional_node.base; } const pointer_node = try transCreateNodePtrType( rp.c, ZigClangQualType_isConstQualified(child_qt), ZigClangQualType_isVolatileQualified(child_qt), .BracketStarCBracket, "[*c]", ); pointer_node.rhs = try transQualType(rp, child_qt, source_loc); return &pointer_node.base; }, else => { const type_name = rp.c.str(ZigClangType_getTypeClassName(ty)); return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported type: '{}'", type_name); }, } } const FnDeclContext = struct { fn_name: []const u8, has_body: bool, storage_class: ZigClangStorageClass, scope: **Scope, is_export: bool, }; fn transCC( rp: RestorePoint, fn_ty: *const ZigClangFunctionType, source_loc: ZigClangSourceLocation, ) !CallingConvention { const clang_cc = ZigClangFunctionType_getCallConv(fn_ty); switch (clang_cc) { .C => return CallingConvention.C, .X86StdCall => return CallingConvention.Stdcall, else => return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported calling convention: {}", @tagName(clang_cc)), } } fn transFnProto( rp: RestorePoint, fn_proto_ty: *const ZigClangFunctionProtoType, source_loc: ZigClangSourceLocation, fn_decl_context: ?FnDeclContext, is_pub: bool, ) !*ast.Node.FnProto { const fn_ty = @ptrCast(*const ZigClangFunctionType, fn_proto_ty); const cc = try transCC(rp, fn_ty, source_loc); const is_var_args = ZigClangFunctionProtoType_isVariadic(fn_proto_ty); const param_count: usize = ZigClangFunctionProtoType_getNumParams(fn_proto_ty); var i: usize = 0; while (i < param_count) : (i += 1) { return revertAndWarn(rp, error.UnsupportedType, source_loc, "TODO: implement parameters for FunctionProto in transType"); } return finishTransFnProto(rp, fn_ty, source_loc, fn_decl_context, is_var_args, cc, is_pub); } fn transFnNoProto( rp: RestorePoint, fn_ty: *const ZigClangFunctionType, source_loc: ZigClangSourceLocation, fn_decl_context: ?FnDeclContext, is_pub: bool, ) !*ast.Node.FnProto { const cc = try transCC(rp, fn_ty, source_loc); const is_var_args = if (fn_decl_context) |ctx| !ctx.is_export else true; return finishTransFnProto(rp, fn_ty, source_loc, fn_decl_context, is_var_args, cc, is_pub); } fn finishTransFnProto( rp: RestorePoint, fn_ty: *const ZigClangFunctionType, source_loc: ZigClangSourceLocation, fn_decl_context: ?FnDeclContext, is_var_args: bool, cc: CallingConvention, is_pub: bool, ) !*ast.Node.FnProto { const is_export = if (fn_decl_context) |ctx| ctx.is_export else false; const is_extern = if (fn_decl_context) |ctx| !ctx.has_body else true; // TODO check for always_inline attribute // TODO check for align attribute // pub extern fn name(...) T const pub_tok = if (is_pub) try appendToken(rp.c, .Keyword_pub, "pub") else null; const cc_tok = if (cc == .Stdcall) try appendToken(rp.c, .Keyword_stdcallcc, "stdcallcc") else null; const extern_export_inline_tok = if (is_export) try appendToken(rp.c, .Keyword_export, "export") else if (cc == .C and is_extern) try appendToken(rp.c, .Keyword_extern, "extern") else null; const fn_tok = try appendToken(rp.c, .Keyword_fn, "fn"); const name_tok = if (fn_decl_context) |ctx| try appendToken(rp.c, .Identifier, ctx.fn_name) else null; const lparen_tok = try appendToken(rp.c, .LParen, "("); const var_args_tok = if (is_var_args) try appendToken(rp.c, .Ellipsis3, "...") else null; const rparen_tok = try appendToken(rp.c, .RParen, ")"); const return_type_node = blk: { if (ZigClangFunctionType_getNoReturnAttr(fn_ty)) { break :blk try appendIdentifier(rp.c, "noreturn"); } else { const return_qt = ZigClangFunctionType_getReturnType(fn_ty); if (ZigClangType_isVoidType(qualTypeCanon(return_qt))) { break :blk try appendIdentifier(rp.c, "void"); } else { break :blk transQualType(rp, return_qt, source_loc) catch |err| switch (err) { error.UnsupportedType => { try emitWarning(rp.c, source_loc, "unsupported function proto return type"); return err; }, error.OutOfMemory => |e| return e, }; } } }; const fn_proto = try rp.c.a().create(ast.Node.FnProto); fn_proto.* = ast.Node.FnProto{ .base = ast.Node{ .id = ast.Node.Id.FnProto }, .doc_comments = null, .visib_token = pub_tok, .fn_token = fn_tok, .name_token = name_tok, .params = ast.Node.FnProto.ParamList.init(rp.c.a()), .return_type = ast.Node.FnProto.ReturnType{ .Explicit = return_type_node }, .var_args_token = null, // TODO this field is broken in the AST data model .extern_export_inline_token = extern_export_inline_tok, .cc_token = cc_tok, .body_node = null, .lib_name = null, .align_expr = null, .section_expr = null, }; if (is_var_args) { const var_arg_node = try rp.c.a().create(ast.Node.ParamDecl); var_arg_node.* = ast.Node.ParamDecl{ .base = ast.Node{ .id = ast.Node.Id.ParamDecl }, .doc_comments = null, .comptime_token = null, .noalias_token = null, .name_token = null, .type_node = undefined, .var_args_token = var_args_tok, }; try fn_proto.params.push(&var_arg_node.base); } return fn_proto; } fn revertAndWarn( rp: RestorePoint, err: var, source_loc: ZigClangSourceLocation, comptime format: []const u8, args: ..., ) (@typeOf(err) || error{OutOfMemory}) { rp.activate(); try emitWarning(rp.c, source_loc, format, args); return err; } fn emitWarning(c: *Context, loc: ZigClangSourceLocation, comptime format: []const u8, args: ...) !void { _ = try appendTokenFmt(c, .LineComment, "// {}: warning: " ++ format, c.locStr(loc), args); } fn failDecl(c: *Context, loc: ZigClangSourceLocation, name: []const u8, comptime format: []const u8, args: ...) !void { // const name = @compileError(msg); const const_tok = try appendToken(c, .Keyword_const, "const"); const name_tok = try appendToken(c, .Identifier, name); const eq_tok = try appendToken(c, .Equal, "="); const builtin_tok = try appendToken(c, .Builtin, "@compileError"); const lparen_tok = try appendToken(c, .LParen, "("); const msg_tok = try appendTokenFmt(c, .StringLiteral, "\"" ++ format ++ "\"", args); const rparen_tok = try appendToken(c, .RParen, ")"); const semi_tok = try appendToken(c, .Semicolon, ";"); const msg_node = try c.a().create(ast.Node.StringLiteral); msg_node.* = ast.Node.StringLiteral{ .base = ast.Node{ .id = ast.Node.Id.StringLiteral }, .token = msg_tok, }; const call_node = try c.a().create(ast.Node.BuiltinCall); call_node.* = ast.Node.BuiltinCall{ .base = ast.Node{ .id = ast.Node.Id.BuiltinCall }, .builtin_token = builtin_tok, .params = ast.Node.BuiltinCall.ParamList.init(c.a()), .rparen_token = rparen_tok, }; try call_node.params.push(&msg_node.base); const var_decl_node = try c.a().create(ast.Node.VarDecl); var_decl_node.* = ast.Node.VarDecl{ .base = ast.Node{ .id = ast.Node.Id.VarDecl }, .doc_comments = null, .visib_token = null, .thread_local_token = null, .name_token = name_tok, .eq_token = eq_tok, .mut_token = const_tok, .comptime_token = null, .extern_export_token = null, .lib_name = null, .type_node = null, .align_node = null, .section_node = null, .init_node = &call_node.base, .semicolon_token = semi_tok, }; try c.tree.root_node.decls.push(&var_decl_node.base); } fn appendToken(c: *Context, token_id: Token.Id, bytes: []const u8) !ast.TokenIndex { return appendTokenFmt(c, token_id, "{}", bytes); } fn appendTokenFmt(c: *Context, token_id: Token.Id, comptime format: []const u8, args: ...) !ast.TokenIndex { const S = struct { fn callback(context: *Context, bytes: []const u8) error{OutOfMemory}!void { return context.source_buffer.append(bytes); } }; const start_index = c.source_buffer.len(); errdefer c.source_buffer.shrink(start_index); try std.fmt.format(c, error{OutOfMemory}, S.callback, format, args); const end_index = c.source_buffer.len(); const token_index = c.tree.tokens.len; const new_token = try c.tree.tokens.addOne(); errdefer c.tree.tokens.shrink(token_index); new_token.* = Token{ .id = token_id, .start = start_index, .end = end_index, }; try c.source_buffer.appendByte(' '); return token_index; } fn appendIdentifier(c: *Context, name: []const u8) !*ast.Node { const token_index = try appendToken(c, .Identifier, name); const identifier = try c.a().create(ast.Node.Identifier); identifier.* = ast.Node.Identifier{ .base = ast.Node{ .id = ast.Node.Id.Identifier }, .token = token_index, }; return &identifier.base; } pub fn freeErrors(errors: []ClangErrMsg) void { ZigClangErrorMsg_delete(errors.ptr, errors.len); }
src-self-hosted/translate_c.zig
const std = @import("std"); const print = std.debug.print; usingnamespace @import("common.zig"); usingnamespace @import("value.zig"); usingnamespace @import("chunk.zig"); usingnamespace @import("scanner.zig"); usingnamespace @import("compiler.zig"); usingnamespace @import("vm.zig"); const Precedence = enum { PREC_NONE, // PREC_ASSIGNMENT, // = PREC_OR, // or PREC_AND, // and PREC_EQUALITY, // == != PREC_COMPARISON, // < > <= >= PREC_TERM, // + - PREC_FACTOR, // * / PREC_UNARY, // ! - PREC_CALL, // . () PREC_PRIMARY }; const ParseFn = fn (self: *Parser, canAssign: bool) anyerror!void; const ParseRule = struct { prefix: ?ParseFn, infix: ?ParseFn, precedence: Precedence, const rules = [_]ParseRule{ .{ .prefix = Parser.grouping, .infix = null, .precedence = .PREC_NONE }, //TOKEN_LEFT_PAREN .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_RIGHT_PAREN .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_LEFT_BRACE .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_RIGHT_BRACE .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_COMMA .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_DOT .{ .prefix = Parser.unary, .infix = Parser.binary, .precedence = .PREC_TERM }, //TOKEN_MINUS .{ .prefix = null, .infix = Parser.binary, .precedence = .PREC_TERM }, //TOKEN_PLUS .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_SEMICOLON .{ .prefix = null, .infix = Parser.binary, .precedence = .PREC_FACTOR }, //TOKEN_SLASH .{ .prefix = null, .infix = Parser.binary, .precedence = .PREC_FACTOR }, //TOKEN_STAR .{ .prefix = Parser.unary, .infix = null, .precedence = .PREC_NONE }, //TOKEN_BANG .{ .prefix = null, .infix = Parser.binary, .precedence = .PREC_EQUALITY }, //TOKEN_BANG_EQUAL .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_EQUAL .{ .prefix = null, .infix = Parser.binary, .precedence = .PREC_EQUALITY }, //TOKEN_EQUAL_EQUAL .{ .prefix = null, .infix = Parser.binary, .precedence = .PREC_COMPARISON }, //TOKEN_GREATER .{ .prefix = null, .infix = Parser.binary, .precedence = .PREC_COMPARISON }, //TOKEN_GREATER_EQUAL .{ .prefix = null, .infix = Parser.binary, .precedence = .PREC_COMPARISON }, //TOKEN_LESS .{ .prefix = null, .infix = Parser.binary, .precedence = .PREC_COMPARISON }, //TOKEN_LESS_EQUAL .{ .prefix = Parser.variable, .infix = null, .precedence = .PREC_NONE }, //TOKEN_IDENTIFIER .{ .prefix = Parser.string, .infix = null, .precedence = .PREC_NONE }, //TOKEN_STRING .{ .prefix = Parser.number, .infix = null, .precedence = .PREC_NONE }, //TOKEN_NUMBER .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_AND .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_CLASS .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_ELSE .{ .prefix = Parser.literal, .infix = null, .precedence = .PREC_NONE }, //TOKEN_FALSE .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_FOR .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_FUN .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_IF .{ .prefix = Parser.literal, .infix = null, .precedence = .PREC_NONE }, //TOKEN_NIL .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_OR .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_PRINT .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_RETURN .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_SUPER .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_THIS .{ .prefix = Parser.literal, .infix = null, .precedence = .PREC_NONE }, // TOKEN_TRUE .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_VAR .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_WHILE .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_ERROR .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, //TOKEN_EOF }; pub fn getRule(idx: TokenType) ParseRule { return rules[@enumToInt(idx)]; } }; pub const Parser = struct { compiler: *Compiler, scanner: *Scanner, current: Token, previous: Token, hadError: bool, panicMode: bool, vm: *VM, pub fn init(compiler: *Compiler, scanner: *Scanner) Parser { return Parser{ .compiler = compiler, .scanner = scanner, .current = undefined, .previous = undefined, .hadError = false, .panicMode = false, .vm = compiler.vm, }; } pub fn expression(self: *Parser) !void { try self.parsePrecedence(.PREC_ASSIGNMENT); } pub fn declaration(self: *Parser) anyerror!void { if (self.match(.TOKEN_VAR)) { try self.varDeclaration(); } else { try self.statement(); } if (self.panicMode) self.synchronize(); } fn statement(self: *Parser) anyerror!void { if (self.match(.TOKEN_PRINT)) { try self.printStatement(); } else if (self.match(.TOKEN_IF)) { try self.ifStatement(); } else if (self.match(.TOKEN_LEFT_BRACE)) { self.beginScope(); try self.block(); try self.endScope(); } else { try self.expressionStatement(); } } fn ifStatement(self: *Parser) !void { self.consume(.TOKEN_LEFT_PAREN, "Expect '(' after 'if'."); try self.expression(); self.consume(.TOKEN_RIGHT_PAREN, "Expect ')' after condition."); const thenJump = try self.emitJump(.OP_JUMP_IF_FALSE); try self.statement(); self.patchJump(thenJump); } fn beginScope(self: *Parser) void { self.compiler.scopeDepth += 1; } fn block(self: *Parser) !void { while (!self.check(.TOKEN_RIGHT_BRACE) and !self.check(.TOKEN_EOF)) { try self.declaration(); } self.consume(.TOKEN_RIGHT_BRACE, "Expect '}' after block."); } fn endScope(self: *Parser) !void { self.compiler.scopeDepth -= 1; for (self.compiler.locals.items) |local| { if (local.depth > self.compiler.scopeDepth) { try self.emitCode(.OP_POP); _ = self.compiler.locals.pop(); } } } fn expressionStatement(self: *Parser) !void { try self.expression(); self.consume(.TOKEN_SEMICOLON, "Expect ';' after expression."); try self.emitCode(.OP_POP); } fn varDeclaration(self: *Parser) !void { const global = try self.parseVariable("Except variable name"); if (self.match(.TOKEN_EQUAL)) { try self.expression(); } else { try self.emitCode(.OP_NIL); } self.consume(.TOKEN_SEMICOLON, "Expect ';' after var declaration."); try self.defineVariable(global); } fn printStatement(self: *Parser) !void { try self.expression(); self.consume(.TOKEN_SEMICOLON, "Exepect ';' after value."); try self.emitCode(.OP_PRINT); } // 变量的使用,全局变量从vm中获取,本地变量编译时设置 fn namedVariable(self: *Parser, name: Token, canAssign: bool) !void { var getOp: u8 = undefined; var setOp: u8 = undefined; var arg = self.resolveLocal(self.compiler, &name); if (arg != -1) { getOp = @enumToInt(OpCode.OP_GET_LOCAL); setOp = @enumToInt(OpCode.OP_SET_LOCAL); } else { arg = try self.identifierConstant(name); getOp = @enumToInt(OpCode.OP_GET_GLOBAL); setOp = @enumToInt(OpCode.OP_SET_GLOBAL); } if (canAssign and self.match(.TOKEN_EQUAL)) { try self.expression(); try self.emitBytes(setOp, @intCast(u8, arg)); } else { try self.emitBytes(getOp, @intCast(u8, arg)); } } fn resolveLocal(self: *Parser, compiler: *Compiler, name: *const Token) i32 { if (compiler.locals.items.len > 0) { var i: i32 = @intCast(i32, compiler.locals.items.len - 1); while (i >= 0) : (i -= 1) { const local = &self.compiler.locals.items[@intCast(usize, i)]; if (identifiersEqual(name, &local.name)) { if (local.depth == -1) { self.error0("Can't read local variable in its own initializer."); } return i; } } } return -1; } fn parseVariable(self: *Parser, errorMessage: []const u8) !u8 { self.consume(.TOKEN_IDENTIFIER, errorMessage); try self.declareVariable(); // 处理本地变量, 保存到当前编译器locals数组中 if (self.compiler.scopeDepth > 0) return 0; // 处理全局变量, 保存到vm的globals中 return try self.identifierConstant(self.previous); } fn declareVariable(self: *Parser) !void { if (self.compiler.scopeDepth == 0) return; const name = &self.previous; if (self.compiler.locals.items.len > 0) { var i: i32 = @intCast(i32, self.compiler.locals.items.len - 1); while (i >= 0) : (i -= 1) { const local = &self.compiler.locals.items[@intCast(usize, i)]; if (local.depth != -1 and local.depth < self.compiler.scopeDepth) break; if (identifiersEqual(name, &local.name)) { self.error0("Already variable with this name in this scope."); } } } try self.compiler.addLocal(name.*); } fn identifiersEqual(a: *const Token, b: *Token) bool { return std.mem.eql(u8, a.literal, b.literal); } fn identifierConstant(self: *Parser, name: Token) !u8 { return try self.makeConstant(OBJ_STRING_VAL(try self.vm.heap.copyString(name.literal))); } fn defineVariable(self: *Parser, global: u8) !void { if (self.compiler.scopeDepth > 0) { self.markInitialized(); return; } try self.emitBytes(@enumToInt(OpCode.OP_DEFINE_GLOBAL), global); } fn markInitialized(self: *Parser) void { self.compiler.locals.items[self.compiler.locals.items.len - 1].depth = self.compiler.scopeDepth; } pub fn match(self: *Parser, tokenType: TokenType) bool { if (!self.check(tokenType)) return false; self.advance(); return true; } fn check(self: *Parser, tokenType: TokenType) bool { return self.current.tokenType == tokenType; } pub fn advance(self: *Parser) void { self.previous = self.current; while (true) { self.current = self.scanner.scanToken(); if (self.current.tokenType != .TOKEN_ERROR) break; self.errorAtCurrent(self.current.literal); } } pub fn consume(self: *Parser, tokenType: TokenType, message: []const u8) void { if (self.current.tokenType == tokenType) { _ = self.advance(); return; } self.errorAtCurrent(message); } fn variable(self: *Parser, canAssign: bool) !void { try self.namedVariable(self.previous, canAssign); } fn literal(self: *Parser, canAssign: bool) !void { switch (self.previous.tokenType) { .TOKEN_FALSE => try self.emitCode(.OP_FALSE), .TOKEN_NIL => try self.emitCode(.OP_NIL), .TOKEN_TRUE => try self.emitCode(.OP_TRUE), else => unreachable, } } fn number(self: *Parser, canAssign: bool) !void { const value = try std.fmt.parseFloat(f64, self.previous.literal); try self.emitConstant(NUMBER_VAL(value)); } fn string(self: *Parser, canAssign: bool) !void { try self.emitConstant(OBJ_VAL(@ptrCast(*Obj, try self.vm.heap.copyString(self.previous.literal[1 .. self.previous.literal.len - 1])))); } fn grouping(self: *Parser, canAssign: bool) !void { try self.expression(); self.consume(.TOKEN_RIGHT_PAREN, "Expect ')' after expression."); } fn binary(self: *Parser, canAssign: bool) !void { // Remember the operator. const operatorType = self.previous.tokenType; // Compile the right operand. const rule = ParseRule.getRule(operatorType); try self.parsePrecedence(@intToEnum(Precedence, (@enumToInt(rule.precedence) + 1))); // Emit the operator instruction. switch (operatorType) { .TOKEN_PLUS => try self.emitCode(.OP_ADD), .TOKEN_MINUS => try self.emitCode(.OP_SUBTRACT), .TOKEN_STAR => try self.emitCode(.OP_MULTIPLY), .TOKEN_SLASH => try self.emitCode(.OP_DIVIDE), .TOKEN_BANG_EQUAL => try self.emitBytes(@enumToInt(OpCode.OP_EQUAL), @enumToInt(OpCode.OP_NOT)), .TOKEN_EQUAL_EQUAL => try self.emitCode(.OP_EQUAL), .TOKEN_GREATER => try self.emitCode(.OP_GREATER), .TOKEN_GREATER_EQUAL => try self.emitBytes(@enumToInt(OpCode.OP_LESS), @enumToInt(OpCode.OP_NOT)), .TOKEN_LESS => try self.emitCode(.OP_LESS), .TOKEN_LESS_EQUAL => try self.emitBytes(@enumToInt(OpCode.OP_GREATER), @enumToInt(OpCode.OP_NOT)), else => unreachable, } } fn unary(self: *Parser, canAssign: bool) !void { const operatorType = self.previous.tokenType; // Compile the operand. try self.parsePrecedence(.PREC_UNARY); // Emit the operator instruction. switch (operatorType) { .TOKEN_MINUS => try self.emitCode(.OP_NEGATE), .TOKEN_BANG => try self.emitCode(.OP_NOT), else => unreachable, } } pub fn endParse(self: *Parser) !void { try self.emitReturn(); if (DEBUG_PRINT_CODE) { if (!self.hadError) { _ = self.currentChunk().disassemble("code"); } } } fn parsePrecedence(self: *Parser, precedence: Precedence) !void { self.advance(); const prefixRule = ParseRule.getRule(self.previous.tokenType).prefix; if (prefixRule) |prefixRuleFn| { const canAssign = @enumToInt(precedence) <= @enumToInt(Precedence.PREC_ASSIGNMENT); try prefixRuleFn(self, canAssign); while (@enumToInt(precedence) <= @enumToInt(ParseRule.getRule(self.current.tokenType).precedence)) { self.advance(); const infixRule = ParseRule.getRule(self.previous.tokenType).infix.?; try infixRule(self, canAssign); } if (canAssign and self.match(.TOKEN_EQUAL)) { self.error0("Invaild assignment target."); } } else { self.error0("Expect expression."); return; } } fn emitReturn(self: *Parser) !void { try self.emitCode(.OP_RETURN); } fn emitByte(self: *Parser, byte: u8) !void { try self.currentChunk().writeByte(byte, self.previous.line); } fn emitBytes(self: *Parser, byte1: u8, byte2: u8) !void { try self.emitByte(byte1); try self.emitByte(byte2); } fn emitJump(self: *Parser, code: OpCode) !usize { try self.emitCode(code); try self.emitByte(0xff); try self.emitByte(0xff); return self.currentChunk().code.items.len - 2; } fn patchJump(self: *Parser, offset: usize) void { // -2 to adjust for the bytecode for the jump offset iteself. const jump = self.currentChunk().code.items.len - offset - 2; self.currentChunk().code.items[offset] = @intCast(u8, (jump >> 8) & 0xff); self.currentChunk().code.items[offset] = @intCast(u8, jump & 0xff); } fn emitCode(self: *Parser, code: OpCode) !void { try self.currentChunk().writeCode(code, self.previous.line); } fn emitConstant(self: *Parser, value: Value) !void { try self.emitBytes(@enumToInt(OpCode.OP_CONSTANT), try self.makeConstant(value)); } fn makeConstant(self: *Parser, value: Value) !u8 { const constant = try self.currentChunk().addConstant(value); if (constant > std.math.maxInt(u8)) { self.error0("Too many constants in one chunk."); return 0; } return constant; } fn currentChunk(self: *Parser) *Chunk { return self.compiler.chunk; } fn errorAtCurrent(self: *Parser, message: []const u8) void { self.errorAt(&self.current, message); } fn error0(self: *Parser, message: []const u8) void { self.errorAt(&self.previous, message); } fn errorAt(self: *Parser, token: *Token, message: []const u8) void { if (self.panicMode) return; self.panicMode = true; print("[line {}] Error", .{token.line}); if (token.tokenType == .TOKEN_EOF) { print(" at end", .{}); } else if (token.tokenType == .TOKEN_ERROR) { // nothing } else { print(" at '{}'", .{token.literal}); } print(": {}\n", .{message}); self.hadError = true; } fn synchronize(self: *Parser) void { self.panicMode = false; while (self.current.tokenType != .TOKEN_EOF) { if (self.previous.tokenType == .TOKEN_SEMICOLON) return; switch (self.current.tokenType) { .TOKEN_CLASS, .TOKEN_FUN, .TOKEN_VAR, .TOKEN_FOR, .TOKEN_IF, .TOKEN_WHILE, .TOKEN_PRINT, .TOKEN_RETURN, => return, else => {}, } self.advance(); } } };
vm/src/parser.zig
const std = @import("std"); const mem = std.mem; const Target = std.Target; const Compilation = @import("compilation.zig").Compilation; const introspect = @import("introspect.zig"); const testing = std.testing; const errmsg = @import("errmsg.zig"); const ZigCompiler = @import("compilation.zig").ZigCompiler; var ctx: TestContext = undefined; test "stage2" { // TODO provide a way to run tests in evented I/O mode if (!std.io.is_async) return error.SkipZigTest; // TODO https://github.com/ziglang/zig/issues/1364 // TODO https://github.com/ziglang/zig/issues/3117 if (true) return error.SkipZigTest; try ctx.init(); defer ctx.deinit(); try @import("stage2_tests").addCases(&ctx); try ctx.run(); } const file1 = "1.zig"; // TODO https://github.com/ziglang/zig/issues/3783 const allocator = std.heap.page_allocator; pub const TestContext = struct { zig_compiler: ZigCompiler, zig_lib_dir: []u8, file_index: std.atomic.Int(usize), group: std.event.Group(anyerror!void), any_err: anyerror!void, const tmp_dir_name = "stage2_test_tmp"; fn init(self: *TestContext) !void { self.* = TestContext{ .any_err = {}, .zig_compiler = undefined, .zig_lib_dir = undefined, .group = undefined, .file_index = std.atomic.Int(usize).init(0), }; self.zig_compiler = try ZigCompiler.init(allocator); errdefer self.zig_compiler.deinit(); self.group = std.event.Group(anyerror!void).init(allocator); errdefer self.group.wait() catch {}; self.zig_lib_dir = try introspect.resolveZigLibDir(allocator); errdefer allocator.free(self.zig_lib_dir); try std.fs.cwd().makePath(tmp_dir_name); errdefer std.fs.cwd().deleteTree(tmp_dir_name) catch {}; } fn deinit(self: *TestContext) void { std.fs.cwd().deleteTree(tmp_dir_name) catch {}; allocator.free(self.zig_lib_dir); self.zig_compiler.deinit(); } fn run(self: *TestContext) !void { std.event.Loop.startCpuBoundOperation(); self.any_err = self.group.wait(); return self.any_err; } fn testCompileError( self: *TestContext, source: []const u8, path: []const u8, line: usize, column: usize, msg: []const u8, ) !void { var file_index_buf: [20]u8 = undefined; const file_index = try std.fmt.bufPrint(file_index_buf[0..], "{}", .{self.file_index.incr()}); const file1_path = try std.fs.path.join(allocator, [_][]const u8{ tmp_dir_name, file_index, file1 }); if (std.fs.path.dirname(file1_path)) |dirname| { try std.fs.cwd().makePath(dirname); } // TODO async I/O try std.io.writeFile(file1_path, source); var comp = try Compilation.create( &self.zig_compiler, "test", file1_path, .Native, .Obj, .Debug, true, // is_static self.zig_lib_dir, ); errdefer comp.destroy(); comp.start(); try self.group.call(getModuleEvent, comp, source, path, line, column, msg); } fn testCompareOutputLibC( self: *TestContext, source: []const u8, expected_output: []const u8, ) !void { var file_index_buf: [20]u8 = undefined; const file_index = try std.fmt.bufPrint(file_index_buf[0..], "{}", .{self.file_index.incr()}); const file1_path = try std.fs.path.join(allocator, [_][]const u8{ tmp_dir_name, file_index, file1 }); const output_file = try std.fmt.allocPrint(allocator, "{}-out{}", .{ file1_path, (Target{ .Native = {} }).exeFileExt() }); if (std.fs.path.dirname(file1_path)) |dirname| { try std.fs.cwd().makePath(dirname); } // TODO async I/O try std.io.writeFile(file1_path, source); var comp = try Compilation.create( &self.zig_compiler, "test", file1_path, .Native, .Exe, .Debug, false, self.zig_lib_dir, ); errdefer comp.destroy(); _ = try comp.addLinkLib("c", true); comp.link_out_file = output_file; comp.start(); try self.group.call(getModuleEventSuccess, comp, output_file, expected_output); } async fn getModuleEventSuccess( comp: *Compilation, exe_file: []const u8, expected_output: []const u8, ) anyerror!void { defer comp.destroy(); const build_event = comp.events.get(); switch (build_event) { .Ok => { const argv = [_][]const u8{exe_file}; // TODO use event loop const child = try std.ChildProcess.exec(allocator, argv, null, null, 1024 * 1024); switch (child.term) { .Exited => |code| { if (code != 0) { return error.BadReturnCode; } }, else => { return error.Crashed; }, } if (!mem.eql(u8, child.stdout, expected_output)) { return error.OutputMismatch; } }, .Error => @panic("Cannot return error: https://github.com/ziglang/zig/issues/3190"), // |err| return err, .Fail => |msgs| { const stderr = std.io.getStdErr(); try stderr.write("build incorrectly failed:\n"); for (msgs) |msg| { defer msg.destroy(); try msg.printToFile(stderr, .Auto); } }, } } async fn getModuleEvent( comp: *Compilation, source: []const u8, path: []const u8, line: usize, column: usize, text: []const u8, ) anyerror!void { defer comp.destroy(); const build_event = comp.events.get(); switch (build_event) { .Ok => { @panic("build incorrectly succeeded"); }, .Error => |err| { @panic("build incorrectly failed"); }, .Fail => |msgs| { testing.expect(msgs.len != 0); for (msgs) |msg| { if (mem.endsWith(u8, msg.realpath, path) and mem.eql(u8, msg.text, text)) { const span = msg.getSpan(); const first_token = msg.getTree().tokens.at(span.first); const last_token = msg.getTree().tokens.at(span.first); const start_loc = msg.getTree().tokenLocationPtr(0, first_token); if (start_loc.line + 1 == line and start_loc.column + 1 == column) { return; } } } std.debug.warn("\n=====source:=======\n{}\n====expected:========\n{}:{}:{}: error: {}\n", .{ source, path, line, column, text, }); std.debug.warn("\n====found:========\n", .{}); const stderr = std.io.getStdErr(); for (msgs) |msg| { defer msg.destroy(); try msg.printToFile(stderr, errmsg.Color.Auto); } std.debug.warn("============\n", .{}); return error.TestFailed; }, } } };
src-self-hosted/test.zig
const kernel = @import("kernel.zig"); const log = kernel.log.scoped(.RNUFS); const Filesystem = @import("filesystem.zig"); const RNUFS = @import("../common/fs.zig"); const GenericDriver = kernel.driver; const Driver = @This(); fs: Filesystem, pub const Initialization = struct { pub const Context = *kernel.Disk; pub const Error = error{ allocation_failure, }; pub fn callback(allocate: GenericDriver.AllocationCallback, initialization_context: Context) Filesystem.InitializationError!*Driver { const driver_allocation = allocate(@sizeOf(Driver)) orelse return Error.allocation_failure; const driver = @intToPtr(*Driver, driver_allocation); driver.fs.disk = initialization_context; driver.fs.read_file_callback = read_file; return driver; } }; pub fn seek_file(fs_driver: *Filesystem, name: []const u8) ?SeekResult { const sectors_to_read_at_time = 1; var sector: u64 = 0; var search_buffer: [kernel.arch.sector_size]u8 = undefined; while (true) { log.debug("FS driver asking read", .{}); const sectors_read = fs_driver.disk.read_callback(fs_driver.disk, &search_buffer, sector, sectors_to_read_at_time); log.debug("FS driver ending read", .{}); if (sectors_read != sectors_to_read_at_time) @panic("driver failure"); var node = @ptrCast(*RNUFS.Node, @alignCast(@alignOf(RNUFS.Node), &search_buffer)); const node_name_cstr = @ptrCast([*:0]const u8, &node.name); const node_name = node_name_cstr[0..kernel.cstr_len(node_name_cstr)]; if (node_name.len == 0) @panic("file not found: no files"); log.debug("Node name: {s}", .{node_name}); if (kernel.string_eq(node_name, name)) { return SeekResult{ .sector = sector, .node = node.*, }; } log.debug("Node size: {}", .{node.size}); const sectors_to_add = 1 + kernel.bytes_to_sector(node.size); log.debug("Sectors to add: {}", .{sectors_to_add}); sector += sectors_to_add; } } pub fn read_file(fs_driver: *Filesystem, name: []const u8) []const u8 { log.debug("About to read a file...", .{}); if (seek_file(fs_driver, name)) |seek_result| { const file_allocation = kernel.heap.allocate(seek_result.node.size, true, true) orelse @panic("unable to allocate file buffer"); const file_buffer = @intToPtr([*]u8, file_allocation.virtual)[0..file_allocation.given_size]; const sectors_to_read = kernel.bytes_to_sector(seek_result.node.size); // Add one to skip the metadata const sectors_read = fs_driver.disk.read_callback(fs_driver.disk, file_buffer, seek_result.sector + 1, sectors_to_read); if (sectors_read != sectors_to_read) @panic("driver failure"); return file_buffer[0..seek_result.node.size]; } else { @panic("unable to find file"); } } pub const SeekResult = struct { sector: u64, node: RNUFS.Node, };
src/kernel/rnu_fs.zig
const std = @import("std"); const mem = std.mem; const fmt = std.fmt; const hash_map = std.hash_map; const math = std.math; const meta = std.meta; // ***************************************************************************** pub fn splitToInts(comptime T: type, allocator: *mem.Allocator, buffer: []const u8, delim: []const u8 ) ![]T { var ints = std.ArrayList(T).init(allocator); errdefer ints.deinit(); var it = mem.split(buffer, delim); while (it.next()) |field| { if (field.len == 0) continue; const int = try fmt.parseInt(T, field, 10); try ints.append(int); } return ints.toOwnedSlice(); } test "split ints" { var allocator = std.testing.allocator; const txt = "123\n456\n"; const ints = try splitToInts(u16, allocator, txt, "\n"); defer allocator.free(ints); std.testing.expectEqualSlices(u16, &[_]u16{123, 456}, ints); } // ***************************************************************************** pub fn HashSet(comptime K: type) type { return std.HashMap( K, void, hash_map.getAutoHashFn(K), hash_map.getAutoEqlFn(K), hash_map.DefaultMaxLoadPercentage ); } // ***************************************************************************** pub fn xor(a: bool, b: bool) bool { return (a and !b) or (b and !a); } // ***************************************************************************** /// inspired by: https://github.com/ziglang/zig/issues/793 pub fn EnumArray(comptime T: type, comptime U: type) type { return struct { data: [std.meta.fields(T).len]U, pub fn get(self: *const @This(), tag: T) U { return self.data[@enumToInt(tag)]; // return self.data[std.meta.fieldIndex(T, std.meta.tagName(tag))]; } pub fn set(self: *@This(), tag: T, value: U) void { self.data[@enumToInt(tag)] = value; // self.data[std.meta.fieldIndex(T, std.meta.tagName(tag))] = value; } }; } test "EnumArray" { const Weekdays = enum(usize) { monday, tuesday, wednesday, thursday, friday }; var map = EnumArray(Weekdays, bool){.data = [_]bool{false} ** std.meta.fields(Weekdays).len}; std.debug.print("\nEnumArray.get(.monday): {}\n", .{map.get(Weekdays.monday)}); map.set(.monday, true); std.debug.print("\nEnumArray.get(.monday): {}\n", .{map.get(.monday)}); } // ***************************************************************************** // heavily referenced the radix sort here: https://github.com/Snektron/aoc20/blob/master/src/aoc.zig pub fn sort(comptime T: type, allocator: *mem.Allocator, src: []T) !void { const aux = try allocator.alloc(T, src.len); defer allocator.free(aux); radixSort(T, 4, src, aux); } /// Sort src. pub fn radixSort(comptime T: type, comptime bits_per_bin: math.Log2Int(T), src: []T, aux: []T ) void { const windows = (8 * @sizeOf(T)) / @as(usize, bits_per_bin); var i: usize = 0; while (i < windows) : (i += 1) { const offset = @intCast(math.Log2Int(T), i * bits_per_bin); if (i % 2 == 0) { countingSort(T, bits_per_bin, offset, src, aux); } else { countingSort(T, bits_per_bin, offset, aux, src); } } if (windows % 2 == 1) { mem.copy(T, src, aux); } } /// Sort src into dst fn countingSort(comptime T: type, comptime bits_per_bin: math.Log2Int(T), offset: math.Log2Int(T), src: []const T, dst: []T ) void { const bins = 1 << bits_per_bin; // count occurrences of each set/span of bits var counts = [_]usize{0} ** bins; for (src) |num| { counts[bit_span(T, bits_per_bin, offset, num)] += 1; } // translate counts to their indices in the destination slice. // (the counts array will be reused for indices) var index: usize = 0; for (counts) |*count| { const next_index = index + count.*; count.* = index; index = next_index; } // insert nums into their cooresponding indices in dst. for (src) |num| { const span = bit_span(T, bits_per_bin, offset, num); const idx = &counts[span]; // destination idx for this number dst[idx.*] = num; idx.* += 1; // update the index for the next number placement } } /// Mask out a span of bits fn bit_span(comptime T: type, comptime bits_per_bin: math.Log2Int(T), offset: math.Log2Int(T), value: T ) meta.Int(.unsigned, bits_per_bin) { const BitSpan = meta.Int(.unsigned, bits_per_bin); const mask = math.maxInt(BitSpan); return @intCast(BitSpan, (value >> offset) & mask); } const asc_u32 = std.sort.asc(u32); test "radix sort" { var allocator = std.testing.allocator; var src = [_]u32{18, 421, 6, 5888, 1991, 10, 0}; var src_cpy = try allocator.alloc(u32, src.len); defer allocator.free(src_cpy); mem.copy(u32, src_cpy[0..], src[0..]); std.testing.expectEqualSlices(u32, src[0..], src_cpy[0..]); const aux = try allocator.alloc(u32, src.len); defer allocator.free(aux); radixSort(u32, 4, src[0..], aux[0..]); std.sort.sort(u32, src_cpy[0..], {}, asc_u32); std.testing.expectEqualSlices(u32, src[0..], src_cpy[0..]); } // *****************************************************************************
src/utils.zig
const std = @import("std"); const Granularity = enum(u1) { byte = 0, page = 1, }; const SegmentSize = enum(u1) { bits16 = 0, bits32 = 1, }; const Descriptor = packed struct { pub const Access = packed struct { accessed: bool = false, writeable: bool, direction: bool, executable: bool, segment: bool, priviledge: u2, present: bool, }; pub const Flags = packed struct { userbit: u1 = 0, longmode: bool, size: SegmentSize, granularity: Granularity, }; limit0: u16, // 0 Limit 0-7 // 1 Limit 8-15 base0: u24, // 2 Base 0-7 // 3 Base 8-15 // 4 Base 16-23 access: Access, // 5 Accessbyte 0-7 (vollständig) limit1: u4, // 6 Limit 16-19 flags: Flags, // 6 Flags 0-3 (vollständig) base1: u8, // 7 Base 24-31 pub fn init(base: u32, limit: u32, access: Access, flags: Flags) Descriptor { return Descriptor{ .limit0 = @truncate(u16, limit & 0xFFFF), .limit1 = @truncate(u4, (limit >> 16) & 0xF), .base0 = @truncate(u24, base & 0xFFFFFF), .base1 = @truncate(u8, (base >> 24) & 0xFF), .access = access, .flags = flags, }; } }; comptime { if (comptime @sizeOf(Descriptor) != 8) { @compileLog(@sizeOf(Descriptor)); } } var gdt: [3]Descriptor align(16) = [_]Descriptor{ // null descriptor Descriptor.init(0, 0, Descriptor.Access{ .writeable = false, .direction = false, .executable = false, .segment = false, .priviledge = 0, .present = false, }, Descriptor.Flags{ .granularity = .byte, .size = .bits16, .longmode = false, }), // Kernel Code Segment Descriptor.init(0, 0xfffff, Descriptor.Access{ .writeable = true, .direction = false, .executable = true, .segment = true, .priviledge = 0, .present = true, }, Descriptor.Flags{ .granularity = .page, .size = .bits32, .longmode = false, }), // Kernel Data Segment Descriptor.init(0, 0xfffff, Descriptor.Access{ .writeable = true, .direction = false, .executable = false, .segment = true, .priviledge = 0, .present = true, }, Descriptor.Flags{ .granularity = .page, .size = .bits32, .longmode = false, }), }; const DescriptorTable = packed struct { limit: u16, table: [*]Descriptor, }; export const gdtp = DescriptorTable{ .table = &gdt, .limit = @sizeOf(@TypeOf(gdt)) - 1, }; const Terminal = @import("text-terminal.zig"); fn load() void { // TODO: This is kinda dirty, is this possible otherwise? asm volatile ("lgdt gdtp"); asm volatile ( \\ mov $0x10, %%ax \\ mov %%ax, %%ds \\ mov %%ax, %%es \\ mov %%ax, %%fs \\ mov %%ax, %%gs \\ mov %%ax, %%ss \\ ljmp $0x8, $.reload \\ .reload: ); } pub fn init() void { // for (gdt) |descriptor| { // Terminal.println("0x{X:0>16} = {}", @bitCast(u64, descriptor), descriptor); // } load(); }
src/kernel/arch/x86/boot/gdt.zig
const std = @import("std"); const utils = @import("utils.zig"); const Registry = @import("registry.zig").Registry; const Storage = @import("registry.zig").Storage; const SparseSet = @import("sparse_set.zig").SparseSet; const Entity = @import("registry.zig").Entity; /// BasicGroups do not own any components. Internally, they keep a SparseSet that is always kept up-to-date with the matching /// entities. pub const BasicGroup = struct { registry: *Registry, group_data: *Registry.GroupData, pub fn init(registry: *Registry, group_data: *Registry.GroupData) BasicGroup { return .{ .registry = registry, .group_data = group_data, }; } pub fn len(self: BasicGroup) usize { return self.group_data.entity_set.len(); } /// Direct access to the array of entities pub fn data(self: BasicGroup) []const Entity { return self.group_data.entity_set.data(); } pub fn get(self: BasicGroup, comptime T: type, entity: Entity) *T { return self.registry.assure(T).get(entity); } pub fn getConst(self: BasicGroup, comptime T: type, entity: Entity) T { return self.registry.assure(T).getConst(entity); } /// iterates the matched entities backwards, so the current entity can always be removed safely /// and newly added entities wont affect it. pub fn iterator(self: BasicGroup) utils.ReverseSliceIterator(Entity) { return self.group_data.entity_set.reverseIterator(); } pub fn sort(self: BasicGroup, comptime T: type, context: anytype, comptime lessThan: fn (@TypeOf(context), T, T) bool) void { if (T == Entity) { self.group_data.entity_set.sort(context, lessThan); } else { // TODO: in debug mode, validate that T is present in the group const SortContext = struct { group: BasicGroup, wrapped_context: @TypeOf(context), lessThan: fn (@TypeOf(context), T, T) bool, fn sort(this: @This(), a: Entity, b: Entity) bool { const real_a = this.group.getConst(T, a); const real_b = this.group.getConst(T, b); return this.lessThan(this.wrapped_context, real_a, real_b); } }; var wrapper = SortContext{ .group = self, .wrapped_context = context, .lessThan = lessThan }; self.group_data.entity_set.sort(wrapper, SortContext.sort); } } }; pub const OwningGroup = struct { registry: *Registry, group_data: *Registry.GroupData, super: *usize, /// iterator the provides the data from all the requested owned components in a single struct. Access to the current Entity /// being iterated is available via the entity() method, useful for accessing non-owned component data. The get() method can /// also be used to fetch non-owned component data for the currently iterated Entity. /// TODO: support const types in the Components struct in addition to the current ptrs fn Iterator(comptime Components: anytype) type { return struct { group: OwningGroup, index: usize, storage: *Storage(u1), component_ptrs: [@typeInfo(Components).Struct.fields.len][*]u8, pub fn init(group: OwningGroup) @This() { const component_info = @typeInfo(Components).Struct; var component_ptrs: [component_info.fields.len][*]u8 = undefined; inline for (component_info.fields) |field, i| { const storage = group.registry.assure(@typeInfo(field.field_type).Pointer.child); component_ptrs[i] = @ptrCast([*]u8, storage.instances.items.ptr); } return .{ .group = group, .index = group.group_data.current, .storage = group.firstOwnedStorage(), .component_ptrs = component_ptrs, }; } pub fn next(it: *@This()) ?Components { if (it.index == 0) return null; it.index -= 1; // fill and return the struct var comps: Components = undefined; inline for (@typeInfo(Components).Struct.fields) |field, i| { const typed_ptr = @ptrCast([*]@typeInfo(field.field_type).Pointer.child, @alignCast(@alignOf(@typeInfo(field.field_type).Pointer.child), it.component_ptrs[i])); @field(comps, field.name) = &typed_ptr[it.index]; } return comps; } pub fn entity(it: @This()) Entity { std.debug.assert(it.index >= 0 and it.index < it.group.group_data.current); return it.storage.set.dense.items[it.index]; } pub fn get(it: @This(), comptime T: type) *T { return it.group.registry.get(T, it.entity()); } // Reset the iterator to the initial index pub fn reset(it: *@This()) void { it.index = it.group.group_data.current; } }; } pub fn init(registry: *Registry, group_data: *Registry.GroupData, super: *usize) OwningGroup { return .{ .registry = registry, .group_data = group_data, .super = super, }; } /// grabs an untyped (u1) reference to the first Storage(T) in the owned array fn firstOwnedStorage(self: OwningGroup) *Storage(u1) { const ptr = self.registry.components.get(self.group_data.owned[0]).?; return @intToPtr(*Storage(u1), ptr); } /// total number of entities in the group pub fn len(self: OwningGroup) usize { return self.group_data.current; } /// direct access to the array of entities of the first owning group pub fn data(self: OwningGroup) []const Entity { return self.firstOwnedStorage().data(); } pub fn contains(self: OwningGroup, entity: Entity) bool { var storage = self.firstOwnedStorage(); return storage.contains(entity) and storage.set.index(entity) < self.len(); } fn validate(self: OwningGroup, comptime Components: anytype) void { if (std.builtin.mode == .Debug and self.group_data.owned.len > 0) { std.debug.assert(@typeInfo(Components) == .Struct); inline for (@typeInfo(Components).Struct.fields) |field| { std.debug.assert(@typeInfo(field.field_type) == .Pointer); const found = std.mem.indexOfScalar(u32, self.group_data.owned, utils.typeId(std.meta.Child(field.field_type))); std.debug.assert(found != null); } } } pub fn getOwned(self: OwningGroup, entity: Entity, comptime Components: anytype) Components { self.validate(Components); const component_info = @typeInfo(Components).Struct; var component_ptrs: [component_info.fields.len][*]u8 = undefined; inline for (component_info.fields) |field, i| { const storage = self.registry.assure(std.meta.Child(field.field_type)); component_ptrs[i] = @ptrCast([*]u8, storage.instances.items.ptr); } // fill the struct const index = self.firstOwnedStorage().set.index(entity); var comps: Components = undefined; inline for (component_info.fields) |field, i| { const typed_ptr = @ptrCast([*]std.meta.Child(field.field_type), @alignCast(@alignOf(std.meta.Child(field.field_type)), component_ptrs[i])); @field(comps, field.name) = &typed_ptr[index]; } return comps; } pub fn each(self: OwningGroup, comptime func: anytype) void { const Components = switch (@typeInfo(@TypeOf(func))) { .BoundFn => |func_info| func_info.args[1].arg_type.?, .Fn => |func_info| func_info.args[0].arg_type.?, else => std.debug.assert("invalid func"), }; self.validate(Components); // optionally we could just use an Iterator here and pay for some slight indirection for code sharing var iter = self.iterator(Components); while (iter.next()) |comps| { @call(.{ .modifier = .always_inline }, func, .{comps}); } } /// returns the component storage for the given type for direct access pub fn getStorage(self: OwningGroup, comptime T: type) *Storage(T) { return self.registry.assure(T); } pub fn get(self: OwningGroup, comptime T: type, entity: Entity) *T { return self.registry.assure(T).get(entity); } pub fn getConst(self: OwningGroup, comptime T: type, entity: Entity) T { return self.registry.assure(T).getConst(entity); } pub fn sortable(self: OwningGroup) bool { return self.group_data.super == self.group_data.size; } /// returns an iterator with optimized access to the owend Components. Note that Components should be a struct with /// fields that are pointers to the component types that you want to fetch. Only types that are owned are valid! Non-owned /// types should be fetched via Iterator.get. pub fn iterator(self: OwningGroup, comptime Components: anytype) Iterator(Components) { self.validate(Components); return Iterator(Components).init(self); } pub fn entityIterator(self: OwningGroup) utils.ReverseSliceIterator(Entity) { return utils.ReverseSliceIterator(Entity).init(self.firstOwnedStorage().set.dense.items[0..self.group_data.current]); } pub fn sort(self: OwningGroup, comptime T: type, context: anytype, comptime lessThan: fn (@TypeOf(context), T, T) bool) void { var first_storage = self.firstOwnedStorage(); if (T == Entity) { // only sort up to self.group_data.current first_storage.sort(Entity, self.group_data.current, context, lessThan); } else { // TODO: in debug mode, validate that T is present in the group const SortContext = struct { group: OwningGroup, wrapped_context: @TypeOf(context), lessThan: fn (@TypeOf(context), T, T) bool, fn sort(this: @This(), a: Entity, b: Entity) bool { const real_a = this.group.getConst(T, a); const real_b = this.group.getConst(T, b); return this.lessThan(this.wrapped_context, real_a, real_b); } }; const wrapper = SortContext{ .group = self, .wrapped_context = context, .lessThan = lessThan }; first_storage.sort(Entity, self.group_data.current, wrapper, SortContext.sort); } // sync up the rest of the owned components var next: usize = self.group_data.current; while (true) : (next -= 1) { if (next == 0) break; const pos = next - 1; const entity = first_storage.data()[pos]; // skip the first one since its what we are using to sort with for (self.group_data.owned[1..]) |type_id| { var other_ptr = self.registry.components.get(type_id).?; var storage = @intToPtr(*Storage(u1), other_ptr); storage.swap(storage.data()[pos], entity); } } } }; test "BasicGroup creation/iteration" { var reg = Registry.init(std.testing.allocator); defer reg.deinit(); var group = reg.group(.{}, .{ i32, u32 }, .{}); try std.testing.expectEqual(group.len(), 0); var e0 = reg.create(); reg.add(e0, @as(i32, 44)); reg.add(e0, @as(u32, 55)); std.debug.assert(group.len() == 1); var iterated_entities: usize = 0; var iter = group.iterator(); while (iter.next()) |_| { iterated_entities += 1; } try std.testing.expectEqual(iterated_entities, 1); iterated_entities = 0; for (group.data()) |_| { iterated_entities += 1; } try std.testing.expectEqual(iterated_entities, 1); reg.remove(i32, e0); std.debug.assert(group.len() == 0); } test "BasicGroup excludes" { var reg = Registry.init(std.testing.allocator); defer reg.deinit(); var group = reg.group(.{}, .{i32}, .{u32}); try std.testing.expectEqual(group.len(), 0); var e0 = reg.create(); reg.add(e0, @as(i32, 44)); std.debug.assert(group.len() == 1); var iterated_entities: usize = 0; var iter = group.iterator(); while (iter.next()) |_| { iterated_entities += 1; } try std.testing.expectEqual(iterated_entities, 1); reg.add(e0, @as(u32, 55)); std.debug.assert(group.len() == 0); } test "BasicGroup create late" { var reg = Registry.init(std.testing.allocator); defer reg.deinit(); var e0 = reg.create(); reg.add(e0, @as(i32, 44)); reg.add(e0, @as(u32, 55)); var group = reg.group(.{}, .{ i32, u32 }, .{}); try std.testing.expectEqual(group.len(), 1); } test "OwningGroup" { var reg = Registry.init(std.testing.allocator); defer reg.deinit(); var group = reg.group(.{ i32, u32 }, .{}, .{}); var e0 = reg.create(); reg.add(e0, @as(i32, 44)); reg.add(e0, @as(u32, 55)); try std.testing.expectEqual(group.len(), 1); try std.testing.expect(group.contains(e0)); try std.testing.expectEqual(group.get(i32, e0).*, 44); try std.testing.expectEqual(group.getConst(u32, e0), 55); var vals = group.getOwned(e0, struct { int: *i32, uint: *u32 }); try std.testing.expectEqual(vals.int.*, 44); try std.testing.expectEqual(vals.uint.*, 55); vals.int.* = 666; var vals2 = group.getOwned(e0, struct { int: *i32, uint: *u32 }); try std.testing.expectEqual(vals2.int.*, 666); } test "OwningGroup add/remove" { var reg = Registry.init(std.testing.allocator); defer reg.deinit(); var group = reg.group(.{ i32, u32 }, .{}, .{}); var e0 = reg.create(); reg.add(e0, @as(i32, 44)); reg.add(e0, @as(u32, 55)); try std.testing.expectEqual(group.len(), 1); reg.remove(u32, e0); try std.testing.expectEqual(group.len(), 0); } test "OwningGroup iterate" { var reg = Registry.init(std.testing.allocator); defer reg.deinit(); var e0 = reg.create(); reg.add(e0, @as(i32, 44)); reg.add(e0, @as(u32, 55)); reg.add(e0, @as(u8, 11)); var e1 = reg.create(); reg.add(e1, @as(i32, 666)); reg.add(e1, @as(u32, 999)); reg.add(e1, @as(f32, 55.5)); var group = reg.group(.{ i32, u32 }, .{}, .{}); var iter = group.iterator(struct { int: *i32, uint: *u32 }); while (iter.next()) |item| { if (iter.entity() == e0) { try std.testing.expectEqual(item.int.*, 44); try std.testing.expectEqual(item.uint.*, 55); try std.testing.expectEqual(iter.get(u8).*, 11); } else { try std.testing.expectEqual(item.int.*, 666); try std.testing.expectEqual(item.uint.*, 999); try std.testing.expectEqual(iter.get(f32).*, 55.5); } } } fn each(components: struct { int: *i32, uint: *u32, }) void { std.testing.expectEqual(components.int.*, 44) catch unreachable; std.testing.expectEqual(components.uint.*, 55) catch unreachable; } test "OwningGroup each" { var reg = Registry.init(std.testing.allocator); defer reg.deinit(); var e0 = reg.create(); reg.add(e0, @as(i32, 44)); reg.add(e0, @as(u32, 55)); const Thing = struct { fn each(_: @This(), components: struct { int: *i32, uint: *u32, }) void { std.testing.expectEqual(components.int.*, 44) catch unreachable; std.testing.expectEqual(components.uint.*, 55) catch unreachable; } }; var thing = Thing{}; var group = reg.group(.{ i32, u32 }, .{}, .{}); group.each(thing.each); group.each(each); } test "multiple OwningGroups" { const Sprite = struct { x: f32 }; const Transform = struct { x: f32 }; const Renderable = struct { x: f32 }; const Rotation = struct { x: f32 }; var reg = Registry.init(std.testing.allocator); defer reg.deinit(); // var group1 = reg.group(.{u64, u32}, .{}, .{}); // var group2 = reg.group(.{u64, u32, u8}, .{}, .{}); _ = reg.group(.{ Sprite, Transform }, .{ Renderable, Rotation }, .{}); _ = reg.group(.{Sprite}, .{Renderable}, .{}); _ = reg.group(.{ Sprite, Transform }, .{Renderable}, .{}); // ensure groups are ordered correctly internally var last_size: u8 = 0; for (reg.groups.items) |grp| { try std.testing.expect(last_size <= grp.size); last_size = grp.size; } try std.testing.expect(!reg.sortable(Sprite)); // this will break the group // var group6 = reg.group(.{Sprite, Rotation}, .{}, .{}); }
src/ecs/groups.zig
const std = @import("std"); const allocPrint0 = std.fmt.allocPrint0; const stdout = std.io.getStdOut().outStream(); const print = stdout.print; const ps = @import("parse.zig"); const Node = ps.Node; const Member = ps.Member; const newCast = ps.newCast; const tk = @import("tokenize.zig"); const Token = tk.Token; const atoi = tk.atoi; const allocator = @import("allocator.zig"); const getAllocator = allocator.getAllocator; const err = @import("error.zig"); const errorAt = err.errorAt; const errorAtToken = err.errorAtToken; pub const TypeKind = enum { TyVoid, TyChar, TyShort, TyInt, TyLong, TyPtr, TyFunc, TyArray, TyStruct, TyUnion, }; pub const Type = struct { kind: TypeKind, size: usize, // sizeof alignment: usize, base: ?*Type, // ポインタの場合に使う name: ?*Token, // 宣言のときに使う // Array array_len: usize, // Struct members: ?*Member, // 関数 return_ty: ?*Type, params: ?*Type, next: ?*Type, pub var INT_SIZE_STR: [:0]u8 = undefined; pub fn initGlobals() void { Type.INT_SIZE_STR = stringToSlice("8"); } pub fn init(kind: TypeKind) Type { return Type{ .kind = kind, .size = 0, .alignment = 0, .base = null, .name = null, .array_len = 0, .members = null, .return_ty = null, .params = null, .next = null, }; } pub fn allocInit(kind: TypeKind) *Type { var ty = getAllocator().create(Type) catch @panic("cannot allocate Type"); ty.* = Type.init(kind); return ty; } pub fn typeVoid() *Type { var ty = Type.allocInit(.TyVoid); ty.*.size = 1; ty.*.alignment = 1; return ty; } pub fn typeChar() *Type { var ty = Type.allocInit(.TyChar); ty.*.size = 1; ty.*.alignment = 1; return ty; } pub fn typeShort() *Type { var ty = Type.allocInit(.TyShort); ty.*.size = 2; ty.*.alignment = 2; return ty; } pub fn typeInt() *Type { var ty = Type.allocInit(.TyInt); ty.*.size = 4; ty.*.alignment = 4; return ty; } pub fn typeLong() *Type { var ty = Type.allocInit(.TyLong); ty.*.size = 8; ty.*.alignment = 8; return ty; } pub fn pointerTo(base: *Type) *Type { var ty = Type.allocInit(.TyPtr); ty.*.base = base; ty.*.size = 8; ty.*.alignment = 8; return ty; } pub fn isInteger(self: *Type) bool { return self.*.kind == .TyChar or self.*.kind == .TyShort or self.*.kind == .TyInt or self.*.kind == .TyLong; } pub fn funcType(return_ty: *Type) *Type { var ty = Type.allocInit(.TyFunc); ty.return_ty = return_ty; return ty; } pub fn arrayOf(base: *Type, len: usize) *Type { var ty = Type.allocInit(.TyArray); ty.*.size = base.*.size * len; ty.*.alignment = base.*.alignment; ty.*.base = base; ty.*.array_len = len; return ty; } }; pub fn addType(nodeWithNull: ?*Node) void { if (nodeWithNull == null or nodeWithNull.?.*.ty != null) return; var node = nodeWithNull.?; addType(node.*.lhs); addType(node.*.rhs); addType(node.*.cond); addType(node.*.then); addType(node.*.els); addType(node.*.init); addType(node.*.inc); var n = node.*.body; while (n != null) { addType(n.?); n = n.?.*.next; } n = node.*.args; while (n != null) { addType(n.?); n = n.?.*.next; } switch (node.*.kind) { .NdNum => { const valueAsI64 = atoi(node.*.val.?); @setRuntimeSafety(false); node.*.ty = if (valueAsI64 == @intCast(i32, valueAsI64)) Type.typeInt() else Type.typeLong(); return; }, .NdAdd, .NdSub, .NdMul, .NdDiv => { usualArithConv(&(node.*.lhs.?), &(node.*.rhs.?)); node.*.ty = node.*.lhs.?.*.ty; return; }, .NdNeg => { var ty = getCommonType(Type.typeInt(), node.*.lhs.?.*.ty.?); node.*.lhs = newCast(node.*.lhs.?, ty); node.*.ty = ty; return; }, .NdAssign => { if (node.*.lhs.?.*.ty.?.*.kind == .TyArray) errorAtToken(node.*.lhs.?.*.tok, "not an lvalue"); if (node.*.lhs.?.*.ty.?.*.kind != .TyStruct) node.*.rhs = newCast(node.*.rhs.?, node.*.lhs.?.*.ty.?); node.*.ty = node.*.lhs.?.*.ty; return; }, .NdEq, .NdNe, .NdLt, .NdLe => { usualArithConv(&(node.*.lhs.?), &(node.*.rhs.?)); node.*.ty = Type.typeLong(); return; }, .NdVar => { node.*.ty = node.*.variable.?.*.ty; return; }, .NdFuncall => { node.*.ty = Type.typeLong(); return; }, .NdComma => { node.*.ty = node.*.rhs.?.*.ty; return; }, .NdMember => { node.*.ty = node.*.member.?.*.ty; return; }, .NdAddr => { if (node.*.lhs.?.*.ty.?.*.kind == .TyArray) { node.*.ty = Type.pointerTo(node.*.lhs.?.*.ty.?.*.base.?); } else { node.*.ty = Type.pointerTo(node.*.lhs.?.*.ty.?); } return; }, .NdDeref => { if (node.*.lhs.?.*.ty.?.*.base == null) errorAtToken(node.*.tok, "Invalid pointer dereference"); if (node.*.lhs.?.*.ty.?.*.base.?.*.kind == .TyVoid) errorAtToken(node.*.tok, "void型をdereferenceしようとしています"); node.*.ty = node.*.lhs.?.*.ty.?.*.base; return; }, .NdStmtExpr => { if (node.*.body != null) { var stmt = node.*.body.?; while (stmt.*.next != null) stmt = stmt.*.next.?; if (stmt.*.kind == .NdExprStmt) { node.*.ty = stmt.*.lhs.?.*.ty.?; return; } } errorAtToken(node.*.tok, "statement expression returning void is not supported"); }, else => { return; }, } } pub fn getCommonType(ty1: *Type, ty2: *Type) *Type { if (ty1.*.base != null) return Type.pointerTo(ty1.*.base.?); if (ty1.*.size == 8 or ty2.*.size == 8) return Type.typeLong(); return Type.typeInt(); } pub fn usualArithConv(lhs: **Node, rhs: **Node) void { var ty = getCommonType(lhs.*.*.ty.?, rhs.*.*.ty.?); lhs.* = newCast(lhs.*, ty); rhs.* = newCast(rhs.*, ty); } fn stringToSlice(s: [*:0]const u8) [:0]u8 { return allocPrint0(getAllocator(), "{}", .{s}) catch @panic("cannot allocate string"); } pub fn copyType(ty: *Type) *Type { var newType = Type.allocInit(ty.*.kind); newType.*.size = ty.*.size; newType.*.alignment = ty.*.alignment; newType.*.base = ty.*.base; newType.*.name = ty.*.name; newType.*.array_len = ty.*.array_len; newType.*.members = ty.*.members; newType.*.return_ty = ty.*.return_ty; newType.*.params = ty.*.params; newType.*.next = ty.*.next; return newType; }
src/type.zig
const std = @import("../../std.zig"); const io = std.io; const os = std.os; const ip = std.x.net.ip; const fmt = std.fmt; const mem = std.mem; const builtin = std.builtin; const testing = std.testing; const IPv4 = std.x.os.IPv4; const IPv6 = std.x.os.IPv6; const Socket = std.x.os.Socket; /// A generic TCP socket abstraction. const tcp = @This(); /// A TCP client-address pair. pub const Connection = struct { client: tcp.Client, address: ip.Address, /// Enclose a TCP client and address into a client-address pair. pub fn from(conn: Socket.Connection) tcp.Connection { return .{ .client = tcp.Client.from(conn.socket), .address = ip.Address.from(conn.address), }; } /// Unravel a TCP client-address pair into a socket-address pair. pub fn into(self: tcp.Connection) Socket.Connection { return .{ .socket = self.client.socket, .address = self.address.into(), }; } /// Closes the underlying client of the connection. pub fn deinit(self: tcp.Connection) void { self.client.deinit(); } }; /// Possible domains that a TCP client/listener may operate over. pub const Domain = enum(u16) { ip = os.AF_INET, ipv6 = os.AF_INET6, }; /// A TCP client. pub const Client = struct { socket: Socket, /// Implements `std.io.Reader`. pub const Reader = struct { client: Client, flags: u32, /// Implements `readFn` for `std.io.Reader`. pub fn read(self: Client.Reader, buffer: []u8) !usize { return self.client.read(buffer, self.flags); } }; /// Implements `std.io.Writer`. pub const Writer = struct { client: Client, flags: u32, /// Implements `writeFn` for `std.io.Writer`. pub fn write(self: Client.Writer, buffer: []const u8) !usize { return self.client.write(buffer, self.flags); } }; /// Opens a new client. pub fn init(domain: tcp.Domain, flags: u32) !Client { return Client{ .socket = try Socket.init( @enumToInt(domain), os.SOCK_STREAM | flags, os.IPPROTO_TCP, ), }; } /// Enclose a TCP client over an existing socket. pub fn from(socket: Socket) Client { return Client{ .socket = socket }; } /// Closes the client. pub fn deinit(self: Client) void { self.socket.deinit(); } /// Shutdown either the read side, write side, or all sides of the client's underlying socket. pub fn shutdown(self: Client, how: os.ShutdownHow) !void { return self.socket.shutdown(how); } /// Have the client attempt to the connect to an address. pub fn connect(self: Client, address: ip.Address) !void { return self.socket.connect(address.into()); } /// Extracts the error set of a function. /// TODO: remove after Socket.{read, write} error unions are well-defined across different platforms fn ErrorSetOf(comptime Function: anytype) type { return @typeInfo(@typeInfo(@TypeOf(Function)).Fn.return_type.?).ErrorUnion.error_set; } /// Wrap `tcp.Client` into `std.io.Reader`. pub fn reader(self: Client, flags: u32) io.Reader(Client.Reader, ErrorSetOf(Client.Reader.read), Client.Reader.read) { return .{ .context = .{ .client = self, .flags = flags } }; } /// Wrap `tcp.Client` into `std.io.Writer`. pub fn writer(self: Client, flags: u32) io.Writer(Client.Writer, ErrorSetOf(Client.Writer.write), Client.Writer.write) { return .{ .context = .{ .client = self, .flags = flags } }; } /// Read data from the socket into the buffer provided with a set of flags /// specified. It returns the number of bytes read into the buffer provided. pub fn read(self: Client, buf: []u8, flags: u32) !usize { return self.socket.read(buf, flags); } /// Write a buffer of data provided to the socket with a set of flags specified. /// It returns the number of bytes that are written to the socket. pub fn write(self: Client, buf: []const u8, flags: u32) !usize { return self.socket.write(buf, flags); } /// Writes multiple I/O vectors with a prepended message header to the socket /// with a set of flags specified. It returns the number of bytes that are /// written to the socket. pub fn writeVectorized(self: Client, msg: os.msghdr_const, flags: u32) !usize { return self.socket.writeVectorized(msg, flags); } /// Read multiple I/O vectors with a prepended message header from the socket /// with a set of flags specified. It returns the number of bytes that were /// read into the buffer provided. pub fn readVectorized(self: Client, msg: *os.msghdr, flags: u32) !usize { return self.socket.readVectorized(msg, flags); } /// Query and return the latest cached error on the client's underlying socket. pub fn getError(self: Client) !void { return self.socket.getError(); } /// Query the read buffer size of the client's underlying socket. pub fn getReadBufferSize(self: Client) !u32 { return self.socket.getReadBufferSize(); } /// Query the write buffer size of the client's underlying socket. pub fn getWriteBufferSize(self: Client) !u32 { return self.socket.getWriteBufferSize(); } /// Query the address that the client's socket is locally bounded to. pub fn getLocalAddress(self: Client) !ip.Address { return ip.Address.from(try self.socket.getLocalAddress()); } /// Query the address that the socket is connected to. pub fn getRemoteAddress(self: Client) !ip.Address { return ip.Address.from(try self.socket.getRemoteAddress()); } /// Have close() or shutdown() syscalls block until all queued messages in the client have been successfully /// sent, or if the timeout specified in seconds has been reached. It returns `error.UnsupportedSocketOption` /// if the host does not support the option for a socket to linger around up until a timeout specified in /// seconds. pub fn setLinger(self: Client, timeout_seconds: ?u16) !void { return self.socket.setLinger(timeout_seconds); } /// Have keep-alive messages be sent periodically. The timing in which keep-alive messages are sent are /// dependant on operating system settings. It returns `error.UnsupportedSocketOption` if the host does /// not support periodically sending keep-alive messages on connection-oriented sockets. pub fn setKeepAlive(self: Client, enabled: bool) !void { return self.socket.setKeepAlive(enabled); } /// Disable Nagle's algorithm on a TCP socket. It returns `error.UnsupportedSocketOption` if /// the host does not support sockets disabling Nagle's algorithm. pub fn setNoDelay(self: Client, enabled: bool) !void { if (comptime @hasDecl(os, "TCP_NODELAY")) { const bytes = mem.asBytes(&@as(usize, @boolToInt(enabled))); return self.socket.setOption(os.IPPROTO_TCP, os.TCP_NODELAY, bytes); } return error.UnsupportedSocketOption; } /// Enables TCP Quick ACK on a TCP socket to immediately send rather than delay ACKs when necessary. It returns /// `error.UnsupportedSocketOption` if the host does not support TCP Quick ACK. pub fn setQuickACK(self: Client, enabled: bool) !void { if (comptime @hasDecl(os, "TCP_QUICKACK")) { return self.socket.setOption(os.IPPROTO_TCP, os.TCP_QUICKACK, mem.asBytes(&@as(u32, @boolToInt(enabled)))); } return error.UnsupportedSocketOption; } /// Set the write buffer size of the socket. pub fn setWriteBufferSize(self: Client, size: u32) !void { return self.socket.setWriteBufferSize(size); } /// Set the read buffer size of the socket. pub fn setReadBufferSize(self: Client, size: u32) !void { return self.socket.setReadBufferSize(size); } /// Set a timeout on the socket that is to occur if no messages are successfully written /// to its bound destination after a specified number of milliseconds. A subsequent write /// to the socket will thereafter return `error.WouldBlock` should the timeout be exceeded. pub fn setWriteTimeout(self: Client, milliseconds: u32) !void { return self.socket.setWriteTimeout(milliseconds); } /// Set a timeout on the socket that is to occur if no messages are successfully read /// from its bound destination after a specified number of milliseconds. A subsequent /// read from the socket will thereafter return `error.WouldBlock` should the timeout be /// exceeded. pub fn setReadTimeout(self: Client, milliseconds: u32) !void { return self.socket.setReadTimeout(milliseconds); } }; /// A TCP listener. pub const Listener = struct { socket: Socket, /// Opens a new listener. pub fn init(domain: tcp.Domain, flags: u32) !Listener { return Listener{ .socket = try Socket.init( @enumToInt(domain), os.SOCK_STREAM | flags, os.IPPROTO_TCP, ), }; } /// Closes the listener. pub fn deinit(self: Listener) void { self.socket.deinit(); } /// Shuts down the underlying listener's socket. The next subsequent call, or /// a current pending call to accept() after shutdown is called will return /// an error. pub fn shutdown(self: Listener) !void { return self.socket.shutdown(.recv); } /// Binds the listener's socket to an address. pub fn bind(self: Listener, address: ip.Address) !void { return self.socket.bind(address.into()); } /// Start listening for incoming connections. pub fn listen(self: Listener, max_backlog_size: u31) !void { return self.socket.listen(max_backlog_size); } /// Accept a pending incoming connection queued to the kernel backlog /// of the listener's socket. pub fn accept(self: Listener, flags: u32) !tcp.Connection { return tcp.Connection.from(try self.socket.accept(flags)); } /// Query and return the latest cached error on the listener's underlying socket. pub fn getError(self: Client) !void { return self.socket.getError(); } /// Query the address that the listener's socket is locally bounded to. pub fn getLocalAddress(self: Listener) !ip.Address { return ip.Address.from(try self.socket.getLocalAddress()); } /// Allow multiple sockets on the same host to listen on the same address. It returns `error.UnsupportedSocketOption` if /// the host does not support sockets listening the same address. pub fn setReuseAddress(self: Listener, enabled: bool) !void { return self.socket.setReuseAddress(enabled); } /// Allow multiple sockets on the same host to listen on the same port. It returns `error.UnsupportedSocketOption` if /// the host does not supports sockets listening on the same port. pub fn setReusePort(self: Listener, enabled: bool) !void { return self.socket.setReusePort(enabled); } /// Enables TCP Fast Open (RFC 7413) on a TCP socket. It returns `error.UnsupportedSocketOption` if the host does not /// support TCP Fast Open. pub fn setFastOpen(self: Listener, enabled: bool) !void { if (comptime @hasDecl(os, "TCP_FASTOPEN")) { return self.socket.setOption(os.IPPROTO_TCP, os.TCP_FASTOPEN, mem.asBytes(&@as(u32, @boolToInt(enabled)))); } return error.UnsupportedSocketOption; } /// Set a timeout on the listener that is to occur if no new incoming connections come in /// after a specified number of milliseconds. A subsequent accept call to the listener /// will thereafter return `error.WouldBlock` should the timeout be exceeded. pub fn setAcceptTimeout(self: Listener, milliseconds: usize) !void { return self.socket.setReadTimeout(milliseconds); } }; test "tcp: create client/listener pair" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const listener = try tcp.Listener.init(.ip, os.SOCK_CLOEXEC); defer listener.deinit(); try listener.bind(ip.Address.initIPv4(IPv4.unspecified, 0)); try listener.listen(128); var binded_address = try listener.getLocalAddress(); switch (binded_address) { .ipv4 => |*ipv4| ipv4.host = IPv4.localhost, .ipv6 => |*ipv6| ipv6.host = IPv6.localhost, } const client = try tcp.Client.init(.ip, os.SOCK_CLOEXEC); defer client.deinit(); try client.connect(binded_address); const conn = try listener.accept(os.SOCK_CLOEXEC); defer conn.deinit(); } test "tcp/client: set read timeout of 1 millisecond on blocking client" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const listener = try tcp.Listener.init(.ip, os.SOCK_CLOEXEC); defer listener.deinit(); try listener.bind(ip.Address.initIPv4(IPv4.unspecified, 0)); try listener.listen(128); var binded_address = try listener.getLocalAddress(); switch (binded_address) { .ipv4 => |*ipv4| ipv4.host = IPv4.localhost, .ipv6 => |*ipv6| ipv6.host = IPv6.localhost, } const client = try tcp.Client.init(.ip, os.SOCK_CLOEXEC); defer client.deinit(); try client.connect(binded_address); try client.setReadTimeout(1); const conn = try listener.accept(os.SOCK_CLOEXEC); defer conn.deinit(); var buf: [1]u8 = undefined; try testing.expectError(error.WouldBlock, client.reader(0).read(&buf)); } test "tcp/listener: bind to unspecified ipv4 address" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const listener = try tcp.Listener.init(.ip, os.SOCK_CLOEXEC); defer listener.deinit(); try listener.bind(ip.Address.initIPv4(IPv4.unspecified, 0)); try listener.listen(128); const address = try listener.getLocalAddress(); try testing.expect(address == .ipv4); } test "tcp/listener: bind to unspecified ipv6 address" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const listener = try tcp.Listener.init(.ipv6, os.SOCK_CLOEXEC); defer listener.deinit(); try listener.bind(ip.Address.initIPv6(IPv6.unspecified, 0)); try listener.listen(128); const address = try listener.getLocalAddress(); try testing.expect(address == .ipv6); }
lib/std/x/net/tcp.zig
// Modular crypt(3) format for scrypt // https://en.wikipedia.org/wiki/Crypt_(C) // https://gitlab.com/jas/scrypt-unix-crypt/blob/master/unix-scrypt.txt const std = @import("std"); const io = std.io; const math = std.math; const mem = std.mem; const meta = std.meta; pub const Error = std.crypto.errors.Error || error{NoSpaceLeft}; /// Standard type for a set of scrypt parameters, with the salt and hash. pub fn HashResult(comptime max_hash_len: usize) type { return struct { ln: u6, r: u30, p: u30, salt: []const u8, hash: BinValue(max_hash_len), }; } /// scrypt parameters only - no salt nor hash. pub const HashParameters = struct { ln: u6, r: u30, p: u30, }; /// A wrapped binary value whose maximum size is `max_len`. /// /// This type must be used whenever a binary value is encoded in a PHC-formatted string. /// This includes `salt`, `hash`, and any other binary parameters such as keys. /// /// Once initialized, the actual value can be read with the `unwrap()` function. pub fn BinValue(comptime max_len: usize) type { return struct { const Self = @This(); const capacity = max_len; const max_encoded_length = Codec.encodedLen(max_len); buf: [max_len]u8 = undefined, len: usize = 0, /// Wrap an existing byte slice pub fn fromSlice(slice: []const u8) Error!Self { if (slice.len > capacity) return Error.NoSpaceLeft; var bin_value: Self = undefined; mem.copy(u8, &bin_value.buf, slice); bin_value.len = slice.len; return bin_value; } /// Return the slice containing the actual value. pub fn unwrap(self: Self) []const u8 { return self.buf[0..self.len]; } fn fromB64(self: *Self, str: []const u8) !void { const len = Codec.decodedLen(str.len); if (len > self.buf.len) return Error.NoSpaceLeft; try Codec.decode(self.buf[0..len], str); self.len = len; } fn toB64(self: Self, buf: []u8) ![]const u8 { const value = self.unwrap(); const len = Codec.encodedLen(value.len); if (len > buf.len) return Error.NoSpaceLeft; var encoded = buf[0..len]; Codec.encode(encoded, value); return encoded; } }; } /// Expand binary data into a salt for the modular crypt format. pub fn saltFromBin(comptime len: usize, salt: [len]u8) [Codec.encodedLen(len)]u8 { var buf: [Codec.encodedLen(len)]u8 = undefined; Codec.encode(&buf, &salt); return buf; } const Codec = CustomB64Codec("./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".*); /// String prefix for scrypt pub const prefix = "$7$"; /// Deserialize a string into a structure `T` (matching `HashResult`). pub fn deserialize(comptime T: type, str: []const u8) Error!T { var out: T = undefined; if (str.len < 16) return Error.InvalidEncoding; if (!mem.eql(u8, prefix, str[0..3])) return Error.InvalidEncoding; out.ln = try Codec.intDecode(u6, str[3..4]); out.r = try Codec.intDecode(u30, str[4..9]); out.p = try Codec.intDecode(u30, str[9..14]); var it = mem.split(u8, str[14..], "$"); const salt = it.next() orelse return Error.InvalidEncoding; if (@hasField(T, "salt")) out.salt = salt; const hash_str = it.next() orelse return Error.InvalidEncoding; if (@hasField(T, "hash")) try out.hash.fromB64(hash_str); return out; } /// Serialize parameters into a string in modular crypt format. pub fn serialize(params: anytype, str: []u8) Error![]const u8 { var buf = io.fixedBufferStream(str); try serializeTo(params, buf.writer()); return buf.getWritten(); } /// Compute the number of bytes required to serialize `params` pub fn calcSize(params: anytype) usize { var buf = io.countingWriter(io.null_writer); serializeTo(params, buf.writer()) catch unreachable; return @intCast(usize, buf.bytes_written); } fn serializeTo(params: anytype, out: anytype) !void { var header: [14]u8 = undefined; mem.copy(u8, header[0..3], prefix); Codec.intEncode(header[3..4], params.ln); Codec.intEncode(header[4..9], params.r); Codec.intEncode(header[9..14], params.p); try out.writeAll(&header); try out.writeAll(params.salt); try out.writeAll("$"); var buf: [@TypeOf(params.hash).max_encoded_length]u8 = undefined; const hash_str = try params.hash.toB64(&buf); try out.writeAll(hash_str); } /// Custom codec that maps 6 bits into 8 like regular Base64, but uses its own alphabet, /// encodes bits in little-endian, and can also encode integers. fn CustomB64Codec(comptime map: [64]u8) type { return struct { const map64 = map; fn encodedLen(len: usize) usize { return (len * 4 + 2) / 3; } fn decodedLen(len: usize) usize { return len / 4 * 3 + (len % 4) * 3 / 4; } fn intEncode(dst: []u8, src: anytype) void { var n = src; for (dst) |*x| { x.* = map64[@truncate(u6, n)]; n = math.shr(@TypeOf(src), n, 6); } } fn intDecode(comptime T: type, src: *const [(meta.bitCount(T) + 5) / 6]u8) !T { var v: T = 0; for (src) |x, i| { const vi = mem.indexOfScalar(u8, &map64, x) orelse return Error.InvalidEncoding; v |= @intCast(T, vi) << @intCast(math.Log2Int(T), i * 6); } return v; } fn decode(dst: []u8, src: []const u8) !void { std.debug.assert(dst.len == decodedLen(src.len)); var i: usize = 0; while (i < src.len / 4) : (i += 1) { mem.writeIntSliceLittle(u24, dst[i * 3 ..], try intDecode(u24, src[i * 4 ..][0..4])); } const leftover = src[i * 4 ..]; var v: u24 = 0; for (leftover) |_, j| { v |= @as(u24, try intDecode(u6, leftover[j..][0..1])) << @intCast(u5, j * 6); } for (dst[i * 3 ..]) |*x, j| { x.* = @truncate(u8, v >> @intCast(u5, j * 8)); } } fn encode(dst: []u8, src: []const u8) void { std.debug.assert(dst.len == encodedLen(src.len)); var i: usize = 0; while (i < src.len / 3) : (i += 1) { intEncode(dst[i * 4 ..][0..4], mem.readIntSliceLittle(u24, src[i * 3 ..])); } const leftover = src[i * 3 ..]; var v: u24 = 0; for (leftover) |x, j| { v |= @as(u24, x) << @intCast(u5, j * 8); } intEncode(dst[i * 4 ..], v); } }; } test "scrypt crypt format" { const str = "$7$C6..../....SodiumChloride$kBGj9fHznVYFQMEn/qDCfrDevf9YDtcDdKvEqHJLV8D"; const params = try deserialize(HashResult(32), str); var buf: [str.len]u8 = undefined; const s1 = try serialize(params, &buf); try std.testing.expectEqualStrings(s1, str); }
src/crypt_encoding_scrypt.zig
const builtin = @import("builtin"); const std = @import("std"); const Builder = std.build.Builder; const LibExeObjStep = std.build.LibExeObjStep; fn linkWasmtime(step: *LibExeObjStep, search_path: ?[]const u8) void { if (builtin.os.tag == .windows) { // On Windows, link dynamic library as otherwise lld will have a // hard time satisfying `libwasmtime` deps step.linkSystemLibrary("wasmtime.dll"); } else { step.linkSystemLibrary("wasmtime"); } if (search_path) |path| { step.addLibPath(path); } } pub fn build(b: *Builder) !void { const mode = b.standardReleaseOptions(); const lib_path = b.option([]const u8, "library-search-path", "Add additional system library search path."); const lib = b.addStaticLibrary("wasmtime-zig", "src/main.zig"); lib.setBuildMode(mode); lib.install(); var main_tests = b.addTest("src/main.zig"); main_tests.setBuildMode(mode); linkWasmtime(main_tests, lib_path); main_tests.step.dependOn(b.getInstallStep()); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&main_tests.step); const example = b.option([]const u8, "example", "The example to run from the /example folder"); const example_path = blk: { const ex = example orelse "simple"; const path = try std.fs.path.join(b.allocator, &[_][]const u8{ "example", ex }); break :blk try std.mem.concat(b.allocator, u8, &[_][]const u8{ path, ".zig" }); }; const simple_exe = b.addExecutable(example orelse "simple", example_path); simple_exe.setBuildMode(mode); simple_exe.addPackagePath("wasmtime", "src/main.zig"); simple_exe.linkLibC(); linkWasmtime(simple_exe, lib_path); simple_exe.step.dependOn(b.getInstallStep()); const run_simple_cmd = simple_exe.run(); const run_simple_step = b.step("run", "Runs an example. If no -Dexample arg is provided, the simple example will be ran"); run_simple_step.dependOn(&run_simple_cmd.step); }
build.zig
const std = @import("std"); const mem = std.mem; const file = @embedFile("../input.txt"); // \\mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X // \\mem[8] = 11 // \\mem[7] = 101 // \\mem[8] = 0 // ; const Mask = struct { and_mask: u64, or_mask: u64, }; const Memory = struct { address: u64, value: u64, }; const Instruction = union(enum) { set_mask: Mask, set_memory: Memory, }; pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var allocator = &arena.allocator; var instructions = std.ArrayList(Instruction).init(allocator); defer instructions.deinit(); var line_iterator = mem.tokenize(file, "\n"); while (line_iterator.next()) |line| { if (mem.startsWith(u8, line, "mem")) { const end_of_address = mem.indexOf(u8, line, "]").?; const start_of_value = mem.lastIndexOf(u8, line, " ").? + 1; try instructions.append(.{ .set_memory = .{ .address = try std.fmt.parseUnsigned(u64, line[4..end_of_address], 10), .value = try std.fmt.parseUnsigned(u64, line[start_of_value..], 10), }, }); } else { var mask = Mask{ .and_mask = 0, .or_mask = 0 }; var index: usize = 0; for (line[7..]) |char| { switch (char) { '1' => mask.or_mask |= 1, '0' => mask.and_mask |= 1, else => {}, } mask.or_mask <<= 1; mask.and_mask <<= 1; } // undo the last shift mask.or_mask >>= 1; mask.and_mask >>= 1; mask.and_mask = ~mask.and_mask; try instructions.append(.{ .set_mask = mask }); } } var memory_map = std.AutoHashMap(u64, u64).init(allocator); defer memory_map.deinit(); var last_mask: Mask = undefined; for (instructions.items) |instruction| { switch (instruction) { .set_mask => |mask| last_mask = mask, .set_memory => |memory| { // std.debug.print("value: {}, after or: {}, after and: try memory_map.put(memory.address, (memory.value | last_mask.or_mask) & last_mask.and_mask); }, } } var sum: u64 = 0; var memory_iter = memory_map.iterator(); while (memory_iter.next()) |entry| { sum += entry.value; } std.debug.print("{}\n", .{sum}); }
2020/day14/zig/day14.zig
const cpu = @import("../cpu/index.zig"); /// commands to send to the vga device cursor pub const Command = enum(u8) { High = 0xE, Low = 0xF, }; /// ports for talking to the vga device cursor pub const Port = enum(u16) { Command = 0x3D4, Data = 0x3D5, }; /// colors for outputting text to the vga device pub const Color = enum(u8) { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magenta = 5, Brown = 6, LightGrey = 7, DarkGrey = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightMagenta = 13, Yellow = 14, White = 15 }; /// the height of the vga textbuffer pub const width = 80; /// the width of the vga textbuffer pub const height = 25; // escape codes for strings const ESCAPES = []u8 { '\n', '\r', '\t' }; // an array mapped to the textbuffer var buffer_ptr = @intToPtr([*]volatile u16, 0xB8000); var buffer = buffer_ptr[0..width * height]; // the current row of the textbuffer's cursor var row: usize = 0; // the current column of the textbuffer's cursor var column: usize = 0; // the current textbuffer background color var background_color: Color = Color.LightGrey; // the current textbuffer foregorund color var foreground_color: Color = Color.Black; // the u8 that represents the current foreground and background color var color_byte: u8 = 0; // returns a u8 that represents the given foreground and background color fn entryColor(fg: Color, bg: Color) u8 { return @enumToInt(fg) | (@enumToInt(bg) << 4); } // returns a u16 that represents the given char and it's color fn entry(char: u8, color: u8) u16 { return @intCast(u16, char) | (@intCast(u16, color) << 8); } fn moveCursor(x: usize, y: usize) void { const pos = @intCast(u16, y * width + x); cpu.io.write(Port.Command, Command.High); cpu.io.write(Port.Data, @truncate(u8, pos >> 8)); cpu.io.write(Port.Command, Command.Low); cpu.io.write(Port.Data, @truncate(u8, pos)); } // updates the cursor's positon fn updateCursor() void { moveCursor(column, row); } /// clears the textbuffer pub fn clear() void { for (buffer) |*byte| { byte.* = entry(' ', color_byte); } } /// init everything we need to use the textbuffer pub fn init() void { color_byte = entryColor(foreground_color, background_color); clear(); updateCursor(); } /// sets the textbuffer's foreground color pub fn setForeGroundColor(color: Color) void { foreground_color = color; color_byte = entryColor(foreground_color, background_color); } /// returns the current foreground color pub fn getForeGroundColor(color: Color) usize { return foreground_color; } /// sets the textbuffer's background color pub fn setBackGroundColor(color: Color) void { background_color = color; color_byte = entryColor(foreground_color, background_color); } /// returns the current background color pub fn getBackGroundColor(color: Color) usize { return background_color; } /// set the foreground and background color at once pub fn setColor(fg: Color, bg: Color) void { foreground_color = fg; background_color = bg; color_byte = entryColor(foreground_color, background_color); } /// try to set the cursor's row pub fn setRow(row: usize) !void { if (row > (width - 1)) { return error.OutOfBounds; } updateCursor(); } /// get the cursor's current row pub fn getRow() usize { return row; } /// try to set the cursor's column pub fn setColumn(column: usize) !void { if (column > (height - 1)) { return error.OutOfBounds; } updateCursor(); } /// get the cursor's current column pub fn getColumn() usize { return column; } // set the textbuffer entry at (x, y) fn putEntryAt(char: u8, x: usize, y: usize) void { buffer[y * width + x] = entry(char, color_byte); } // handles our escape sequences fn handleEscape(char: u8) bool { switch (char) { '\n' => { row += 1; column = 0; }, '\r' => { column = 0; const offset = row * width + column; for (buffer[offset..(offset + width + 1)]) |*byte| { // byte.* = entry(' ', byte_color); byte.* = entry(' ', @enumToInt(Color.Brown)); } }, '\t' => { column += 4; }, else => return false, } return true; } /// place a char in the textbuffer pub fn putChar(char: u8) void { // handle escapes if (!handleEscape(char)) { putEntryAt(char, column, row); column += 1; } // handle newlines/line breaks if (column >= width) { column = 0; row += 1; } // handle scrolling if (row >= height) { const blank = entry(' ', color_byte); const line = (height - 1) * width; for (buffer[0..line]) |*byte, idx| { byte.* = buffer[idx + 80]; } for (buffer[line..(width * height)]) |*byte| { byte.* = blank; } row = height - 1; } // move the cursor as needed updateCursor(); } /// write a string to the textbuffer pub fn write(data: []const u8) void { for (data) |char| { putChar(char); } }
osmium/driver/vga.zig
const std = @import("std"); const assert = std.debug.assert; const x86 = @import("../x86.zig"); pub const TSS = packed struct { _reserved1: u32, rsp: [3]u64, _reserved2: u32, _reserved3: u32, ist: [8]u64, _reserved4: u16, io_map_addr: u16, }; comptime { assert(@sizeOf(TSS) == 104); } pub const PrivilegeLevel = enum(u2) { Ring0 = 0, Ring3 = 3, }; pub const SegmentSelector = struct { raw: u16, pub fn new(_index: u16, _rpl: PrivilegeLevel) SegmentSelector { return .{ .raw = _index << 3 | @enumToInt(_rpl) }; } pub fn index(self: @This()) u16 { return self.raw >> 3; } pub fn rpl(self: @This()) SegmentSelector { return @intToEnum(PrivilegeLevel, self.raw & 0b11); } }; pub fn GlobalDescriptorTable(n: u16) type { return packed struct { entries: [n]Entry align(0x10), free_slot: u16, pub const Entry = packed struct { raw: u64, const WRITABLE = 1 << 41; const CONFORMING = 1 << 42; const EXECUTABLE = 1 << 43; const USER = 1 << 44; const RING_3 = 3 << 45; const PRESENT = 1 << 47; const LONG_MODE = 1 << 53; const DEFAULT_SIZE = 1 << 54; const GRANULARITY = 1 << 55; const LIMIT_LO = 0xffff; const LIMIT_HI = 0xf << 48; const ORDINARY = USER | PRESENT | WRITABLE | LIMIT_LO | LIMIT_HI | GRANULARITY; pub const nil = Entry{ .raw = 0 }; pub const KernelData = Entry{ .raw = ORDINARY | DEFAULT_SIZE }; pub const KernelCode = Entry{ .raw = ORDINARY | EXECUTABLE | LONG_MODE }; pub const UserCode = Entry{ .raw = KernelCode.raw | RING_3 }; pub const UserData = Entry{ .raw = KernelData.raw | RING_3 }; pub fn TaskState(tss: *TSS) [2]Entry { var high: u64 = 0; var ptr = @ptrToInt(tss); var low: u64 = 0; low |= PRESENT; // 64 bit available TSS; low |= 0b1001 << 40; // set limit low |= (@sizeOf(TSS) - 1) & 0xffff; low |= ((ptr >> 24) & 0xff) << 56; // set pointer // 0..24 bits low |= (ptr & 0xffffff) << 16; // high bits part high |= ptr >> 32; return [2]Entry{ .{ .raw = low }, .{ .raw = high } }; } }; const Self = @This(); pub fn new() Self { var gdt = Self{ .entries = std.mem.zeroes([n]Entry), .free_slot = 0 }; return gdt; } pub fn add_entry(self: *Self, entry: Entry) SegmentSelector { assert(self.free_slot < n); self.entries[self.free_slot] = entry; self.free_slot += 1; const dpl = @intToEnum(PrivilegeLevel, @intCast(u2, (entry.raw >> 45) & 0b11)); return SegmentSelector.new(self.free_slot - 1, dpl); } pub fn load(self: Self) void { const descriptor = packed struct { size: u16, base: u64, }{ .base = @ptrToInt(&self.entries), .size = @sizeOf(@TypeOf(self.entries)) - 1, }; x86.lgdt(@ptrToInt(&descriptor)); } pub fn reload_cs(_: Self, selector: SegmentSelector) void { __reload_cs(selector.raw); } }; } extern fn __reload_cs(selector: u32) void; comptime { asm ( \\ .global __reload_cs; \\ .type __reload_cs, @function; \\ __reload_cs: \\ pop %rsi \\ push %rdi \\ push %rsi \\ lretq ); }
kernel/arch/x86/gdt.zig
const regs = @import("rp2040_ras"); pub const IODir = enum { Input, Output, }; pub const Function = enum { F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, NULL, }; pub const GPIO = enum { P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23, P24, P25, P26, P27, P28, P29, }; fn GPIOCtrl(comptime CtrlReg: type) type { _ = CtrlReg; return struct { reg: anytype, const Self = @This(); fn init(ctrl_reg: anytype) Self { return Self{ .reg = ctrl_reg }; } pub fn get_ctrl_reg_for(pin: GPIO) Self { return switch (pin) { GPIO.P0 => init(regs.IO_BANK0.GPIO1_CTRL), GPIO.P1 => init(regs.IO_BANK0.GPIO1_CTRL), GPIO.P2 => init(regs.IO_BANK0.GPIO2_CTRL), GPIO.P3 => init(regs.IO_BANK0.GPIO3_CTRL), GPIO.P4 => init(regs.IO_BANK0.GPIO4_CTRL), GPIO.P5 => init(regs.IO_BANK0.GPIO5_CTRL), GPIO.P6 => init(regs.IO_BANK0.GPIO6_CTRL), GPIO.P7 => init(regs.IO_BANK0.GPIO7_CTRL), GPIO.P8 => init(regs.IO_BANK0.GPIO8_CTRL), GPIO.P9 => init(regs.IO_BANK0.GPIO9_CTRL), GPIO.P10 => init(regs.IO_BANK0.GPIO10_CTRL), GPIO.P11 => init(regs.IO_BANK0.GPIO11_CTRL), GPIO.P12 => init(regs.IO_BANK0.GPIO12_CTRL), GPIO.P13 => init(regs.IO_BANK0.GPIO13_CTRL), GPIO.P14 => init(regs.IO_BANK0.GPIO14_CTRL), GPIO.P15 => init(regs.IO_BANK0.GPIO15_CTRL), GPIO.P16 => init(regs.IO_BANK0.GPIO16_CTRL), GPIO.P17 => init(regs.IO_BANK0.GPIO17_CTRL), GPIO.P18 => init(regs.IO_BANK0.GPIO18_CTRL), GPIO.P19 => init(regs.IO_BANK0.GPIO19_CTRL), GPIO.P20 => init(regs.IO_BANK0.GPIO20_CTRL), GPIO.P21 => init(regs.IO_BANK0.GPIO21_CTRL), GPIO.P22 => init(regs.IO_BANK0.GPIO22_CTRL), GPIO.P23 => init(regs.IO_BANK0.GPIO23_CTRL), GPIO.P24 => init(regs.IO_BANK0.GPIO24_CTRL), GPIO.P25 => init(regs.IO_BANK0.GPIO25_CTRL), GPIO.P26 => init(regs.IO_BANK0.GPIO26_CTRL), GPIO.P27 => init(regs.IO_BANK0.GPIO27_CTRL), GPIO.P28 => init(regs.IO_BANK0.GPIO28_CTRL), GPIO.P29 => init(regs.IO_BANK0.GPIO29_CTRL), }; } }; } pub fn set_dir(comptime pin: GPIO, dir: IODir) void { const gpio_ctrl = GPIOCtrl(@TypeOf(pin)).get_ctrl_reg_for(pin); const ctrl_reg = gpio_ctrl.reg; switch (dir) { IODir.Input => ctrl_reg.modify(.{ .OEOVER = 0x02 }), IODir.Output => ctrl_reg.modify(.{ .OEOVER = 0x03 }), } } pub fn set_function(comptime pin: GPIO, function: Function) void { const gpio_ctrl = GPIOCtrl(@TypeOf(pin)).get_ctrl_reg_for(pin); const ctrl_reg = gpio_ctrl.reg; switch (function) { Function.F0 => ctrl_reg.modify(.{ .FUNCSEL = 0x00 }), Function.F1 => ctrl_reg.modify(.{ .FUNCSEL = 0x01 }), Function.F2 => ctrl_reg.modify(.{ .FUNCSEL = 0x02 }), Function.F3 => ctrl_reg.modify(.{ .FUNCSEL = 0x03 }), Function.F4 => ctrl_reg.modify(.{ .FUNCSEL = 0x04 }), Function.F5 => ctrl_reg.modify(.{ .FUNCSEL = 0x05 }), Function.F6 => ctrl_reg.modify(.{ .FUNCSEL = 0x06 }), Function.F7 => ctrl_reg.modify(.{ .FUNCSEL = 0x07 }), Function.F8 => ctrl_reg.modify(.{ .FUNCSEL = 0x08 }), Function.F9 => ctrl_reg.modify(.{ .FUNCSEL = 0x09 }), Function.NULL => ctrl_reg.modify(.{ .FUNCSEL = 0x1F }), } }
src/hal/gpio.zig
//-------------------------------------------------------------------------------- // Section: Types (1) //-------------------------------------------------------------------------------- pub const OOBE_COMPLETED_CALLBACK = fn( CallbackContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; //-------------------------------------------------------------------------------- // Section: Functions (3) //-------------------------------------------------------------------------------- pub extern "KERNEL32" fn OOBEComplete( isOOBEComplete: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "KERNEL32" fn RegisterWaitUntilOOBECompleted( OOBECompletedCallback: ?OOBE_COMPLETED_CALLBACK, CallbackContext: ?*anyopaque, WaitHandle: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "KERNEL32" fn UnregisterWaitUntilOOBECompleted( WaitHandle: ?*anyopaque, ) 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 (1) //-------------------------------------------------------------------------------- const BOOL = @import("../foundation.zig").BOOL; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "OOBE_COMPLETED_CALLBACK")) { _ = OOBE_COMPLETED_CALLBACK; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/system/setup_and_migration.zig
const std = @import("std"); const input = @embedFile("data/input11"); usingnamespace @import("util.zig"); pub fn main() !void { var allocator_state = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer allocator_state.deinit(); const allocator = &allocator_state.allocator; const part1 = try findFinalOccupied(allocator, input, .adjacent); const part2 = try findFinalOccupied(allocator, input, .first_visible); print("[Part1] Number of occupied seats: {}", .{part1}); print("[Part2] Number of occupied seats: {}", .{part2}); } const floor = '.'; const empty = 'L'; const occupied = '#'; const State = struct { width: usize, height: usize, grids: [2][]u8, curr_grid: usize, next_grid: usize, pub fn init(allocator: *std.mem.Allocator, grid: []const u8) !State { return State { .width = std.mem.indexOf(u8, grid, "\n") orelse return error.InvalidGrid, .height = std.mem.count(u8, grid, "\n"), .grids = [_][]u8 { try std.mem.dupe(allocator, u8, grid), try std.mem.dupe(allocator, u8, grid), }, .curr_grid = 0, .next_grid = 1, }; } pub inline fn getCurrGrid(state: State) []const u8 { return state.grids[state.curr_grid]; } pub inline fn index(state: State, x: usize, y: usize) usize { return y * (state.width + 1) + x; } pub inline fn get(state: State, x: usize, y: usize) u8 { return state.getCurrGrid()[state.index(x, y)]; } pub inline fn setNext(state: *State, x: usize, y: usize, s: u8) void { state.grids[state.next_grid][state.index(x, y)] = s; } pub inline fn switchGrids(state: *State) void { state.curr_grid = (state.curr_grid + 1) & 1; state.next_grid = (state.next_grid + 1) & 1; } }; fn step(state: *State, comptime method: CountMethod) void { var x: usize = 0; while (x < state.width) : (x += 1) { var y: usize = 0; while (y < state.height) : (y += 1) { const s = state.get(x, y); if (s != floor) { const occupied_limit = if (method == .first_visible) 5 else 4; const num_occupied = countOccupiedNeighbours(state.*, x, y, method); const next: u8 = switch (s) { empty => @as(u8, if (num_occupied == 0) occupied else empty), occupied => @as(u8, if (num_occupied >= occupied_limit) empty else occupied), else => unreachable, }; state.setNext(x, y, next); } } } state.switchGrids(); } const CountMethod = enum { adjacent, first_visible }; fn countOccupiedNeighbours(state: State, x: usize, y: usize, comptime method: CountMethod) usize { const offsets_x = [_]isize { -1, 0, 1, -1, 1, -1, 0, 1 }; const offsets_y = [_]isize { -1, -1, -1, 0, 0, 1, 1, 1 }; var count: usize = 0; comptime var i: usize = 0; inline while (i < offsets_x.len) : (i += 1) { var neighbour_x = @intCast(isize, x); var neighbour_y = @intCast(isize, y); inner: while (true) { neighbour_x += offsets_x[i]; neighbour_y += offsets_y[i]; const in_bounds = neighbour_x >= 0 and neighbour_x < state.width and neighbour_y >= 0 and neighbour_y < state.height; const neighbour = if (in_bounds) state.get(@intCast(usize, neighbour_x), @intCast(usize, neighbour_y)) else floor; switch (method) { .adjacent => { count += @boolToInt(neighbour == occupied); break :inner; }, .first_visible => { if (!in_bounds) { break :inner; } if (neighbour != floor) { count += @boolToInt(neighbour == occupied); break :inner; } } } } } return count; } fn findFinalOccupied(allocator: *std.mem.Allocator, initial_grid: []const u8, comptime method: CountMethod) !usize { var state = try State.init(allocator, initial_grid); while (true) { step(&state, method); if (std.mem.eql(u8, state.grids[0], state.grids[1])) { // grid didn't change break; } } var num_occupied: usize = 0; var x: usize = 0; while (x < state.width) : (x += 1) { var y: usize = 0; while (y < state.height) : (y += 1) { const s = state.get(x, y); num_occupied += @boolToInt(s == occupied); } } return num_occupied; } const expectEqualStrings = std.testing.expectEqualStrings; const expectEqual = std.testing.expectEqual; test "step adjacent" { var allocator_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer allocator_state.deinit(); const allocator = &allocator_state.allocator; var state = try State.init(allocator, test_grid_initial); expectEqualStrings(test_grid_initial, state.getCurrGrid()); step(&state, .adjacent); expectEqualStrings(test_grid_step1, state.getCurrGrid()); step(&state, .adjacent); expectEqualStrings(test_grid_step2, state.getCurrGrid()); step(&state, .adjacent); expectEqualStrings(test_grid_step3, state.getCurrGrid()); step(&state, .adjacent); expectEqualStrings(test_grid_step4, state.getCurrGrid()); step(&state, .adjacent); expectEqualStrings(test_grid_step5, state.getCurrGrid()); step(&state, .adjacent); expectEqualStrings(test_grid_step5, state.getCurrGrid()); } test "step first visible" { var allocator_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer allocator_state.deinit(); const allocator = &allocator_state.allocator; var state = try State.init(allocator, test_grid_initial); expectEqualStrings(test_grid_initial, state.getCurrGrid()); step(&state, .first_visible); expectEqualStrings(test_grid_step1_first_visible, state.getCurrGrid()); step(&state, .first_visible); expectEqualStrings(test_grid_step2_first_visible, state.getCurrGrid()); step(&state, .first_visible); expectEqualStrings(test_grid_step3_first_visible, state.getCurrGrid()); step(&state, .first_visible); expectEqualStrings(test_grid_step4_first_visible, state.getCurrGrid()); step(&state, .first_visible); expectEqualStrings(test_grid_step5_first_visible, state.getCurrGrid()); step(&state, .first_visible); expectEqualStrings(test_grid_step6_first_visible, state.getCurrGrid()); step(&state, .first_visible); expectEqualStrings(test_grid_step6_first_visible, state.getCurrGrid()); } test "findFinalOccupied" { var allocator_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer allocator_state.deinit(); const allocator = &allocator_state.allocator; expectEqual(@as(usize, 37), try findFinalOccupied(allocator, test_grid_initial, .adjacent)); expectEqual(@as(usize, 26), try findFinalOccupied(allocator, test_grid_initial, .first_visible)); } const test_grid_initial = \\L.LL.LL.LL \\LLLLLLL.LL \\L.L.L..L.. \\LLLL.LL.LL \\L.LL.LL.LL \\L.LLLLL.LL \\..L.L..... \\LLLLLLLLLL \\L.LLLLLL.L \\L.LLLLL.LL \\ ; const test_grid_step1 = \\#.##.##.## \\#######.## \\#.#.#..#.. \\####.##.## \\#.##.##.## \\#.#####.## \\..#.#..... \\########## \\#.######.# \\#.#####.## \\ ; const test_grid_step2 = \\#.LL.L#.## \\#LLLLLL.L# \\L.L.L..L.. \\#LLL.LL.L# \\#.LL.LL.LL \\#.LLLL#.## \\..L.L..... \\#LLLLLLLL# \\#.LLLLLL.L \\#.#LLLL.## \\ ; const test_grid_step3 = \\#.##.L#.## \\#L###LL.L# \\L.#.#..#.. \\#L##.##.L# \\#.##.LL.LL \\#.###L#.## \\..#.#..... \\#L######L# \\#.LL###L.L \\#.#L###.## \\ ; const test_grid_step4 = \\#.#L.L#.## \\#LLL#LL.L# \\L.L.L..#.. \\#LLL.##.L# \\#.LL.LL.LL \\#.LL#L#.## \\..L.L..... \\#L#LLLL#L# \\#.LLLLLL.L \\#.#L#L#.## \\ ; const test_grid_step5 = \\#.#L.L#.## \\#LLL#LL.L# \\L.#.L..#.. \\#L##.##.L# \\#.#L.LL.LL \\#.#L#L#.## \\..L.L..... \\#L#L##L#L# \\#.LLLLLL.L \\#.#L#L#.## \\ ; const test_grid_step1_first_visible = \\#.##.##.## \\#######.## \\#.#.#..#.. \\####.##.## \\#.##.##.## \\#.#####.## \\..#.#..... \\########## \\#.######.# \\#.#####.## \\ ; const test_grid_step2_first_visible = \\#.LL.LL.L# \\#LLLLLL.LL \\L.L.L..L.. \\LLLL.LL.LL \\L.LL.LL.LL \\L.LLLLL.LL \\..L.L..... \\LLLLLLLLL# \\#.LLLLLL.L \\#.LLLLL.L# \\ ; const test_grid_step3_first_visible = \\#.L#.##.L# \\#L#####.LL \\L.#.#..#.. \\##L#.##.## \\#.##.#L.## \\#.#####.#L \\..#.#..... \\LLL####LL# \\#.L#####.L \\#.L####.L# \\ ; const test_grid_step4_first_visible = \\#.L#.L#.L# \\#LLLLLL.LL \\L.L.L..#.. \\##LL.LL.L# \\L.LL.LL.L# \\#.LLLLL.LL \\..L.L..... \\LLLLLLLLL# \\#.LLLLL#.L \\#.L#LL#.L# \\ ; const test_grid_step5_first_visible = \\#.L#.L#.L# \\#LLLLLL.LL \\L.L.L..#.. \\##L#.#L.L# \\L.L#.#L.L# \\#.L####.LL \\..#.#..... \\LLL###LLL# \\#.LLLLL#.L \\#.L#LL#.L# \\ ; const test_grid_step6_first_visible = \\#.L#.L#.L# \\#LLLLLL.LL \\L.L.L..#.. \\##L#.#L.L# \\L.L#.LL.L# \\#.LLLL#.LL \\..#.L..... \\LLL###LLL# \\#.LLLLL#.L \\#.L#LL#.L# \\ ;
src/day11.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const print = std.debug.print; const input = @embedFile("../input/day14.txt"); fn part1(allocator: *Allocator) !void { var and_mask: u36 = 0; var or_mask: u36 = 0; var mem = try allocator.alloc(u36, 1 << 16); defer allocator.free(mem); std.mem.set(u36, mem, 0); var lines = std.mem.tokenize(input, "\r\n"); while (lines.next()) |line| { if (std.mem.eql(u8, line[0..4], "mask")) { var mask = line[7 .. 7 + 36]; and_mask = 0b111111111111111111111111111111111111; or_mask = 0b000000000000000000000000000000000000; for (mask) |c, i| { const bit: u6 = 35 - @intCast(u6, i); switch (c) { '0' => and_mask &= ~(@as(u36, 1) << bit), '1' => or_mask |= @as(u36, 1) << bit, else => {}, } } } else if (std.mem.eql(u8, line[0..3], "mem")) { var token = std.mem.tokenize(line[4..], "] ="); const address = try std.fmt.parseUnsigned(u16, token.next().?, 10); var value = try std.fmt.parseUnsigned(u36, token.next().?, 10); // apply masks value &= and_mask; value |= or_mask; mem[address] = value; } } var sum: u64 = 0; for (mem) |value| { sum += @as(u64, value); } print("part1: {}\n", .{sum}); } fn enumerateAddresses(mask: []const u8, address: u36, addresses: *std.ArrayList(u36)) void { if (mask.len == 0) { addresses.append(address) catch unreachable; } else { const bit = @intCast(u6, mask.len - 1); switch (mask[0]) { '0' => enumerateAddresses(mask[1..], address, addresses), '1' => enumerateAddresses(mask[1..], address | @as(u36, 1) << bit, addresses), 'X' => { enumerateAddresses(mask[1..], address & ~(@as(u36, 1) << bit), addresses); enumerateAddresses(mask[1..], address | @as(u36, 1) << bit, addresses); }, else => {}, } } } fn part2(allocator: *Allocator) !void { var mem = std.AutoHashMap(u64, u36).init(allocator); // if I use u36 as key, garbage data will be hashed defer mem.deinit(); var mask: []const u8 = undefined; var lines = std.mem.tokenize(input, "\r\n"); while (lines.next()) |line| { if (std.mem.eql(u8, line[0..4], "mask")) { mask = line[7 .. 7 + 36]; } else if (std.mem.eql(u8, line[0..3], "mem")) { var token = std.mem.tokenize(line[4..], "] ="); const address = try std.fmt.parseUnsigned(u16, token.next().?, 10); var value = try std.fmt.parseUnsigned(u36, token.next().?, 10); var addresses = std.ArrayList(u36).init(allocator); defer addresses.deinit(); enumerateAddresses(mask, address, &addresses); for (addresses.items) |a| { try mem.put(@as(u64, a), value); } } } var sum: u64 = 0; var iter = mem.iterator(); while (iter.next()) |entry| { sum += @as(u64, entry.value); } print("part2: {}\n", .{sum}); } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = &gpa.allocator; try part1(allocator); try part2(allocator); } const example = \\mask = 000000000000000000000000000000X1001X \\mem[42] = 100 \\mask = 00000000000000000000000000000000X0XX \\mem[26] = 1 ;
src/day14.zig
const types = @import("protocol/types.zig"); pub const Server = struct { pub fn DidChangeWorkspaceFolders(self: *Server, param: *DidChangeWorkspaceFoldersParams) !void {} pub fn Initialized(self: *Server, param: *InitializedParams) !void {} pub fn Exit(self: *Server) !void {} pub fn DidChangeConfiguration(self: *Server, param: *DidChangeConfigurationParams) !void {} pub fn DidOpen(self: *Server, param: *DidOpenTextDocumentParams) !void {} pub fn DidChange(self: *Server, param: *DidChangeTextDocumentParams) !void {} pub fn DidClose(self: *Server, param: *DidCloseTextDocumentParams) !void {} pub fn DidSave(self: *Server, param: *DidSaveTextDocumentParams) !void {} pub fn WillSave(self: *Server, param: *WillSaveTextDocumentParams) !void {} pub fn DidChangeWatchedFiles(self: *Server, param: *DidChangeWatchedFilesParams) !void {} pub fn SetTraceNotification(self: *Server, param: *SetTraceParams) !void {} pub fn LogTraceNotification(self: *Server, param: *LogTraceParams) !void {} pub fn Implementation(self: *Server, param: *TextDocumentPositionParams) !ArrayList(Location) {} pub fn TypeDefinition(self: *Server, param: *TextDocumentPositionParams) !ArrayList(Location) {} pub fn DocumentColor(self: *Server, param: *DocumentColorParams) !ArrayList(ColorInformation) {} pub fn ColorPresentation(self: *Server, param: *ColorPresentationParams) !ArrayList(ColorPresentation) {} pub fn FoldingRange(self: *Server, param: *FoldingRangeParams) !ArrayList(FoldingRange) {} pub fn Declaration(self: *Server, param: *TextDocumentPositionParams) !ArrayList(DeclarationLink) {} pub fn SelectionRange(self: *Server, param: *SelectionRangeParams) !ArrayList(SelectionRange) {} pub fn Initialize(self: *Server, param: *InitializeParams) !*InitializeResult {} pub fn Shutdown(self: *Server) !void {} pub fn WillSaveWaitUntil(self: *Server, param: *WillSaveTextDocumentParams) ArrayList(TextEdit) {} pub fn Completion(self: *Server, param: *CompletionParams) !*CompletionList {} pub fn Resolve(self: *Server, param: *CompletionItem) !*CompletionItem {} pub fn Hover(self: *Server, param: *TextDocumentPositionParams) !*Hover {} pub fn SignatureHelp(self: *Server, param: *TextDocumentPositionParams) !*SignatureHelp {} pub fn Definition(self: *Server, param: *TextDocumentPositionParams) !ArrayList(Location) {} pub fn References(self: *Server, param: *ReferenceParams) !ArrayList(Location) {} pub fn DocumentHighlight(self: *Server, param: *TextDocumentPositionParams) !ArrayList(DocumentHighlight) {} pub fn DocumentSymbol(self: *Server, param: *DocumentSymbolParams) !ArrayList(DocumentSymbol) {} pub fn Symbol(self: *Server, param: *WorkspaceSymbolParams) !ArrayList(SymbolInformation) {} pub fn CodeAction(self: *Server, param: *CodeActionParams) !ArrayList(CodeAction) {} pub fn CodeLens(self: *Server, param: *CodeLensParams) !ArrayList(CodeLens) {} pub fn ResolveCodeLens(self: *Server, param: *CodeLens) !*CodeLens {} pub fn Formatting(self: *Server, param: *DocumentFormattingParams) !ArrayList(TextEdit) {} pub fn RangeFormatting(self: *Server, param: *DocumentRangeFormattingParams) !ArrayList(TextEdit) {} pub fn OnTypeFormatting(self: *Server, param: *DocumentOnTypeFormattingParams) !ArrayList(TextEdit) {} pub fn Rename(self: *Server, param: *RenameParams) !*WorkspaceEdit {} pub fn PrepareRename(self: *Server, param: *TextDocumentPositionParams) !*Range {} pub fn DocumentLink(self: *Server, param: *DocumentLinkParams) !ArrayList(DocumentLink) {} pub fn ResolveDocumentLink(self: *Server, param: *DocumentLink) !*DocumentLink {} pub fn ExecuteCommand(self: *Server, param: *ExecuteCommandParams) !json.Value {} };
src/lsp/server/server.zig
const std = @import("std"); const wasmtime = @import("wasmtime"); const builtin = std.builtin; const fs = std.fs; const ga = std.heap.c_allocator; const Allocator = std.mem.Allocator; pub fn main() !void { const wasm_path = if (builtin.os.tag == .windows) "examples\\linking1.wat" else "examples/linking1.wat"; const wasm_path2 = if (builtin.os.tag == .windows) "examples\\linking2.wat" else "examples/linking2.wat"; const wasm_file = try fs.cwd().openFile(wasm_path, .{}); defer wasm_file.close(); const wasm_file2 = try fs.cwd().openFile(wasm_path2, .{}); defer wasm_file2.close(); const wasm = try wasm_file.readToEndAlloc(ga, std.math.maxInt(u64)); defer ga.free(wasm); const wasm2 = try wasm_file2.readToEndAlloc(ga, std.math.maxInt(u64)); defer ga.free(wasm2); const engine = try wasmtime.Engine.init(); defer engine.deinit(); std.debug.print("Engine initialized...\n", .{}); const module = try wasmtime.Module.initFromWat(engine, wasm); defer module.deinit(); const module2 = try wasmtime.Module.initFromWat(engine, wasm2); defer module2.deinit(); const store = try wasmtime.Store.init(engine); defer store.deinit(); std.debug.print("Store initialized...\n", .{}); // intantiate wasi const config = try wasmtime.WasiConfig.init(); config.inherit(.{}); var trap: ?*wasmtime.Trap = null; const wasi = try wasmtime.WasiInstance.init(store, "wasi_snapshot_preview1", config, &trap); if (trap) |t| { std.debug.print("Unexpected trap during WasiInstance initialization\n", .{}); t.deinit(); return; } defer wasi.deinit(); std.debug.print("wasi instance initialized...\n", .{}); // create our linker and then add our WASI instance to it. const linker = try wasmtime.Linker.init(store); defer linker.deinit(); if (linker.defineWasi(wasi)) |err| { var msg = err.getMessage(); defer msg.deinit(); std.debug.print("Linking init err: '{s}'\n", .{msg.toSlice()}); return; } // Instantiate `linking2` with our linker. var linking2: ?*wasmtime.wasm.Instance = null; const link_error2 = linker.instantiate(module2, &linking2, &trap); if (trap) |t| { std.debug.print("Unexpected trap during linker initialization\n", .{}); t.deinit(); return; } if (link_error2) |err| { var msg = err.getMessage(); defer msg.deinit(); std.debug.print("Linker instantiate err: '{s}'\n", .{msg.toSlice()}); return; } // Register our new `linking2` instance with the linker const name = wasmtime.NameVec.fromSlice("linking2"); if (linker.defineInstance(&name, linking2.?)) |err| { var msg = err.getMessage(); defer msg.deinit(); std.debug.print("Define instance err: '{s}'\n", .{msg.toSlice()}); return; } var instance: ?*wasmtime.wasm.Instance = undefined; if (linker.instantiate(module, &instance, &trap)) |err| { var msg = err.getMessage(); defer msg.deinit(); std.debug.print("Instantiate err: '{s}'\n", .{msg.toSlice()}); return; } if (trap) |t| { std.debug.print("Unexpected trap during linker initialization\n", .{}); t.deinit(); return; } defer instance.?.deinit(); std.debug.print("Instance initialized...\n", .{}); std.debug.print("Wasm linking completed...\n", .{}); if (instance.?.getExportFunc(module.inner, "run")) |f| { std.debug.print("Calling export...\n", .{}); try f.call(void, .{}); } else { std.debug.print("Export not found...\n", .{}); } }
examples/linking.zig
const std = @import("std"); usingnamespace @import("utils.zig"); const app = @import("app.zig"); const log = std.log; pub const log_level = if (std.builtin.mode == .Debug) .debug else .info; const Allocator = std.mem.Allocator; pub const PipelineShaderInfo = struct { filename: []const u8, spirv: bool, stage: vk.ShaderStageFlagBits, }; pub var manageFramebuffer = true; pub var enableValidationLayers = true; pub var quitSignaled = false; const sampleCountFlag = .SAMPLE_COUNT_1_BIT; fn extendName(comptime name: []const u8) [256]u8 { var x = [1]u8{0} ** 256; var i: usize = 0; while (i < 256 and i < name.len) : (i += 1) { x[i] = name[i]; } return x; } var window: *c.Window = undefined; var windowWidth: i32 = 600; var windowHeight: i32 = 400; var instance: vk.Instance = undefined; var physicalDevice: vk.PhysicalDevice = null; var surface: vk.SurfaceKHR = null; var device: vk.Device = null; var swapchain: vez.Swapchain = null; var keyMap: [c.KEY_LAST]bool = std.mem.zeroes([c.KEY_LAST]bool); var callbacks: Callbacks = undefined; pub fn getInstance() vk.Instance { return instance; } pub fn getPhysicalDevice() vk.PhysicalDevice { return physicalDevice; } pub fn getDevice() vk.Device { return device; } pub fn getSwapchain() vez.Swapchain { return swapchain; } pub fn getWindow() *c.Window { return window; } pub fn getWindowSize() [2]u32 { return .{ @intCast(u32, windowWidth), @intCast(u32, windowHeight) }; } // pub fn hasWindowResized() bool { // var new_width: i32 = 0; // var new_height: i32 = 0; // c.glfwGetWindowSize(window, &new_width, &new_height); // return new_width != windowWidth or new_height != windowHeight; // } pub fn getCursorPos() [2]i32 { var x: f64 = 0; var y: f64 = 0; c.glfwGetCursorPos(window, &x, &y); return .{ @floatToInt(i32, x), @floatToInt(i32, y) }; } pub fn getKey(key: c_int) bool { return keyMap[@intCast(usize, key)]; } pub fn roundUp(a: u32, b: u32) u32 { return (a + b - 1) / b; } var previous_size: [2]i32 = undefined; pub fn toggleFullscreen() void { if (c.glfwGetWindowMonitor(window)) |_| { c.glfwSetWindowMonitor(window, null, 0, 0, previous_size[0], previous_size[1], c.DONT_CARE); } else { previous_size[0] = windowWidth; previous_size[1] = windowHeight; const m = c.glfwGetPrimaryMonitor(); const vidmode: *const c.Vidmode = c.glfwGetVideoMode(m); c.glfwSetWindowMonitor(window, m, 0, 0, vidmode.width, vidmode.height, c.DONT_CARE); } } pub var framebuffer = FrameBuffer{}; const FrameBuffer = struct { colorImage: vk.Image = null, colorImageView: vk.ImageView = null, depthStencilImage: vk.Image = null, depthStencilImageView: vk.ImageView = null, handle: vez.Framebuffer = null, fn deinit(self: FrameBuffer, dev: vk.Device) void { if (self.handle) |hndl| { vez.destroyFramebuffer(dev, self.handle); vez.destroyImageView(dev, self.colorImageView); vez.destroyImageView(dev, self.depthStencilImageView); vez.destroyImage(dev, self.colorImage); vez.destroyImage(dev, self.depthStencilImage); } } }; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; // defer _ = gpa.deinit(); const allocator = &gpa.allocator; const stdout = std.io.getStdOut().writer(); var availableLayers = try getInstanceLayers(allocator); defer availableLayers.deinit(); if (c.glfwInit() != c.TRUE) { return error.CouldNotInitGlfw; } if (c.glfwVulkanSupported() != c.TRUE) { log.crit("No GLFW-Vulkan support", .{}); return; } var instanceExtensionCount: u32 = 0; var instanceExtensions = c.glfwGetRequiredInstanceExtensions(&instanceExtensionCount)[0..instanceExtensionCount]; var instanceLayers = std.ArrayList([*:0]const u8).init(allocator); defer instanceLayers.deinit(); if (enableValidationLayers) { if (availableLayers.contains(extendName("VK_LAYER_KHRONOS_validation"))) { try instanceLayers.append("VK_LAYER_KHRONOS_validation"); } else if (availableLayers.contains(extendName("VK_LAYER_LUNARG_standard_validation"))) { try instanceLayers.append("VK_LAYER_LUNARG_standard_validation"); } else { log.warn("Did not find a Vulkan validation layer.", .{}); } } var result: vk.Result = undefined; var appInfo = vez.ApplicationInfo{ .pApplicationName = app.app_title, .applicationVersion = makeVkVersion(1, 0, 0), .pEngineName = "ADF custom", .engineVersion = makeVkVersion(0, 0, 0), }; var createInfo = vez.InstanceCreateInfo{ .pApplicationInfo = &appInfo, .enabledLayerCount = @intCast(u32, instanceLayers.items.len), .ppEnabledLayerNames = instanceLayers.items.ptr, .enabledExtensionCount = instanceExtensionCount, .ppEnabledExtensionNames = instanceExtensions.ptr, }; try convert(vez.createInstance(&createInfo, &instance)); // Enumerate all attached physical devices. var physicalDeviceCount: u32 = 0; try convert(vez.enumeratePhysicalDevices(instance, &physicalDeviceCount, null)); if (physicalDeviceCount == 0) { return error.NoPhysicalDeviceFound; } var physicalDevices = try allocator.alloc(vk.PhysicalDevice, physicalDeviceCount); defer allocator.free(physicalDevices); try convert(vez.enumeratePhysicalDevices(instance, &physicalDeviceCount, physicalDevices.ptr)); const chosenDevice = 0; for (physicalDevices) |pdevice, i| { const name = @ptrCast([*:0]const u8, &props(pdevice).deviceName); if (i == chosenDevice) { log.debug("-> {s}\n", .{name}); } else { log.debug(" {s}\n", .{name}); } } physicalDevice = physicalDevices[chosenDevice]; // Create the Vulkan device handle. var deviceExtensions: []const [*:0]const u8 = &[_][*:0]const u8{vk.KHR_SWAPCHAIN_EXTENSION_NAME}; var deviceCreateInfo = vez.DeviceCreateInfo{ .enabledLayerCount = 0, .ppEnabledLayerNames = null, .enabledExtensionCount = @intCast(u32, deviceExtensions.len), .ppEnabledExtensionNames = deviceExtensions.ptr, }; try convert(vez.createDevice(physicalDevice, &deviceCreateInfo, &device)); try app.load(allocator); c.glfwWindowHint(c.CLIENT_API, c.NO_API); window = c.glfwCreateWindow(windowWidth, windowHeight, app.app_title, null, null) orelse return error.FailedToCreateWindow; _ = c.glfwSetWindowSizeCallback(window, windowSizeCallback); _ = c.glfwSetMouseButtonCallback(window, mouseButtonCallback); _ = c.glfwSetKeyCallback(window, keyCallback); // Create a surface from the GLFW window handle and create a swapchain for it. try convert(c.glfwCreateWindowSurface(instance, window, null, &surface)); const format = .{ .format = .FORMAT_B8G8R8A8_UNORM, .colorSpace = .COLOR_SPACE_SRGB_NONLINEAR_KHR }; var swapchainCreateInfo = vez.SwapchainCreateInfo{ .surface = surface, .format = format, .tripleBuffer = vk.TRUE, }; try convert(vez.createSwapchain(device, &swapchainCreateInfo, &swapchain)); try convert(vez.vezSwapchainSetVSync(swapchain, vk.FALSE)); if (manageFramebuffer) { try createFramebuffer(); } try app.initialize(allocator); var last_time = c.glfwGetTime(); var elapsed_time: f64 = 0; var frameCount: u32 = 0; // Message loop. while (!shouldQuit()) { // Check for window messages to process. c.glfwPollEvents(); // Update the application. var cur_time = c.glfwGetTime(); cur_time = c.glfwGetTime(); var delta = cur_time - last_time; last_time = cur_time; elapsed_time += delta; try app.update(@floatCast(f32, delta)); try app.draw(); // Display the fps in the window title bar. frameCount += 1; if (elapsed_time >= 1.0) { const size = getWindowSize(); const fps = @intToFloat(f64, frameCount) / elapsed_time; const nspp = 1000_000_000.0 / fps / @intToFloat(f64, size[0] * size[1]); const text = try std.fmt.allocPrintZ(allocator, "{s} ({d:.1} FPS, {d:.1} nspp)", .{ app.app_title, fps, nspp }); defer allocator.free(text); c.glfwSetWindowTitle(window, text.ptr); elapsed_time = 0.0; frameCount = 0; } } try convert(vez.deviceWaitIdle(device)); try app.cleanup(); if (manageFramebuffer) { framebuffer.deinit(device); } vez.destroySwapchain(device, swapchain); vez.destroyDevice(device); vk.vkDestroySurfaceKHR(instance, surface, null); vez.destroyInstance(instance); } pub fn createFramebuffer() !void { framebuffer.deinit(device); var size = getWindowSize(); var swapchainFormat: vk.SurfaceFormatKHR = undefined; vez.getSwapchainSurfaceFormat(swapchain, &swapchainFormat); // Create the color image for the framebuffer. var imageCreateInfo = vez.ImageCreateInfo{ .format = swapchainFormat.format, .extent = .{ .width = size[0], .height = size[1], .depth = 1 }, .samples = sampleCountFlag, .tiling = .IMAGE_TILING_OPTIMAL, .usage = vk.IMAGE_USAGE_TRANSFER_SRC_BIT | vk.IMAGE_USAGE_TRANSFER_DST_BIT | vk.IMAGE_USAGE_COLOR_ATTACHMENT_BIT, }; try convert(vez.createImage(device, vez.MEMORY_GPU_ONLY, &imageCreateInfo, &framebuffer.colorImage)); // Create the image view for binding the texture as a resource. var imageViewCreateInfo = vez.ImageViewCreateInfo{ .image = framebuffer.colorImage, .viewType = .IMAGE_VIEW_TYPE_2D, .format = imageCreateInfo.format, }; try convert(vez.createImageView(device, &imageViewCreateInfo, &framebuffer.colorImageView)); // Create the depth image for the m_framebuffer. imageCreateInfo.format = .FORMAT_D32_SFLOAT; imageCreateInfo.extent = vk.Extent3D{ .width = size[0], .height = size[1], .depth = 1 }; imageCreateInfo.usage = vk.IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; try convert(vez.createImage(device, vez.MEMORY_GPU_ONLY, &imageCreateInfo, &framebuffer.depthStencilImage)); // Create the image view for binding the texture as a resource. imageViewCreateInfo.image = framebuffer.depthStencilImage; imageViewCreateInfo.viewType = .IMAGE_VIEW_TYPE_2D; imageViewCreateInfo.format = imageCreateInfo.format; try convert(vez.createImageView(device, &imageViewCreateInfo, &framebuffer.depthStencilImageView)); // Create the m_framebuffer. var attachments: []vk.ImageView = &[_]vk.ImageView{ framebuffer.colorImageView, framebuffer.depthStencilImageView }; const framebufferCreateInfo = vez.FramebufferCreateInfo{ .attachmentCount = @intCast(u32, attachments.len), .pAttachments = attachments.ptr, .width = size[0], .height = size[1], .layers = 1, }; try convert(vez.createFramebuffer(device, &framebufferCreateInfo, &framebuffer.handle)); } fn createShaderModule(allocator: *Allocator, filename: []const u8, spirv: bool, entryPoint: []const u8, stage: vk.ShaderStageFlagBits) !vk.ShaderModule { // Load the GLSL shader code from disk. var file = try std.fs.cwd().openFile(filename, .{}); const len = try file.getEndPos(); const code = try allocator.alignedAlloc(u8, @alignOf(u32), len); defer allocator.free(code); const readlen = try file.read(code); if (readlen != len) return error.CouldNotReadShaderFile; file.close(); // Create the shader module. var createInfo = vez.ShaderModuleCreateInfo{ .stage = stage, .codeSize = code.len, .pEntryPoint = entryPoint.ptr, .pCode = null, .pGLSLSource = null, }; if (spirv) { createInfo.pCode = @ptrCast([*]const u32, code.ptr); } else { createInfo.pGLSLSource = code.ptr; } var shaderModule: vk.ShaderModule = null; var result = vez.createShaderModule(device, &createInfo, &shaderModule); if (result != .SUCCESS) { if (shaderModule == null) return error.CouldNotCreateShader; // If shader module creation failed but error is from GLSL compilation, get the error log. var infoLogSize: u32 = 0; vez.getShaderModuleInfoLog(shaderModule, &infoLogSize, null); var infoLog = try allocator.alloc(u8, infoLogSize); std.mem.set(u8, infoLog, 0); vez.getShaderModuleInfoLog(shaderModule, &infoLogSize, &infoLog[0]); vez.destroyShaderModule(device, shaderModule); log.err("{s}\n", .{infoLog}); return error.CouldNotCompile; } return shaderModule; } pub fn createPipeline(allocator: *Allocator, pipelineShaderInfo: []const PipelineShaderInfo, pPipeline: *vez.Pipeline, shaderModules: []vk.ShaderModule) !void { // Create shader modules. var shaderStageCreateInfo = try allocator.alloc(vez.PipelineShaderStageCreateInfo, pipelineShaderInfo.len); defer allocator.free(shaderStageCreateInfo); var exe_path: []const u8 = try std.fs.selfExeDirPathAlloc(allocator); defer allocator.free(exe_path); for (pipelineShaderInfo) |info, i| { var filename = try std.fs.path.join(allocator, &[_][]const u8{ exe_path, "shaders", info.filename }); defer allocator.free(filename); var shaderModule = try createShaderModule(allocator, filename, info.spirv, "main", info.stage); shaderStageCreateInfo[i] = .{ .module = shaderModule, .pEntryPoint = "main", .pSpecializationInfo = null, }; shaderModules[i] = shaderModule; } // Determine if this is a compute only pipeline. var isComputePipeline: bool = pipelineShaderInfo.len == 1 and pipelineShaderInfo[0].stage == .SHADER_STAGE_COMPUTE_BIT; // Create the graphics pipeline or compute pipeline. if (isComputePipeline) { const pipelineCreateInfo = vez.ComputePipelineCreateInfo{ .pStage = shaderStageCreateInfo.ptr, }; try convert(vez.createComputePipeline(device, &pipelineCreateInfo, pPipeline)); } else { const pipelineCreateInfo = vez.GraphicsPipelineCreateInfo{ .stageCount = @intCast(u32, shaderStageCreateInfo.len), .pStages = shaderStageCreateInfo.ptr, }; try convert(vez.createGraphicsPipeline(device, &pipelineCreateInfo, pPipeline)); } } pub fn cmdSetFullViewport() void { var size = getWindowSize(); const viewport = vk.Viewport{ .width = @intToFloat(f32, size[0]), .height = @intToFloat(f32, size[1]), }; const scissor = vk.Rect2D{ .offset = .{ .x = 0, .y = 0 }, .extent = .{ .width = size[0], .height = size[1] }, }; vez.cmdSetViewport(0, 1, &[_]vk.Viewport{viewport}); vez.cmdSetScissor(0, 1, &[_]vk.Rect2D{scissor}); } fn props(dev: vk.PhysicalDevice) vk.PhysicalDeviceProperties { var properties: vk.PhysicalDeviceProperties = undefined; vez.getPhysicalDeviceProperties(dev, &properties); return properties; } fn shouldQuit() bool { return c.glfwWindowShouldClose(window) != 0 or quitSignaled; } export fn windowSizeCallback(wndw: ?*c.Window, width: c_int, height: c_int) callconv(.C) void { resize() catch |err| log.err("resize failed: {}", .{err}); } pub fn resize() !void { c.glfwGetWindowSize(window, &windowWidth, &windowHeight); try convert(vk.vkDeviceWaitIdle(device)); if (manageFramebuffer) { try createFramebuffer(); } try app.onResize(@intCast(u32, windowWidth), @intCast(u32, windowHeight)); } export fn mouseButtonCallback(wndw: ?*c.Window, button: c_int, action: c_int, mods: c_int) void { var p = getCursorPos(); switch (action) { c.PRESS => app.onMouseButton(@intCast(i32, button), true, p[0], p[1]) catch unreachable, c.RELEASE => app.onMouseButton(@intCast(i32, button), false, p[0], p[1]) catch unreachable, else => return, } } export fn keyCallback(wndw: ?*c.Window, key: c_int, scancode: c_int, action: c_int, mods: c_int) void { var p = getCursorPos(); var press = switch (action) { c.PRESS => true, c.RELEASE => false, else => return, }; if (key == c.KEY_UNKNOWN) return; keyMap[@intCast(usize, key)] = press; app.onKey(@intCast(i32, key), press) catch unreachable; }
src/main.zig
const std = @import("std"); const Allocator = std.mem.Allocator; pub fn RingBuffer(comptime T: type) type { return struct { const Self = @This(); const Iterator = struct { target: *Self, direction: enum { forward, backward }, index: usize, pub fn next(self: *Iterator) ?*T { if (self.index >= self.target.len()) return null; const real_index = if (self.direction == .forward) self.index else self.target.len() - 1 - self.index; if (self.target.get(real_index)) |item| { self.index += 1; return item; } return null; } }; allocator: Allocator, buffer: []T = &[_]T{}, head: usize = 0, tail: usize = 0, _len: usize = 0, /// Initialize a new buffer, no allocations are made until a `push*` method is called pub fn init(allocator: Allocator) Self { return .{ .allocator = allocator }; } /// Initialize a new buffer that will be able to hold at least `num` items before allocating. pub fn initCapacity(allocator: Allocator, num: usize) !Self { var new = Self.init(allocator); try new.ensureTotalCapacityPrecise(num); return new; } /// Get the number of items that this buffer can hold before a reallocation is made. pub fn capacity(self: *const Self) usize { return self.buffer.len; } /// Get the numbers of items the buffer currently holds pub fn len(self: *const Self) usize { return self._len; } /// Reset without freeing memory pub fn clearRetainingCapacity(self: *Self) void { self._len = 0; self.head = 0; self.tail = 0; } /// Reset all internal fields and free the buffer. pub fn deinit(self: *Self) void { self.clearRetainingCapacity(); if (self.capacity() > 0) { self.allocator.free(self.buffer); self.buffer.len = 0; } } /// Ensure the internal buffer can hold at least `needed` more elements, and reallocate if it can't. pub fn ensureUnusedCapacity(self: *Self, needed: usize) !void { return self.ensureTotalCapacity(self.capacity() + needed); } /// Grow the internal buffer to hold at least `target_capacity` pub fn ensureTotalCapacity(self: *Self, target_capacity: usize) !void { // Using the same algorithm for finding a better capacity as std.ArrayList (as of zig v0.9.0) if (target_capacity < self.capacity()) return; var better_capacity = self.capacity(); while(true) { better_capacity += better_capacity / 2 + 8; if (better_capacity >= target_capacity) break; } return self.ensureTotalCapacityPrecise(better_capacity); } /// Grow the internal buffer to hold as close to `new_capacity` items as possible. /// It may hold more depending on the allocators realloc implementation pub fn ensureTotalCapacityPrecise(self: *Self, new_capacity: usize) !void { const old_capacity = self.capacity(); if (old_capacity >= new_capacity) return; const new_buffer = try self.allocator.reallocAtLeast(self.buffer, new_capacity); self.buffer = new_buffer; // The buffer can be in three possible states // 1) The head is at the end of the buffer // 2) The head is closer to the start than the tail is to the end // 3) The tail is closer to the end than the head is to the start // Nothing needs to be done for case 1), // it means the buffer looks similar to a normal array if (self.tail < self.head) return; if (self.head < old_capacity - self.tail) { // case 2) // unwrap the head, moving after the tail if (self.head > 0) std.mem.copy(T, self.buffer[old_capacity..], self.buffer[0..self.head]); self.head = old_capacity + self.head; } else if (self.head > old_capacity - self.tail) { // case 3) // shift the tail to the end of the array const new_tail = new_capacity - (old_capacity - self.tail); std.mem.copy(T, self.buffer[new_tail..], self.buffer[self.tail..old_capacity]); self.tail = new_tail; } } /// Add an item at the end of the buffer pub fn pushBack(self: *Self, item: T) !void { if (self.len() == self.capacity()) try self.ensureUnusedCapacity(1); self.buffer[self.head] = item; self.head = (self.head + 1) % self.capacity(); self._len += 1; } /// Remove the last item in the buffer, or null if its empty pub fn popBack(self: *Self) ?T { if (self.len() == 0) return null; if (self.head == 0) self.head = self.capacity(); self.head -= 1; self._len -= 1; return self.buffer[self.head]; } /// Add an item at the start of the buffer pub fn pushFront(self: *Self, item: T) !void { if (self.len() == self.capacity()) try self.ensureUnusedCapacity(1); if (self.tail == 0) self.tail = self.capacity(); self.tail -= 1; self._len += 1; self.buffer[self.tail] = item; } /// Remove the first item in the buffer, or null if its empty pub fn popFront(self: *Self) ?T { if (self.len() == 0) return null; const data = self.buffer[self.tail]; self.tail = (self.tail + 1) % self.capacity(); self._len -= 1; return data; } /// Get an item by index from the buffer pub fn get(self: *Self, i: usize) ?*T { if (i >= self.len()) return null; return &self.buffer[(self.tail + i) % self.capacity()]; } /// Returns a new `Iterator` instance, for easy use with a while loop pub fn iter(self: *Self) Iterator { return .{ .direction = .forward, .target = self, .index = 0, }; } /// Same as `iter()` but iterates backwards from the end of a buffer pub fn iterReverse(self: *Self) Iterator { return .{ .direction = .backward, .target = self, .index = 0, }; } }; } test "RingBuffer: pushBack / popBack" { { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); try std.testing.expectEqual(ring.len(), 0); try ring.pushBack(1); try std.testing.expectEqual(ring.len(), 1); try ring.pushBack(2); try std.testing.expectEqual(ring.len(), 2); try ring.pushBack(3); try std.testing.expectEqual(ring.len(), 3); try ring.pushBack(4); try std.testing.expectEqual(ring.len(), 4); try std.testing.expectEqual(ring.popBack(), 4); try std.testing.expectEqual(ring.len(), 3); try std.testing.expectEqual(ring.popBack(), 3); try std.testing.expectEqual(ring.len(), 2); try std.testing.expectEqual(ring.popBack(), 2); try std.testing.expectEqual(ring.len(), 1); try std.testing.expectEqual(ring.popBack(), 1); try std.testing.expectEqual(ring.len(), 0); try std.testing.expectEqual(ring.popBack(), null); } { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); try ring.pushBack(1); try std.testing.expectEqual(ring.len(), 1); try ring.pushBack(2); try std.testing.expectEqual(ring.len(), 2); try std.testing.expectEqual(ring.popBack(), 2); try std.testing.expectEqual(ring.len(), 1); try std.testing.expectEqual(ring.popBack(), 1); try std.testing.expectEqual(ring.len(), 0); try ring.pushBack(3); try std.testing.expectEqual(ring.len(), 1); try std.testing.expectEqual(ring.popBack(), 3); try std.testing.expectEqual(ring.len(), 0); try ring.pushBack(4); try std.testing.expectEqual(ring.len(), 1); try std.testing.expectEqual(ring.popBack(), 4); try std.testing.expectEqual(ring.len(), 0); try std.testing.expectEqual(ring.popBack(), null); try std.testing.expectEqual(ring.popBack(), null); try std.testing.expectEqual(ring.popBack(), null); } } test "RingBuffer: pushFront / popFront" { { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); try std.testing.expectEqual(ring.len(), 0); try ring.pushFront(1); try std.testing.expectEqual(ring.len(), 1); try ring.pushFront(2); try std.testing.expectEqual(ring.len(), 2); try ring.pushFront(3); try std.testing.expectEqual(ring.len(), 3); try ring.pushFront(4); try std.testing.expectEqual(ring.len(), 4); try std.testing.expectEqual(ring.popFront(), 4); try std.testing.expectEqual(ring.len(), 3); try std.testing.expectEqual(ring.popFront(), 3); try std.testing.expectEqual(ring.len(), 2); try std.testing.expectEqual(ring.popFront(), 2); try std.testing.expectEqual(ring.len(), 1); try std.testing.expectEqual(ring.popFront(), 1); try std.testing.expectEqual(ring.len(), 0); try std.testing.expectEqual(ring.popFront(), null); } { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); try ring.pushFront(1); try std.testing.expectEqual(ring.len(), 1); try ring.pushFront(2); try std.testing.expectEqual(ring.len(), 2); try std.testing.expectEqual(ring.popFront(), 2); try std.testing.expectEqual(ring.len(), 1); try std.testing.expectEqual(ring.popFront(), 1); try std.testing.expectEqual(ring.len(), 0); try ring.pushFront(3); try std.testing.expectEqual(ring.len(), 1); try std.testing.expectEqual(ring.popFront(), 3); try std.testing.expectEqual(ring.len(), 0); try ring.pushFront(4); try std.testing.expectEqual(ring.len(), 1); try std.testing.expectEqual(ring.popFront(), 4); try std.testing.expectEqual(ring.len(), 0); try std.testing.expectEqual(ring.popFront(), null); try std.testing.expectEqual(ring.popFront(), null); try std.testing.expectEqual(ring.popFront(), null); } } test "RingBuffer: append to back and front" { { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); try ring.pushFront(1); try ring.pushBack(2); try ring.pushFront(3); try ring.pushBack(4); try ring.pushFront(5); try ring.pushBack(6); try ring.pushFront(7); try ring.pushBack(8); try std.testing.expectEqual(ring.len(), 8); try std.testing.expectEqual(ring.popBack(), 8); try std.testing.expectEqual(ring.popFront(), 7); try std.testing.expectEqual(ring.popBack(), 6); try std.testing.expectEqual(ring.popFront(), 5); try std.testing.expectEqual(ring.popBack(), 4); try std.testing.expectEqual(ring.popFront(), 3); try std.testing.expectEqual(ring.popBack(), 2); try std.testing.expectEqual(ring.popFront(), 1); } } test "RingBuffer: realloc with tail before head" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); try ring.pushBack(1); try ring.pushBack(2); try ring.pushBack(3); try ring.pushBack(4); try ring.pushBack(5); try ring.pushBack(6); try ring.pushBack(7); try ring.pushBack(8); try ring.pushBack(9); try std.testing.expectEqual(ring.len(), 9); try std.testing.expectEqual(ring.popBack(), 9); try std.testing.expectEqual(ring.popBack(), 8); try std.testing.expectEqual(ring.popBack(), 7); try std.testing.expectEqual(ring.popBack(), 6); try std.testing.expectEqual(ring.popBack(), 5); try std.testing.expectEqual(ring.popBack(), 4); try std.testing.expectEqual(ring.popBack(), 3); try std.testing.expectEqual(ring.popBack(), 2); try std.testing.expectEqual(ring.popBack(), 1); try std.testing.expectEqual(ring.popBack(), null); } test "RingBuffer: realloc with tail before head, after wrapping" { var ring = try RingBuffer(u32).initCapacity(std.testing.allocator, 8); defer ring.deinit(); // Wrap front around to the last index, push until it is at the first index again try ring.pushFront(0); try ring.pushFront(1); try ring.pushFront(2); try ring.pushFront(3); try ring.pushFront(4); try ring.pushFront(5); try ring.pushFront(6); try ring.pushFront(7); // wrap the head to the last index try std.testing.expectEqual(ring.popBack(), 0); try std.testing.expectEqual(ring.len(), 7); try ring.ensureTotalCapacity(ring.capacity() + 1); try std.testing.expectEqual(ring.len(), 7); try std.testing.expectEqual(ring.popBack(), 1); try std.testing.expectEqual(ring.popBack(), 2); try std.testing.expectEqual(ring.popBack(), 3); try std.testing.expectEqual(ring.popBack(), 4); try std.testing.expectEqual(ring.popBack(), 5); try std.testing.expectEqual(ring.popBack(), 6); try std.testing.expectEqual(ring.popBack(), 7); try std.testing.expectEqual(ring.popBack(), null); } test "RingBuffer: realloc with tail after head, shorter head" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); try ring.pushBack(2); try ring.pushBack(1); try ring.pushFront(3); try ring.pushFront(4); try ring.pushFront(5); try ring.pushFront(6); try ring.pushFront(7); try ring.pushFront(8); try ring.pushFront(9); try std.testing.expectEqual(ring.len(), 9); try std.testing.expectEqual(ring.popBack(), 1); try std.testing.expectEqual(ring.popBack(), 2); try std.testing.expectEqual(ring.popBack(), 3); try std.testing.expectEqual(ring.popBack(), 4); try std.testing.expectEqual(ring.popBack(), 5); try std.testing.expectEqual(ring.popBack(), 6); try std.testing.expectEqual(ring.popBack(), 7); try std.testing.expectEqual(ring.popBack(), 8); try std.testing.expectEqual(ring.popBack(), 9); try std.testing.expectEqual(ring.popBack(), null); } test "RingBuffer: realloc with tail after head, shorter tail" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); try ring.pushFront(2); try ring.pushFront(1); try ring.pushBack(3); try ring.pushBack(4); try ring.pushBack(5); try ring.pushBack(6); try ring.pushBack(7); try ring.pushBack(8); try ring.pushBack(9); try std.testing.expectEqual(ring.len(), 9); try std.testing.expectEqual(ring.popBack(), 9); try std.testing.expectEqual(ring.popBack(), 8); try std.testing.expectEqual(ring.popBack(), 7); try std.testing.expectEqual(ring.popBack(), 6); try std.testing.expectEqual(ring.popBack(), 5); try std.testing.expectEqual(ring.popBack(), 4); try std.testing.expectEqual(ring.popBack(), 3); try std.testing.expectEqual(ring.popBack(), 2); try std.testing.expectEqual(ring.popBack(), 1); try std.testing.expectEqual(ring.popBack(), null); } test "RingBuffer: get" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); try ring.pushBack(1); try ring.pushBack(2); try ring.pushBack(3); try ring.pushBack(4); try ring.pushBack(5); try ring.pushBack(6); try ring.pushBack(7); try ring.pushBack(8); try std.testing.expectEqual(ring.len(), 8); try std.testing.expectEqual(ring.get(0).?.*, 1); try std.testing.expectEqual(ring.get(1).?.*, 2); try std.testing.expectEqual(ring.get(2).?.*, 3); try std.testing.expectEqual(ring.get(3).?.*, 4); try std.testing.expectEqual(ring.get(4).?.*, 5); try std.testing.expectEqual(ring.get(5).?.*, 6); try std.testing.expectEqual(ring.get(6).?.*, 7); try std.testing.expectEqual(ring.get(7).?.*, 8); try std.testing.expectEqual(ring.get(8), null); } test "RingBuffer: get, wrapping" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); try ring.pushFront(4); try ring.pushFront(3); try ring.pushFront(2); try ring.pushFront(1); try ring.pushBack(5); try ring.pushBack(6); try ring.pushBack(7); try ring.pushBack(8); try std.testing.expectEqual(ring.len(), 8); try std.testing.expectEqual(ring.get(0).?.*, 1); try std.testing.expectEqual(ring.get(1).?.*, 2); try std.testing.expectEqual(ring.get(2).?.*, 3); try std.testing.expectEqual(ring.get(3).?.*, 4); try std.testing.expectEqual(ring.get(4).?.*, 5); try std.testing.expectEqual(ring.get(5).?.*, 6); try std.testing.expectEqual(ring.get(6).?.*, 7); try std.testing.expectEqual(ring.get(7).?.*, 8); try std.testing.expectEqual(ring.get(8), null); } test "RingBuffer: iterators" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); try ring.pushBack(1); try ring.pushBack(2); try ring.pushBack(3); try ring.pushBack(4); try ring.pushBack(5); try ring.pushBack(6); try ring.pushBack(7); try ring.pushBack(8); var iter = ring.iter(); var expected: u32 = 1; while (iter.next()) |i| { try std.testing.expectEqual(i.*, expected); expected += 1; } try std.testing.expectEqual(expected, 9); var iter_rev = ring.iterReverse(); while (iter_rev.next()) |i| { expected -= 1; try std.testing.expectEqual(i.*, expected); } try std.testing.expectEqual(expected, 1); } test "RingBuffer: popBack while iterating forward" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); try ring.pushBack(1); try ring.pushBack(2); try ring.pushBack(3); try ring.pushBack(4); try ring.pushBack(5); var iter = ring.iter(); try std.testing.expectEqual(iter.next().?.*, 1); _ = ring.popBack().?; try std.testing.expectEqual(iter.next().?.*, 2); _ = ring.popBack().?; try std.testing.expectEqual(iter.next().?.*, 3); _ = ring.popBack().?; try std.testing.expectEqual(iter.next(), null); } test "RingBuffer: popBack while iterating backwards" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); try ring.pushBack(1); try ring.pushBack(2); try ring.pushBack(3); try ring.pushBack(4); try ring.pushBack(5); var iter = ring.iterReverse(); try std.testing.expectEqual(iter.next().?.*, 5); _ = ring.popBack().?; try std.testing.expectEqual(iter.next().?.*, 3); _ = ring.popBack().?; try std.testing.expectEqual(iter.next().?.*, 1); _ = ring.popBack().?; try std.testing.expectEqual(iter.next(), null); } test "RingBuffer: popFront while iterating backwards" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); try ring.pushBack(1); try ring.pushBack(2); try ring.pushBack(3); try ring.pushBack(4); try ring.pushBack(5); var iter = ring.iterReverse(); try std.testing.expectEqual(iter.next().?.*, 5); _ = ring.popFront().?; try std.testing.expectEqual(iter.next().?.*, 4); _ = ring.popFront().?; try std.testing.expectEqual(iter.next().?.*, 3); _ = ring.popFront().?; try std.testing.expectEqual(iter.next(), null); } test "RingBuffer: popFront while iterating forwards" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); try ring.pushBack(1); try ring.pushBack(2); try ring.pushBack(3); try ring.pushBack(4); try ring.pushBack(5); var iter = ring.iter(); try std.testing.expectEqual(iter.next().?.*, 1); _ = ring.popFront().?; try std.testing.expectEqual(iter.next().?.*, 3); _ = ring.popFront().?; try std.testing.expectEqual(iter.next().?.*, 5); _ = ring.popFront().?; try std.testing.expectEqual(iter.next(), null); } test "RingBuffer: deinit while iterating" { var ring = RingBuffer(u32).init(std.testing.allocator); try ring.pushBack(1); try ring.pushBack(2); try ring.pushBack(3); try ring.pushBack(4); try ring.pushBack(5); var iter = ring.iter(); ring.deinit(); try std.testing.expectEqual(iter.next(), null); } test "RingBuffer: pushBack while iterating forward" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); var iter = ring.iter(); try ring.pushBack(1); try std.testing.expectEqual(iter.next().?.*, 1); try ring.pushBack(2); try ring.pushBack(3); try ring.pushBack(4); try std.testing.expectEqual(iter.next().?.*, 2); try std.testing.expectEqual(iter.next().?.*, 3); try ring.pushBack(5); try std.testing.expectEqual(iter.next().?.*, 4); try std.testing.expectEqual(iter.next().?.*, 5); } test "RingBuffer: pushFront while iterating backwards" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); var iter = ring.iterReverse(); try ring.pushFront(1); try std.testing.expectEqual(iter.next().?.*, 1); try ring.pushFront(2); try ring.pushFront(3); try ring.pushFront(4); try std.testing.expectEqual(iter.next().?.*, 2); try std.testing.expectEqual(iter.next().?.*, 3); try ring.pushFront(5); try std.testing.expectEqual(iter.next().?.*, 4); try std.testing.expectEqual(iter.next().?.*, 5); } test "RingBuffer: pushBack while iterating backwards" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); var iter = ring.iterReverse(); try ring.pushBack(1); try std.testing.expectEqual(iter.next().?.*, 1); try ring.pushBack(2); try ring.pushBack(3); try ring.pushBack(4); try std.testing.expectEqual(iter.next().?.*, 3); try std.testing.expectEqual(iter.next().?.*, 2); try ring.pushBack(5); try std.testing.expectEqual(iter.next().?.*, 2); try std.testing.expectEqual(iter.next().?.*, 1); } test "RingBuffer: pushFront while iterating forwards" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); var iter = ring.iter(); try ring.pushFront(1); try std.testing.expectEqual(iter.next().?.*, 1); try ring.pushFront(2); try ring.pushFront(3); try ring.pushFront(4); try std.testing.expectEqual(iter.next().?.*, 3); try std.testing.expectEqual(iter.next().?.*, 2); try ring.pushFront(5); try std.testing.expectEqual(iter.next().?.*, 2); try std.testing.expectEqual(iter.next().?.*, 1); } test "RingBuffer: stress pushBack" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); var i: u32 = 0; while (i < 1024 * 8) : (i += 1) { try ring.pushBack(i * 2); } } test "RingBuffer: stress pushFront" { var ring = RingBuffer(u32).init(std.testing.allocator); defer ring.deinit(); var i: u32 = 0; while (i < 1024 * 8) : (i += 1) { try ring.pushFront(i * 2); } } test "RingBuffer: stress ensureTotalCapacity" { var ring = RingBuffer(u32).init(std.testing.FailingAllocator.init(std.testing.allocator, 1).allocator()); defer ring.deinit(); const num_elems = 1024 * 8; var i: u32 = 0; try ring.ensureTotalCapacity(num_elems); while (i < num_elems) : (i += 1){ try ring.pushFront(i * 2); } } test "RingBuffer: initCapacity" { var ring = try RingBuffer(u32).initCapacity(std.testing.FailingAllocator.init(std.testing.allocator, 1).allocator(), 5); defer ring.deinit(); var i: u32 = 0; while (i < 5) : (i += 1) { try ring.pushFront(i * 2); } }
src/lib.zig
const std = @import("std"); /// Bell Sound pub const BELL = "\x07"; /// Backspace pub const BS = "\x08"; /// Tab pub const HT = "\x09"; /// Line Feed pub const LF = "\x0A"; /// From Feed pub const FF = "\x0C"; /// Carriage Return pub const CR = "\x0D"; /// ANSI Escape Code pub const ESC = "\x1B"; /// Single Shift Two pub const SS2 = "\u{8E}"; /// Single Shift Three pub const SS3 = "\u{8F}"; /// Device Control String pub const DCS = "\u{90}"; /// Control Sequence Introducer pub const CSI = "\u{9B}"; /// String Terminator pub const ST = "\u{9C}"; /// Operating System Command pub const OSC = "\u{9D}"; /// Start of String pub const SOS = "\u{98}"; /// Privacy Message pub const PM = "\u{9E}"; /// Application Program Command pub const APC = "\u{9F}"; pub const Until = enum { screen_start, screen_end, line_start, line_end, }; pub const GraphicRendition = enum(u7) { reset = 0, bold = 1, dim = 2, italic = 3, underline = 4, blinking = 5, reverse = 7, hidden = 8, strike = 9, font_primary = 10, font_alt_1 = 11, font_alt_2 = 12, font_alt_3 = 13, font_alt_4 = 14, font_alt_5 = 15, font_alt_6 = 16, font_alt_7 = 17, font_alt_8 = 18, font_alt_9 = 19, font_gothic = 20, double_underline = 21, no_bold_or_dim = 22, no_italic = 23, no_underline = 24, no_blinking = 25, no_reverse = 27, no_hidden = 28, no_strike = 29, // ... // Color4 // ... frame = 51, encircle = 52, overline = 53, not_frame_or_encircle = 54, not_overline = 55, underline_color = 58, default_underline_color = 59, ideogram_underline = 60, ideogram_double_underline = 61, ideogram_overline = 62, ideogram_double_overline = 63, ideogram_stress_marking = 64, no_ideogram = 65, }; pub const Color4 = enum(u7) { black = 30, red = 31, green = 32, yellow = 33, blue = 34, magenta = 35, cyan = 36, white = 37, default = 39, bright_black = 90, bright_red = 91, bright_green = 92, bright_yellow = 93, bright_blue = 94, bright_magenta = 95, bright_cyan = 96, bright_white = 97, }; // // Cursor // pub fn cursorPosZero(writer: anytype) !void { try writer.writeAll(CSI ++ "H"); } pub fn setCursorPos(writer: anytype, row: usize, col: usize) !void { try writer.print(CSI ++ "{d};{d}H", .{ row + 1, col + 1 }); } pub fn setCursorRow(writer: anytype, row: usize) !void { try writer.print(CSI ++ "{d}H", .{row + 1}); } pub fn setCursorColumn(writer: anytype, column: usize) !void { try writer.print(CSI ++ "{d}G", .{column + 1}); } pub fn cursorUp(writer: anytype, lines: u16) !void { try writer.print(CSI ++ "{d}A", .{lines}); } pub fn cursorDown(writer: anytype, lines: u16) !void { try writer.print(CSI ++ "{d}B", .{lines}); } pub fn cursorForward(writer: anytype, columns: u16) !void { try writer.print(CSI ++ "{d}C", .{columns}); } pub fn cursorBackward(writer: anytype, columns: u16) !void { try writer.print(CSI ++ "{d}D", .{columns}); } pub fn cursorNextLine(writer: anytype, lines: usize) !void { try writer.print(CSI ++ "{d}E", .{lines}); } pub fn cursorPrevLine(writer: anytype, lines: usize) !void { try writer.print(CSI ++ "{d}F", .{lines}); } pub fn saveCursor(writer: anytype) !void { try writer.writeAll(ESC ++ "s"); } pub fn restoreCursor(writer: anytype) !void { try writer.writeAll(ESC ++ "u"); } pub fn showCursor(writer: anytype) !void { try writer.writeAll(CSI ++ "?25h"); } pub fn hideCursor(writer: anytype) !void { try writer.writeAll(CSI ++ "?25l"); } /// after calling this, terminal reports the cursor position (CPR) by transmitting `ESC[<Row>;<Column>R` pub fn requestCursorPos(writer: anytype) !void { try writer.writeAll(CSI ++ "6n"); } // // Clear // pub fn clearScreen(writer: anytype) !void { try cursorPosZero(writer); try writer.writeAll(CSI ++ "2J" ++ CSI ++ "3J"); } pub fn clearLine(writer: anytype) !void { try writer.writeAll(CSI ++ "2K"); } /// clear from cursor to to specified position pub fn clearUntil(writer: anytype, until: Until) !void { try cursorPosZero(); try writer.print(CSI ++ "{s}", .{switch (until) { .screen_start => "1J", .screen_end => "0J", .line_start => "1K", .line_end => "0K", }}); } // // Screen // pub fn saveScreen(writer: anytype) !void { try writer.writeAll(CSI ++ "?47h"); } pub fn restoreScreen(writer: anytype) !void { try writer.writeAll(CSI ++ "?47l"); } pub fn enableAltBuffer(writer: anytype) !void { try writer.writeAll(CSI ++ "?1049h"); } pub fn disableAltBuffer(writer: anytype) !void { try writer.writeAll(CSI ++ "?1049l"); } /// scroll whole page up by `lines`. new lines are added at the bottom pub fn scrollUp(writer: anytype, lines: usize) !void { try writer.print(CSI ++ "{d}S", .{lines}); } /// scroll whole page down by `lines`. new lines are added at the bottom pub fn scrollDown(writer: anytype, lines: usize) !void { try writer.print(CSI ++ "{d}T", .{lines}); } // // Color, Graphic, etc // /// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR pub fn sgr(writer: anytype, mode: GraphicRendition) !void { try writer.print(CSI ++ "{d}m", .{@enumToInt(mode)}); } /// https://en.wikipedia.org/wiki/ANSI_escape_code#3-bit_and_4-bit pub fn fgColor4(writer: anytype, mode: Color4) !void { try writer.print(CSI ++ "{d}m", .{@enumToInt(mode)}); } /// https://en.wikipedia.org/wiki/ANSI_escape_code#3-bit_and_4-bit pub fn bgColor4(writer: anytype, mode: Color4) !void { try writer.print(CSI ++ "{d}m", .{@enumToInt(mode) + 10}); } /// https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit pub fn fgColor8(writer: anytype, code: u8) !void { try writer.print(CSI ++ "38;5;{d}m", .{code}); } /// https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit pub fn bgColor8(writer: anytype, code: u8) !void { try writer.print(CSI ++ "48;5;{d}m", .{code}); } /// rarely implemented (Kitty, iTerm2, VTE, etc) /// https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit pub fn underlineColor8(writer: anytype, code: u8) !void { try writer.print(CSI ++ "58;5;{d}m", .{code}); } /// https://en.wikipedia.org/wiki/ANSI_escape_code#24-bit pub fn fgColorRGB(writer: anytype, r: u8, g: u8, b: u8) !void { try writer.print(CSI ++ "38;2;{d};{d};{d}m", .{ r, g, b }); } /// https://en.wikipedia.org/wiki/ANSI_escape_code#24-bit pub fn bgColorRGB(writer: anytype, r: u8, g: u8, b: u8) !void { try writer.print(CSI ++ "48;2;{d};{d};{d}m", .{ r, g, b }); } /// rarely implemented (Kitty, iTerm2, VTE, etc) /// https://en.wikipedia.org/wiki/ANSI_escape_code#24-bit pub fn underlineColorRGB(writer: anytype, r: u8, g: u8, b: u8) !void { try writer.print(CSI ++ "58;2;{d};{d};{d}m", .{ r, g, b }); } /// reset all SGR attributes off pub fn resetSGR(writer: anytype) !void { try writer.writeAll(CSI ++ "0m"); } // // Other // /// in bracketed paste mode and you paste into your terminal the content will be wrapped by the sequences `ESC[200~` and `ESC[201~`. /// https://cirw.in/blog/bracketed-paste pub fn enableBracketedPasteMode(writer: anytype) !void { try writer.writeAll(CSI ++ "?2004h"); } pub fn disableBracketedPasteMode(writer: anytype) !void { try writer.writeAll(CSI ++ "?2004l"); } pub fn setWindowTitle(writer: anytype, title: []const u8) !void { try writer.print(OSC ++ "0;{s}" ++ BELL, .{title}); } pub fn resetAll(writer: anytype) !void { try writer.writeAll(ESC ++ "c"); } // // Tests // test { const stderr = std.io.getStdErr().writer(); try setWindowTitle(stderr, "Hello"); try clearScreen(stderr); inline for (std.meta.fields(GraphicRendition)) |f| { try sgr(stderr, @field(GraphicRendition, f.name)); try stderr.print(" {s} ", .{f.name}); try resetSGR(stderr); } try sgr(stderr, .underline); try underlineColor8(stderr, 131); try stderr.writeAll(" uc8bit "); try underlineColorRGB(stderr, 0, 131, 0); try stderr.writeAll(" ucRGB "); try resetSGR(stderr); try sgr(stderr, .bold); inline for (std.meta.fields(Color4)) |f| { try bgColor4(stderr, @field(Color4, f.name)); try stderr.print(" {s} ", .{f.name}); } try bgColor4(stderr, .default); var i: u8 = 17; while (i < 255) : (i += 1) { try bgColor8(stderr, i); try stderr.print(" {d} ", .{i}); } try stderr.writeAll("\n"); }
conc.zig
// SPDX-License-Identifier: MIT // This file is part of the Termelot project under the MIT license. const std = @import("std"); const termelot = @import("termelot"); usingnamespace termelot.style; const Rune = termelot.Rune; const Position = termelot.Position; const Cell = termelot.Cell; var running: bool = true; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const config = termelot.Config{ .raw_mode = true, .alternate_screen = true, .initial_buffer_size = .{ .rows = 800, .cols = 800 }, }; // Initialize Termelot var term: termelot.Termelot = undefined; term = try term.init(&gpa.allocator, config); defer _ = term.deinit(); try term.setCursorVisibility(false); // Hide the cursor const default_style = Style{ .fg_color = Color.named(.White), .bg_color = Color.named(.Black), .decorations = Decorations{ .bold = false, .italic = false, .underline = false, .blinking = false, }, }; // Rune color overrides for the castle art const castle_color_pairs = [_]ColorPair{ .{ .rune = 'm', .color = Color.named(.BrightBlack) }, .{ .rune = '>', .color = Color.named(.Red) }, }; // ... overrides for text logo const text_logo_color_pairs = [_]ColorPair{ .{ .rune = '\"', .color = Color.named(.BrightBlack) }, .{ .rune = '`', .color = Color.named(.Red) }, .{ .rune = '\'', .color = Color.named(.Red) }, .{ .rune = '.', .color = Color.named(.Red) }, .{ .rune = 'L', .color = Color.named(.Red) }, .{ .rune = 'd', .color = Color.named(.Red) }, }; // Override the style the internal buffer uses to draw clear cells term.screen_buffer.default_style = default_style; var text_pos = SignedPos{ .row = -15, .col = 29 }; var text_target_row: i32 = 21; var last_frame_time = std.time.milliTimestamp(); while (running) { const this_frame_time = std.time.milliTimestamp(); const delta = this_frame_time - last_frame_time; // ms between render calls _ = delta; // Clear Termelot's internal screen buffer term.screen_buffer.clear(); // Render ascii to internal screen buffer renderAscii(&term, SignedPos{ .col = 0, .row = 10 }, default_style, castle_string[0..], castle_color_pairs[0..]); renderAscii(&term, text_pos, default_style, text_logo_string[0..], text_logo_color_pairs[0..]); // Make draw call, rendering internal buffer to terminal try term.drawScreen(); // Update if (text_pos.row != text_target_row) { text_pos.row += 1; } else { // Text falldown completed... } // Sleep 50 milliseconds after frames (to keep computer calm) std.time.sleep(50 * std.time.ns_per_ms); last_frame_time = this_frame_time; //running = false; //try term.setCursorVisibility(true); //term.clearScreen(); } } /// Termelot offers a Position, which is a struct of two unsigned 16-bit integers for /// console interactions. Unsigned integers make sense in the console, but if we want /// to have anything moving in or out of the screen, we need signed positions. const SignedPos = struct { row: i32, col: i32, }; /// Overrides the color for a rune in the renderAscii function. const ColorPair = struct { rune: Rune, color: Color, }; /// Draw a string `slice` starting at `draw_pos`, with default style `style`. fn renderAscii(term: *termelot.Termelot, draw_pos: SignedPos, style: Style, slice: []const u8, color_pairs: ?[]const ColorPair) void { var pos = draw_pos; var i: usize = 0; while (i < slice.len) : (i += 1) { const c = slice[i]; if (c == 0) break; if (c == '\n') { pos.col = draw_pos.col; pos.row += 1; continue; } // Skip out of bounds chars (see SignedPos) if (pos.row < 0 or pos.col < 0) continue; if (c == '0') { // Don't modify cell here } else { // Get any overriden color for the current rune var fg = style.fg_color; if (color_pairs) |pairs| { for (pairs) |pair| { if (pair.rune == c) { fg = pair.color; break; } } } term.setCell( Position{ .row = @intCast(u16, pos.row), .col = @intCast(u16, pos.col) }, Cell{ .rune = c, .style = Style{ .fg_color = fg, .bg_color = style.bg_color, .decorations = style.decorations, }, }, ); } pos.col += 1; } } // Zeros in an ascii art string in this program are interpreted as transparency. const text_logo_string = \\ 0000000000000000000000000000000000000000000 ,, 00000000000 0000 \\ MMP""MM""YMM 00000000000000000000000000000000000000000 `7MM 000000000 mm 000 \\ P' MM `7 MM MM 0 \\ MM .gP"Ya `7Mb,op8 `7MMpMMMb.pMMMb. .gP"Ya MM ,pW"Wq. mmMMmm 0 \\ MM ,M' Yb MM' "' MM MM MM ,M' Yb MM 6W' `Wb MM \\ MM 8M"""""" MM MM MM MM 8M"""""" MM 8M M8 MM \\ MM YM. , MM MM MM MM YM. , MM YA. ,A9 Mb \\ .JMML. `Mbmmd' .JMML. .JMML JMML JMML. `Mbmmd' .JMML. `Ybmd9' `Mbmo \\ ; const castle_string = \\ `-:: ::` \\ ... ... .+o/`oo+. ... ..., ..., syyy+hd/ ... ... ... \\ ,...sh. :/oo+`: .. .+syy: :yyy-/yhhydddo ``` `.s hy/ -yyyo .yyyy+. ---, shhhdddo-://++` -sooso-./:- \\ .-`ossyyhd:sssshhhhhyh. +yh-.yoyhhs/ohhhoshdhddddh` yyy -yyy dhysyhhhhyydhhdds.yhh+ +yhyyhmhhyyyhd/-+dddddo+ddh+ \\.sy:yyyhhddsdhhhdddhhdhy/-` oyhyyhsyhhdhhhhhhhhhhhddmd +dddosddy hhhdhhddhhddhyhdmhhhho /yysyhmdhyyyhhddhhhhdddmdddy \\.oyysyyyhhhhhhhhhhddddhhhd+ oyhhhyoyhhddhdddhdddyhhdmm ddddddhhy yddmhdmmhdmdhhddmdhhho +yysyyhhhhhhhhhhhhhhddddddds \\.sssssyyyhhhhhhhhdddddhdddo +yydmdsydmmmdmmmdNmmhddmm mdddddhddhy mmmddmmhdmmdddmyymddo ohyysyssssyyyyyyyhhhhhhhddd+ \\ osssyyyhhhhhhhhddddddhdhhs `mmddddydddhhddddmmdddmm mmm.""""".dhd ddhdhhhdddhhmNyymmm. +hssssssssysyhyyhhhhddddddd/ \\ osssyyyhhhhhhhhdddddddddh+ .:--:- `mmmmMmmmmmddmmmmdmmmm mmm'mdddddd'dyy mymmmhdmmyymmmdmm -hssssssyyssyyhhhhhdddddddd/ \\`ss syyyyhhhhhhdddddddddddo `-+hyhh+ /yyyyyyyhdyyhyyhhhyhm mm|ddddddddd|yy syyyyhdyyyymmmdd+ |> .++o +dyyyyyydyyyyhhhhhhhhdddd h/ \\`ss syyyyyyhhhhdhdddddddddh /yyyhhh: /yyhhyyyhdyyhyyhhhyhm mm|ddddddddd|yy yysssyhyyyymmddh+ | -syh ydyyyyyydsyyyhhhhhhhhhdhd h/ \\`sssssyyyyyhhhhhddddddddddd hhyyhhh: /yyhhyyyydhyhyyhhhyhm mm|ddddddddh|hy hyysssyyyyymmddds://-```| -yhd ddyyyyyyhhyyyyhhhhhhhhhhhhh/ \\`oosssyyyyyhhhhhddddddddddd hysyhhh+`` ```/yyyhyhyyhhhhhyhhhyhm mm|dmmdddddh|hy hhsyysyyyyymmdddd ddssyy+. `---/+yd hdyyyyyyy yyyhhhhhhhhhddhhh: \\`ooossyyyyyhhhhhdddddddddmm dddhhhhhyy/ /ss yyyhhyhhyyyyhhyhhhyhm mm|ddmdddddh|hy hhyyyyyyhyymmdddd dmssdhdh-ohhdh+yd ddyyyyyyy yyyyyyyyhhhhhhhhh- \\`ooossyyyyyhhhhhhdddddddmmm ddddddhhhhhshhh hhhhyyhhyyhhdhyhhhyhm mm|ddddddddd|yy hhyyyyyyhyymmdddd ddddddddhdhhddddh ddhyyyyyyyyyyyyyyhhhhhhhhhh- \\`+osssyyyyhyhhhhddhhd ddmmm dddddddhhhddddh hhhhyyhyyyyhhhddhdhhm mm|ddNdddddh|hy hhyhyyhyhyymmdddddddddmmddddhhhhdhh ddhyyyyyyyyyyyyyyyhhhhhhhhh- \\ +ossssyyyyyyhhhhhhdd ddmmm ddhhhhhhhhhhhhhdhyyyyyyyyyyhdhdmhhhhm mm|ddNddddhh|yy hyyyyyddhyymmdddddddddddhddhhhhhhhh hhhhyyyyyyyyyyyyyyyyymhhhhh- \\ oosssyyyyyyhhhhddddddddmmm ddhhhhhhhhhhhhhhhhhyyhyyyyhhdhddhdhhm mm|ddmmdddhh|dh dhyhhyhhhyymmmddddddddddddddddddhdh ddhhyyyysyyyyyyyy yyymhhh h- \\ +osssyyyyyyhhhhddd dddmmmm dddddhhhhhddddddhhhyyhhyyyhhddhdddhhm mm|ddddddddd|mm mmyhhyhyhyymmmmddmddmdddddddddddddh ddhhyyyyysyysyyyy yyhddhh h: \\ +s ssyyyhhhhhhhddd dddmmmm mddddhhhdhddhhddhyyyyyhyyhhhddhhdhhhm dd|ddhddhddh|mm mmhhhyhyhyymmmdddmddddddddddddhhddh mdhhyyysyyssyssyy yhhhhhhhho \\ +o ssyyyyhhhhhhddd ddmmmmm ddddddhdddhdhhhhhyyyyyhhyyyhddhhdhhhm dd|dddddddhh|mN mNhhhyyyhyymmmddmmddmmmmddddhhhhhhh ddhhhyyyyyyyyyyyy yyyhhhhhh/ \\ osssyyyyyhhhhhdddd dddmmmm ddddhdhdddhhhhhhhyyyyyhyyyhhddhdddhdm dddd'''''''hhmm mmmhhyyyhyymmddddmmdddmmdddhhhhhhhh ddhhhyyyyyyysyyyyyyyyhhhhhh/ \\ oysssyyyyyyhhhmdddddddmmmm dddhhdhhdhhhhhhhhyhyyyhyyyhhddhhhdhhm ddm NNNmmdd hdm mmdhyhyhhyydmdddddddddmmddhhhhhhhhy ddhhyhyyhyyysyyyyyyyyhhhhhh/ \\ oyssyyyyyyyhhhmdddddddmmmm mddhhhhhdhhhmhhhyyyyyyhyyyhhddhhddhhm mm mNNNNmmhh hm mdhyhhyyhyydmddddddddmmmdddhhhhhhhh dhhhhyyhmssyysssyyyyyyhyyhh/ \\ osssyyyyyyyhhhddddddddmmmm ddhhhhhhhhhhmhhhyyyyyyhyyhhdddhhhdhdm mm mmmmmmdhh hm mdhhhhyhhyydmdddddddmmmmddhhhhhhhhh hhhhhyyhdssssyyyyyyyyhhyhhh/ \\ osssyyyyyyhhhhhhhdddddmmmm mdhhhhhhhhhhdhhhyyyyyhhyhhhhhdhhhdhdm mm mmmmmmmhh hd mddhhyhyyyhdmdddddddddmmdddhhhhyyhy ddhyhyyhhyssyyyyyyyyyhhhhhh/ \\ ossyyyyyyyyyyyhhhhdddddmmm mdhhhhhhhhhhhhhhhyyyyyhhhhhhhdhdddhhm mm mmmmmmmhh hd mmdhhydyhhhdmdddddddddddddddhhhhhhy ddhhhyyyyysyssyyyyyyhyhhhhh/ \\ ossyyyyyyyyyyhhhhhhhhddmmm ddddhhhhhhhhdhhhhyyyhyhyyyhdddhdddhdm mm mmmmmmmhh hd mmdhhddhhhhddddddmddddddddddddhhhhh ddhyyyyyyssssssyyyyyyhhhhhh/ \\ osyyyyyhhyyhhhhhhhhhdddmmm dddddddhhhdhhhhhhhhhhhhhhhhhddhhhhhdm mm ddddddddh dd mmdddhhhhddmdddddmmmddddddhhhhhhhhd ddhyyyysssssssssyyyyyhhhhhhs \\ ::::::///:::/:::///////+/////////////////////////::://////shhhhyyhysyyyyyyhdmdhhdmmmmy:---::::::::::-..````````````````...........`.............. \\ .:``` ```````:+++/:/++- ;
examples/castle.zig