code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const Allocator = std.mem.Allocator; const Writer = std.io.Writer; const GPA = std.heap.GeneralPurposeAllocator(.{}); const art = @embedFile("../art.txt"); const Days = @import("days.zig").Days; const days: usize = std.meta.declarations(Days).len; pub fn main() !void { var gpa: GPA = .{}; const alloc = gpa.allocator(); const stdout = std.io.getStdOut().writer(); try stdout.print("{s}\n", .{art}); var args = try std.process.argsAlloc(alloc); defer std.process.argsFree(alloc, args); const num_opt: ?usize = if (args.len <= 1) null else std.fmt.parseUnsigned(usize, args[1], 0) catch null; const num = num_opt orelse days; if (num < 1 or num > days) { std.log.err("Invalid day number!\n", .{}); } else { var buffer: [5]u8 = undefined; const day = try std.fmt.bufPrint(&buffer, "day{d:0>2}", .{num}); inline for (std.meta.declarations(Days)) |decl| { if (std.mem.eql(u8, day, decl.name)) { const cmd = @field(Days, decl.name); try stdout.print("-- Day {} --\n", .{num}); return bench(alloc, cmd.run, stdout); } } // if we're here, none of the days have been executed. std.log.err("This day hasn't been solved yet!\n", .{}); } } // Modified from <https://github.com/SpexGuy/Advent2021/blob/a71d4f299815cc191f6f0951ee22da9c8c4dafc9/src/day03.zig#L74-L93> // Copyright (c) 2020-2021 Martin Wickham licensed under MIT fn bench(alloc: Allocator, run: anytype, stdout: anytype) !void { var i: usize = 0; var best_time: usize = std.math.maxInt(usize); var total_time: usize = 0; const num_runs = 10000; while (i < num_runs and total_time < 20 * 1000 * 1000 * 1000) : (i += 1) { if (i % 100 == 0) { try stdout.print("\rIteration no. {}", .{i}); } std.mem.doNotOptimizeAway(total_time); const timer = try std.time.Timer.start(); try @call(.{}, run, .{ alloc, null }); asm volatile ("" ::: "memory"); const lap_time = timer.read(); if (best_time > lap_time) best_time = lap_time; total_time += lap_time; } try stdout.print("\n\nmin: ", .{}); try printTime(stdout, best_time); try stdout.print("avg: ", .{}); try printTime(stdout, total_time / i); } fn printTime(stdout: anytype, time: u64) !void { if (time < 1_000) { try stdout.print("{}ns\n", .{time}); } else if (time < 1_000_000) { const ftime: f64 = @intToFloat(f64, time) / 1000.0; try stdout.print("{d:.2}μs\n", .{ftime}); } else { const ftime: f64 = @intToFloat(f64, time) / 1_000_000.0; try stdout.print("{d:.2}ms\n", .{ftime}); } }
src/bench.zig
const std = @import("std"); const print = std.debug.print; const ArrayList = std.ArrayList; const Allocator = std.mem.Allocator; const helpers = @import("./helpers.zig"); const Definitions = @import("./definitions.zig"); const Error = Definitions.Error; const FieldInfo = @import("./result.zig").FieldInfo; pub const SQL = enum { Insert, Select, Delete, Update }; pub const Builder = struct { table_name: []const u8 = "", where_clause: ?[]const u8 = null, buffer: ArrayList(u8), columns: ArrayList([]const u8), values: ArrayList([]const u8), allocator: *Allocator, build_type: SQL, pub fn new(build_type: SQL, allocator: *Allocator) Builder { return Builder{ .buffer = ArrayList(u8).init(allocator), .columns = ArrayList([]const u8).init(allocator), .values = ArrayList([]const u8).init(allocator), .allocator = allocator, .build_type = build_type, }; } pub fn table(self: *Builder, table_name: []const u8) *Builder { self.table_name = table_name; return self; } pub fn where(self: *Builder, query: []const u8) *Builder { self.where_clause = query; return self; } pub fn addColumn(self: *Builder, column_name: []const u8) !void { try self.columns.append(column_name); } pub fn addIntValue(self: *Builder, value: anytype) !void { try self.values.append(try std.fmt.allocPrint(self.allocator, "{d}", .{value})); } pub fn addStringValue(self: *Builder, value: []const u8) !void { try self.values.append(try std.fmt.allocPrint(self.allocator, "'{s}'", .{value})); } pub fn addValue(self: *Builder, value: anytype) !void { switch (@TypeOf(value)) { u8, u16, u32, usize, i8, i16, i32 => { try self.addIntValue(value); }, []const u8 => { try self.addStringValue(value); }, else => { const int: ?u32 = std.fmt.parseInt(u32, value, 10) catch null; if (int != null) { try self.addIntValue(int.?); } else { try self.addStringValue(value); } }, } } pub fn addStringArray(self: *Builder, values: [][]const u8) !void { _ = try self.buffer.writer().write("ARRAY["); for (values) |entry, i| _ = { _ = try self.buffer.writer().write(try std.fmt.allocPrint(self.allocator, "'{s}'", .{entry})); if (i < values.len - 1) _ = try self.buffer.writer().write(","); }; _ = try self.buffer.writer().write("]"); try self.values.append(self.buffer.toOwnedSlice()); } pub fn addJson(self: *Builder, data: anytype) !void { _ = try self.buffer.writer().write("('"); var buffer = std.ArrayList(u8).init(self.allocator); try std.json.stringify(data, .{}, buffer.writer()); _ = try self.buffer.writer().write(buffer.toOwnedSlice()); _ = try self.buffer.writer().write("')"); _ = try self.values.append(self.buffer.toOwnedSlice()); } pub fn autoAdd(self: *Builder, struct_info: anytype, comptime field_info: FieldInfo, field_value: anytype, extended: bool) !void { if (@typeInfo(field_info.type) == .Optional and field_value == null) return; switch (field_info.type) { i16, i32, u8, u16, u32, usize => { try self.addIntValue(field_value); }, []const u8 => { try self.addStringValue(field_value); }, ?[]const u8 => { try self.addStringValue(field_value.?); }, else => { if (extended) try @field(struct_info, "onSave")(field_info, self, field_value); }, } } pub fn end(self: *Builder) !void { switch (self.build_type) { .Insert => { _ = try self.buffer.writer().write("INSERT INTO "); _ = try self.buffer.writer().write(self.table_name); for (self.columns.items) |column, index| { if (index == 0) _ = try self.buffer.writer().write(" ("); if (index == self.columns.items.len - 1) { _ = try self.buffer.writer().write(column); _ = try self.buffer.writer().write(") "); } else { _ = try self.buffer.writer().write(column); _ = try self.buffer.writer().write(","); } } _ = try self.buffer.writer().write("VALUES"); for (self.values.items) |value, index| { const columns_mod = index % self.columns.items.len; const final_value = index == self.values.items.len - 1; if (index == 0) _ = try self.buffer.writer().write(" ("); if (columns_mod == 0 and index != 0) { _ = try self.buffer.writer().write(")"); _ = try self.buffer.writer().write(","); _ = try self.buffer.writer().write("("); } _ = try self.buffer.writer().write(value); if (!final_value and columns_mod != self.columns.items.len - 1) { _ = try self.buffer.writer().write(","); } if (final_value) { _ = try self.buffer.writer().write(")"); _ = try self.buffer.writer().write(";"); } } }, .Update => { if (self.columns.items.len != self.values.items.len) { std.debug.warn("Columns and Values must match in length \n", .{}); return Error.QueryFailure; } if (self.where_clause == null) { std.debug.warn("Where clause must be set \n", .{}); return Error.QueryFailure; } _ = try self.buffer.writer().write("UPDATE "); _ = try self.buffer.writer().write(self.table_name); _ = try self.buffer.writer().write(" SET "); for (self.columns.items) |column, index| { const final_value = index == self.columns.items.len - 1; _ = try self.buffer.writer().write(column); _ = try self.buffer.writer().write("="); _ = try self.buffer.writer().write(self.values.items[index]); if (!final_value) { _ = try self.buffer.writer().write(","); } else { _ = try self.buffer.writer().write(" "); } } _ = try self.buffer.writer().write(self.where_clause.?); }, else => { return Error.NotImplemented; }, } } pub fn command(self: *Builder) []const u8 { return self.buffer.items; } pub fn deinit(self: *Builder) void { if (self.where_clause != null) self.allocator.free(self.where_clause.?); self.columns.deinit(); self.values.deinit(); self.buffer.deinit(); } //Build query string for executing in sql pub fn buildQuery(comptime query: []const u8, values: anytype, allocator: *Allocator) ![]const u8 { comptime var values_info = @typeInfo(@TypeOf(values)); comptime var temp_fields: [values_info.Struct.fields.len]std.builtin.TypeInfo.StructField = undefined; inline for (values_info.Struct.fields) |field, index| { switch (field.field_type) { i16, i32, u8, u16, u32, usize, comptime_int => { temp_fields[index] = std.builtin.TypeInfo.StructField{ .name = field.name, .field_type = i32, .default_value = null, .is_comptime = false, .alignment = if (@sizeOf(field.field_type) > 0) @alignOf(field.field_type) else 0, }; }, else => { temp_fields[index] = std.builtin.TypeInfo.StructField{ .name = field.name, .field_type = []const u8, .default_value = null, .is_comptime = false, .alignment = if (@sizeOf(field.field_type) > 0) @alignOf(field.field_type) else 0, }; }, } } values_info.Struct.fields = &temp_fields; var parsed_values: @Type(values_info) = undefined; inline for (std.meta.fields(@TypeOf(parsed_values))) |field| { const value = @field(values, field.name); switch (field.field_type) { comptime_int => { @field(parsed_values, field.name) = @intCast(i32, value); return; }, i16, i32, u8, u16, u32, usize => { @field(parsed_values, field.name) = @as(i32, value); }, else => { @field(parsed_values, field.name) = try std.fmt.allocPrint(allocator, "'{s}'", .{value}); }, } } return try std.fmt.allocPrint(allocator, query, parsed_values); } };
src/sql_builder.zig
const std = @import("std"); const renderkit = @import("renderkit"); const gk = @import("../gamekit.zig"); const math = gk.math; const Vertex = gk.gfx.Vertex; const DynamicMesh = gk.gfx.DynamicMesh; pub const TriangleBatcher = struct { mesh: DynamicMesh(void, Vertex), draw_calls: std.ArrayList(i32), white_tex: gk.gfx.Texture = undefined, begin_called: bool = false, frame: u32 = 0, // tracks when a batch is started in a new frame so that state can be reset vert_index: usize = 0, // current index into the vertex array vert_count: i32 = 0, // total verts that we have not yet rendered buffer_offset: i32 = 0, // offset into the vertex buffer of the first non-rendered vert fn createDynamicMesh(allocator: std.mem.Allocator, max_tris: u16) !DynamicMesh(void, Vertex) { return try DynamicMesh(void, Vertex).init(allocator, max_tris * 3, &[_]void{}); } pub fn init(allocator: std.mem.Allocator, max_tris: u16) !TriangleBatcher { var batcher = TriangleBatcher{ .mesh = try createDynamicMesh(allocator, max_tris * 3), .draw_calls = try std.ArrayList(i32).initCapacity(allocator, 10), }; errdefer batcher.deinit(); var pixels = [_]u32{ 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }; batcher.white_tex = gk.gfx.Texture.initWithData(u32, 2, 2, pixels[0..]); return batcher; } pub fn deinit(self: TriangleBatcher) void { self.mesh.deinit(); self.draw_calls.deinit(); self.white_tex.deinit(); } pub fn begin(self: *TriangleBatcher) void { std.debug.assert(!self.begin_called); // reset all state for new frame if (self.frame != gk.time.frames()) { self.frame = gk.time.frames(); self.vert_index = 0; self.buffer_offset = 0; } self.begin_called = true; } /// call at the end of the frame when all drawing is complete. Flushes the batch and resets local state. pub fn end(self: *TriangleBatcher) void { std.debug.assert(self.begin_called); self.flush(); self.begin_called = false; } pub fn flush(self: *TriangleBatcher) void { if (self.vert_index == 0) return; self.mesh.updateVertSlice(self.vert_index); self.mesh.bindImage(self.white_tex.img, 0); // draw const tris = self.vert_index / 3; self.mesh.draw(0, @intCast(c_int, tris * 3)); self.vert_index = 0; } /// ensures the vert buffer has enough space fn ensureCapacity(self: *TriangleBatcher) !void { // if we run out of buffer we have to flush the batch and possibly discard the whole buffer if (self.vert_index + 3 > self.mesh.verts.len) { self.flush(); self.vert_index = 0; self.buffer_offset = 0; // with GL we can just orphan the buffer self.mesh.updateAllVerts(); self.mesh.bindings.vertex_buffer_offsets[0] = 0; } // start a new draw call if we dont already have one going if (self.draw_calls.items.len == 0) { try self.draw_calls.append(0); } } pub fn drawTriangle(self: *TriangleBatcher, pt1: math.Vec2, pt2: math.Vec2, pt3: math.Vec2, color: math.Color) void { self.ensureCapacity() catch |err| { std.log.warn("TriangleBatcher.draw failed to append a draw call with error: {}\n", .{err}); return; }; // copy the triangle positions, uvs and color into vertex array transforming them with the matrix after we do it self.mesh.verts[self.vert_index].pos = pt1; self.mesh.verts[self.vert_index].col = color.value; self.mesh.verts[self.vert_index + 1].pos = pt2; self.mesh.verts[self.vert_index + 1].col = color.value; self.mesh.verts[self.vert_index + 2].pos = pt3; self.mesh.verts[self.vert_index + 2].col = color.value; const mat = math.Mat32.identity; mat.transformVertexSlice(self.mesh.verts[self.vert_index .. self.vert_index + 3]); self.draw_calls.items[self.draw_calls.items.len - 1] += 3; self.vert_count += 3; self.vert_index += 3; } }; test "test triangle batcher" { var batcher = try TriangleBatcher.init(null, 10); _ = try batcher.ensureCapacity(null); batcher.flush(false); batcher.deinit(); }
gamekit/graphics/triangle_batcher.zig
const std = @import("std"); const crypto = std.crypto; const debug = std.debug; const mem = std.mem; const meta = std.meta; const ArrayList = std.ArrayList; const FixedBufferAllocator = std.heap.FixedBufferAllocator; const BoundedArray = std.BoundedArray; const hpke_version = [7]u8{ 'H', 'P', 'K', 'E', '-', 'v', '1' }; /// HPKE mode pub const Mode = enum(u8) { base = 0x00, psk = 0x01, auth = 0x02, authPsk = 0x03 }; /// Maximum length of a public key in bytes pub const max_public_key_length: usize = 32; /// Maximum length of a secret key in bytes pub const max_secret_key_length: usize = 32; /// Maximum length of a shared key in bytes pub const max_shared_key_length: usize = 32; /// Maximum length of a PRK in bytes pub const max_prk_length: usize = 32; /// Maximum length of a label in bytes pub const max_label_length: usize = 64; /// Maximum length of an info string in bytes pub const max_info_length: usize = 64; /// Maximum length of a suite ID pub const max_suite_id_length: usize = 10; /// Maximum length of a hash function pub const max_digest_length: usize = 32; /// Maximum length of input keying material pub const max_ikm_length: usize = 64; /// Maximum length of an AEAD key pub const max_aead_key_length: usize = 32; /// Maximum length of an AEAD nonce pub const max_aead_nonce_length: usize = 12; /// Maximum length of an AEAD tag pub const max_aead_tag_length: usize = 16; /// HPKE primitives pub const primitives = struct { /// Key exchange mechanisms pub const Kem = struct { id: u16, secret_length: usize, public_length: usize, shared_length: usize, digest_length: usize, generateKeyPairFn: fn () anyerror!KeyPair, deterministicKeyPairFn: fn (secret_key: []const u8) anyerror!KeyPair, dhFn: fn (out: []u8, pk: []const u8, sk: []const u8) anyerror!void, /// X25519-HKDF-SHA256 pub const X25519HkdfSha256 = struct { const H = crypto.hash.sha2.Sha256; const K = crypto.kdf.hkdf.HkdfSha256; pub const id: u16 = 0x0020; pub const secret_length: usize = crypto.dh.X25519.secret_length; pub const public_length: usize = crypto.dh.X25519.public_length; pub const shared_length: usize = crypto.dh.X25519.shared_length; fn generateKeyPair() !KeyPair { const kp = try crypto.dh.X25519.KeyPair.create(null); return KeyPair{ .public_key = try BoundedArray(u8, max_public_key_length).fromSlice(&kp.public_key), .secret_key = try BoundedArray(u8, max_secret_key_length).fromSlice(&kp.secret_key), }; } fn deterministicKeyPair(secret_key: []const u8) !KeyPair { debug.assert(secret_key.len == secret_length); const public_key = try crypto.dh.X25519.recoverPublicKey(secret_key[0..secret_length].*); return KeyPair{ .public_key = try BoundedArray(u8, max_public_key_length).fromSlice(&public_key), .secret_key = try BoundedArray(u8, max_secret_key_length).fromSlice(secret_key), }; } fn dh(out: []u8, pk: []const u8, sk: []const u8) !void { if (pk.len != public_length or sk.len != secret_length or out.len != shared_length) { return error.InvalidParameters; } const dh_secret = try crypto.dh.X25519.scalarmult(sk[0..secret_length].*, pk[0..public_length].*); mem.copy(u8, out, &dh_secret); } pub const kem = Kem{ .id = 0x0020, .secret_length = secret_length, .shared_length = shared_length, .public_length = public_length, .digest_length = H.digest_length, .generateKeyPairFn = generateKeyPair, .deterministicKeyPairFn = deterministicKeyPair, .dhFn = dh, }; }; /// Return a suite given a suite ID pub fn fromId(id: u16) !Kem { return switch (id) { X25519HkdfSha256.id => X25519HkdfSha256.kem, else => error.UnsupportedKem, }; } }; /// Key derivation functions pub const Kdf = struct { id: u16, prk_length: usize, extract: fn (out: []u8, salt: []const u8, ikm: []const u8) void, expand: fn (out: []u8, ctx: []const u8, prk: []const u8) void, /// HKDF-SHA-256 pub const HkdfSha256 = struct { const M = crypto.auth.hmac.sha2.HmacSha256; const F = crypto.kdf.hkdf.Hkdf(M); pub const prk_length = M.mac_length; pub const id: u16 = 0x0001; fn extract(out: []u8, salt: []const u8, ikm: []const u8) void { const prk = F.extract(salt, ikm); debug.assert(prk.len == out.len); mem.copy(u8, out, &prk); } fn expand(out: []u8, ctx: []const u8, prk: []const u8) void { debug.assert(prk.len == prk_length); F.expand(out, ctx, prk[0..prk_length].*); } pub const kdf = Kdf{ .id = id, .prk_length = prk_length, .extract = extract, .expand = expand, }; }; /// Return a KDF from a KDF id pub fn fromId(id: u16) !Kdf { return switch (id) { HkdfSha256.id => HkdfSha256.kdf, else => error.UnsupportedKdf, }; } }; /// AEADs pub const Aead = struct { id: u16, key_length: usize, nonce_length: usize, tag_length: usize, newStateFn: fn (key: []const u8, base_nonce: []const u8) error{ InvalidParameters, Overflow }!State, /// An AEAD state pub const State = struct { base_nonce: BoundedArray(u8, max_aead_nonce_length), counter: BoundedArray(u8, max_aead_nonce_length), key: BoundedArray(u8, max_aead_key_length), encryptFn: fn (c: []u8, m: []const u8, ad: []const u8, nonce: []const u8, key: []const u8) void, decryptFn: fn (m: []u8, c: []const u8, ad: []const u8, nonce: []const u8, key: []const u8) crypto.errors.AuthenticationError!void, fn incrementCounter(counter: []u8) void { var i = counter.len; var carry: u1 = 1; var x: u8 = undefined; while (true) { i -= 1; carry = @boolToInt(@addWithOverflow(u8, counter[i], carry, &x)); counter[i] = x; if (i == 0) break; } debug.assert(carry == 0); // Counter overflow } /// Increment the nonce pub fn nextNonce(state: *State) BoundedArray(u8, max_aead_nonce_length) { debug.assert(state.counter.len == state.base_nonce.len); var base_nonce = @TypeOf(state.base_nonce).fromSlice(state.base_nonce.constSlice()) catch unreachable; var nonce = base_nonce.slice(); var counter = state.counter.slice(); for (nonce) |*p, i| { p.* ^= counter[i]; } incrementCounter(counter); return BoundedArray(u8, max_aead_nonce_length).fromSlice(nonce) catch unreachable; } }; /// AES-128-GCM pub const Aes128Gcm = struct { const A = crypto.aead.aes_gcm.Aes128Gcm; pub const id: u16 = 0x0001; fn newState(key: []const u8, base_nonce: []const u8) error{ InvalidParameters, Overflow }!State { if (key.len != A.key_length or base_nonce.len != A.nonce_length) { return error.InvalidParameters; } var counter = try BoundedArray(u8, max_aead_nonce_length).init(A.nonce_length); mem.set(u8, counter.slice(), 0); var state = State{ .base_nonce = try BoundedArray(u8, max_aead_nonce_length).fromSlice(base_nonce), .counter = counter, .key = try BoundedArray(u8, max_aead_key_length).fromSlice(key), .encryptFn = encrypt, .decryptFn = decrypt, }; return state; } fn encrypt(c: []u8, m: []const u8, ad: []const u8, nonce: []const u8, key: []const u8) void { A.encrypt(c[0..m.len], c[m.len..][0..A.tag_length], m, ad, nonce[0..A.nonce_length].*, key[0..A.key_length].*); } fn decrypt(m: []u8, c: []const u8, ad: []const u8, nonce: []const u8, key: []const u8) !void { return A.decrypt(m, c[0..m.len], c[m.len..][0..A.tag_length].*, ad, nonce[0..A.nonce_length].*, key[0..A.key_length].*); } pub const aead = Aead{ .id = id, .key_length = A.key_length, .nonce_length = A.nonce_length, .tag_length = A.tag_length, .newStateFn = newState, }; }; /// Use an external AEAD pub const ExportOnly = struct { pub const id: u16 = 0xffff; }; /// Return an AEAD given an ID pub fn fromId(id: u16) !?Aead { return switch (id) { Aes128Gcm.id => Aes128Gcm.aead, ExportOnly.id => null, else => error.UnsupportedKdf, }; } }; }; /// A pre-shared key pub const Psk = struct { key: []u8, id: []u8, }; /// A key pair pub const KeyPair = struct { public_key: BoundedArray(u8, max_public_key_length), secret_key: BoundedArray(u8, max_secret_key_length), }; /// An HPKE suite pub const Suite = struct { id: struct { context: [10]u8, kem: [5]u8, }, kem: primitives.Kem, kdf: primitives.Kdf, aead: ?primitives.Aead, fn contextSuiteId(kem: primitives.Kem, kdf: primitives.Kdf, aead: ?primitives.Aead) [10]u8 { var id = [10]u8{ 'H', 'P', 'K', 'E', 0, 0, 0, 0, 0, 0 }; mem.writeIntBig(u16, id[4..6], kem.id); mem.writeIntBig(u16, id[6..8], kdf.id); mem.writeIntBig(u16, id[8..10], if (aead) |a| a.id else primitives.Aead.ExportOnly.id); return id; } fn kemSuiteId(kem: primitives.Kem) [5]u8 { var id = [5]u8{ 'K', 'E', 'M', 0, 0 }; mem.writeIntBig(u16, id[3..5], kem.id); return id; } /// Create an HPKE suite given its components identifiers pub fn init(kem_id: u16, kdf_id: u16, aead_id: u16) !Suite { const kem = switch (kem_id) { primitives.Kem.X25519HkdfSha256.id => primitives.Kem.X25519HkdfSha256.kem, else => unreachable, }; const kdf = try primitives.Kdf.fromId(kdf_id); const aead = try primitives.Aead.fromId(aead_id); return Suite{ .id = .{ .context = contextSuiteId(kem, kdf, aead), .kem = kemSuiteId(kem), }, .kem = kem, .kdf = kdf, .aead = aead, }; } /// Extract a PRK out of input keying material and an optional salt pub fn extract(suite: Suite, prk: []u8, salt: ?[]const u8, ikm: []const u8) void { const prk_length = suite.kdf.prk_length; debug.assert(prk.len == prk_length); suite.kdf.extract(prk, salt orelse "", ikm); } /// Expand a PRK into an arbitrary-long key for the context `ctx` pub fn expand(suite: Suite, out: []u8, ctx: []const u8, prk: []const u8) void { suite.kdf.expand(out, ctx, prk); } pub const Prk = BoundedArray(u8, max_prk_length); /// Create a PRK given a suite ID, a label, input keying material and an optional salt pub fn labeledExtract(suite: Suite, suite_id: []const u8, salt: ?[]const u8, label: []const u8, ikm: []const u8) !Prk { var buffer: [hpke_version.len + max_suite_id_length + max_label_length + max_ikm_length]u8 = undefined; var alloc = FixedBufferAllocator.init(&buffer); var secret = try ArrayList(u8).initCapacity(alloc.allocator(), alloc.buffer.len); try secret.appendSlice(&hpke_version); try secret.appendSlice(suite_id); try secret.appendSlice(label); try secret.appendSlice(ikm); var prk = try Prk.init(suite.kdf.prk_length); suite.extract(prk.slice(), salt, secret.items); return prk; } /// Expand a PRK using a suite, a label and optional information pub fn labeledExpand(suite: Suite, out: []u8, suite_id: []const u8, prk: Prk, label: []const u8, info: ?[]const u8) !void { var out_length = [_]u8{ 0, 0 }; mem.writeIntBig(u16, &out_length, @intCast(u16, out.len)); var buffer: [out_length.len + hpke_version.len + max_suite_id_length + max_label_length + max_info_length]u8 = undefined; var alloc = FixedBufferAllocator.init(&buffer); var labeled_info = try ArrayList(u8).initCapacity(alloc.allocator(), alloc.buffer.len); try labeled_info.appendSlice(&out_length); try labeled_info.appendSlice(&hpke_version); try labeled_info.appendSlice(suite_id); try labeled_info.appendSlice(label); if (info) |i| try labeled_info.appendSlice(i); suite.expand(out, labeled_info.items, prk.constSlice()); } fn verifyPskInputs(mode: Mode, psk: ?Psk) !void { if (psk) |p| { if ((p.key.len == 0) != (psk == null)) { return error.PskKeyAndIdMustBeSet; } if (mode == .base or mode == .auth) { return error.PskNotRequired; } } else if (mode == .psk or mode == .authPsk) { return error.PskRequired; } } fn keySchedule(suite: Suite, mode: Mode, dh_secret: []const u8, info: []const u8, psk: ?Psk) !Context { try verifyPskInputs(mode, psk); const psk_id: []const u8 = if (psk) |p| p.id else &[_]u8{}; var psk_id_hash = try suite.labeledExtract(&suite.id.context, null, "psk_id_hash", psk_id); var info_hash = try suite.labeledExtract(&suite.id.context, null, "info_hash", info); var buffer: [1 + max_prk_length + max_prk_length]u8 = undefined; var alloc = FixedBufferAllocator.init(&buffer); var key_schedule_ctx = try ArrayList(u8).initCapacity(alloc.allocator(), alloc.buffer.len); try key_schedule_ctx.append(@enumToInt(mode)); try key_schedule_ctx.appendSlice(psk_id_hash.constSlice()); try key_schedule_ctx.appendSlice(info_hash.constSlice()); var secret = try suite.labeledExtract(&suite.id.context, dh_secret, "secret", psk_id); var exporter_secret = try BoundedArray(u8, max_prk_length).init(suite.kdf.prk_length); try suite.labeledExpand(exporter_secret.slice(), &suite.id.context, secret, "exp", key_schedule_ctx.items); var outbound_state = if (suite.aead) |aead| blk: { var outbound_key = try BoundedArray(u8, max_aead_key_length).init(aead.key_length); try suite.labeledExpand(outbound_key.slice(), &suite.id.context, secret, "key", key_schedule_ctx.items); var outbound_base_nonce = try BoundedArray(u8, max_aead_nonce_length).init(aead.nonce_length); try suite.labeledExpand(outbound_base_nonce.slice(), &suite.id.context, secret, "base_nonce", key_schedule_ctx.items); break :blk try aead.newStateFn(outbound_key.constSlice(), outbound_base_nonce.constSlice()); } else null; return Context{ .suite = suite, .exporter_secret = exporter_secret, .outbound_state = outbound_state, }; } /// Create a new key pair pub fn generateKeyPair(suite: Suite) !KeyPair { return suite.kem.generateKeyPairFn(); } /// Create a new deterministic key pair pub fn deterministicKeyPair(suite: Suite, seed: []const u8) !KeyPair { var prk = try suite.labeledExtract(&suite.id.kem, null, "dkp_prk", seed); var secret_key = try BoundedArray(u8, max_secret_key_length).init(suite.kem.secret_length); try suite.labeledExpand(secret_key.slice(), &suite.id.kem, prk, "sk", null); return suite.kem.deterministicKeyPairFn(secret_key.constSlice()); } fn extractAndExpandDh(suite: Suite, dh: []const u8, kem_ctx: []const u8) !BoundedArray(u8, max_shared_key_length) { const prk = try suite.labeledExtract(&suite.id.kem, null, "eae_prk", dh); var dh_secret = try BoundedArray(u8, max_digest_length).init(suite.kem.shared_length); try suite.labeledExpand(dh_secret.slice(), &suite.id.kem, prk, "shared_secret", kem_ctx); return dh_secret; } /// A secret, and an encapsulated (encrypted) representation of it pub const EncapsulatedSecret = struct { secret: BoundedArray(u8, max_digest_length), encapsulated: BoundedArray(u8, max_public_key_length), }; /// Generate a secret, return it as well as its encapsulation pub fn encap(suite: Suite, server_pk: []const u8, seed: ?[]const u8) !EncapsulatedSecret { var eph_kp = if (seed) |s| try suite.deterministicKeyPair(s) else try suite.generateKeyPair(); var dh = try BoundedArray(u8, max_shared_key_length).init(suite.kem.shared_length); try suite.kem.dhFn(dh.slice(), server_pk, eph_kp.secret_key.slice()); var buffer: [max_public_key_length + max_public_key_length]u8 = undefined; var alloc = FixedBufferAllocator.init(&buffer); var kem_ctx = try ArrayList(u8).initCapacity(alloc.allocator(), alloc.buffer.len); try kem_ctx.appendSlice(eph_kp.public_key.constSlice()); try kem_ctx.appendSlice(server_pk); const dh_secret = try suite.extractAndExpandDh(dh.constSlice(), kem_ctx.items); return EncapsulatedSecret{ .secret = dh_secret, .encapsulated = eph_kp.public_key, }; } /// Generate a secret, return it as well as its encapsulation, with authentication support pub fn authEncap(suite: Suite, server_pk: []const u8, client_kp: KeyPair, seed: ?[]const u8) !EncapsulatedSecret { var eph_kp = if (seed) |s| try suite.deterministicKeyPair(s) else try suite.generateKeyPair(); var dh1 = try BoundedArray(u8, max_shared_key_length).init(suite.kem.shared_length); try suite.kem.dhFn(dh1.slice(), server_pk, eph_kp.secret_key.constSlice()); var dh2 = try BoundedArray(u8, max_shared_key_length).init(suite.kem.shared_length); try suite.kem.dhFn(dh2.slice(), server_pk, client_kp.secret_key.constSlice()); var dh = try BoundedArray(u8, 2 * max_shared_key_length).init(dh1.len + dh2.len); mem.copy(u8, dh.slice()[0..dh1.len], dh1.constSlice()); mem.copy(u8, dh.slice()[dh1.len..][0..dh2.len], dh2.constSlice()); var buffer: [3 * max_public_key_length]u8 = undefined; var alloc = FixedBufferAllocator.init(&buffer); var kem_ctx = try ArrayList(u8).initCapacity(alloc.allocator(), alloc.buffer.len); try kem_ctx.appendSlice(eph_kp.public_key.constSlice()); try kem_ctx.appendSlice(server_pk); try kem_ctx.appendSlice(client_kp.public_key.constSlice()); const dh_secret = try suite.extractAndExpandDh(dh.constSlice(), kem_ctx.items); return EncapsulatedSecret{ .secret = dh_secret, .encapsulated = eph_kp.public_key, }; } /// Decapsulate a secret pub fn decap(suite: Suite, eph_pk: []const u8, server_kp: KeyPair) !BoundedArray(u8, max_shared_key_length) { var dh = try BoundedArray(u8, max_shared_key_length).init(suite.kem.shared_length); try suite.kem.dhFn(dh.slice(), eph_pk, server_kp.secret_key.constSlice()); var buffer: [2 * max_public_key_length]u8 = undefined; var alloc = FixedBufferAllocator.init(&buffer); var kem_ctx = try ArrayList(u8).initCapacity(alloc.allocator(), alloc.buffer.len); try kem_ctx.appendSlice(eph_pk); try kem_ctx.appendSlice(server_kp.public_key.constSlice()); return suite.extractAndExpandDh(dh.constSlice(), kem_ctx.items); } /// Authenticate a client using its public key and decapsulate a secret pub fn authDecap(suite: Suite, eph_pk: []const u8, server_kp: KeyPair, client_pk: []const u8) !BoundedArray(u8, max_shared_key_length) { var dh1 = try BoundedArray(u8, max_shared_key_length).init(suite.kem.shared_length); try suite.kem.dhFn(dh1.slice(), eph_pk, server_kp.secret_key.constSlice()); var dh2 = try BoundedArray(u8, max_shared_key_length).init(suite.kem.shared_length); try suite.kem.dhFn(dh2.slice(), client_pk, server_kp.secret_key.constSlice()); var dh = try BoundedArray(u8, 2 * max_shared_key_length).init(dh1.len + dh2.len); mem.copy(u8, dh.slice()[0..dh1.len], dh1.constSlice()); mem.copy(u8, dh.slice()[dh1.len..][0..dh2.len], dh2.constSlice()); var buffer: [3 * max_public_key_length]u8 = undefined; var alloc = FixedBufferAllocator.init(&buffer); var kem_ctx = try ArrayList(u8).initCapacity(alloc.allocator(), alloc.buffer.len); try kem_ctx.appendSlice(eph_pk); try kem_ctx.appendSlice(server_kp.public_key.constSlice()); try kem_ctx.appendSlice(client_pk); return suite.extractAndExpandDh(dh.constSlice(), kem_ctx.items); } /// A client context as well as an encapsulated secret pub const ClientContextAndEncapsulatedSecret = struct { client_ctx: ClientContext, encapsulated_secret: EncapsulatedSecret, }; /// Create a new client context pub fn createClientContext(suite: Suite, server_pk: []const u8, info: []const u8, psk: ?Psk, seed: ?[]const u8) !ClientContextAndEncapsulatedSecret { const encapsulated_secret = try suite.encap(server_pk, seed); const mode: Mode = if (psk) |_| .psk else .base; const inner_ctx = try suite.keySchedule(mode, encapsulated_secret.secret.constSlice(), info, psk); const client_ctx = ClientContext{ .ctx = inner_ctx }; return ClientContextAndEncapsulatedSecret{ .client_ctx = client_ctx, .encapsulated_secret = encapsulated_secret, }; } /// Create a new client authenticated context pub fn createAuthenticatedClientContext(suite: Suite, client_kp: KeyPair, server_pk: []const u8, info: []const u8, psk: ?Psk, seed: ?[]const u8) !ClientContextAndEncapsulatedSecret { const encapsulated_secret = try suite.authEncap(server_pk, client_kp, seed); const mode: Mode = if (psk) |_| .authPsk else .auth; const inner_ctx = try suite.keySchedule(mode, encapsulated_secret.secret.constSlice(), info, psk); const client_ctx = ClientContext{ .ctx = inner_ctx }; return ClientContextAndEncapsulatedSecret{ .client_ctx = client_ctx, .encapsulated_secret = encapsulated_secret, }; } /// Create a new server context pub fn createServerContext(suite: Suite, encapsulated_secret: []const u8, server_kp: KeyPair, info: []const u8, psk: ?Psk) !ServerContext { const dh_secret = try suite.decap(encapsulated_secret, server_kp); const mode: Mode = if (psk) |_| .psk else .base; const inner_ctx = try suite.keySchedule(mode, dh_secret.constSlice(), info, psk); return ServerContext{ .ctx = inner_ctx }; } /// Create a new authenticated server context pub fn createAuthenticatedServerContext(suite: Suite, client_pk: []const u8, encapsulated_secret: []const u8, server_kp: KeyPair, info: []const u8, psk: ?Psk) !ServerContext { const dh_secret = try suite.authDecap(encapsulated_secret, server_kp, client_pk); const mode: Mode = if (psk) |_| .authPsk else .auth; const inner_ctx = try suite.keySchedule(mode, dh_secret.constSlice(), info, psk); return ServerContext{ .ctx = inner_ctx }; } }; const Context = struct { suite: Suite, exporter_secret: BoundedArray(u8, max_prk_length), inbound_state: ?primitives.Aead.State = null, outbound_state: ?primitives.Aead.State = null, fn exportSecret(ctx: Context, out: []u8, exporter_context: []const u8) !void { try ctx.suite.labeledExpand(out, &ctx.suite.id.context, ctx.exporter_secret, "sec", exporter_context); } fn responseState(ctx: Context) !primitives.Aead.State { var inbound_key = try BoundedArray(u8, max_aead_key_length).init(ctx.suite.aead.?.key_length); var inbound_base_nonce = try BoundedArray(u8, max_aead_nonce_length).init(ctx.suite.aead.?.nonce_length); try ctx.exportSecret(inbound_key.slice(), "response key"); try ctx.exportSecret(inbound_base_nonce.slice(), "response nonce"); return ctx.suite.aead.?.newStateFn(inbound_key.constSlice(), inbound_base_nonce.constSlice()); } }; /// A client context pub const ClientContext = struct { ctx: Context, /// Encrypt a message for the server pub fn encryptToServer(client_context: *ClientContext, ciphertext: []u8, message: []const u8, ad: []const u8) void { const required_ciphertext_length = client_context.ctx.suite.aead.?.tag_length + message.len; debug.assert(ciphertext.len == required_ciphertext_length); var state = &client_context.ctx.outbound_state.?; const nonce = state.nextNonce(); state.encryptFn(ciphertext, message, ad, nonce.constSlice(), state.key.constSlice()); } /// Decrypt a response from the server pub fn decryptFromServer(client_context: *ClientContext, message: []u8, ciphertext: []const u8, ad: []const u8) !void { if (client_context.ctx.inbound_state == null) { client_context.ctx.inbound_state = client_context.ctx.responseState() catch unreachable; } const required_ciphertext_length = client_context.ctx.suite.aead.?.tag_length + message.len; debug.assert(ciphertext.len == required_ciphertext_length); var state = &client_context.ctx.inbound_state.?; const nonce = state.nextNonce(); try state.decryptFn(message, ciphertext, ad, nonce.constSlice(), state.key.constSlice()); } /// Return the exporter secret pub fn exporterSecret(client_context: ClientContext) BoundedArray(u8, max_prk_length) { return client_context.ctx.exporter_secret; } /// Derive an arbitrary-long secret pub fn exportSecret(client_context: ClientContext, out: []u8, info: []const u8) !void { try client_context.ctx.exportSecret(out, info); } /// Return the tag length pub fn tagLength(client_context: ClientContext) usize { return client_context.ctx.suite.aead.?.tag_length; } }; /// A server context pub const ServerContext = struct { ctx: Context, /// Decrypt a ciphertext received from the client pub fn decryptFromClient(server_context: *ServerContext, message: []u8, ciphertext: []const u8, ad: []const u8) !void { const required_ciphertext_length = server_context.ctx.suite.aead.?.tag_length + message.len; debug.assert(ciphertext.len == required_ciphertext_length); var state = &server_context.ctx.outbound_state.?; const nonce = state.nextNonce(); try state.decryptFn(message, ciphertext, ad, nonce.constSlice(), state.key.constSlice()); } /// Encrypt a response to the client pub fn encryptToClient(server_context: *ServerContext, ciphertext: []u8, message: []const u8, ad: []const u8) void { if (server_context.ctx.inbound_state == null) { server_context.ctx.inbound_state = server_context.ctx.responseState() catch unreachable; } const required_ciphertext_length = server_context.ctx.suite.aead.?.tag_length + message.len; debug.assert(ciphertext.len == required_ciphertext_length); var state = &server_context.ctx.inbound_state.?; const nonce = state.nextNonce(); state.encryptFn(ciphertext, message, ad, nonce.constSlice(), state.key.constSlice()); } /// Return the exporter secret pub fn exporterSecret(server_context: ServerContext) BoundedArray(u8, max_prk_length) { return server_context.ctx.exporter_secret; } /// Derive an arbitrary-long secret pub fn exportSecret(server_context: ServerContext, out: []u8, info: []const u8) !void { try server_context.ctx.exportSecret(out, info); } /// Return the tag length pub fn tagLength(server_context: ServerContext) usize { return server_context.ctx.suite.aead.?.tag_length; } }; test { _ = @import("tests.zig"); }
src/main.zig
const std = @import("std"); const array = @import("array.zig"); const Array = array.Array; const module = @import("module.zig"); pub const SGD = struct { parameters: []module.Parameter, momentums: []Array, momentum: f32, alc: *std.mem.Allocator, const Self = @This(); pub fn init(alc: *std.mem.Allocator, parameters: []module.Parameter, momentum: f32) !Self { var momentums = try alc.alloc(Array, parameters.len); for (momentums) |_, index| { momentums[index] = try array.zerosLikeAlloc(alc, parameters[index].value.grad.?); } return Self{.parameters=parameters, .alc=alc, .momentum=momentum, .momentums=momentums}; } pub fn deinit(self: *Self) void { for (self.momentums) |v| { v.release(); } self.alc.free(self.momentums); } pub fn zeroGrad(self: *Self) !void { for (self.parameters) |param| { var grad = param.value.grad.?; var zero = try array.scalarAlloc(self.alc, grad.dtype, 0.0); defer zero.release(); array.copy(zero, grad); } } pub fn step(self: *Self, lr: f32) !void { for (self.parameters) |param, index| { var grad = param.value.grad.?; if (self.momentum != 0) { // update momentum var v = self.momentums[index]; var new_v = try array.expr(self.alc, "m .* v .+ g", .{.m=self.momentum, .v=v, .g=grad}); defer new_v.release(); array.copy(new_v, v); grad = v; } var update = try array.expr(self.alc, "-lr .* g", .{.lr=lr, .g=grad}); defer update.release(); var data = param.value.data; array.plus(data, update, data); } } }; // Adam: A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 pub const Adam = struct { parameters: []module.Parameter, first_moments: []Array, second_moments: []Array, beta1: f32, beta2: f32, epsilon: f32, step_count: u64, alc: *std.mem.Allocator, const Self = @This(); pub fn init(alc: *std.mem.Allocator, parameters: []module.Parameter, beta1: f32, beta2: f32, epsilon: f32) !Self { var first_moments = try alc.alloc(Array, parameters.len); var second_moments = try alc.alloc(Array, parameters.len); for (first_moments) |_, index| { first_moments[index] = try array.zerosLikeAlloc(alc, parameters[index].value.grad.?); second_moments[index] = try array.zerosLikeAlloc(alc, parameters[index].value.grad.?); } return Self{.parameters=parameters, .alc=alc, .beta1=beta1, .beta2=beta2, .epsilon=epsilon, .step_count=0, .first_moments=first_moments, .second_moments=second_moments}; } pub fn deinit(self: *Self) void { for (self.first_moments) |v| { v.release(); } self.alc.free(self.first_moments); for (self.second_moments) |v| { v.release(); } self.alc.free(self.second_moments); } pub fn zeroGrad(self: *Self) !void { for (self.parameters) |param| { var grad = param.value.grad.?; var zero = try array.scalarAlloc(self.alc, grad.dtype, 0.0); defer zero.release(); array.copy(zero, grad); } } pub fn step(self: *Self, lr: f32) !void { self.step_count += 1; for (self.parameters) |param, index| { var grad = param.value.grad.?; var m = self.first_moments[index]; var new_m = try array.expr(self.alc, "beta1 .* m + (1 - beta1) .* g", .{.m=m, .beta1=self.beta1, .g=grad}); defer new_m.release(); array.copy(new_m, m); var v = self.second_moments[index]; var new_v = try array.expr(self.alc, "beta2 .* v + (1 - beta2) .* (g .* g)", .{.v=v, .beta2=self.beta2, .g=grad}); defer new_v.release(); array.copy(new_v, v); var m_hat = try array.expr(self.alc, "m ./ (1 - beta1 .^ step)", .{.m=m, .beta1=self.beta1, .step=self.step_count}); defer m_hat.release(); var v_hat = try array.expr(self.alc, "v ./ (1 - beta2 .^ step)", .{.v=v, .beta2=self.beta2, .step=self.step_count}); defer v_hat.release(); var update = try array.expr(self.alc, "-lr .* m_hat ./ (v_hat .^ 0.5 + epsilon)", .{.lr=lr, .m_hat=m_hat, .v_hat=v_hat, .epsilon=self.epsilon}); defer update.release(); var data = param.value.data; array.plus(data, update, data); } } };
src/optim.zig
const std = @import("std"); usingnamespace (@import("../machine.zig")); usingnamespace (@import("../util.zig")); test "SSE" { const m32 = Machine.init(.x86_32); const m64 = Machine.init(.x64); const reg = Operand.register; const regRm = Operand.registerRm; const imm = Operand.immediate; debugPrint(false); const rm16 = Operand.memoryRm(.DefaultSeg, .WORD, .EAX, 0); const rm32 = Operand.memoryRm(.DefaultSeg, .DWORD, .EAX, 0); const rm64 = Operand.memoryRm(.DefaultSeg, .QWORD, .EAX, 0); const mem_32 = rm32; const mem_64 = rm64; const rm_mem8 = Operand.memoryRm(.DefaultSeg, .BYTE, .EAX, 0); const rm_mem16 = Operand.memoryRm(.DefaultSeg, .WORD, .EAX, 0); const rm_mem32 = Operand.memoryRm(.DefaultSeg, .DWORD, .EAX, 0); const rm_mem64 = Operand.memoryRm(.DefaultSeg, .QWORD, .EAX, 0); const rm_mem128 = Operand.memoryRm(.DefaultSeg, .XMM_WORD, .EAX, 0); const mem_128 = Operand.memoryRm(.DefaultSeg, .OWORD, .EAX, 0); testOp2(m32, .ADDPD, reg(.XMM0), mem_128, "66 0f 58 00"); testOp2(m32, .ADDPS, reg(.XMM0), mem_128, "0f 58 00"); testOp2(m32, .ADDSD, reg(.XMM0), mem_64, "f2 0f 58 00"); testOp2(m32, .ADDSS, reg(.XMM0), mem_32, "f3 0f 58 00"); testOp2(m32, .ADDSUBPD, reg(.XMM0), mem_128, "66 0f D0 00"); testOp2(m32, .ADDSUBPS, reg(.XMM0), mem_128, "f2 0f D0 00"); testOp2(m32, .ANDPD, reg(.XMM0), mem_128, "66 0f 54 00"); testOp2(m32, .ANDPS, reg(.XMM0), mem_128, "0f 54 00"); testOp2(m32, .ANDNPD, reg(.XMM0), mem_128, "66 0f 55 00"); testOp2(m32, .ANDNPS, reg(.XMM0), mem_128, "0f 55 00"); testOp3(m32, .CMPSD, reg(.XMM0), mem_64, imm(0), "f2 0f c2 00 00"); testOp3(m32, .CMPSS, reg(.XMM0), mem_32, imm(0), "f3 0f c2 00 00"); { // BLENDPD testOp3(m64, .BLENDPD, reg(.XMM0), reg(.XMM0), imm(0), "66 0f 3a 0d c0 00"); // BLENDPS testOp3(m64, .BLENDPS, reg(.XMM0), reg(.XMM0), imm(0), "66 0f 3a 0c c0 00"); // BLENDVPD testOp3(m64, .BLENDVPD, reg(.XMM0), reg(.XMM0), reg(.XMM0), "66 0f 38 15 c0"); testOp2(m64, .BLENDVPD, reg(.XMM0), reg(.XMM0), "66 0f 38 15 c0"); // BLENDVPS testOp3(m64, .BLENDVPS, reg(.XMM0), reg(.XMM0), reg(.XMM0), "66 0f 38 14 c0"); testOp2(m64, .BLENDVPS, reg(.XMM0), reg(.XMM0), "66 0f 38 14 c0"); } { // COMISD testOp2(m64, .COMISD, reg(.XMM0), reg(.XMM0), "66 0f 2f c0"); // COMISS testOp2(m64, .COMISS, reg(.XMM0), reg(.XMM0), "0f 2f c0"); } { // CVTDQ2PD testOp2(m64, .CVTDQ2PD, reg(.XMM0), reg(.XMM0), "f3 0f e6 c0"); // CVTDQ2PS testOp2(m64, .CVTDQ2PS, reg(.XMM0), reg(.XMM0), "0f 5b c0"); // CVTPD2DQ testOp2(m64, .CVTPD2DQ, reg(.XMM0), reg(.XMM0), "f2 0f e6 c0"); // CVTPD2PI testOp2(m64, .CVTPD2PI, reg(.MM0), reg(.XMM0), "66 0f 2d c0"); // CVTPD2PS testOp2(m64, .CVTPD2PS, reg(.XMM0), reg(.XMM0), "66 0f 5a c0"); // CVTPI2PD testOp2(m64, .CVTPI2PD, reg(.XMM0), reg(.MM0), "66 0f 2a c0"); // CVTPI2PS testOp2(m64, .CVTPI2PS, reg(.XMM0), reg(.MM0), "0f 2a c0"); // CVTPS2DQ testOp2(m64, .CVTPS2DQ, reg(.XMM0), reg(.XMM0), "66 0f 5b c0"); // CVTPS2PD testOp2(m64, .CVTPS2PD, reg(.XMM0), reg(.XMM0), "0f 5a c0"); // CVTPS2PI testOp2(m64, .CVTPS2PI, reg(.MM0), reg(.XMM0), "0f 2d c0"); // CVTSD2SI testOp2(m64, .CVTSD2SI, reg(.EAX), reg(.XMM0), "f2 0f 2d c0"); testOp2(m64, .CVTSD2SI, reg(.RAX), reg(.XMM0), "f2 48 0f 2d c0"); testOp2(m32, .CVTSD2SI, reg(.RAX), reg(.XMM0), AsmError.InvalidOperand); // CVTSD2SS testOp2(m64, .CVTSD2SS, reg(.XMM0), reg(.XMM0), "f2 0f 5a c0"); // CVTSI2SD testOp2(m64, .CVTSI2SD, reg(.XMM0), rm32, "67 f2 0f 2a 00"); testOp2(m64, .CVTSI2SD, reg(.XMM0), rm64, "67 f2 48 0f 2a 00"); // CVTSI2SS testOp2(m64, .CVTSI2SS, reg(.XMM0), rm32, "67 f3 0f 2a 00"); testOp2(m64, .CVTSI2SS, reg(.XMM0), rm64, "67 f3 48 0f 2a 00"); // CVTSS2SD testOp2(m64, .CVTSS2SD, reg(.XMM0), reg(.XMM0), "f3 0f 5a c0"); // CVTSS2SI testOp2(m64, .CVTSS2SI, reg(.EAX), reg(.XMM0), "f3 0f 2d c0"); testOp2(m64, .CVTSS2SI, reg(.RAX), reg(.XMM0), "f3 48 0f 2d c0"); testOp2(m32, .CVTSS2SI, reg(.RAX), reg(.XMM0), AsmError.InvalidOperand); // CVTTPD2DQ testOp2(m64, .CVTTPD2DQ, reg(.XMM0), reg(.XMM0), "66 0f e6 c0"); // CVTTPD2PI testOp2(m64, .CVTTPD2PI, reg(.MM0), reg(.XMM0), "66 0f 2c c0"); // CVTTPS2DQ testOp2(m64, .CVTTPS2DQ, reg(.XMM0), reg(.XMM0), "f3 0f 5b c0"); // CVTTPS2PI testOp2(m64, .CVTTPS2PI, reg(.MM0), reg(.XMM0), "0f 2c c0"); // CVTTSD2SI testOp2(m64, .CVTTSD2SI, reg(.EAX), reg(.XMM0), "f2 0f 2c c0"); testOp2(m64, .CVTTSD2SI, reg(.RAX), reg(.XMM0), "f2 48 0f 2c c0"); testOp2(m32, .CVTTSD2SI, reg(.RAX), reg(.XMM0), AsmError.InvalidOperand); // CVTTSS2SI testOp2(m64, .CVTTSS2SI, reg(.EAX), reg(.XMM0), "f3 0f 2c c0"); testOp2(m64, .CVTTSS2SI, reg(.RAX), reg(.XMM0), "f3 48 0f 2c c0"); testOp2(m32, .CVTTSS2SI, reg(.RAX), reg(.XMM0), AsmError.InvalidOperand); } { // DIVPD testOp2(m64, .DIVPD, reg(.XMM0), reg(.XMM0), "66 0f 5e c0"); // DIVPS testOp2(m64, .DIVPS, reg(.XMM0), reg(.XMM0), "0f 5e c0"); // DIVSD testOp2(m64, .DIVSD, reg(.XMM0), reg(.XMM0), "f2 0f 5e c0"); // DIVSS testOp2(m64, .DIVSS, reg(.XMM0), reg(.XMM0), "f3 0f 5e c0"); // DPPD testOp3(m64, .DPPD, reg(.XMM0), reg(.XMM0), imm(0), "66 0f 3a 41 c0 00"); // DPPS testOp3(m64, .DPPS, reg(.XMM0), reg(.XMM0), imm(0), "66 0f 3a 40 c0 00"); } { // EXTRACTPS testOp3(m64, .EXTRACTPS, rm32, reg(.XMM0), imm(0), "67 66 0f 3a 17 00 00"); testOp3(m64, .EXTRACTPS, reg(.EAX), reg(.XMM0), imm(0), "66 0f 3a 17 c0 00"); testOp3(m64, .EXTRACTPS, reg(.RAX), reg(.XMM0), imm(0), "66 0f 3a 17 c0 00"); testOp3(m32, .EXTRACTPS, reg(.RAX), reg(.XMM0), imm(0), AsmError.InvalidOperand); } { // HADDPD testOp2(m64, .HADDPD, reg(.XMM0), reg(.XMM0), "66 0f 7c c0"); // HADDPS testOp2(m64, .HADDPS, reg(.XMM0), reg(.XMM0), "f2 0f 7c c0"); // HSUBPD testOp2(m64, .HSUBPD, reg(.XMM0), reg(.XMM0), "66 0f 7d c0"); // HSUBPS testOp2(m64, .HSUBPS, reg(.XMM0), reg(.XMM0), "f2 0f 7d c0"); } { // INSERTPS testOp3(m64, .INSERTPS, reg(.XMM0),reg(.XMM0),imm(0), "660f3a21c000"); } { // MAXPD testOp2(m64, .MAXPD, reg(.XMM0), reg(.XMM0), "66 0f 5f c0"); // MAXPS testOp2(m64, .MAXPS, reg(.XMM0), reg(.XMM0), "0f 5f c0"); // MAXSD testOp2(m64, .MAXSD, reg(.XMM0), reg(.XMM0), "f2 0f 5f c0"); // MAXSS testOp2(m64, .MAXSS, reg(.XMM0), reg(.XMM0), "f3 0f 5f c0"); // MINPD testOp2(m64, .MINPD, reg(.XMM0), reg(.XMM0), "66 0f 5d c0"); // MINPS testOp2(m64, .MINPS, reg(.XMM0), reg(.XMM0), "0f 5d c0"); // MINSD testOp2(m64, .MINSD, reg(.XMM0), reg(.XMM0), "f2 0f 5d c0"); // MINSS testOp2(m64, .MINSS, reg(.XMM0), reg(.XMM0), "f3 0f 5d c0"); } { // LDDQU testOp2(m64, .LDDQU, reg(.XMM0), rm_mem128, "67 f2 0f f0 00"); } { // MASKMOVDQU testOp2(m64, .MASKMOVDQU,reg(.XMM0), reg(.XMM0), "66 0f f7 c0"); // MASKMOVQ testOp2(m64, .MASKMOVQ, reg(.MM0), reg(.MM0), "0f f7 c0"); } { // MAXPD testOp2(m64, .MAXPD, reg(.XMM0), reg(.XMM0), "66 0f 5f c0"); // MAXPS testOp2(m64, .MAXPS, reg(.XMM0), reg(.XMM0), "0f 5f c0"); // MAXSD testOp2(m64, .MAXSD, reg(.XMM0), reg(.XMM0), "f2 0f 5f c0"); // MAXSS testOp2(m64, .MAXSS, reg(.XMM0), reg(.XMM0), "f3 0f 5f c0"); // MINPD testOp2(m64, .MINPD, reg(.XMM0), reg(.XMM0), "66 0f 5d c0"); // MINPS testOp2(m64, .MINPS, reg(.XMM0), reg(.XMM0), "0f 5d c0"); // MINSD testOp2(m64, .MINSD, reg(.XMM0), reg(.XMM0), "f2 0f 5d c0"); // MINSS testOp2(m64, .MINSS, reg(.XMM0), reg(.XMM0), "f3 0f 5d c0"); } { // MOVAPD testOp2(m64, .MOVAPD, reg(.XMM0), reg(.XMM0), "660f28c0"); testOp2(m64, .MOVAPD, regRm(.XMM0), reg(.XMM0), "660f29c0"); // MOVAPS testOp2(m64, .MOVAPS, reg(.XMM0), reg(.XMM0), "0f28c0"); testOp2(m64, .MOVAPS, regRm(.XMM0), reg(.XMM0), "0f29c0"); } { { testOp2(m32, .MOVD, reg(.XMM0), rm32, "66 0F 6E 00"); testOp2(m32, .MOVD, reg(.XMM7), rm32, "66 0F 6E 38"); testOp2(m32, .MOVD, reg(.XMM15), rm32, AsmError.InvalidMode); testOp2(m32, .MOVD, reg(.XMM31), rm32, AsmError.InvalidOperand); // testOp2(m64, .MOVD, reg(.XMM0), rm32, "67 66 0F 6E 00"); testOp2(m64, .MOVD, reg(.XMM7), rm32, "67 66 0F 6E 38"); testOp2(m64, .MOVD, reg(.XMM15), rm32, "67 66 44 0F 6E 38"); testOp2(m64, .MOVD, reg(.XMM31), rm32, AsmError.InvalidOperand); } { testOp2(m32, .MOVD, reg(.XMM0), rm64, AsmError.InvalidOperand); testOp2(m32, .MOVD, reg(.XMM7), rm64, AsmError.InvalidOperand); testOp2(m32, .MOVD, reg(.XMM15), rm64, AsmError.InvalidOperand); testOp2(m32, .MOVD, reg(.XMM31), rm64, AsmError.InvalidOperand); // testOp2(m64, .MOVD, reg(.XMM0), rm64, "67 66 48 0F 6E 00"); testOp2(m64, .MOVD, reg(.XMM7), rm64, "67 66 48 0F 6E 38"); testOp2(m64, .MOVD, reg(.XMM15), rm64, "67 66 4C 0F 6E 38"); testOp2(m64, .MOVD, reg(.XMM31), rm64, AsmError.InvalidOperand); } { testOp2(m32, .MOVQ, reg(.XMM0), reg(.RAX), AsmError.InvalidOperand); testOp2(m32, .MOVQ, reg(.XMM15), reg(.RAX), AsmError.InvalidOperand); // testOp2(m64, .MOVQ, reg(.XMM0), reg(.RAX), "66 48 0F 6E C0"); testOp2(m64, .MOVQ, reg(.XMM15), reg(.RAX), "66 4C 0F 6E F8"); testOp2(m64, .MOVQ, reg(.XMM31), reg(.RAX), AsmError.InvalidOperand); } { testOp2(m32, .MOVQ, reg(.RAX), reg(.XMM0), AsmError.InvalidOperand); testOp2(m32, .MOVQ, reg(.RAX), reg(.XMM15), AsmError.InvalidOperand); // testOp2(m64, .MOVQ, reg(.RAX), reg(.XMM0), "66 48 0F 7E C0"); testOp2(m64, .MOVQ, reg(.RAX), reg(.XMM7), "66 48 0F 7E F8"); testOp2(m64, .MOVQ, reg(.RAX), reg(.XMM15), "66 4C 0F 7E F8"); testOp2(m64, .MOVQ, reg(.RAX), reg(.XMM31), AsmError.InvalidOperand); } { testOp2(m32, .MOVQ, reg(.XMM0), mem_64, "F3 0F 7E 00"); testOp2(m32, .MOVQ, reg(.XMM7), mem_64, "F3 0F 7E 38"); testOp2(m32, .MOVQ, reg(.XMM15), mem_64, AsmError.InvalidMode); // testOp2(m64, .MOVQ, reg(.XMM0), mem_64, "67 F3 0F 7E 00"); testOp2(m64, .MOVQ, reg(.XMM7), mem_64, "67 F3 0F 7E 38"); testOp2(m64, .MOVQ, reg(.XMM15), mem_64, "67 F3 44 0F 7E 38"); testOp2(m64, .MOVQ, reg(.XMM31), mem_64, AsmError.InvalidOperand); // testOp2(m64, .MOVD, reg(.XMM0), mem_64, "67 66 48 0F 6E 00"); testOp2(m64, .MOVD, reg(.XMM7), mem_64, "67 66 48 0F 6E 38"); testOp2(m64, .MOVD, reg(.XMM15), mem_64, "67 66 4C 0F 6E 38"); testOp2(m64, .MOVD, reg(.XMM31), mem_64, AsmError.InvalidOperand); } { testOp2(m32, .MOVQ, mem_64, reg(.XMM0), "66 0F D6 00"); testOp2(m32, .MOVQ, mem_64, reg(.XMM7), "66 0F D6 38"); testOp2(m32, .MOVQ, mem_64, reg(.XMM15), AsmError.InvalidMode); // testOp2(m64, .MOVQ, mem_64, reg(.XMM0), "67 66 0F D6 00"); testOp2(m64, .MOVQ, mem_64, reg(.XMM7), "67 66 0F D6 38"); testOp2(m64, .MOVQ, mem_64, reg(.XMM15), "67 66 44 0F D6 38"); testOp2(m64, .MOVQ, mem_64, reg(.XMM31), AsmError.InvalidOperand); // testOp2(m64, .MOVD, mem_64, reg(.XMM0), "67 66 48 0F 7E 00"); testOp2(m64, .MOVD, mem_64, reg(.XMM7), "67 66 48 0F 7E 38"); testOp2(m64, .MOVD, mem_64, reg(.XMM15), "67 66 4C 0F 7E 38"); testOp2(m64, .MOVD, mem_64, reg(.XMM31), AsmError.InvalidOperand); } { testOp2(m32, .MOVQ, reg(.XMM0), reg(.XMM0), "F3 0F 7E c0"); testOp2(m32, .MOVQ, reg(.XMM7), reg(.XMM7), "F3 0F 7E ff"); testOp2(m32, .MOVQ, reg(.XMM15), reg(.XMM15), AsmError.InvalidMode); // testOp2(m64, .MOVQ, reg(.XMM0), reg(.XMM0), "F3 0F 7E c0"); testOp2(m64, .MOVQ, reg(.XMM7), reg(.XMM7), "F3 0F 7E ff"); testOp2(m64, .MOVQ, reg(.XMM15), reg(.XMM15), "F3 45 0F 7E ff"); testOp2(m64, .MOVQ, reg(.XMM31), reg(.XMM15), AsmError.InvalidOperand); // testOp2(m64, .MOVQ, regRm(.XMM0), reg(.XMM0), "66 0F D6 c0"); testOp2(m64, .MOVQ, regRm(.XMM7), reg(.XMM7), "66 0F D6 ff"); testOp2(m64, .MOVQ, regRm(.XMM15), reg(.XMM15), "66 45 0F D6 ff"); testOp2(m64, .MOVQ, regRm(.XMM31), reg(.XMM15), AsmError.InvalidOperand); } } { // MOVDDUP testOp2(m64, .MOVDDUP, reg(.XMM1), regRm(.XMM0), "f2 0f 12 c8"); // MOVDQA testOp2(m64, .MOVDQA, reg(.XMM0), reg(.XMM0), "66 0f 6f c0"); testOp2(m64, .MOVDQA, regRm(.XMM0), reg(.XMM0), "66 0f 7f c0"); // MOVDQU testOp2(m64, .MOVDQU, reg(.XMM0), reg(.XMM0), "f3 0f 6f c0"); testOp2(m64, .MOVDQU, regRm(.XMM0), reg(.XMM0), "f3 0f 7f c0"); // MOVDQ2Q testOp2(m64, .MOVDQ2Q, reg(.MM0), reg(.XMM0), "f2 0f d6 c0"); // MOVHLPS testOp2(m64, .MOVHLPS, reg(.XMM0), reg(.XMM0), "0f 12 c0"); // MOVHPD testOp2(m64, .MOVHPD, reg(.XMM0), rm_mem64, "67 66 0f 16 00"); // MOVHPS testOp2(m64, .MOVHPS, reg(.XMM0), rm_mem64, "67 0f 16 00"); // MOVLHPS testOp2(m64, .MOVLHPS, reg(.XMM0), reg(.XMM0), "0f 16 c0"); // MOVLPD testOp2(m64, .MOVLPD, reg(.XMM0), rm_mem64, "67 66 0f 12 00"); // MOVLPS testOp2(m64, .MOVLPS, reg(.XMM0), rm_mem64, "67 0f 12 00"); // MOVMSKPD testOp2(m64, .MOVMSKPD, reg(.EAX), reg(.XMM0), "66 0f 50 c0"); testOp2(m64, .MOVMSKPD, reg(.RAX), reg(.XMM0), "66 0f 50 c0"); // MOVMSKPS testOp2(m64, .MOVMSKPS, reg(.EAX), reg(.XMM0), "0f 50 c0"); testOp2(m64, .MOVMSKPS, reg(.RAX), reg(.XMM0), "0f 50 c0"); // MOVNTDQA testOp2(m64, .MOVNTDQA, reg(.XMM0), rm_mem128, "67 66 0f 38 2a 00"); // MOVNTDQ testOp2(m64, .MOVNTDQ, rm_mem128, reg(.XMM0), "67 66 0f e7 00"); // MOVNTPD testOp2(m64, .MOVNTPD, rm_mem128, reg(.XMM0), "67 66 0f 2b 00"); // MOVNTPS testOp2(m64, .MOVNTPS, rm_mem128, reg(.XMM0), "67 0f 2b 00"); // MOVNTQ testOp2(m64, .MOVNTQ, rm_mem64, reg(.MM0), "67 0f e7 00"); // MOVQ2DQ testOp2(m64, .MOVQ2DQ, reg(.XMM0), reg(.MM0), "f3 0f d6 c0"); // MOVSD testOp2(m64, .MOVSD, reg(.XMM0), reg(.XMM0), "f2 0f 10 c0"); testOp2(m64, .MOVSD, regRm(.XMM0), reg(.XMM0), "f2 0f 11 c0"); // MOVSHDUP testOp2(m64, .MOVSHDUP, reg(.XMM0), reg(.XMM0), "f3 0f 16 c0"); // MOVSLDUP testOp2(m64, .MOVSLDUP, reg(.XMM0), reg(.XMM0), "f3 0f 12 c0"); // MOVSS testOp2(m64, .MOVSS, reg(.XMM0), reg(.XMM0), "f3 0f 10 c0"); testOp2(m64, .MOVSS, regRm(.XMM0), reg(.XMM0), "f3 0f 11 c0"); // MOVUPD testOp2(m64, .MOVUPD, reg(.XMM0), reg(.XMM0), "66 0f 10 c0"); testOp2(m64, .MOVUPD, regRm(.XMM0), reg(.XMM0), "66 0f 11 c0"); // MOVUPS testOp2(m64, .MOVUPS, reg(.XMM0), reg(.XMM0), "0f 10 c0"); testOp2(m64, .MOVUPS, regRm(.XMM0), reg(.XMM0), "0f 11 c0"); } { // MPSADBW testOp3(m64, .MPSADBW, reg(.XMM1),regRm(.XMM0),imm(0), "66 0f 3a 42 c8 00"); // MULPD testOp2(m64, .MULPD, reg(.XMM1), regRm(.XMM0), "66 0f 59 c8"); // MULPS testOp2(m64, .MULPS, reg(.XMM1), regRm(.XMM0), "0f 59 c8"); // MULSD testOp2(m64, .MULSD, reg(.XMM1), regRm(.XMM0), "f2 0f 59 c8"); // MULSS testOp2(m64, .MULSS, reg(.XMM1), regRm(.XMM0), "f3 0f 59 c8"); } { // ORPD testOp2(m64, .ORPD, reg(.XMM1), regRm(.XMM0), "66 0f 56 c8"); // ORPS testOp2(m64, .ORPS, reg(.XMM1), regRm(.XMM0), "0f 56 c8"); } { // PABSB testOp2(m64, .PABSB, reg(.MM1), regRm(.MM0), "0f 38 1c c8"); testOp2(m64, .PABSB, reg(.XMM1), regRm(.XMM0), "66 0f 38 1c c8"); // PABSW testOp2(m64, .PABSW, reg(.MM1), regRm(.MM0), "0f 38 1d c8"); testOp2(m64, .PABSW, reg(.XMM1), regRm(.XMM0), "66 0f 38 1d c8"); // PABSD testOp2(m64, .PABSD, reg(.MM1), regRm(.MM0), "0f 38 1e c8"); testOp2(m64, .PABSD, reg(.XMM1), regRm(.XMM0), "66 0f 38 1e c8"); } { testOp2(m32, .PACKSSWB, reg(.XMM0), reg(.XMM0), "66 0F 63 c0"); testOp2(m32, .PACKSSWB, reg(.XMM0), reg(.XMM1), "66 0F 63 c1"); testOp2(m32, .PACKSSWB, reg(.XMM1), reg(.XMM0), "66 0F 63 c8"); testOp2(m32, .PACKSSWB, reg(.XMM0), mem_128, "66 0F 63 00"); testOp2(m32, .PACKSSWB, reg(.XMM0), mem_64, AsmError.InvalidOperand); testOp2(m32, .PACKSSWB, mem_64, mem_64, AsmError.InvalidOperand); testOp2(m32, .PACKSSWB, mem_64, reg(.XMM1), AsmError.InvalidOperand); testOp2(m32, .PACKSSWB, mem_128, mem_128, AsmError.InvalidOperand); testOp2(m32, .PACKSSWB, mem_128, reg(.XMM1), AsmError.InvalidOperand); testOp2(m32, .PACKSSDW, reg(.XMM0), reg(.XMM0), "66 0F 6B c0"); testOp2(m32, .PACKSSDW, reg(.XMM0), reg(.XMM1), "66 0F 6B c1"); testOp2(m32, .PACKSSDW, reg(.XMM1), reg(.XMM0), "66 0F 6B c8"); testOp2(m32, .PACKSSDW, reg(.XMM0), mem_128, "66 0F 6B 00"); testOp2(m32, .PACKSSDW, reg(.XMM0), mem_64, AsmError.InvalidOperand); testOp2(m32, .PACKSSDW, mem_64, mem_64, AsmError.InvalidOperand); testOp2(m32, .PACKSSDW, mem_64, reg(.XMM1), AsmError.InvalidOperand); testOp2(m32, .PACKUSWB, reg(.XMM0), reg(.XMM0), "66 0F 67 c0"); testOp2(m32, .PACKUSWB, reg(.XMM0), reg(.XMM1), "66 0F 67 c1"); testOp2(m32, .PACKUSWB, reg(.XMM1), reg(.XMM0), "66 0F 67 c8"); testOp2(m32, .PACKUSWB, reg(.XMM0), mem_128, "66 0F 67 00"); testOp2(m32, .PACKUSWB, mem_64, mem_64, AsmError.InvalidOperand); testOp2(m32, .PACKUSWB, mem_64, reg(.XMM1), AsmError.InvalidOperand); testOp2(m32, .PACKUSWB, mem_128, mem_128, AsmError.InvalidOperand); testOp2(m32, .PACKUSWB, mem_128, reg(.XMM1), AsmError.InvalidOperand); testOp2(m32, .PACKUSDW, reg(.XMM0), reg(.XMM0), "66 0F 38 2B c0"); testOp2(m32, .PACKUSDW, reg(.XMM0), reg(.XMM1), "66 0F 38 2B c1"); testOp2(m32, .PACKUSDW, reg(.XMM1), reg(.XMM0), "66 0F 38 2B c8"); testOp2(m32, .PACKUSDW, reg(.XMM0), mem_128, "66 0F 38 2B 00"); testOp2(m32, .PACKUSDW, mem_64, mem_64, AsmError.InvalidOperand); testOp2(m32, .PACKUSDW, mem_64, reg(.XMM1), AsmError.InvalidOperand); testOp2(m32, .PACKUSDW, mem_128, mem_128, AsmError.InvalidOperand); testOp2(m32, .PACKUSDW, mem_128, reg(.XMM1), AsmError.InvalidOperand); } { // PABSB / PABSW /PABSD // PABSB testOp2(m64, .PABSB, reg(.MM1), regRm(.MM0), "0f 38 1c c8"); testOp2(m64, .PABSB, reg(.XMM1), regRm(.XMM0), "66 0f 38 1c c8"); // PABSW testOp2(m64, .PABSW, reg(.MM1), regRm(.MM0), "0f 38 1d c8"); testOp2(m64, .PABSW, reg(.XMM1), regRm(.XMM0), "66 0f 38 1d c8"); // PABSD testOp2(m64, .PABSD, reg(.MM1), regRm(.MM0), "0f 38 1e c8"); testOp2(m64, .PABSD, reg(.XMM1), regRm(.XMM0), "66 0f 38 1e c8"); // PACKSSWB / PACKSSDW testOp2(m64, .PACKSSWB, reg(.MM1), regRm(.MM0), "0f 63 c8"); testOp2(m64, .PACKSSWB, reg(.XMM1), regRm(.XMM0), "66 0f 63 c8"); // testOp2(m64, .PACKSSDW, reg(.MM1), regRm(.MM0), "0f 6b c8"); testOp2(m64, .PACKSSDW, reg(.XMM1), regRm(.XMM0), "66 0f 6b c8"); // PACKUSWB testOp2(m64, .PACKUSWB, reg(.MM1), regRm(.MM0), "0f 67 c8"); testOp2(m64, .PACKUSWB, reg(.XMM1), regRm(.XMM0), "66 0f 67 c8"); // PACKUSDW testOp2(m64, .PACKUSDW, reg(.XMM1), regRm(.XMM0), "66 0f 38 2b c8"); // PADDB / PADDW / PADDD / PADDQ testOp2(m64, .PADDB, reg(.MM1), regRm(.MM0), "0f fc c8"); testOp2(m64, .PADDB, reg(.XMM1), regRm(.XMM0), "66 0f fc c8"); // testOp2(m64, .PADDW, reg(.MM1), regRm(.MM0), "0f fd c8"); testOp2(m64, .PADDW, reg(.XMM1), regRm(.XMM0), "66 0f fd c8"); // testOp2(m64, .PADDD, reg(.MM1), regRm(.MM0), "0f fe c8"); testOp2(m64, .PADDD, reg(.XMM1), regRm(.XMM0), "66 0f fe c8"); // testOp2(m64, .PADDQ, reg(.MM1), regRm(.MM0), "0f d4 c8"); testOp2(m64, .PADDQ, reg(.XMM1), regRm(.XMM0), "66 0f d4 c8"); // PADDSB / PADDSW testOp2(m64, .PADDSB, reg(.MM1), regRm(.MM0), "0f ec c8"); testOp2(m64, .PADDSB, reg(.XMM1), regRm(.XMM0), "66 0f ec c8"); // testOp2(m64, .PADDSW, reg(.MM1), regRm(.MM0), "0f ed c8"); testOp2(m64, .PADDSW, reg(.XMM1), regRm(.XMM0), "66 0f ed c8"); // PADDUSB / PADDSW testOp2(m64, .PADDUSB, reg(.MM1), regRm(.MM0), "0f dc c8"); testOp2(m64, .PADDUSB, reg(.XMM1), regRm(.XMM0), "66 0f dc c8"); // testOp2(m64, .PADDUSW, reg(.MM1), regRm(.MM0), "0f dd c8"); testOp2(m64, .PADDUSW, reg(.XMM1), regRm(.XMM0), "66 0f dd c8"); // PALIGNR testOp3(m64, .PALIGNR, reg(.MM1),regRm(.MM0),imm(0), "0f 3a 0f c8 00"); testOp3(m64, .PALIGNR, reg(.XMM1),regRm(.XMM0),imm(0), "66 0f 3a 0f c8 00"); } { // PAND testOp2(m64, .PAND, reg(.MM1), regRm(.MM0), "0f db c8"); testOp2(m64, .PAND, reg(.XMM1), regRm(.XMM0), "66 0f db c8"); // PANDN testOp2(m64, .PANDN, reg(.MM1), regRm(.MM0), "0f df c8"); testOp2(m64, .PANDN, reg(.XMM1), regRm(.XMM0), "66 0f df c8"); // PAVGB / PAVGW testOp2(m64, .PAVGB, reg(.MM1), regRm(.MM0), "0f e0 c8"); testOp2(m64, .PAVGB, reg(.XMM1), regRm(.XMM0), "66 0f e0 c8"); // testOp2(m64, .PAVGW, reg(.MM1), regRm(.MM0), "0f e3 c8"); testOp2(m64, .PAVGW, reg(.XMM1), regRm(.XMM0), "66 0f e3 c8"); // PBLENDVB testOp3(m64, .PBLENDVB, reg(.XMM1),regRm(.XMM0),reg(.XMM0), "66 0f 38 10 c8"); testOp2(m64, .PBLENDVB, reg(.XMM1),regRm(.XMM0), "66 0f 38 10 c8"); // PBLENDVW testOp3(m64, .PBLENDW, reg(.XMM1),regRm(.XMM0),imm(0), "66 0f 3a 0e c8 00"); // PCLMULQDQ testOp3(m64, .PCLMULQDQ, reg(.XMM1),regRm(.XMM0),imm(0), "66 0f 3a 44 c8 00"); } { // PCMPEQB / PCMPEQW / PCMPEQD testOp2(m64, .PCMPEQB, reg(.MM1), regRm(.MM0), "0f 74 c8"); testOp2(m64, .PCMPEQB, reg(.XMM1), regRm(.XMM0), "66 0f 74 c8"); // testOp2(m64, .PCMPEQW, reg(.MM1), regRm(.MM0), "0f 75 c8"); testOp2(m64, .PCMPEQW, reg(.XMM1), regRm(.XMM0), "66 0f 75 c8"); // testOp2(m64, .PCMPEQD, reg(.MM1), regRm(.MM0), "0f 76 c8"); testOp2(m64, .PCMPEQD, reg(.XMM1), regRm(.XMM0), "66 0f 76 c8"); // PCMPEQQ testOp2(m64, .PCMPEQQ, reg(.XMM1), regRm(.XMM0), "66 0f 38 29 c8"); // PCMPESTRI testOp3(m64, .PCMPESTRI, reg(.XMM1),regRm(.XMM0),imm(0), "66 0f 3a 61 c8 00"); // PCMPESTRM testOp3(m64, .PCMPESTRM, reg(.XMM1),regRm(.XMM0),imm(0), "66 0f 3a 60 c8 00"); // PCMPGTB / PCMPGTW / PCMPGTD testOp2(m64, .PCMPGTB, reg(.MM1), regRm(.MM0), "0f 64 c8"); testOp2(m64, .PCMPGTB, reg(.XMM1), regRm(.XMM0), "66 0f 64 c8"); // testOp2(m64, .PCMPGTW, reg(.MM1), regRm(.MM0), "0f 65 c8"); testOp2(m64, .PCMPGTW, reg(.XMM1), regRm(.XMM0), "66 0f 65 c8"); // testOp2(m64, .PCMPGTD, reg(.MM1), regRm(.MM0), "0f 66 c8"); testOp2(m64, .PCMPGTD, reg(.XMM1), regRm(.XMM0), "66 0f 66 c8"); // PCMPISTRI testOp3(m64, .PCMPISTRI, reg(.XMM1),regRm(.XMM0),imm(0), "66 0f 3a 63 c8 00"); // PCMPISTRM testOp3(m64, .PCMPISTRM, reg(.XMM1),regRm(.XMM0),imm(0), "66 0f 3a 62 c8 00"); // testOp2(m32, .PCMPEQB, reg(.XMM0), reg(.XMM0), "66 0f 74 c0"); testOp2(m32, .PCMPEQW, reg(.XMM0), reg(.XMM0), "66 0f 75 c0"); testOp2(m32, .PCMPEQD, reg(.XMM0), reg(.XMM0), "66 0f 76 c0"); // testOp2(m32, .PCMPGTB, reg(.XMM0), reg(.XMM0), "66 0f 64 c0"); testOp2(m32, .PCMPGTW, reg(.XMM0), reg(.XMM0), "66 0f 65 c0"); testOp2(m32, .PCMPGTD, reg(.XMM0), reg(.XMM0), "66 0f 66 c0"); } { // PEXTRB / PEXTRD / PEXTRQ testOp3(m64, .PEXTRB, rm_mem8, reg(.XMM1), imm(0), "67 66 0f 3a 14 08 00"); testOp3(m64, .PEXTRB, reg(.EAX), reg(.XMM1), imm(0), "66 0f 3a 14 c8 00"); testOp3(m64, .PEXTRB, reg(.RAX), reg(.XMM1), imm(0), "66 0f 3a 14 c8 00"); testOp3(m64, .PEXTRD, rm32, reg(.XMM1), imm(0), "67 66 0f 3a 16 08 00"); testOp3(m64, .PEXTRQ, rm64, reg(.XMM1), imm(0), "67 66 48 0f 3a 16 08 00"); // PEXTRW testOp3(m64, .PEXTRW, reg(.EAX), reg(.MM1), imm(0), "0f c5 c1 00"); testOp3(m64, .PEXTRW, reg(.RAX), reg(.MM1), imm(0), "0f c5 c1 00"); testOp3(m64, .PEXTRW, reg(.EAX), reg(.XMM1), imm(0), "66 0f c5 c1 00"); testOp3(m64, .PEXTRW, reg(.RAX), reg(.XMM1), imm(0), "66 0f c5 c1 00"); testOp3(m64, .PEXTRW, rm_mem16, reg(.XMM1), imm(0), "67 66 0f 3a 15 08 00"); testOp3(m64, .PEXTRW, regRm(.EAX), reg(.XMM1), imm(0), "66 0f 3a 15 c8 00"); testOp3(m64, .PEXTRW, regRm(.RAX), reg(.XMM1), imm(0), "66 0f 3a 15 c8 00"); testOp3(m64, .PEXTRW, reg(.EAX), reg(.XMM1), imm(0), "66 0f c5 c1 00"); testOp3(m64, .PEXTRW, reg(.RAX), reg(.XMM1), imm(0), "66 0f c5 c1 00"); // testOp3(m32, .PEXTRB, reg(.EAX), reg(.XMM0), imm(0), "66 0f 3a 14 c0 00"); testOp3(m32, .PEXTRB, reg(.RAX), reg(.XMM0), imm(0), AsmError.InvalidOperand); // testOp3(m32, .PEXTRW, reg(.EAX), reg(.XMM0), imm(0), "66 0f c5 c0 00"); testOp3(m32, .PEXTRW, reg(.RAX), reg(.XMM0), imm(0), AsmError.InvalidOperand); // testOp3(m32, .PEXTRW, regRm(.EAX), reg(.XMM0), imm(0), "66 0f 3A 15 c0 00"); testOp3(m32, .PEXTRW, regRm(.RAX), reg(.XMM0), imm(0), AsmError.InvalidOperand); // testOp3(m32, .PEXTRD, reg(.EAX), reg(.XMM0), imm(0), "66 0f 3a 16 c0 00"); testOp3(m32, .PEXTRQ, reg(.RAX), reg(.XMM0), imm(0), AsmError.InvalidOperand); } { // PHADDW / PHAD DD testOp2(m64, .PHADDW, reg(.MM1), regRm(.MM0), "0f 38 01 c8"); testOp2(m64, .PHADDW, reg(.XMM1), regRm(.XMM0), "66 0f 38 01 c8"); testOp2(m64, .PHADDD, reg(.MM1), regRm(.MM0), "0f 38 02 c8"); testOp2(m64, .PHADDD, reg(.XMM1), regRm(.XMM0), "66 0f 38 02 c8"); // PHADDSW testOp2(m64, .PHADDSW, reg(.MM1), regRm(.MM0), "0f 38 03 c8"); testOp2(m64, .PHADDSW, reg(.XMM1), regRm(.XMM0), "66 0f 38 03 c8"); // PHMINPOSUW testOp2(m64, .PHMINPOSUW,reg(.XMM1), regRm(.XMM0), "66 0f 38 41 c8"); // PHSUBW / PHSUBD testOp2(m64, .PHSUBW, reg(.MM1), regRm(.MM0), "0f 38 05 c8"); testOp2(m64, .PHSUBW, reg(.XMM1), regRm(.XMM0), "66 0f 38 05 c8"); testOp2(m64, .PHSUBD, reg(.MM1), regRm(.MM0), "0f 38 06 c8"); testOp2(m64, .PHSUBD, reg(.XMM1), regRm(.XMM0), "66 0f 38 06 c8"); // PHSUBSW testOp2(m64, .PHSUBSW, reg(.MM1), regRm(.MM0), "0f 38 07 c8"); testOp2(m64, .PHSUBSW, reg(.XMM1), regRm(.XMM0), "66 0f 38 07 c8"); // PINSRB / PINSRD / PINSRQ testOp3(m64, .PINSRB, reg(.XMM1), rm_mem8, imm(0), "67 66 0f 3a 20 08 00"); testOp3(m64, .PINSRB, reg(.XMM1), regRm(.EAX), imm(0), "66 0f 3a 20 c8 00"); // testOp3(m64, .PINSRD, reg(.XMM1), rm32, imm(0), "67 66 0f 3a 22 08 00"); // testOp3(m64, .PINSRQ, reg(.XMM1), rm64, imm(0), "67 66 48 0f 3a 22 08 00"); testOp3(m32, .PINSRQ, reg(.XMM1), rm64, imm(0), AsmError.InvalidOperand); // PINSRW testOp3(m64, .PINSRW, reg(.MM1), rm_mem16, imm(0), "67 0f c4 08 00"); testOp3(m64, .PINSRW, reg(.MM1), regRm(.EAX), imm(0), "0f c4 c8 00"); testOp3(m64, .PINSRW, reg(.XMM1), rm_mem16, imm(0), "67 66 0f c4 08 00"); testOp3(m64, .PINSRW, reg(.XMM1), regRm(.EAX), imm(0), "66 0f c4 c8 00"); } { // PMADDUBSW testOp2(m64, .PMADDUBSW, reg(.MM1), regRm(.MM0), "0f 38 04 c8"); testOp2(m64, .PMADDUBSW, reg(.XMM1), regRm(.XMM0), "66 0f 38 04 c8"); // PMADDWD testOp2(m64, .PMADDWD, reg(.MM1), regRm(.MM0), "0f f5 c8"); testOp2(m64, .PMADDWD, reg(.XMM1), regRm(.XMM0), "66 0f f5 c8"); // PMAXSB / PMAXSW / PMAXSD testOp2(m64, .PMAXSW, reg(.MM1), regRm(.MM0), "0f ee c8"); testOp2(m64, .PMAXSW, reg(.XMM1), regRm(.XMM0), "66 0f ee c8"); testOp2(m64, .PMAXSB, reg(.XMM1), regRm(.XMM0), "66 0f 38 3c c8"); testOp2(m64, .PMAXSD, reg(.XMM1), regRm(.XMM0), "66 0f 38 3d c8"); // PMAXUB / PMAXUW testOp2(m64, .PMAXUB, reg(.MM1), regRm(.MM0), "0f de c8"); testOp2(m64, .PMAXUB, reg(.XMM1), regRm(.XMM0), "66 0f de c8"); testOp2(m64, .PMAXUW, reg(.XMM1), regRm(.XMM0), "66 0f 38 3e c8"); // PMAXUD testOp2(m64, .PMAXUD, reg(.XMM1), regRm(.XMM0), "66 0f 38 3f c8"); // PMINSB / PMINSW testOp2(m64, .PMINSW, reg(.MM1), regRm(.MM0), "0f ea c8"); testOp2(m64, .PMINSW, reg(.XMM1), regRm(.XMM0), "66 0f ea c8"); testOp2(m64, .PMINSB, reg(.XMM1), regRm(.XMM0), "66 0f 38 38 c8"); // PMINSD testOp2(m64, .PMINSD, reg(.XMM1), regRm(.XMM0), "66 0f 38 39 c8"); // PMINUB / PMINUW testOp2(m64, .PMINUB, reg(.MM1), regRm(.MM0), "0f da c8"); testOp2(m64, .PMINUB, reg(.XMM1), regRm(.XMM0), "66 0f da c8"); testOp2(m64, .PMINUW, reg(.XMM1), regRm(.XMM0), "66 0f 38 3a c8"); // PMINUD testOp2(m64, .PMINUD, reg(.XMM1), regRm(.XMM0), "66 0f 38 3b c8"); { testOp2(m32, .PMADDWD, reg(.XMM0), reg(.XMM0), "66 0f f5 c0"); } } { // PMOVMSKB testOp2(m64, .PMOVMSKB, reg(.EAX), regRm(.MM0), "0f d7 c0"); testOp2(m64, .PMOVMSKB, reg(.RAX), regRm(.MM0), "0f d7 c0"); testOp2(m64, .PMOVMSKB, reg(.EAX), regRm(.XMM0), "66 0f d7 c0"); testOp2(m64, .PMOVMSKB, reg(.RAX), regRm(.XMM0), "66 0f d7 c0"); // PMOVSX testOp2(m64, .PMOVSXBW, reg(.XMM1), regRm(.XMM0), "66 0f 38 20 c8"); testOp2(m64, .PMOVSXBD, reg(.XMM1), regRm(.XMM0), "66 0f 38 21 c8"); testOp2(m64, .PMOVSXBQ, reg(.XMM1), regRm(.XMM0), "66 0f 38 22 c8"); // testOp2(m64, .PMOVSXWD, reg(.XMM1), regRm(.XMM0), "66 0f 38 23 c8"); testOp2(m64, .PMOVSXWQ, reg(.XMM1), regRm(.XMM0), "66 0f 38 24 c8"); testOp2(m64, .PMOVSXDQ, reg(.XMM1), regRm(.XMM0), "66 0f 38 25 c8"); // PMOVZX testOp2(m64, .PMOVZXBW, reg(.XMM1), regRm(.XMM0), "66 0f 38 30 c8"); testOp2(m64, .PMOVZXBD, reg(.XMM1), regRm(.XMM0), "66 0f 38 31 c8"); testOp2(m64, .PMOVZXBQ, reg(.XMM1), regRm(.XMM0), "66 0f 38 32 c8"); // testOp2(m64, .PMOVZXWD, reg(.XMM1), regRm(.XMM0), "66 0f 38 33 c8"); testOp2(m64, .PMOVZXWQ, reg(.XMM1), regRm(.XMM0), "66 0f 38 34 c8"); testOp2(m64, .PMOVZXDQ, reg(.XMM1), regRm(.XMM0), "66 0f 38 35 c8"); } { // PMULDQ testOp2(m64, .PMULDQ, reg(.XMM1), regRm(.XMM0), "66 0f 38 28 c8"); // PMULHRSW testOp2(m64, .PMULHRSW, reg(.MM1), regRm(.MM0), "0f 38 0b c8"); testOp2(m64, .PMULHRSW, reg(.XMM1), regRm(.XMM0), "66 0f 38 0b c8"); // PMULHUW testOp2(m64, .PMULHUW, reg(.MM1), regRm(.MM0), "0f e4 c8"); testOp2(m64, .PMULHUW, reg(.XMM1), regRm(.XMM0), "66 0f e4 c8"); // PMULHW testOp2(m64, .PMULHW, reg(.MM1), regRm(.MM0), "0f e5 c8"); testOp2(m64, .PMULHW, reg(.XMM1), regRm(.XMM0), "66 0f e5 c8"); // PMULLD testOp2(m64, .PMULLD, reg(.XMM1), regRm(.XMM0), "66 0f 38 40 c8"); // PMULLW testOp2(m64, .PMULLW, reg(.MM1), regRm(.MM0), "0f d5 c8"); testOp2(m64, .PMULLW, reg(.XMM1), regRm(.XMM0), "66 0f d5 c8"); // PMULUDQ testOp2(m64, .PMULUDQ, reg(.MM1), regRm(.MM0), "0f f4 c8"); testOp2(m64, .PMULUDQ, reg(.XMM1), regRm(.XMM0), "66 0f f4 c8"); // POR testOp2(m64, .POR, reg(.MM1), regRm(.MM0), "0f eb c8"); testOp2(m64, .POR, reg(.XMM1), regRm(.XMM0), "66 0f eb c8"); testOp2(m32, .POR, reg(.XMM0), reg(.XMM0), "66 0f eb c0"); // PSADBW testOp2(m64, .PSADBW, reg(.MM1), regRm(.MM0), "0f f6 c8"); testOp2(m64, .PSADBW, reg(.XMM1), regRm(.XMM0), "66 0f f6 c8"); // PSHUFB testOp2(m64, .PSHUFB, reg(.MM1), regRm(.MM0), "0f 38 00 c8"); testOp2(m64, .PSHUFB, reg(.XMM1), regRm(.XMM0), "66 0f 38 00 c8"); // PSHUFD testOp3(m64, .PSHUFD, reg(.XMM1),regRm(.XMM0),imm(0), "66 0f 70 c8 00"); // PSHUFHW testOp3(m64, .PSHUFHW, reg(.XMM1),regRm(.XMM0),imm(0), "f3 0f 70 c8 00"); // PSHUFLW testOp3(m64, .PSHUFLW, reg(.XMM1),regRm(.XMM0),imm(0), "f2 0f 70 c8 00"); // PSHUFW testOp3(m64, .PSHUFW, reg(.MM1), regRm(.MM0), imm(0), "0f 70 c8 00"); // PSIGNB / PSIGNW / PSIGND testOp2(m64, .PSIGNB, reg(.MM1), regRm(.MM0), "0f 38 08 c8"); testOp2(m64, .PSIGNB, reg(.XMM1), regRm(.XMM0), "66 0f 38 08 c8"); // testOp2(m64, .PSIGNW, reg(.MM1), regRm(.MM0), "0f 38 09 c8"); testOp2(m64, .PSIGNW, reg(.XMM1), regRm(.XMM0), "66 0f 38 09 c8"); // testOp2(m64, .PSIGND, reg(.MM1), regRm(.MM0), "0f 38 0a c8"); testOp2(m64, .PSIGND, reg(.XMM1), regRm(.XMM0), "66 0f 38 0a c8"); { testOp2(m32, .PMULHW, reg(.XMM0), reg(.XMM0), "66 0f e5 c0"); testOp2(m32, .PMULLW, reg(.XMM0), reg(.XMM0), "66 0f d5 c0"); } } { // PSLLDQ testOp2(m64, .PSLLDQ, regRm(.XMM0), imm(0), "66 0f 73 f8 00"); // PSLLW / PSLLD / PSLLQ // PSLLW testOp2(m64, .PSLLW, reg(.MM1), regRm(.MM0), "0f f1 c8"); testOp2(m64, .PSLLW, reg(.XMM1), regRm(.XMM0), "66 0f f1 c8"); // testOp2(m64, .PSLLW, regRm(.MM0), imm(0), "0f 71 f0 00"); testOp2(m64, .PSLLW, regRm(.XMM0), imm(0), "66 0f 71 f0 00"); // PSLLD testOp2(m64, .PSLLD, reg(.MM1), regRm(.MM0), "0f f2 c8"); testOp2(m64, .PSLLD, reg(.XMM1), regRm(.XMM0), "66 0f f2 c8"); // testOp2(m64, .PSLLD, regRm(.MM0), imm(0), "0f 72 f0 00"); testOp2(m64, .PSLLD, regRm(.XMM0), imm(0), "66 0f 72 f0 00"); // PSLLQ testOp2(m64, .PSLLQ, reg(.MM1), regRm(.MM0), "0f f3 c8"); testOp2(m64, .PSLLQ, reg(.XMM1), regRm(.XMM0), "66 0f f3 c8"); // testOp2(m64, .PSLLQ, regRm(.MM0), imm(0), "0f 73 f0 00"); testOp2(m64, .PSLLQ, regRm(.XMM0), imm(0), "66 0f 73 f0 00"); // PSRAW / PSRAD // PSRAW testOp2(m64, .PSRAW, reg(.MM1), regRm(.MM0), "0f e1 c8"); testOp2(m64, .PSRAW, reg(.XMM1), regRm(.XMM0), "66 0f e1 c8"); // testOp2(m64, .PSRAW, reg(.MM1), imm(0), "0f 71 e1 00"); testOp2(m64, .PSRAW, reg(.XMM1), imm(0), "66 0f 71 e1 00"); // PSRAD testOp2(m64, .PSRAD, reg(.MM1), regRm(.MM0), "0f e2 c8"); testOp2(m64, .PSRAD, reg(.XMM1), regRm(.XMM0), "66 0f e2 c8"); // testOp2(m64, .PSRAD, reg(.MM1), imm(0), "0f 72 e1 00"); testOp2(m64, .PSRAD, reg(.XMM1), imm(0), "66 0f 72 e1 00"); // PSRLDQ testOp2(m64, .PSRLDQ, regRm(.XMM0), imm(0), "66 0f 73 d8 00"); // PSRLW / PSRLD / PSRLQ // PSRLW testOp2(m64, .PSRLW, reg(.MM1), regRm(.MM0), "0f d1 c8"); testOp2(m64, .PSRLW, reg(.XMM1), regRm(.XMM0), "66 0f d1 c8"); // testOp2(m64, .PSRLW, reg(.MM1), imm(0), "0f 71 d1 00"); testOp2(m64, .PSRLW, reg(.XMM1), imm(0), "66 0f 71 d1 00"); // PSRLD testOp2(m64, .PSRLD, reg(.MM1), regRm(.MM0), "0f d2 c8"); testOp2(m64, .PSRLD, reg(.XMM1), regRm(.XMM0), "66 0f d2 c8"); // testOp2(m64, .PSRLD, reg(.MM1), imm(0), "0f 72 d1 00"); testOp2(m64, .PSRLD, reg(.XMM1), imm(0), "66 0f 72 d1 00"); // PSRLQ testOp2(m64, .PSRLQ, reg(.MM1), regRm(.MM0), "0f d3 c8"); testOp2(m64, .PSRLQ, reg(.XMM1), regRm(.XMM0), "66 0f d3 c8"); // testOp2(m64, .PSRLQ, reg(.MM1), imm(0), "0f 73 d1 00"); testOp2(m64, .PSRLQ, reg(.XMM1), imm(0), "66 0f 73 d1 00"); { testOp2(m32, .PSLLW, reg(.XMM0), reg(.XMM0), "66 0f f1 c0"); testOp2(m32, .PSLLW, reg(.XMM0), imm(0), "66 0f 71 f0 00"); testOp2(m32, .PSLLD, reg(.XMM0), reg(.XMM0), "66 0f f2 c0"); testOp2(m32, .PSLLD, reg(.XMM0), imm(0), "66 0f 72 f0 00"); testOp2(m32, .PSLLQ, reg(.XMM0), reg(.XMM0), "66 0f f3 c0"); testOp2(m32, .PSLLQ, reg(.XMM0), imm(0), "66 0f 73 f0 00"); // testOp2(m32, .PSRAW, reg(.XMM0), reg(.XMM0), "66 0f e1 c0"); testOp2(m32, .PSRAW, reg(.XMM0), imm(0), "66 0f 71 e0 00"); testOp2(m32, .PSRAD, reg(.XMM0), reg(.XMM0), "66 0f e2 c0"); testOp2(m32, .PSRAD, reg(.XMM0), imm(0), "66 0f 72 e0 00"); // testOp2(m32, .PSRLW, reg(.XMM0), reg(.XMM0), "66 0f d1 c0"); testOp2(m32, .PSRLW, reg(.XMM0), imm(0), "66 0f 71 d0 00"); testOp2(m32, .PSRLD, reg(.XMM0), reg(.XMM0), "66 0f d2 c0"); testOp2(m32, .PSRLD, reg(.XMM0), imm(0), "66 0f 72 d0 00"); testOp2(m32, .PSRLQ, reg(.XMM0), reg(.XMM0), "66 0f d3 c0"); testOp2(m32, .PSRLQ, reg(.XMM0), imm(0), "66 0f 73 d0 00"); } } { // PSUBB / PSUBW / PSUBD // PSUBB testOp2(m64, .PSUBB, reg(.MM1), regRm(.MM0), "0f f8 c8"); testOp2(m64, .PSUBB, reg(.XMM1), regRm(.XMM0), "66 0f f8 c8"); // PSUBW testOp2(m64, .PSUBW, reg(.MM1), regRm(.MM0), "0f f9 c8"); testOp2(m64, .PSUBW, reg(.XMM1), regRm(.XMM0), "66 0f f9 c8"); // PSUBD testOp2(m64, .PSUBD, reg(.MM1), regRm(.MM0), "0f fa c8"); testOp2(m64, .PSUBD, reg(.XMM1), regRm(.XMM0), "66 0f fa c8"); // PSUBQ testOp2(m64, .PSUBQ, reg(.MM1), regRm(.MM0), "0f fb c8"); testOp2(m64, .PSUBQ, reg(.XMM1), regRm(.XMM0), "66 0f fb c8"); // PSUBSB / PSUBSW // PSUBSB testOp2(m64, .PSUBSB, reg(.MM1), regRm(.MM0), "0f e8 c8"); testOp2(m64, .PSUBSB, reg(.XMM1), regRm(.XMM0), "66 0f e8 c8"); // PSUBSW testOp2(m64, .PSUBSW, reg(.MM1), regRm(.MM0), "0f e9 c8"); testOp2(m64, .PSUBSW, reg(.XMM1), regRm(.XMM0), "66 0f e9 c8"); // PSUBUSB / PSUBUSW // PSUBUSB testOp2(m64, .PSUBUSB, reg(.MM1), regRm(.MM0), "0f d8 c8"); testOp2(m64, .PSUBUSB, reg(.XMM1), regRm(.XMM0), "66 0f d8 c8"); // PSUBUSW testOp2(m64, .PSUBUSW, reg(.MM1), regRm(.MM0), "0f d9 c8"); testOp2(m64, .PSUBUSW, reg(.XMM1), regRm(.XMM0), "66 0f d9 c8"); // PTEST testOp2(m64, .PTEST, reg(.XMM1), regRm(.XMM0), "66 0f 38 17 c8"); // PUNPCKHBW / PUNPCKHWD / PUNPCKHDQ / PUNPCKHQDQ testOp2(m64, .PUNPCKHBW, reg(.MM1), regRm(.MM0), "0f 68 c8"); testOp2(m64, .PUNPCKHBW, reg(.XMM1), regRm(.XMM0), "66 0f 68 c8"); // testOp2(m64, .PUNPCKHWD, reg(.MM1), regRm(.MM0), "0f 69 c8"); testOp2(m64, .PUNPCKHWD, reg(.XMM1), regRm(.XMM0), "66 0f 69 c8"); // testOp2(m64, .PUNPCKHDQ, reg(.MM1), regRm(.MM0), "0f 6a c8"); testOp2(m64, .PUNPCKHDQ, reg(.XMM1), regRm(.XMM0), "66 0f 6a c8"); // testOp2(m64, .PUNPCKHQDQ,reg(.XMM1), regRm(.XMM0), "66 0f 6d c8"); // PUNPCKLBW / PUNPCKLWD / PUNPCKLDQ / PUNPCKLQDQ testOp2(m64, .PUNPCKLBW, reg(.MM1), regRm(.MM0), "0f 60 c8"); testOp2(m64, .PUNPCKLBW, reg(.XMM1), regRm(.XMM0), "66 0f 60 c8"); // testOp2(m64, .PUNPCKLWD, reg(.MM1), regRm(.MM0), "0f 61 c8"); testOp2(m64, .PUNPCKLWD, reg(.XMM1), regRm(.XMM0), "66 0f 61 c8"); // testOp2(m64, .PUNPCKLDQ, reg(.MM1), regRm(.MM0), "0f 62 c8"); testOp2(m64, .PUNPCKLDQ, reg(.XMM1), regRm(.XMM0), "66 0f 62 c8"); // testOp2(m64, .PUNPCKLQDQ,reg(.XMM1), regRm(.XMM0), "66 0f 6c c8"); { testOp2(m32, .PSUBB, reg(.XMM0), reg(.XMM0), "66 0f f8 c0"); testOp2(m32, .PSUBW, reg(.XMM0), reg(.XMM0), "66 0f f9 c0"); testOp2(m32, .PSUBD, reg(.XMM0), reg(.XMM0), "66 0f fa c0"); // testOp2(m32, .PSUBUSB, reg(.XMM0), reg(.XMM0), "66 0f d8 c0"); testOp2(m32, .PSUBUSW, reg(.XMM0), reg(.XMM0), "66 0f d9 c0"); // testOp2(m32, .PUNPCKHBW, reg(.XMM0), reg(.XMM0), "66 0f 68 c0"); testOp2(m32, .PUNPCKHWD, reg(.XMM0), reg(.XMM0), "66 0f 69 c0"); testOp2(m32, .PUNPCKHDQ, reg(.XMM0), reg(.XMM0), "66 0f 6a c0"); testOp2(m32, .PUNPCKHQDQ,reg(.XMM0), reg(.XMM0), "66 0f 6d c0"); // testOp2(m32, .PUNPCKLBW, reg(.XMM0), reg(.XMM0), "66 0f 60 c0"); testOp2(m32, .PUNPCKLWD, reg(.XMM0), reg(.XMM0), "66 0f 61 c0"); testOp2(m32, .PUNPCKLDQ, reg(.XMM0), reg(.XMM0), "66 0f 62 c0"); testOp2(m32, .PUNPCKLQDQ,reg(.XMM0), reg(.XMM0), "66 0f 6c c0"); } } { // PXOR testOp2(m64, .PXOR, reg(.MM1), regRm(.MM0), "0f ef c8"); testOp2(m64, .PXOR, reg(.XMM1), regRm(.XMM0), "66 0f ef c8"); testOp2(m32, .PXOR, reg(.XMM0), reg(.XMM0), "66 0f ef c0"); // RCPPS testOp2(m64, .RCPPS, reg(.XMM1), regRm(.XMM0), "0f 53 c8"); // RCPSS testOp2(m64, .RCPSS, reg(.XMM1), regRm(.XMM0), "f3 0f 53 c8"); // ROUNDPD testOp3(m64, .ROUNDPD, reg(.XMM1),regRm(.XMM0),imm(0), "66 0f 3a 09 c8 00"); // ROUNDPS testOp3(m64, .ROUNDPS, reg(.XMM1),regRm(.XMM0),imm(0), "66 0f 3a 08 c8 00"); // ROUNDSD testOp3(m64, .ROUNDSD, reg(.XMM1),regRm(.XMM0),imm(0), "66 0f 3a 0b c8 00"); // ROUNDSS testOp3(m64, .ROUNDSS, reg(.XMM1),regRm(.XMM0),imm(0), "66 0f 3a 0a c8 00"); // RSQRTPS testOp2(m64, .RSQRTPS, reg(.XMM1), regRm(.XMM0), "0f 52 c8"); // RSQRTSS testOp2(m64, .RSQRTSS, reg(.XMM1), regRm(.XMM0), "f3 0f 52 c8"); // SHUFPD testOp3(m64, .SHUFPD, reg(.XMM1),regRm(.XMM0),imm(0), "66 0f c6 c8 00"); // SHUFPS testOp3(m64, .SHUFPS, reg(.XMM1),regRm(.XMM0),imm(0), "0f c6 c8 00"); // SQRTPD testOp2(m64, .SQRTPD, reg(.XMM1), regRm(.XMM0), "66 0f 51 c8"); // SQRTPS testOp2(m64, .SQRTPS, reg(.XMM1), regRm(.XMM0), "0f 51 c8"); // SQRTSD testOp2(m64, .SQRTSD, reg(.XMM1), regRm(.XMM0), "f2 0f 51 c8"); // SQRTSS testOp2(m64, .SQRTSS, reg(.XMM1), regRm(.XMM0), "f3 0f 51 c8"); // SUBPD testOp2(m64, .SUBPD, reg(.XMM1), regRm(.XMM0), "66 0f 5c c8"); // SUBPS testOp2(m64, .SUBPS, reg(.XMM1), regRm(.XMM0), "0f 5c c8"); // SUBSD testOp2(m64, .SUBSD, reg(.XMM1), regRm(.XMM0), "f2 0f 5c c8"); // SUBSS testOp2(m64, .SUBSS, reg(.XMM1), regRm(.XMM0), "f3 0f 5c c8"); // UCOMISD testOp2(m64, .UCOMISD, reg(.XMM1), regRm(.XMM0), "66 0f 2e c8"); // UCOMISS testOp2(m64, .UCOMISS, reg(.XMM1), regRm(.XMM0), "0f 2e c8"); // UNPCKHPD testOp2(m64, .UNPCKHPD, reg(.XMM1), regRm(.XMM0), "66 0f 15 c8"); // UNPCKHPS testOp2(m64, .UNPCKHPS, reg(.XMM1), regRm(.XMM0), "0f 15 c8"); // UNPCKLPD testOp2(m64, .UNPCKLPD, reg(.XMM1), regRm(.XMM0), "66 0f 14 c8"); // UNPCKLPS testOp2(m64, .UNPCKLPS, reg(.XMM1), regRm(.XMM0), "0f 14 c8"); // XORPD testOp2(m64, .XORPD, reg(.XMM1), regRm(.XMM0), "66 0f 57 c8"); // XORPS testOp2(m64, .XORPS, reg(.XMM1), regRm(.XMM0), "0f 57 c8"); } { // EXTRQ testOp3(m64, .EXTRQ, regRm(.XMM7), imm(0), imm(0x11), "66 0f 78 c7 00 11"); testOp2(m64, .EXTRQ, reg(.XMM1), regRm(.XMM7), "66 0f 79 cf"); // INSERTQ testOp4(m64, .INSERTQ, reg(.XMM1),regRm(.XMM7),imm(0),imm(0x11), "f2 0f 78 cf 00 11"); testOp2(m64, .INSERTQ, reg(.XMM1), regRm(.XMM7), "f2 0f 79 cf"); } { // MOVNTSD testOp2(m64, .MOVNTSD, rm_mem64, reg(.XMM1), "67 f2 0f 2b 08"); // MOVNTSS testOp2(m64, .MOVNTSS, rm_mem32, reg(.XMM1), "67 f3 0f 2b 08"); } }
src/x86/tests/sse.zig
const std = @import("std"); const mem = std.mem; const testing = std.testing; const expectEqual = @import("testutil.zig").expectEqual; // Note: Often, C return is non-const, but const is here to satisfy Zig. export fn strchr(str: [*:0]const u8, ch: c_int) ?*const u8 { const span = mem.span(str); for (span) |src_ch, i| { if (src_ch == @intCast(u8, ch)) { return &str[i]; } } if (ch == 0) { return &str[span.len]; } return null; } test "strchr" { const abccd = "abccd"; try expectEqual(null, strchr(abccd, 'x')); try expectEqual(&abccd[0], strchr(abccd, 'a')); try expectEqual(&abccd[4], strchr(abccd, 'd')); try expectEqual(&abccd[5], strchr(abccd, '\x00')); try expectEqual(&abccd[2], strchr(abccd, 'c')); } export fn strpbrk(dest: [*:0]const u8, breakset: [*:0]const u8) ?*const u8 { for (mem.span(dest)) |c, i| { if (strchr(breakset, c) != null) { return &dest[i]; } } return null; } test "strpbrk" { const abcde = "abcde"; const abcdx = "abcdx"; try expectEqual(null, strpbrk(abcde, "x")); try expectEqual(null, strpbrk(abcde, "xyz")); try expectEqual(&abcdx[4], strpbrk(abcdx, "x")); try expectEqual(&abcdx[4], strpbrk(abcdx, "xyz")); try expectEqual(&abcdx[4], strpbrk(abcdx, "zyx")); try expectEqual(&abcde[0], strpbrk(abcde, "a")); try expectEqual(&abcde[0], strpbrk(abcde, "abc")); try expectEqual(&abcde[0], strpbrk(abcde, "cba")); } export fn strlen(s: [*:0]const u8) usize { return mem.span(s).len; } test "strlen" { try expectEqual(5, strlen("abcde")); try expectEqual(0, strlen("")); } export fn strcmp(lhs: [*:0]const u8, rhs: [*:0]const u8) c_int { var i: usize = 0; while (lhs[i] != 0) : (i += 1) { if (lhs[i] != rhs[i]) { break; } } return @as(c_int, lhs[i]) - @as(c_int, rhs[i]); } test "strcmp" { const abcde = "abcde"; const abcdx = "abcdx"; const cmpabcde = "abcde"; const cmpabcd_ = "abcd\xfc"; const empty = ""; try testing.expect(strcmp(abcde, cmpabcde) == 0); try testing.expect(strcmp(abcde, abcdx) < 0); try testing.expect(strcmp(abcdx, abcde) > 0); try testing.expect(strcmp(empty, abcde) < 0); try testing.expect(strcmp(abcde, empty) > 0); try testing.expect(strcmp(abcde, cmpabcd_) < 0); } export fn strcpy(dest: [*]u8, src: [*:0]const u8) [*]u8 { const src_span = mem.span(src); for (src_span) |c, i| { dest[i] = c; } // The loop doesn't seem to cover the terminating zero, so we copy it // explicitly here. dest[src_span.len] = src_span[src_span.len]; return dest; } test "strcpy" { const abcde = "abcde"; var buf = [_]u8{'x'} ** 6; var s = &buf; try expectEqual(s, strcpy(s, "")); try expectEqual('\x00', s[0]); try expectEqual('x', s[1]); try expectEqual(s, strcpy(s, abcde)); try expectEqual('a', s[0]); try expectEqual('e', s[4]); try expectEqual('\x00', s[5]); } export fn strspn(dest: [*:0]const u8, src: [*:0]const u8) usize { const dest_span = mem.span(dest); for (dest_span) |c, i| { if (strchr(src, c) == null) { return i; } } return dest_span.len; } test "strspn" { const abcde = "abcde"; try expectEqual(3, strspn(abcde, "abc")); try expectEqual(0, strspn(abcde, "b")); try expectEqual(5, strspn(abcde, abcde)); const test_string = "abcde312$#@"; const low_alpha = "qwertyuiopasdfghjklzxcvbnm"; try expectEqual(5, strspn(test_string, low_alpha)); } export fn strcoll(lhs: [*:0]const u8, rhs: [*:0]const u8) c_int { return strcmp(lhs, rhs); }
src/libc/string.zig
const std = @import("std"); const Cigar = @import("cigar.zig").Cigar; pub const HSP = struct { const Self = @This(); start_one: usize, end_one: usize, start_two: usize, end_two: usize, pub fn length(self: Self) usize { return std.math.max(self.end_one - self.start_one, self.end_two - self.start_two) + 1; } pub fn is_overlapping(self: Self, other: HSP) bool { if (self.start_one <= other.end_one and other.start_one <= self.end_one) // overlap in A direction return true; if (self.start_two <= other.end_two and other.start_two <= self.end_two) // overlap in B direction return true; return false; } pub fn distance_to(self: Self, other: HSP) usize { var dx = if (self.start_one > other.end_one) self.start_one - other.end_one else other.start_one - self.end_one; if (dx > 0) dx -= 1; var dy = if (self.start_two > other.end_two) self.start_two - other.end_two else other.start_two - self.end_two; if (dy > 0) dy -= 1; return std.math.sqrt(dx * dx + dy * dy); } pub fn is_downstream_of(self: Self, other: HSP) bool { return self.start_one >= other.end_one and self.start_two >= other.end_two; } }; test "length" { const hsp = HSP{ .start_one = 5, .end_one = 6, .start_two = 11, .end_two = 15 }; try std.testing.expectEqual(@as(usize, 5), hsp.length()); const hsp2 = HSP{ .start_one = 1, .end_one = 6, .start_two = 11, .end_two = 15 }; try std.testing.expectEqual(@as(usize, 6), hsp2.length()); } test "overlapping" { const hsp = HSP{ .start_one = 1, .end_one = 2, .start_two = 25, .end_two = 27 }; try std.testing.expectEqual(true, hsp.is_overlapping(.{ .start_one = 1, .end_one = 2, .start_two = 55, .end_two = 57 })); try std.testing.expectEqual(true, hsp.is_overlapping(.{ .start_one = 2, .end_one = 3, .start_two = 55, .end_two = 57 })); try std.testing.expectEqual(false, hsp.is_overlapping(.{ .start_one = 3, .end_one = 4, .start_two = 55, .end_two = 57 })); try std.testing.expectEqual(true, hsp.is_overlapping(.{ .start_one = 3, .end_one = 4, .start_two = 20, .end_two = 28 })); try std.testing.expectEqual(true, hsp.is_overlapping(.{ .start_one = 3, .end_one = 4, .start_two = 20, .end_two = 25 })); try std.testing.expectEqual(false, hsp.is_overlapping(.{ .start_one = 3, .end_one = 4, .start_two = 20, .end_two = 24 })); try std.testing.expectEqual(true, hsp.is_overlapping(.{ .start_one = 0, .end_one = 100, .start_two = 0, .end_two = 100 })); } test "distance" { { const hsp1 = HSP{ .start_one = 1, .end_one = 1, .start_two = 25, .end_two = 25 }; const hsp2 = HSP{ .start_one = 2, .end_one = 2, .start_two = 26, .end_two = 26 }; try std.testing.expectEqual(@as(usize, 0), hsp1.distance_to(hsp2)); } { const hsp1 = HSP{ .start_one = 1, .end_one = 2, .start_two = 25, .end_two = 26 }; const hsp2 = HSP{ .start_one = 5, .end_one = 10, .start_two = 30, .end_two = 35 }; // x: 2 -> 5 = 2 empty cells // y: 26 -> 30 = 3 empty cells // => sqrt(2*2 + 3*3) try std.testing.expectEqual(@as(usize, 3), hsp1.distance_to(hsp2)); try std.testing.expectEqual(@as(usize, 3), hsp2.distance_to(hsp1)); } } // test "highscore order" { // const allocator = std.testing.allocator; // var queue = std.PriorityDequeue(HSP, void, HSP.lessThanScore).init(allocator, {}); // defer queue.deinit(); // try queue.add(.{ .start_one = 1, .end_one = 1, .start_two = 1, .end_two = 1, .score = 55 }); // try queue.add(.{ .start_one = 1, .end_one = 1, .start_two = 1, .end_two = 1, .score = 11 }); // try queue.add(.{ .start_one = 1, .end_one = 1, .start_two = 1, .end_two = 1, .score = 155 }); // try queue.add(.{ .start_one = 1, .end_one = 1, .start_two = 1, .end_two = 1, .score = -2 }); // try std.testing.expectEqual(@as(i32, 155), queue.removeMax().score); // try std.testing.expectEqual(@as(i32, 55), queue.removeMax().score); // try std.testing.expectEqual(@as(i32, 11), queue.removeMax().score); // try std.testing.expectEqual(@as(i32, -2), queue.removeMax().score); // }
src/hsp.zig
const std = @import("std"); const upaya = @import("upaya"); const parser = @import("parser.zig"); const my_fonts = @import("myscalingfonts.zig"); usingnamespace upaya.imgui; // . // Animation // . pub const frame_dt: f32 = 0.016; // roughly 16ms per frame pub const ButtonState = enum { none = 0, hovered, pressed, released, }; pub const ButtonAnim = struct { ticker_ms: u32 = 0, prevState: ButtonState = .none, currentState: ButtonState = .none, hover_duration: i32 = 200, press_duration: i32 = 100, release_duration: i32 = 100, current_color: ImVec4 = ImVec4{}, arrow_dir: i32 = -1, }; // pub const ImGuiInputTextCallback = ?fn ([*c]ImGuiInputTextCallbackData) callconv(.C) c_int; pub fn my_callback(data: [*c]ImGuiInputTextCallbackData) callconv(.C) c_int { var x: *EditAnim = @ptrCast(*EditAnim, @alignCast(@alignOf(*EditAnim), data.*.UserData)); if (x.editAction) |action| { data.*.CursorPos = @intCast(c_int, action.jump_to_cursor_pos); if (action.highlight_line) { data.*.SelectionStart = data.*.CursorPos; const buf = x.parser_context.?.input; if (std.mem.indexOfPos(u8, buf, action.jump_to_cursor_pos, "\n")) |eol_pos| { data.*.SelectionEnd = @intCast(c_int, eol_pos); } else { data.*.SelectionEnd = data.*.SelectionStart + 10; } } else if (action.selection_size > 0) { data.*.SelectionStart = data.*.CursorPos; data.*.SelectionEnd = data.*.SelectionStart + @intCast(c_int, action.selection_size); } x.editAction = null; } else { if (x.editActionPost) |action| { data.*.CursorPos = @intCast(c_int, action.jump_to_cursor_pos); if (action.highlight_line) { data.*.SelectionStart = data.*.CursorPos; const buf = x.parser_context.?.input; if (std.mem.indexOfPos(u8, buf, action.jump_to_cursor_pos, "\n")) |eol_pos| { data.*.SelectionEnd = @intCast(c_int, eol_pos); } else { data.*.SelectionEnd = data.*.SelectionStart + 10; } } else if (action.selection_size > 0) { data.*.SelectionStart = data.*.CursorPos; data.*.SelectionEnd = data.*.SelectionStart + @intCast(c_int, action.selection_size); } x.editActionPost = null; } x.current_cursor_pos = @intCast(usize, data.*.CursorPos); } return 0; } pub const EditAnim = struct { visible: bool = false, visible_prev: bool = false, current_size: ImVec2 = ImVec2{}, desired_size: ImVec2 = .{ .x = 600, .y = 0 }, slide_button_width: f32 = 10, in_grow_shrink_animation: bool = false, in_flash_editor_animation: bool = false, grow_shrink_from_width: f32 = 0, ticker_ms: u32 = 0, fadein_duration: i32 = 200, fadeout_duration: i32 = 200, flash_editor_duration: i32 = 10, textbuf: [*c]u8 = null, textbuf_size: u32 = 128 * 1024, parser_context: ?*parser.ParserContext = null, selected_error: c_int = 1000, editAction: ?EditActionData = null, editActionPost: ?EditActionData = null, resize_button_anim: ButtonAnim = .{}, resize_mouse_x: f32 = 0, in_resize_mode: bool = false, scroll_lines_after_autosel: i32 = 5, // scroll down this number of lines after auto selecting (jump to slide, find) current_cursor_pos: usize = 0, search_term: [*c]u8 = null, search_term_size: usize = 25, search_ed_active: bool = false, current_search_pos: usize = 0, pub fn shrink(self: *EditAnim) void { if (self.desired_size.x > 300) { self.grow_shrink_from_width = self.desired_size.x; self.desired_size.x /= 1.20; self.visible_prev = false; self.in_grow_shrink_animation = true; } } pub fn grow(self: *EditAnim) void { if (self.desired_size.x < 1920.0 / 1.20 - 200.0) { self.grow_shrink_from_width = self.desired_size.x; self.desired_size.x *= 1.20; self.visible_prev = false; self.in_grow_shrink_animation = true; } } pub fn jumpToPosAndHighlightLine(self: *EditAnim, pos: usize, activate_editor: bool) void { // now honor the scroll_lines_after_autosel var eol_pos: usize = pos; var linecount: i32 = 0; if (pos > self.current_cursor_pos) { // search forwards while (linecount < self.scroll_lines_after_autosel) { if (std.mem.indexOfPos(u8, self.parser_context.?.input, eol_pos, "\n")) |neweol| { eol_pos = neweol + 1; } linecount += 1; } } else { // search backwards while (eol_pos > 0) { if (self.parser_context.?.input[eol_pos] == '\n') { linecount += 1; if (linecount >= self.scroll_lines_after_autosel) { break; } } eol_pos -= 1; } } // first, jump to fix scroll position self.editAction = .{ .jump_to_cursor_pos = eol_pos, .highlight_line = false, }; // then jump, sel, and highlight self.editActionPost = .{ .jump_to_cursor_pos = pos, .highlight_line = true, }; if (activate_editor) { self.activate(); } else { self.startFlashAnimation(); } } pub fn activate(self: *EditAnim) void { igActivateItem(igGetIDStr("editor")); // TODO move ID str into struct } pub fn startFlashAnimation(self: *EditAnim) void { self.ticker_ms = 0; self.in_flash_editor_animation = true; } }; const EditActionData = struct { jump_to_cursor_pos: usize = 0, selection_size: usize = 0, highlight_line: bool = false, }; pub fn animateVec2(from: ImVec2, to: ImVec2, duration_ms: i32, ticker_ms: u32) ImVec2 { if (ticker_ms >= duration_ms) { return to; } if (ticker_ms <= 1) { return from; } var ret = from; var fduration_ms = @intToFloat(f32, duration_ms); var fticker_ms = @intToFloat(f32, ticker_ms); ret.x += (to.x - from.x) / fduration_ms * fticker_ms; ret.y += (to.y - from.y) / fduration_ms * fticker_ms; return ret; } pub fn animateX(from: ImVec2, to: ImVec2, duration_ms: i32, ticker_ms: u32) ImVec2 { if (ticker_ms >= duration_ms) { return to; } if (ticker_ms <= 1) { return from; } var ret = from; var fduration_ms = @intToFloat(f32, duration_ms); var fticker_ms = @intToFloat(f32, ticker_ms); ret.x += (to.x - from.x) / fduration_ms * fticker_ms; return ret; } var bt_save_anim = ButtonAnim{}; var bt_grow_anim = ButtonAnim{}; var bt_shrink_anim = ButtonAnim{}; // returns true if editor is active pub fn animatedEditor(anim: *EditAnim, start_y: f32, content_window_size: ImVec2, internal_render_size: ImVec2) !bool { var fromSize = ImVec2{}; var toSize = ImVec2{}; var anim_duration: i32 = 0; var show: bool = true; var size = anim.desired_size; var editor_pos = ImVec2{ .y = start_y }; var pos = ImVec2{ .y = start_y }; pos.x = internal_render_size.x - anim.current_size.x; pos.x *= content_window_size.x / internal_render_size.x; editor_pos = pos; editor_pos.x += anim.slide_button_width; if (!anim.visible) { anim.current_size.x = 0; } if (anim.textbuf == null) { var allocator = std.heap.page_allocator; const memory = try allocator.alloc(u8, anim.textbuf_size); anim.textbuf = memory.ptr; anim.textbuf[0] = 0; } if (anim.search_term == null) { var allocator = std.heap.page_allocator; const search_mem = try allocator.alloc(u8, anim.search_term_size); anim.search_term = search_mem.ptr; anim.search_term[0] = 0; } // only animate when transitioning if (anim.visible != anim.visible_prev) { if (anim.visible) { // fading in if (!anim.in_grow_shrink_animation) { fromSize = ImVec2{}; } else { fromSize.x = anim.grow_shrink_from_width; } fromSize.y = size.y; toSize = size; anim_duration = anim.fadein_duration; } else { fromSize = size; if (!anim.in_grow_shrink_animation) { toSize = ImVec2{}; } else { toSize.x = anim.grow_shrink_from_width; } toSize.y = size.y; anim_duration = anim.fadeout_duration; } anim.current_size = animateX(fromSize, toSize, anim_duration, anim.ticker_ms); anim.ticker_ms += @floatToInt(u32, frame_dt * 1000); if (anim.ticker_ms >= anim_duration) { anim.visible_prev = anim.visible; anim.in_grow_shrink_animation = false; } } else { if (anim.in_flash_editor_animation) { anim.ticker_ms += 1; if (anim.ticker_ms < anim.flash_editor_duration) { anim.activate(); } else { anim.in_flash_editor_animation = false; igActivateItem(igGetIDStr("dummy")); } } else { anim.ticker_ms = 0; if (!anim.visible) { show = false; } } } if (show) { igSetCursorPos(editor_pos); var s: ImVec2 = trxy(anim.current_size, content_window_size, internal_render_size); // (optional) extra stuff const grow_shrink_button_panel_height = 0; // 22; const find_area_height = 26; const find_area_button_size = 120; const find_area_min_width = 70 + 70; // show the find panel const required_size: f32 = s.x - find_area_min_width; if (required_size > 0) { const gap = 5; const textfield_width = s.x - find_area_button_size - gap * 2; igPushItemWidth(textfield_width); anim.search_ed_active = igInputTextWithHint("##search", "search term...", anim.search_term, anim.search_term_size, 0, null, null); igSetCursorPos(.{ .x = editor_pos.x + textfield_width + gap, .y = editor_pos.y }); if (igButton("Search!", .{ .x = find_area_button_size - gap, .y = 22 })) { if (std.mem.lenZ(anim.search_term) > 0) { // DO SEARCH std.log.debug("Search term is: {s}", .{anim.search_term}); const shit: []u8 = std.mem.spanZ(anim.textbuf); const fuck: []u8 = std.mem.spanZ(anim.search_term); if (std.mem.indexOfPos(u8, shit, anim.current_search_pos, fuck)) |foundindex| { // found, now highlight the search result and jump cursor there anim.jumpToPosAndHighlightLine(foundindex, true); anim.current_search_pos = foundindex + 1; } else { // no (more) finds // if we have to wrap: if (anim.current_search_pos > 0) { // we hadn't started from the beginning anim.current_search_pos = 0; if (std.mem.indexOfPos(u8, shit, anim.current_search_pos, fuck)) |foundindex| { // found, now highlight the search result and jump cursor there anim.jumpToPosAndHighlightLine(foundindex, true); anim.current_search_pos = foundindex + 1; } else { anim.current_search_pos = 0; } } } } } } // on with the editor, shift it down by find_area_height igSetCursorPos(.{ .x = editor_pos.x, .y = find_area_height + pos.y }); s.y = size.y - grow_shrink_button_panel_height - find_area_height; var error_panel_height = s.y * 0.15; // reserve the last quarter for shit const error_panel_fontsize: i32 = 14; var show_error_panel = false; var parser_errors: *std.ArrayList(parser.ParserErrorContext) = undefined; var num_visible_error_lines: c_int = 0; var text_line_height = igGetTextLineHeightWithSpacing(); if (anim.parser_context) |ctx| { parser_errors = &ctx.parser_errors; if (parser_errors.items.len > 0) { show_error_panel = true; my_fonts.pushFontScaled(error_panel_fontsize); // . my_fonts.popFontScaled(); num_visible_error_lines = @floatToInt(c_int, error_panel_height / text_line_height); if (num_visible_error_lines > parser_errors.items.len) { num_visible_error_lines = @intCast(c_int, parser_errors.items.len); } s.y -= text_line_height * @intToFloat(f32, num_visible_error_lines) + 2; } } // show the editor var flags = ImGuiInputTextFlags_Multiline | ImGuiInputTextFlags_AllowTabInput | ImGuiInputTextFlags_CallbackAlways; var x_anim: *EditAnim = anim; igPushStyleColorVec4(ImGuiCol_TextSelectedBg, .{ .x = 1, .w = 0.9 }); igPushStyleColorVec4(ImGuiCol_Text, .{ .x = 1, .y = 1, .z = 1, .w = 1 }); const ret = igInputTextMultiline("editor", anim.textbuf, anim.textbuf_size, ImVec2{ .x = s.x, .y = s.y }, flags, my_callback, @ptrCast(*c_void, x_anim)); igPopStyleColor(2); // show the resize button // const resize_bt_height = content_window_size.y / 10; const resize_bt_pos = ImVec2{ .x = pos.x, .y = (content_window_size.y - resize_bt_height) / 2 }; igSetCursorPos(resize_bt_pos); const resize_ret = animatedButton(" resize", .{ .x = anim.slide_button_width, .y = resize_bt_height }, &anim.resize_button_anim); if (resize_ret == .pressed or anim.in_resize_mode) { var mouse_pos: ImVec2 = undefined; igGetMousePos(&mouse_pos); if (anim.resize_mouse_x > 0) { anim.current_size.x -= mouse_pos.x - anim.resize_mouse_x; if (anim.current_size.x > internal_render_size.x - 300) { anim.current_size.x = internal_render_size.x - 300; } if (anim.current_size.x < 50) { anim.current_size.x = 50; } } anim.resize_mouse_x = mouse_pos.x; anim.in_resize_mode = true; } if (resize_ret == .released or igIsAnyMouseDown() == false) { anim.in_resize_mode = false; anim.resize_mouse_x = 0; } if (show_error_panel) { igSetCursorPos(ImVec2{ .x = editor_pos.x, .y = s.y + 2 + find_area_height + pos.y }); igPushStyleColorVec4(ImGuiCol_Text, .{ .x = 0.95, .y = 0.95, .w = 0.99 }); igPushStyleColorVec4(ImGuiCol_FrameBg, .{ .x = 0, .y = 0.1, .z = 0.2, .w = 0.5 }); var selected: c_int = 0; const item_array = try anim.parser_context.?.allErrorsToCstrArray(anim.parser_context.?.allocator); my_fonts.pushFontScaled(error_panel_fontsize); igPushItemWidth(-1); if (igListBoxStr_arr("Errors", &anim.selected_error, item_array, @intCast(c_int, parser_errors.items.len), num_visible_error_lines + 1)) { // an error was selected anim.jumpToPosAndHighlightLine(parser_errors.items[@intCast(usize, anim.selected_error)].line_offset, true); } igPopItemWidth(); my_fonts.popFontScaled(); igPopStyleColor(2); } // the dummy button is necessary so we have something to activate after flashing the editor // to get out of the editor - or else it would suddenly start consuming keystrokes igSetCursorPos(.{ .x = pos.x, .y = 20 }); // below menu bar igPushStyleColorVec4(ImGuiCol_Button, .{ .w = 0 }); _ = igButton("dummy", .{ .x = 2, .y = 2 }); igPopStyleColor(1); return ret; } return false; } fn trxy(pos: ImVec2, content_window_size: ImVec2, internal_render_size: ImVec2) ImVec2 { return ImVec2{ .x = pos.x * content_window_size.x / internal_render_size.x, .y = pos.y * content_window_size.y / internal_render_size.y }; } pub fn animateColor(from: ImVec4, to: ImVec4, duration_ms: i32, ticker_ms: u32) ImVec4 { if (ticker_ms >= duration_ms) { return to; } if (ticker_ms <= 1) { return from; } var ret = from; var fduration_ms = @intToFloat(f32, duration_ms); var fticker_ms = @intToFloat(f32, ticker_ms); ret.x += (to.x - from.x) / fduration_ms * fticker_ms; ret.y += (to.y - from.y) / fduration_ms * fticker_ms; ret.z += (to.z - from.z) / fduration_ms * fticker_ms; ret.w += (to.w - from.w) / fduration_ms * fticker_ms; return ret; } pub fn doButton(label: [*c]const u8, size: ImVec2, dir: i32) ButtonState { var released: bool = false; if (dir == -1) { // normal button released = igButton(label, size); } else { // arrow button released = igArrowButton(label, dir); } if (released) return .released; if (igIsItemActive() and igIsItemHovered(ImGuiHoveredFlags_RectOnly)) return .pressed; if (igIsItemHovered(ImGuiHoveredFlags_RectOnly)) return .hovered; return .none; } pub fn animatedButton(label: [*c]const u8, size: ImVec2, anim: *ButtonAnim) ButtonState { var fromColor = ImVec4{}; var toColor = ImVec4{}; switch (anim.prevState) { .none => fromColor = igGetStyleColorVec4(ImGuiCol_Button).*, .hovered => fromColor = igGetStyleColorVec4(ImGuiCol_ButtonHovered).*, .pressed => fromColor = igGetStyleColorVec4(ImGuiCol_ButtonActive).*, .released => fromColor = igGetStyleColorVec4(ImGuiCol_ButtonActive).*, } switch (anim.currentState) { .none => toColor = igGetStyleColorVec4(ImGuiCol_Button).*, .hovered => toColor = igGetStyleColorVec4(ImGuiCol_ButtonHovered).*, .pressed => toColor = igGetStyleColorVec4(ImGuiCol_ButtonActive).*, .released => toColor = igGetStyleColorVec4(ImGuiCol_ButtonActive).*, } var anim_duration: i32 = 0; switch (anim.currentState) { .hovered => anim_duration = anim.hover_duration, .pressed => anim_duration = anim.press_duration, .released => anim_duration = anim.release_duration, else => anim_duration = anim.hover_duration, } if (anim.prevState == .released) anim_duration = anim.release_duration; var currentColor = animateColor(fromColor, toColor, anim_duration, anim.ticker_ms); igPushStyleColorVec4(ImGuiCol_Button, currentColor); igPushStyleColorVec4(ImGuiCol_ButtonHovered, currentColor); igPushStyleColorVec4(ImGuiCol_ButtonActive, currentColor); var state = doButton(label, size, anim.arrow_dir); igPopStyleColor(3); anim.ticker_ms += @floatToInt(u32, frame_dt * 1000); if (state != anim.currentState) { anim.prevState = anim.currentState; anim.currentState = state; anim.ticker_ms = 0; } anim.current_color = currentColor; return state; } pub const MsgAnimState = enum { none, fadein, keep, fadeout, }; pub const MsgAnim = struct { ticker_ms: u32 = 0, fadein_duration: i32 = 300, fadeout_duration: i32 = 300, keep_duration: i32 = 800, current_color: ImVec4 = ImVec4{}, anim_state: MsgAnimState = .none, }; pub fn showMsg(msg: [*c]const u8, pos: ImVec2, flyin_pos: ImVec2, color: ImVec4, anim: *MsgAnim) void { var from_color = ImVec4{}; var to_color = ImVec4{}; const hide_color = ImVec4{}; var duration: i32 = 0; var the_pos = pos; const backdrop_color = ImVec4{ .x = 0x80 / 255.0, .y = 0x80 / 255.0, .z = 0x80 / 255.0, .w = 1 }; var current_backdrop_color = backdrop_color; switch (anim.anim_state) { .none => return, .fadein => { from_color = hide_color; to_color = color; duration = anim.fadein_duration; anim.current_color = animateColor(from_color, to_color, duration, anim.ticker_ms); current_backdrop_color = animateColor(hide_color, backdrop_color, duration, anim.ticker_ms); the_pos = animateVec2(flyin_pos, pos, duration, anim.ticker_ms); anim.ticker_ms += @floatToInt(u32, frame_dt * 1000); if (anim.ticker_ms > anim.fadein_duration) { anim.anim_state = .keep; anim.ticker_ms = 0; } }, .fadeout => { from_color = color; to_color = hide_color; duration = anim.fadeout_duration; anim.current_color = animateColor(from_color, to_color, duration, anim.ticker_ms); current_backdrop_color = animateColor(backdrop_color, hide_color, @divTrunc(duration, 2), anim.ticker_ms); anim.ticker_ms += @floatToInt(u32, frame_dt * 1000); if (anim.ticker_ms > anim.fadeout_duration) { anim.anim_state = .none; anim.ticker_ms = 0; } }, .keep => { anim.current_color = color; current_backdrop_color = backdrop_color; anim.ticker_ms += @floatToInt(u32, frame_dt * 1000); if (anim.ticker_ms > anim.keep_duration) { anim.anim_state = .fadeout; anim.ticker_ms = 0; } }, } // backdrop text var offset_1 = the_pos; the_pos.x -= 1; the_pos.y -= 1; igSetCursorPos(offset_1); igPushStyleColorVec4(ImGuiCol_Text, current_backdrop_color); igText(msg); igPopStyleColor(1); // the actual msg igSetCursorPos(the_pos); igPushStyleColorVec4(ImGuiCol_Text, anim.current_color); igText(msg); igPopStyleColor(1); } // auto run through the presentation pub const AutoRunAnim = struct { running: bool = false, ticker_ms: u32 = 0, slide_duration: i32 = 200, screenshot_duration: i32 = 200, flag_switch_slide: bool = false, flag_in_screenshot: bool = false, flag_start_screenshot: bool = false, pub fn animate(self: *AutoRunAnim) void { if (!self.running) return; self.flag_switch_slide = false; self.flag_start_screenshot = false; self.ticker_ms += @floatToInt(u32, frame_dt * 1000); if (self.flag_in_screenshot) { self.flag_start_screenshot = false; if (self.ticker_ms >= self.screenshot_duration) { self.ticker_ms = 0; self.flag_switch_slide = true; self.flag_in_screenshot = false; } } else if (self.ticker_ms >= self.slide_duration) { self.ticker_ms = 0; self.flag_in_screenshot = true; self.flag_start_screenshot = true; } } pub fn toggle(self: *AutoRunAnim) bool { self.running = !self.running; if (!self.running) { self.stop(); } return self.running; } pub fn start(self: *AutoRunAnim) void { self.running = true; } pub fn stop(self: *AutoRunAnim) void { self.running = false; self.flag_start_screenshot = false; self.flag_in_screenshot = false; self.flag_switch_slide = false; } pub fn is_running(self: *AutoRunAnim) bool { return self.running; } };
src/uianim.zig
const std = @import("std"); const VTE = @import("vte"); const c = VTE.c; const gtk = VTE.gtk; const config = @import("config.zig"); const gui = @import("gui.zig"); const RGB = config.RGB; const allocator = std.heap.page_allocator; const fmt = std.fmt; const math = std.math; const mem = std.mem; var grad: ?Gradient = undefined; var gradientEditor: GradientEditor = undefined; var numStops: u8 = 2; pub const StopControls = struct { stops: gtk.SpinButton, stop_selector: gtk.ComboBoxText, stops_stack: gtk.Stack, stop1_grid: gtk.Widget, stop1_color: gtk.ColorButton, stop1_position: gtk.Scale, stop2_grid: gtk.Widget, stop2_color: gtk.ColorButton, stop2_position: gtk.Scale, stop3_grid: gtk.Widget, stop3_color: gtk.ColorButton, stop3_position: gtk.Scale, stop4_grid: gtk.Widget, stop4_color: gtk.ColorButton, stop4_position: gtk.Scale, const Self = @This(); fn init(builder: gtk.Builder) ?Self { return Self{ .stops = builder.get_widget("gradient_stops").?.to_spin_button().?, .stop_selector = builder.get_widget("gradient_stop_selector").?.to_combo_box_text().?, .stops_stack = builder.get_widget("stops_stack").?.to_stack().?, .stop1_grid = builder.get_widget("stop1_grid").?, .stop1_color = builder.get_widget("stop1_color").?.to_color_button().?, .stop1_position = builder.get_widget("stop1_position").?.to_scale().?, .stop2_grid = builder.get_widget("stop2_grid").?, .stop2_color = builder.get_widget("stop2_color").?.to_color_button().?, .stop2_position = builder.get_widget("stop2_position").?.to_scale().?, .stop3_grid = builder.get_widget("stop3_grid").?, .stop3_color = builder.get_widget("stop3_color").?.to_color_button().?, .stop3_position = builder.get_widget("stop3_position").?.to_scale().?, .stop4_grid = builder.get_widget("stop4_grid").?, .stop4_color = builder.get_widget("stop4_color").?.to_color_button().?, .stop4_position = builder.get_widget("stop4_position").?.to_scale().?, }; } fn toggle(self: Self) void { if (self.stop_selector.as_combo_box().get_active()) |id| { switch (id) { 0 => self.stops_stack.set_visible_child(self.stop1_grid), 1 => self.stops_stack.set_visible_child(self.stop2_grid), 2 => self.stops_stack.set_visible_child(self.stop3_grid), 3 => self.stops_stack.set_visible_child(self.stop4_grid), else => unreachable, } } } fn addRemoveStops(self: Self) void { switch (self.stops.get_value_as_int()) { 2 => { switch (numStops) { 3 => self.stop_selector.remove(2), 4 => { self.stop_selector.remove(3); self.stop_selector.remove(2); }, else => {}, } numStops = 2; }, 3 => { switch (numStops) { 4 => self.stop_selector.remove(3), 2 => { self.stop_selector.append("stop3", "Stop 3"); const adj = self.stop2_position.as_range().get_adjustment(); adj.set_value(50); }, else => {}, } numStops = 3; }, 4 => { switch (numStops) { 2 => { self.stop_selector.append("stop3", "Stop 3"); var adj = self.stop2_position.as_range().get_adjustment(); adj.set_value(33); self.stop_selector.append("stop4", "Stop 4"); adj = self.stop2_position.as_range().get_adjustment(); adj.set_value(66); }, 3 => { self.stop_selector.append("stop4", "Stop 4"); const adj = self.stop3_position.as_range().get_adjustment(); adj.set_value(66); }, else => {}, } numStops = 4; }, else => unreachable, } } fn setStops(self: Self) void { if (grad) |g| { self.stop1_color.as_color_chooser().set_rgba(g.stop1.color.toGdk()); self.stop1_position.as_range().set_value(g.stop1.position); self.stop2_color.as_color_chooser().set_rgba(g.stop2.color.toGdk()); self.stop2_position.as_range().set_value(g.stop2.position); if (g.stop3) |s| { self.stop3_color.as_color_chooser().set_rgba(s.color.toGdk()); numStops = 3; self.stops.set_value(3); self.stop_selector.append("stop3", "Stop 3"); } else numStops = 2; if (g.stop4) |s| { self.stop4_color.as_color_chooser().set_rgba(s.color.toGdk()); numStops = 4; self.stops.set_value(4); self.stop_selector.append("stop4", "Stop 4"); } } } fn setup(self: Self) void { self.connectSignals(); self.setStops(); self.toggle(); } fn updateScale2(self: Self) void { const val = self.stop1_position.as_range().get_value(); const adj = self.stop2_position.as_range().get_adjustment(); if (adj.get_value() < val) adj.set_value(val); adj.set_lower(val); } fn updateScale3(self: Self) void { const val = self.stop2_position.as_range().get_value(); const adj = self.stop3_position.as_range().get_adjustment(); if (adj.get_value() < val) adj.set_value(val); adj.set_lower(val); } fn updateScale4(self: Self) void { const val = self.stop3_position.as_range().get_value(); const adj = self.stop4_position.as_range().get_adjustment(); if (adj.get_value() < val) adj.set_value(val); adj.set_lower(val); } fn connectSignals(self: Self) void { const Callbacks = struct { fn stopsValueChanged() void { gradientEditor.stops.addRemoveStops(); gradientEditor.setBg(); } fn stopSelectorChanged() void { gradientEditor.stops.toggle(); } fn stop1PositionValueChanged() void { gradientEditor.stops.updateScale2(); gradientEditor.setBg(); } fn stop2PositionValueChanged() void { gradientEditor.stops.updateScale3(); gradientEditor.setBg(); } fn stop3PositionValueChanged() void { gradientEditor.stops.updateScale4(); gradientEditor.setBg(); } fn updatePreview() void { gradientEditor.setBg(); } }; self.stops.connect_value_changed( @ptrCast(c.GCallback, Callbacks.stopsValueChanged), null ); self.stop_selector.as_combo_box().connect_changed( @ptrCast(c.GCallback, Callbacks.stopSelectorChanged), null ); self.stop1_position.as_range().connect_value_changed( @ptrCast(c.GCallback, Callbacks.stop1PositionValueChanged), null ); self.stop1_color.connect_color_set( @ptrCast(c.GCallback, Callbacks.updatePreview), null ); self.stop2_position.as_range().connect_value_changed( @ptrCast(c.GCallback, Callbacks.stop2PositionValueChanged), null ); self.stop2_color.connect_color_set( @ptrCast(c.GCallback, Callbacks.updatePreview), null ); self.stop3_position.as_range().connect_value_changed( @ptrCast(c.GCallback, Callbacks.stop3PositionValueChanged), null ); self.stop3_color.connect_color_set( @ptrCast(c.GCallback, Callbacks.updatePreview), null ); self.stop4_position.as_range().connect_value_changed( @ptrCast(c.GCallback, Callbacks.updatePreview), null ); self.stop4_color.connect_color_set( @ptrCast(c.GCallback, Callbacks.updatePreview), null ); } fn getStop(self: Self, button: gtk.ColorButton, scale: gtk.Scale) Stop { _ = self; return Stop{ .color = RGB.fromButton(button), .position = scale.as_range().get_value(), }; } }; pub const GradientEditor = struct { editor: gtk.Widget, kind: gtk.ComboBox, position_type: gtk.Stack, start_position: gtk.Widget, end_position: gtk.Widget, dir_type: gtk.ComboBox, dir_stack: gtk.Stack, angle_grid: gtk.Widget, angle: gtk.SpinButton, edge_grid: gtk.Widget, vertical_position: gtk.ComboBox, horizontal_position: gtk.ComboBox, stops: StopControls, const Self = @This(); pub fn init(builder: gtk.Builder, conf: config.Config) ?Self { grad = switch (conf.background) { .gradient => |g| g, else => null, }; gradientEditor = Self{ .editor = builder.get_widget("gradient_editor").?, .kind = builder.get_widget("gradient_kind").?.to_combo_box().?, .position_type = builder.get_widget("position_type_stack").?.to_stack().?, .start_position = builder.get_widget("start_position").?, .end_position = builder.get_widget("end_position").?, .dir_type = builder.get_widget("gradient_direction_type").?.to_combo_box().?, .dir_stack = builder.get_widget("gradient_direction_stack").?.to_stack().?, .angle_grid = builder.get_widget("gradient_angle_grid").?, .angle = builder.get_widget("gradient_angle").?.to_spin_button().?, .edge_grid = builder.get_widget("gradient_edge_grid").?, .vertical_position = builder.get_widget("gradient_vertical_position").?.to_combo_box().?, .horizontal_position = builder.get_widget("gradient_horizontal_position").?.to_combo_box().?, .stops = StopControls.init(builder).?, }; gradientEditor.setup(); return gradientEditor; } fn getKind(self: Self) ?GradientKind { if (self.kind.get_active_id(allocator)) |id| { defer allocator.free(id); return if (config.parseEnum(GradientKind, id)) |k| k else null; } else return null; } fn setKind(self: Self) void { if (grad) |g| { switch (g.kind) { .linear => { self.kind.set_active_id("linear"); self.position_type.set_visible_child(self.end_position); }, .radial => { self.kind.set_active_id("radial"); self.position_type.set_visible_child(self.start_position); }, .elliptical => { self.kind.set_active_id("elliptical"); self.position_type.set_visible_child(self.start_position); }, } } } fn getPlacement(self: Self) ?Placement { const vert = vblk: { if (self.vertical_position.get_active_id(allocator)) |id| { defer allocator.free(id); if (config.parseEnum(VerticalPlacement, id)) |v| break :vblk v else return null; } else return null; }; const hor = hblk: { if (self.horizontal_position.get_active_id(allocator)) |id| { defer allocator.free(id); if (config.parseEnum(HorizontalPlacement, id)) |h| break :hblk h else return null; } else return null; }; return Placement{ .vertical = vert, .horizontal = hor, }; } fn getDirectionType(self: Self) ?DirectionType { if (self.dir_type.get_active_id(allocator)) |id| { defer allocator.free(id); return if (config.parseEnum(DirectionType, id)) |d| d else null; } else return null; } fn getDirection(self: Self) ?Direction { if (self.getDirectionType()) |dtype| { return switch (dtype) { .angle => Direction{ .angle = self.angle.get_value() }, .edge => if (self.getPlacement()) |p| Direction{ .edge = p } else null, }; } else return null; } fn setDirection(self: Self) void { if (grad) |g| { switch (g.pos) { .angle => |a| { self.dir_stack.set_visible_child(self.angle_grid); self.dir_type.set_active_id("angle"); self.angle.set_value(a); }, .edge => |p| { self.dir_stack.set_visible_child(self.edge_grid); self.dir_type.set_active_id("edge"); switch (p.vertical) { .top => self.vertical_position.set_active_id("top"), .center => self.vertical_position.set_active_id("center"), .bottom => self.vertical_position.set_active_id("bottom"), } switch (p.horizontal) { .left => self.horizontal_position.set_active_id("left"), .center => self.horizontal_position.set_active_id("center"), .right => self.horizontal_position.set_active_id("right"), } }, } } } pub fn getGradient(self: Self) ?Gradient { const s3: ?Stop = switch (numStops) { 2 => null, 3, 4 => self.stops.getStop(self.stops.stop3_color, self.stops.stop3_position), else => return null, }; const s4: ?Stop = switch (numStops) { 2, 3 => null, 4 => self.stops.getStop(self.stops.stop4_color, self.stops.stop4_position), else => return null, }; const kind = if (self.getKind()) |k| k else return null; const pos = switch (kind) { .linear => lblk: { if (self.getDirection()) |d| { break :lblk d; } else return null; }, .radial, .elliptical => pblk: { if (self.getPlacement()) |p| { break :pblk Direction{.edge = p, }; } else return null; }, }; return Gradient{ .kind = kind, .pos = pos, .stop1 = self.stops.getStop(self.stops.stop1_color, self.stops.stop1_position), .stop2 = self.stops.getStop(self.stops.stop2_color, self.stops.stop2_position), .stop3 = if (s3) |x| x else null, .stop4 = if (s4) |x| x else null, }; } pub fn setBg(self: Self) void { if (self.getGradient()) |g| { if (g.toCss(".workview stack")) |css| { defer allocator.free(css); const provider = gui.css_provider; _ = c.gtk_css_provider_load_from_data(provider, css, -1, null); } } } fn connectSignals(self: Self) void { const Callbacks = struct { fn kindChanged() void { gradientEditor.togglePositionType(); gradientEditor.setBg(); } fn dirTypeChanged() void { gradientEditor.toggleDirectionType(); gradientEditor.setBg(); } fn setBg() void { gradientEditor.setBg(); } }; self.kind.connect_changed( @ptrCast(c.GCallback, Callbacks.kindChanged), null); self.dir_type.connect_changed( @ptrCast(c.GCallback, Callbacks.dirTypeChanged), null); self.angle.connect_value_changed( @ptrCast(c.GCallback, Callbacks.setBg), null); self.vertical_position.connect_changed( @ptrCast(c.GCallback, Callbacks.setBg), null); self.horizontal_position.connect_changed( @ptrCast(c.GCallback, Callbacks.setBg), null); } fn togglePositionType(self: Self) void { if (self.getKind()) |kind| { switch (kind) { .linear => { self.position_type.set_visible_child(self.end_position); self.toggleDirectionType(); }, .radial, .elliptical => { self.position_type.set_visible_child(self.start_position); self.dir_stack.set_visible_child(self.edge_grid); }, } } } fn toggleDirectionType(self: Self) void { if (self.dir_type.get_active_id(allocator)) |id| { defer allocator.free(id); if (config.parseEnum(DirectionType, id)) |kind| { switch (kind) { .angle => { self.dir_stack.set_visible_child(self.angle_grid); }, .edge => { self.dir_stack.set_visible_child(self.edge_grid); }, } } } } fn toggle(self: Self) void { self.toggleDirectionType(); self.togglePositionType(); } pub fn setup(self: Self) void { self.connectSignals(); self.toggle(); self.setKind(); self.setDirection(); self.stops.setup(); } }; pub const GradientKind = enum { linear, radial, elliptical, const Self = @This(); fn default() Self { return Self.linear; } }; // This isn't used currently, because `zig-nestedtext` doesn't save the tag when // parsing tagged unions and so cannot preserve our variant (linear, radial, elliptical) // I want to keep it around because by using it it becomes impossible to create // a `Gradient` struct that is a radial or elliptical variant with an angular // direction. pub const Kind = union(GradientKind) { linear: Direction, radial: Placement, elliptical: Placement, const Self = @This(); fn default() Self { return Self{ .linear = Direction{ .edge = Placement.default() }}; } }; pub const VerticalPlacement = enum { top, center, bottom, const Self = @This(); fn default() Self { return Self.top; } }; pub const HorizontalPlacement = enum { left, center, right, const Self = @This(); fn default() Self { return Self.left; } }; pub const Placement = struct { vertical: VerticalPlacement, horizontal: HorizontalPlacement, const Self = @This(); fn default() Self { return Self{ .vertical = VerticalPlacement.default(), .horizontal = HorizontalPlacement.default(), }; } }; const DirectionType = enum { angle, edge, }; pub const Direction = union(DirectionType) { angle: f64, edge: Placement, const Self = @This(); fn default() Self { return Self{ .edge = Placement.default(), }; } }; pub const Stop = struct { color: RGB, position: f64, const Self = @This(); fn toCss(self: Self, buf: *[26]u8) ?[]const u8 { const str = fmt.bufPrint(buf, ", rgb({d}, {d}, {d}) {d}%", .{self.color.red, self.color.green, self.color.blue, math.round(self.position)}) catch return null; return str; } }; pub const Gradient = struct { kind: GradientKind, pos: Direction, stop1: Stop, stop2: Stop, stop3: ?Stop, stop4: ?Stop, const Self = @This(); pub fn default() Self { return Self{ .kind = GradientKind.default(), .pos = Direction.default(), .stop1 = Stop{ .color = RGB{ .red = 0, .green = 0, .blue = 0 }, .position = 0.0, }, .stop2 = Stop{ .color = RGB{ .red = 64, .green = 64, .blue = 64 }, .position = 100.0, }, .stop3 = null, .stop4 = null, }; } pub fn toCss(self: Self, class: []const u8) ?[:0]const u8 { var variety: []const u8 = ""; var positioning: []const u8 = ""; var angle: ?u16 = null; switch (self.kind) { .linear => { variety = "linear-gradient"; switch (self.pos) { .angle => |a| { angle = @floatToInt(u16, math.round(a)); }, .edge => |e| { positioning = switch (e.vertical) { .top => switch (e.horizontal) { .left => "to top left", .center => "to top", .right => "to top right", }, .center => switch (e.horizontal) { .left => "to left", .center => "to bottom right", .right => "to top right", }, .bottom => switch (e.horizontal) { .left => "to bottom left", .center => "to bottom", .right => "to bottom right", }, }; }, } }, .radial => { variety = "radial-gradient"; const pos = switch (self.pos) { .angle => return null, .edge => |e| e, }; positioning = switch (pos.vertical) { .top => switch (pos.horizontal) { .left => "circle at top left", .center => "circle at top", .right => "circle at top right", }, .center => switch (pos.horizontal) { .left => "circle at left", .center => "circle at center", .right => "circle at right", }, .bottom => switch (pos.horizontal) { .left => "circle at bottom left", .center => "circle at bottom", .right => "circle at bottom right", }, }; }, .elliptical => { variety = "radial-gradient"; const pos = switch (self.pos) { .angle => return null, .edge => |e| e, }; positioning = switch (pos.vertical) { .top => switch (pos.horizontal) { .left => "ellipse at top left", .center => "ellipse at top", .right => "ellipse at top right", }, .center => switch (pos.horizontal) { .left => "ellipse at left", .center => "ellipse at center", .right => "ellipse at right", }, .bottom => switch (pos.horizontal) { .left => "ellipse at bottom left", .center => "ellipse at bottom", .right => "ellipse at bottom right", }, }; }, } if (angle) |a| { var buf: [7]u8 = undefined; const str = fmt.bufPrint(&buf, "{d}deg", .{a}) catch return null; positioning = str[0..]; } var buf1: [26]u8 = undefined; const s1 = if (self.stop1.toCss(&buf1)) |css| css else return null; var buf2: [26]u8 = undefined; const s2 = if (self.stop2.toCss(&buf2)) |css| css else return null; const s3: []const u8 = if (self.stop3) |s| sblk: { var buf3: [26]u8 = undefined; if (s.toCss(&buf3)) |css| { break :sblk css; } else return null; } else ""; const s4: []const u8 = if (self.stop4) |s| sblk: { var buf4: [26]u8 = undefined; if (s.toCss(&buf4)) |css| { break :sblk css; } else return null; } else ""; const css_string = fmt.allocPrintZ(allocator, "{s} {{\n background-image: {s}({s}{s}{s}{s}{s});\n background-size: 100% 100%;\n\n}}", .{ class, variety, positioning, s1, s2, s3, s4, } ) catch return null; return css_string; } };
src/gradient.zig
const Builder = @import("std").build.Builder; pub fn build(b: *Builder) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const notcurses_source_path = "deps/notcurses"; const notcurses = b.addStaticLibrary("notcurses", null); // notcurses has saome undefined benavior which makes the demo crash with // illegal instruction, disabling UBSAN to make it work (-fno-sanitize-c) notcurses.disable_sanitize_c = true; notcurses.setTarget(target); notcurses.setBuildMode(mode); notcurses.linkLibC(); notcurses.linkSystemLibrary("ncurses"); notcurses.linkSystemLibrary("readline"); notcurses.linkSystemLibrary("unistring"); notcurses.linkSystemLibrary("z"); notcurses.addIncludeDir(notcurses_source_path ++ "/include"); notcurses.addIncludeDir(notcurses_source_path ++ "/build/include"); notcurses.addIncludeDir(notcurses_source_path ++ "/src"); notcurses.addCSourceFiles(&[_][]const u8{ notcurses_source_path ++ "/src/compat/compat.c", notcurses_source_path ++ "/src/lib/automaton.c", notcurses_source_path ++ "/src/lib/banner.c", notcurses_source_path ++ "/src/lib/blit.c", notcurses_source_path ++ "/src/lib/debug.c", notcurses_source_path ++ "/src/lib/direct.c", notcurses_source_path ++ "/src/lib/fade.c", notcurses_source_path ++ "/src/lib/fd.c", notcurses_source_path ++ "/src/lib/fill.c", notcurses_source_path ++ "/src/lib/gpm.c", notcurses_source_path ++ "/src/lib/in.c", notcurses_source_path ++ "/src/lib/kitty.c", notcurses_source_path ++ "/src/lib/layout.c", notcurses_source_path ++ "/src/lib/linux.c", notcurses_source_path ++ "/src/lib/menu.c", notcurses_source_path ++ "/src/lib/metric.c", notcurses_source_path ++ "/src/lib/notcurses.c", notcurses_source_path ++ "/src/lib/plot.c", notcurses_source_path ++ "/src/lib/progbar.c", notcurses_source_path ++ "/src/lib/reader.c", notcurses_source_path ++ "/src/lib/reel.c", notcurses_source_path ++ "/src/lib/render.c", notcurses_source_path ++ "/src/lib/selector.c", notcurses_source_path ++ "/src/lib/signal.c", notcurses_source_path ++ "/src/lib/sixel.c", notcurses_source_path ++ "/src/lib/sprite.c", notcurses_source_path ++ "/src/lib/stats.c", notcurses_source_path ++ "/src/lib/tabbed.c", notcurses_source_path ++ "/src/lib/termdesc.c", notcurses_source_path ++ "/src/lib/tree.c", notcurses_source_path ++ "/src/lib/util.c", notcurses_source_path ++ "/src/lib/visual.c", notcurses_source_path ++ "/src/lib/windows.c", }, &[_][]const u8{ "-std=gnu11", "-D_GNU_SOURCE", // to make memory management work, see sys/mman.h "-DUSE_MULTIMEDIA=none", "-DUSE_QRCODEGEN=OFF", "-DPOLLRDHUP=0x2000", }); const exe = b.addExecutable("demo", "src/main.zig"); exe.setTarget(target); exe.setBuildMode(mode); exe.install(); exe.linkLibC(); // exe.linkSystemLibrary("notcurses-core"); // exe.addObjectFile(notcurses_source_path ++ "/build/libnotcurses-core.a"); exe.addIncludeDir(notcurses_source_path ++ "/include"); exe.linkLibrary(notcurses); exe.linkSystemLibrary("qrcodegen"); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); }
build.zig
const std = @import("std"); const fs = std.fs; const json = std.json; const assert = std.debug.assert; const Record = struct { timestamp: u64, benchmark_name: []const u8, commit_hash: [20]u8, commit_timestamp: u64, zig_version: []const u8, error_message: []const u8 = &[0]u8{}, samples_taken: u64 = 0, wall_time_median: u64 = 0, wall_time_mean: u64 = 0, wall_time_min: u64 = 0, wall_time_max: u64 = 0, utime_median: u64 = 0, utime_mean: u64 = 0, utime_min: u64 = 0, utime_max: u64 = 0, stime_median: u64 = 0, stime_mean: u64 = 0, stime_min: u64 = 0, stime_max: u64 = 0, cpu_cycles_median: u64 = 0, cpu_cycles_mean: u64 = 0, cpu_cycles_min: u64 = 0, cpu_cycles_max: u64 = 0, instructions_median: u64 = 0, instructions_mean: u64 = 0, instructions_min: u64 = 0, instructions_max: u64 = 0, cache_references_median: u64 = 0, cache_references_mean: u64 = 0, cache_references_min: u64 = 0, cache_references_max: u64 = 0, cache_misses_median: u64 = 0, cache_misses_mean: u64 = 0, cache_misses_min: u64 = 0, cache_misses_max: u64 = 0, branch_misses_median: u64 = 0, branch_misses_mean: u64 = 0, branch_misses_min: u64 = 0, branch_misses_max: u64 = 0, maxrss: u64 = 0, const Key = struct { commit_hash: [20]u8, benchmark_name: []const u8, fn eql(self: Key, other: Key) bool { return std.mem.eql(u8, &self.commit_hash, &other.commit_hash) and std.mem.eql(u8, self.benchmark_name, other.benchmark_name); } }; }; fn jsonToRecord( arena: std.mem.Allocator, /// main object mo: json.Value, timestamp: u64, benchmark_name: []const u8, commit_hash: [20]u8, zig_version: []const u8, commit_timestamp: u64, ) !Record { // Example success output of benchmark program: // {"samples_taken":3,"wall_time":{"median":131511898884,"mean":131511898884,"min":131511898884,"max":131511898884},"utime":{"median":131507380000,"mean":131507380000,"min":131507380000,"max":131507380000},"stime":{"median":885000,"mean":885000,"min":885000,"max":885000},"cpu_cycles":{"median":506087170166,"mean":506087170166,"min":506087170166,"max":506087170166},"instructions":{"median":1013354628954,"mean":1013354628954,"min":1013354628954,"max":1013354628954},"cache_references":{"median":22131539,"mean":22131539,"min":22131539,"max":22131539},"cache_misses":{"median":4523975,"mean":4523975,"min":4523975,"max":4523975},"branch_misses":{"median":885333330,"mean":885333330,"min":885333330,"max":885333330},"maxrss":341004} // // Example failure output of the benchmark program: // FileNotFound var record: Record = .{ .timestamp = timestamp, .benchmark_name = try arena.dupe(u8, benchmark_name), .commit_hash = commit_hash, .commit_timestamp = commit_timestamp, .zig_version = zig_version, }; if (mo == .String) { record.error_message = try arena.dupe(u8, mo.String); } else { record.samples_taken = @intCast(u64, mo.Object.get("samples_taken").?.Integer); record.wall_time_median = @intCast(u64, mo.Object.get("wall_time").?.Object.get("median").?.Integer); record.wall_time_mean = @intCast(u64, mo.Object.get("wall_time").?.Object.get("mean").?.Integer); record.wall_time_min = @intCast(u64, mo.Object.get("wall_time").?.Object.get("min").?.Integer); record.wall_time_max = @intCast(u64, mo.Object.get("wall_time").?.Object.get("max").?.Integer); record.utime_median = @intCast(u64, mo.Object.get("utime").?.Object.get("median").?.Integer); record.utime_mean = @intCast(u64, mo.Object.get("utime").?.Object.get("mean").?.Integer); record.utime_min = @intCast(u64, mo.Object.get("utime").?.Object.get("min").?.Integer); record.utime_max = @intCast(u64, mo.Object.get("utime").?.Object.get("max").?.Integer); record.stime_median = @intCast(u64, mo.Object.get("stime").?.Object.get("median").?.Integer); record.stime_mean = @intCast(u64, mo.Object.get("stime").?.Object.get("mean").?.Integer); record.stime_min = @intCast(u64, mo.Object.get("stime").?.Object.get("min").?.Integer); record.stime_max = @intCast(u64, mo.Object.get("stime").?.Object.get("max").?.Integer); record.cpu_cycles_median = @intCast(u64, mo.Object.get("cpu_cycles").?.Object.get("median").?.Integer); record.cpu_cycles_mean = @intCast(u64, mo.Object.get("cpu_cycles").?.Object.get("mean").?.Integer); record.cpu_cycles_min = @intCast(u64, mo.Object.get("cpu_cycles").?.Object.get("min").?.Integer); record.cpu_cycles_max = @intCast(u64, mo.Object.get("cpu_cycles").?.Object.get("max").?.Integer); record.instructions_median = @intCast(u64, mo.Object.get("instructions").?.Object.get("median").?.Integer); record.instructions_mean = @intCast(u64, mo.Object.get("instructions").?.Object.get("mean").?.Integer); record.instructions_min = @intCast(u64, mo.Object.get("instructions").?.Object.get("min").?.Integer); record.instructions_max = @intCast(u64, mo.Object.get("instructions").?.Object.get("max").?.Integer); record.cache_references_median = @intCast(u64, mo.Object.get("cache_references").?.Object.get("median").?.Integer); record.cache_references_mean = @intCast(u64, mo.Object.get("cache_references").?.Object.get("mean").?.Integer); record.cache_references_min = @intCast(u64, mo.Object.get("cache_references").?.Object.get("min").?.Integer); record.cache_references_max = @intCast(u64, mo.Object.get("cache_references").?.Object.get("max").?.Integer); record.cache_misses_median = @intCast(u64, mo.Object.get("cache_misses").?.Object.get("median").?.Integer); record.cache_misses_mean = @intCast(u64, mo.Object.get("cache_misses").?.Object.get("mean").?.Integer); record.cache_misses_min = @intCast(u64, mo.Object.get("cache_misses").?.Object.get("min").?.Integer); record.cache_misses_max = @intCast(u64, mo.Object.get("cache_misses").?.Object.get("max").?.Integer); record.branch_misses_median = @intCast(u64, mo.Object.get("branch_misses").?.Object.get("median").?.Integer); record.branch_misses_mean = @intCast(u64, mo.Object.get("branch_misses").?.Object.get("mean").?.Integer); record.branch_misses_min = @intCast(u64, mo.Object.get("branch_misses").?.Object.get("min").?.Integer); record.branch_misses_max = @intCast(u64, mo.Object.get("branch_misses").?.Object.get("max").?.Integer); record.maxrss = @intCast(u64, mo.Object.get("maxrss").?.Integer); } return record; } const comma = ","; const CommitTable = std.HashMap( Record.Key, usize, CommitTableContext, std.hash_map.default_max_load_percentage, ); const CommitTableContext = struct { pub const Key = Record.Key; pub fn eql(ctx: @This(), a: Key, b: Key) bool { _ = ctx; return a.eql(b); } pub fn hash(ctx: @This(), key: Key) u64 { _ = ctx; var hasher = std.hash.Wyhash.init(0); std.hash.autoHashStrat(&hasher, key, .Deep); return hasher.final(); } }; pub fn main() !void { const gpa = std.heap.page_allocator; var arena_state = std.heap.ArenaAllocator.init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator(); const args = try std.process.argsAlloc(arena); const records_csv_path = args[1]; const zig_exe = args[2]; const commit = try parseCommit(args[3]); const commit_timestamp = try parseTimestamp(args[4]); const zig_version_raw = try execCapture(arena, &[_][]const u8{ zig_exe, "version" }, .{}); const zig_version = std.mem.trim(u8, zig_version_raw, " \r\n\t"); std.debug.print("Detected zig version {s}...\n", .{zig_version}); // Load CSV into memory std.debug.print("Loading CSV data...\n", .{}); var records = std.ArrayList(Record).init(gpa); defer records.deinit(); var commit_table = CommitTable.init(gpa); defer commit_table.deinit(); { const csv_text = try fs.cwd().readFileAlloc(gpa, records_csv_path, 2 * 1024 * 1024 * 1024); defer gpa.free(csv_text); var field_indexes: [@typeInfo(Record).Struct.fields.len]usize = undefined; var seen_fields = [1]bool{false} ** field_indexes.len; var line_it = std.mem.split(u8, csv_text, "\n"); { const first_line = line_it.next() orelse { std.debug.print("empty CSV file", .{}); std.process.exit(1); }; var csv_index: usize = 0; var it = std.mem.split(u8, first_line, comma); while (it.next()) |field_name| : (csv_index += 1) { if (csv_index >= field_indexes.len) { std.debug.print("extra CSV field: {s}\n", .{field_name}); std.process.exit(1); } const field_index = fieldIndex(Record, field_name) orelse { std.debug.print("bad CSV field name: {s}\n", .{field_name}); std.process.exit(1); }; //std.debug.print("found field '{}' = {}\n", .{ field_name, field_index }); field_indexes[csv_index] = field_index; seen_fields[field_index] = true; } inline for (@typeInfo(Record).Struct.fields) |field, i| { if (!seen_fields[i]) { std.debug.print("missing CSV field: {s}", .{field.name}); std.process.exit(1); } } } var line_index: usize = 1; while (line_it.next()) |line| : (line_index += 1) { if (std.mem.eql(u8, line, "")) continue; // Skip blank lines. var it = std.mem.split(u8, line, comma); var csv_index: usize = 0; const record_index = records.items.len; const record = try records.addOne(); while (it.next()) |field| : (csv_index += 1) { if (csv_index >= field_indexes.len) { std.debug.print("extra CSV field on line {d}\n", .{line_index + 1}); std.process.exit(1); } setRecordField(arena, record, field, field_indexes[csv_index]); } if (csv_index != field_indexes.len) { std.debug.print("CSV line {d} missing a field\n", .{line_index + 1}); std.process.exit(1); } const key: Record.Key = .{ .commit_hash = record.commit_hash, .benchmark_name = record.benchmark_name, }; if (try commit_table.fetchPut(key, record_index)) |existing| { //const existing_record = records.items[existing.value]; _ = commit_table.putAssumeCapacity(key, existing.value); records.shrinkRetainingCapacity(records.items.len - 1); } } } var manifest_parser = json.Parser.init(gpa, false); const manifest_text = try fs.cwd().readFileAlloc(gpa, "benchmarks/manifest.json", 3 * 1024 * 1024); const manifest_tree = try manifest_parser.parse(manifest_text); runBenchmarks(gpa, arena, &records, &commit_table, manifest_tree.root, zig_exe, commit, zig_version, commit_timestamp) catch |err| { std.debug.print("error running benchmarks: {s}\n", .{@errorName(err)}); }; // Save CSV std.debug.print("Updating {s}...\n", .{records_csv_path}); { const baf = try std.io.BufferedAtomicFile.create(gpa, fs.cwd(), records_csv_path, .{}); defer baf.destroy(); const out = baf.writer(); inline for (@typeInfo(Record).Struct.fields) |field, i| { if (i != 0) { try out.writeAll(comma); } try out.writeAll(field.name); } try out.writeAll("\n"); for (records.items) |record| { try writeCSVRecord(out, record); try out.writeAll("\n"); } try baf.finish(); } } fn fieldIndex(comptime T: type, name: []const u8) ?usize { inline for (@typeInfo(T).Struct.fields) |field, i| { if (std.mem.eql(u8, field.name, name)) return i; } return null; } fn setRecordField(arena: std.mem.Allocator, record: *Record, data: []const u8, index: usize) void { inline for (@typeInfo(Record).Struct.fields) |field, i| { if (i == index) { setRecordFieldT(arena, field.field_type, &@field(record, field.name), data); return; } } unreachable; } fn setRecordFieldT(arena: std.mem.Allocator, comptime T: type, ptr: *T, data: []const u8) void { if (@typeInfo(T) == .Enum) { ptr.* = std.meta.stringToEnum(T, data) orelse { std.debug.print("bad enum value: {d}\n", .{data}); std.process.exit(1); }; return; } switch (T) { u64 => { ptr.* = std.fmt.parseInt(u64, data, 10) catch |err| { std.debug.print("bad u64 value '{d}': {s}\n", .{ data, @errorName(err) }); std.process.exit(1); }; }, []const u8 => { ptr.* = arena.dupe(u8, data) catch @panic("out of memory"); }, [20]u8 => { ptr.* = parseCommit(data) catch |err| { std.debug.print("wrong format for commit hash: '{d}': {s}", .{ data, @errorName(err) }); std.process.exit(1); }; }, else => @compileError("no deserialization for " ++ @typeName(T)), } } fn writeCSVRecord(out: anytype, record: Record) !void { inline for (@typeInfo(Record).Struct.fields) |field, i| { if (i != 0) { try out.writeAll(comma); } try writeCSVRecordField(out, @field(record, field.name)); } } fn writeCSVRecordField(out: anytype, field: anytype) !void { const T = @TypeOf(field); if (@typeInfo(T) == .Enum) { return out.writeAll(@tagName(field)); } switch (T) { u64 => return out.print("{}", .{field}), []const u8 => return out.writeAll(field), [20]u8 => return out.print("{}", .{std.fmt.fmtSliceHexLower(&field)}), else => @compileError("unsupported writeCSVRecordField type: " ++ @typeName(T)), } } fn parseCommit(text: []const u8) ![20]u8 { var result: [20]u8 = undefined; if (text.len != 40) { return error.WrongSHALength; } var i: usize = 0; while (i < 20) : (i += 1) { const byte = std.fmt.parseInt(u8, text[i * 2 ..][0..2], 16) catch { return error.BadSHACharacter; }; result[i] = byte; } return result; } fn parseTimestamp(text: []const u8) !u64 { return std.fmt.parseInt(u64, std.mem.trim(u8, text, " \n\r\t"), 10) catch |err| { std.debug.print("bad timestamp format: '{s}': {s}\n", .{ text, @errorName(err) }); return error.BadTimestampFormat; }; } fn runBenchmarks( gpa: std.mem.Allocator, arena: std.mem.Allocator, records: *std.ArrayList(Record), commit_table: *CommitTable, manifest: json.Value, zig_exe: []const u8, commit: [20]u8, zig_version: []const u8, commit_timestamp: u64, ) !void { try records.ensureUnusedCapacity(manifest.Object.count() * 2); const timestamp = @intCast(u64, std.time.timestamp()); // cd benchmarks/self-hosted-parser // zig build-exe --main-pkg-path ../.. --pkg-begin app main.zig --pkg-end ../../bench.zig --enable-cache // ./../../zig-cache/path/to/bench zig var benchmarks_it = manifest.Object.iterator(); while (benchmarks_it.next()) |entry| { const benchmark_name = entry.key_ptr.*; const dir_name = entry.value_ptr.Object.get("dir").?.String; const main_basename = entry.value_ptr.Object.get("mainPath").?.String; const bench_cwd = try fs.path.join(gpa, &[_][]const u8{ "benchmarks", dir_name }); defer gpa.free(bench_cwd); const full_main_path = try fs.path.join(gpa, &[_][]const u8{ bench_cwd, main_basename }); defer gpa.free(full_main_path); const abs_main_path = try fs.realpathAlloc(gpa, full_main_path); defer gpa.free(abs_main_path); std.debug.print( "Running '{s}' for {}...\n", .{ benchmark_name, std.fmt.fmtSliceHexLower(&commit) }, ); // Compile first to ensure that it doesn't affect the rusage stats var compile_argv = std.ArrayList([]const u8).init(gpa); defer compile_argv.deinit(); try appendBenchBuildArgs(&compile_argv, zig_exe, abs_main_path, "../../bench.zig"); const compile_stdout = try execCapture(gpa, compile_argv.items, .{ .cwd = bench_cwd }); defer gpa.free(compile_stdout); // Because we compiled with --enable-cache, the path to the cache directory was printed // to stdout. We can append `./` to the front and `bench` to the end to execute it const trimmed_output = std.mem.trimRight(u8, compile_stdout, "\r\n"); const main_exe = try std.fs.path.join(gpa, &.{ ".", trimmed_output, "bench" }); defer gpa.free(main_exe); var main_argv = &[_][]const u8{ main_exe, zig_exe }; const main_stdout = try execCapture(gpa, main_argv, .{ .cwd = bench_cwd }); defer gpa.free(main_stdout); var bench_parser = json.Parser.init(gpa, false); defer bench_parser.deinit(); var main_json = bench_parser.parse(main_stdout) catch |err| { std.debug.print("bad json: {s}\n{s}\n", .{ @errorName(err), main_stdout }); return error.InvalidBenchJSON; }; defer main_json.deinit(); const record = try jsonToRecord( arena, main_json.root, timestamp, benchmark_name, commit, zig_version, commit_timestamp, ); const key: Record.Key = .{ .commit_hash = record.commit_hash, .benchmark_name = record.benchmark_name, }; const main_gop = try commit_table.getOrPut(key); if (main_gop.found_existing) { records.items[main_gop.value_ptr.*] = record; } else { main_gop.value_ptr.* = records.items.len; records.appendAssumeCapacity(record); } } } fn appendBenchBuildArgs( list: *std.ArrayList([]const u8), zig_exe: []const u8, main_path: []const u8, bench_zig: []const u8, ) !void { try list.ensureUnusedCapacity(20); list.appendSliceAssumeCapacity(&[_][]const u8{ zig_exe, "build-exe", "--main-pkg-path", "../..", "--pkg-begin", "app", main_path, "--pkg-end", "-O", "ReleaseFast", "--enable-cache", bench_zig, }); } fn exec( gpa: std.mem.Allocator, argv: []const []const u8, options: struct { cwd: ?[]const u8 = null }, ) !void { const child = try std.ChildProcess.init(argv, gpa); defer child.deinit(); child.stdin_behavior = .Inherit; child.stdout_behavior = .Inherit; child.stderr_behavior = .Inherit; child.cwd = options.cwd; const term = try child.spawnAndWait(); switch (term) { .Exited => |code| { if (code != 0) { return error.ChildProcessBadExitCode; } }, else => { return error.ChildProcessCrashed; }, } } fn execCapture( gpa: std.mem.Allocator, argv: []const []const u8, options: struct { cwd: ?[]const u8 = null }, ) ![]u8 { //std.debug.print("exec argv[0]={} cwd={}\n", .{argv[0], options.cwd}); const child = try std.ChildProcess.init(argv, gpa); defer child.deinit(); child.stdin_behavior = .Inherit; child.stdout_behavior = .Pipe; child.stderr_behavior = .Inherit; child.cwd = options.cwd; //std.debug.print("cwd={}\n", .{child.cwd}); //for (argv) |arg| { // std.debug.print("{} ", .{arg}); //} //std.debug.print("\n", .{}); try child.spawn(); const stdout_in = child.stdout.?.reader(); const stdout = try stdout_in.readAllAlloc(gpa, 9999); errdefer gpa.free(stdout); const term = try child.wait(); switch (term) { .Exited => |code| { if (code != 0) { return error.ChildProcessBadExitCode; } }, else => { return error.ChildProcessCrashed; }, } return stdout; }
collect-measurements.zig
const std = @import("std"); const GeneralPurposeAllocator = std.heap.GeneralPurposeAllocator; const mustache = @import("mustache"); // Mustache template const template_text = \\{{! This is a spec-compliant mustache template }} \\Hello {{name}} from Zig \\This template was generated with \\{{#env}} \\Zig: {{zig_version}} \\Mustache: {{mustache_version}} \\{{/env}} \\Supported features: \\{{#features}} \\ - {{name}} {{condition}} \\{{/features}} ; // Context, can be any Zig struct, supporting optionals, slices, tuples, recursive types, pointers, etc. var ctx = .{ .name = "friends", .env = .{ .zig_version = "master", .mustache_version = "alpha", }, .features = .{ .{ .name = "interpolation", .condition = "✅ done" }, .{ .name = "sections", .condition = "✅ done" }, .{ .name = "comments", .condition = "✅ done" }, .{ .name = "delimiters", .condition = "✅ done" }, .{ .name = "partials", .condition = "✅ done" }, .{ .name = "lambdas", .condition = "✅ done" }, .{ .name = "inheritance", .condition = "⏳ comming soon" }, }, }; pub fn main() anyerror!void { try renderFromString(); try renderComptimeTemplate(); try renderFromCachedTemplate(); try renderFromFile(); try renderComptimePartialTemplate(); } /// Render a template from a string pub fn renderFromString() anyerror!void { var gpa = GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var out = std.io.getStdOut(); // Direct render to save memory try mustache.renderText(allocator, template_text, ctx, out.writer()); } /// Parses a template at comptime to render many times at runtime, no allocations needed pub fn renderComptimeTemplate() anyerror!void { var out = std.io.getStdOut(); // Comptime-parsed template const comptime_template = comptime mustache.parseComptime(template_text, .{}, .{}); var repeat: u32 = 0; while (repeat < 10) : (repeat += 1) { try mustache.render(comptime_template, ctx, out.writer()); } } /// Caches a template to render many times pub fn renderFromCachedTemplate() anyerror!void { var gpa = GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); // Store this template and render many times from it const cached_template = switch (try mustache.parseText(allocator, template_text, .{}, .{ .copy_strings = false })) { .success => |ret| ret, .parse_error => |detail| { std.log.err("Parse error {s} at lin {}, col {}", .{ @errorName(detail.parse_error), detail.lin, detail.col }); return; }, }; var repeat: u32 = 0; while (repeat < 10) : (repeat += 1) { var result = try mustache.allocRender(allocator, cached_template, ctx); defer allocator.free(result); var out = std.io.getStdOut(); try out.writeAll(result); } } /// Render a template from a file path pub fn renderFromFile() anyerror!void { // 16KB should be enough memory for this job var plenty_of_memory = std.heap.GeneralPurposeAllocator(.{ .enable_memory_limit = true }){ .requested_memory_limit = 16 * 1024, }; defer _ = plenty_of_memory.deinit(); const allocator = plenty_of_memory.allocator(); const path = try std.fs.selfExeDirPathAlloc(allocator); defer allocator.free(path); // Creating a temp file const path_to_template = try std.fs.path.join(allocator, &.{ path, "template.mustache" }); defer allocator.free(path_to_template); defer std.fs.deleteFileAbsolute(path_to_template) catch {}; { var file = try std.fs.createFileAbsolute(path_to_template, .{ .truncate = true }); defer file.close(); var repeat: u32 = 0; // Writing the same template 10K times on a file while (repeat < 10_000) : (repeat += 1) { try file.writeAll(template_text); } } var out = std.io.getStdOut(); // Rendering this large template with only 16KB of RAM try mustache.renderFile(allocator, path_to_template, ctx, out.writer()); } /// Parses a template at comptime to render many times at runtime, no allocations needed pub fn renderComptimePartialTemplate() anyerror!void { var out = std.io.getStdOut(); // Comptime-parsed template const comptime_template = comptime mustache.parseComptime( \\{{=[ ]=}} \\📜 hello [>partial], your lucky number is [sub_value.value] \\-------------------------------------- \\ , .{}, .{}); // Comptime tuple with a comptime partial template const comptime_partials = .{ "partial", comptime mustache.parseComptime("from {{name}}", .{}, .{}) }; const Data = struct { name: []const u8, sub_value: struct { value: u32, }, }; // Runtime value var data: Data = .{ .name = "mustache", .sub_value = .{ .value = 42 } }; var repeat: u32 = 0; while (repeat < 10) : (repeat += 1) { try mustache.renderPartials(comptime_template, comptime_partials, data, out.writer()); } }
samples/src/main.zig
const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const kernel = @import("__trig.zig"); const __rem_pio2 = @import("__rem_pio2.zig").__rem_pio2; const __rem_pio2f = @import("__rem_pio2f.zig").__rem_pio2f; /// Returns the cosine of the radian value x. /// /// Special Cases: /// - cos(+-inf) = nan /// - cos(nan) = nan pub fn cos(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => cos32(x), f64 => cos64(x), else => @compileError("cos not implemented for " ++ @typeName(T)), }; } fn cos32(x: f32) f32 { // Small multiples of pi/2 rounded to double precision. const c1pio2: f64 = 1.0 * math.pi / 2.0; // 0x3FF921FB, 0x54442D18 const c2pio2: f64 = 2.0 * math.pi / 2.0; // 0x400921FB, 0x54442D18 const c3pio2: f64 = 3.0 * math.pi / 2.0; // 0x4012D97C, 0x7F3321D2 const c4pio2: f64 = 4.0 * math.pi / 2.0; // 0x401921FB, 0x54442D18 var ix = @bitCast(u32, x); const sign = ix >> 31 != 0; ix &= 0x7fffffff; if (ix <= 0x3f490fda) { // |x| ~<= pi/4 if (ix < 0x39800000) { // |x| < 2**-12 // raise inexact if x != 0 math.doNotOptimizeAway(x + 0x1p120); return 1.0; } return kernel.__cosdf(x); } if (ix <= 0x407b53d1) { // |x| ~<= 5*pi/4 if (ix > 0x4016cbe3) { // |x| ~> 3*pi/4 return -kernel.__cosdf(if (sign) x + c2pio2 else x - c2pio2); } else { if (sign) { return kernel.__sindf(x + c1pio2); } else { return kernel.__sindf(c1pio2 - x); } } } if (ix <= 0x40e231d5) { // |x| ~<= 9*pi/4 if (ix > 0x40afeddf) { // |x| ~> 7*pi/4 return kernel.__cosdf(if (sign) x + c4pio2 else x - c4pio2); } else { if (sign) { return kernel.__sindf(-x - c3pio2); } else { return kernel.__sindf(x - c3pio2); } } } // cos(Inf or NaN) is NaN if (ix >= 0x7f800000) { return x - x; } var y: f64 = undefined; const n = __rem_pio2f(x, &y); return switch (n & 3) { 0 => kernel.__cosdf(y), 1 => kernel.__sindf(-y), 2 => -kernel.__cosdf(y), else => kernel.__sindf(y), }; } fn cos64(x: f64) f64 { var ix = @bitCast(u64, x) >> 32; ix &= 0x7fffffff; // |x| ~< pi/4 if (ix <= 0x3fe921fb) { if (ix < 0x3e46a09e) { // |x| < 2**-27 * sqrt(2) // raise inexact if x!=0 math.doNotOptimizeAway(x + 0x1p120); return 1.0; } return kernel.__cos(x, 0); } // cos(Inf or NaN) is NaN if (ix >= 0x7ff00000) { return x - x; } var y: [2]f64 = undefined; const n = __rem_pio2(x, &y); return switch (n & 3) { 0 => kernel.__cos(y[0], y[1]), 1 => -kernel.__sin(y[0], y[1], 1), 2 => -kernel.__cos(y[0], y[1]), else => kernel.__sin(y[0], y[1], 1), }; } test "math.cos" { try expect(cos(@as(f32, 0.0)) == cos32(0.0)); try expect(cos(@as(f64, 0.0)) == cos64(0.0)); } test "math.cos32" { const epsilon = 0.00001; try expect(math.approxEqAbs(f32, cos32(0.0), 1.0, epsilon)); try expect(math.approxEqAbs(f32, cos32(0.2), 0.980067, epsilon)); try expect(math.approxEqAbs(f32, cos32(0.8923), 0.627623, epsilon)); try expect(math.approxEqAbs(f32, cos32(1.5), 0.070737, epsilon)); try expect(math.approxEqAbs(f32, cos32(-1.5), 0.070737, epsilon)); try expect(math.approxEqAbs(f32, cos32(37.45), 0.969132, epsilon)); try expect(math.approxEqAbs(f32, cos32(89.123), 0.400798, epsilon)); } test "math.cos64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, cos64(0.0), 1.0, epsilon)); try expect(math.approxEqAbs(f64, cos64(0.2), 0.980067, epsilon)); try expect(math.approxEqAbs(f64, cos64(0.8923), 0.627623, epsilon)); try expect(math.approxEqAbs(f64, cos64(1.5), 0.070737, epsilon)); try expect(math.approxEqAbs(f64, cos64(-1.5), 0.070737, epsilon)); try expect(math.approxEqAbs(f64, cos64(37.45), 0.969132, epsilon)); try expect(math.approxEqAbs(f64, cos64(89.123), 0.40080, epsilon)); } test "math.cos32.special" { try expect(math.isNan(cos32(math.inf(f32)))); try expect(math.isNan(cos32(-math.inf(f32)))); try expect(math.isNan(cos32(math.nan(f32)))); } test "math.cos64.special" { try expect(math.isNan(cos64(math.inf(f64)))); try expect(math.isNan(cos64(-math.inf(f64)))); try expect(math.isNan(cos64(math.nan(f64)))); }
lib/std/math/cos.zig
const std = @import("std"); const builtin = @import("builtin"); const assert = std.debug.assert; const Sha256 = std.crypto.hash.sha2.Sha256; const zephyr = @import("zephyr.zig"); const image = @import("image.zig"); const tlv = @import("tlv.zig"); const Image = image.Image; const flashTest = @import("testing.zig").flashTest; const sys = @import("src/sys.zig"); const FlashArea = sys.flash.FlashArea; // Setup Zig logging to output through Zephyr. pub const log_level: std.log.Level = .info; pub const log = zephyr.log; extern fn extra() void; export fn main() void { extra(); std.log.info("Starting zigboot", .{}); const result = if (false) flashTest() else core(); result catch |err| { std.log.err("Fatal: {}", .{err}); }; } // Arm executables start with this header. pub const ArmHeader = extern struct { msp: u32, pc: u32, }; // Execution help is in C. extern fn chain_jump(vt: u32, msp: u32, pc: u32) noreturn; fn core() !void { var img = try Image.init(@enumToInt(image.Slot.PrimarySecure)); try image.dump_layout(); { std.log.info("SHA256 Hash benchmark", .{}); const timer = Timer.start(); try image.hash_bench(img.fa, 1000); timer.stamp("Hash time"); } { std.log.info("Null Hash benchmark", .{}); const timer = Timer.start(); try image.null_bench(img.fa, 100000); timer.stamp("Hash time"); } { std.log.info("Murmur2 Hash benchmark", .{}); const timer = Timer.start(); try image.murmur_bench(img.fa, 100000); timer.stamp("Hash time"); } { std.log.info("SipHash64(2,4) Hash benchmark", .{}); const timer = Timer.start(); try image.murmur_bench(img.fa, 100000); timer.stamp("Hash time"); } const arm_header = try img.readStruct(ArmHeader, img.header.imageStart()); // var arm_header: ArmHeader = undefined; // var bytes = std.mem.asBytes(&arm_header); // try img.fa.read(img.header.imageStart(), bytes); const timer = Timer.start(); var hash: [32]u8 = undefined; try image.hash_image(img.fa, &img.header, &hash); timer.stamp("Time for hash"); try tlv.validateTlv(&img); // try tlv.showTlv(&img); try validateImage(&img, hash); chain_jump(img.fa.off, arm_header.msp, arm_header.pc); } // Go through the TLV, checking hashes and signatures to ensure that // this image is valid. fn validateImage(img: *Image, hash: [32]u8) !void { var iter = try tlv.TlvIter.init(img); while (try iter.next()) |item| { switch (item.tag) { @enumToInt(tlv.TlvTag.Sha256) => { std.log.warn("Checking hash", .{}); const expectHash = try iter.readItem([32]u8, &item); std.log.info("Equal: {}", .{constEql(u8, expectHash[0..], hash[0..])}); }, else => |tag| { const etag = std.meta.intToEnum(tlv.TlvTag, tag) catch .Other; std.log.info("Tag: 0x{x:0>2} {}", .{ tag, etag }); }, } } } // Constant time comparison. "T" must be a numeric type. fn constEql(comptime T: type, a: []const T, b: []const T) bool { assert(a.len == b.len); var mismatch: T = 0; for (a) |aelt, i| { mismatch |= aelt ^ b[i]; } return mismatch == 0; } // Timing utility. const Timer = struct { const Self = @This(); start: i64, fn start() Self { return Self{ .start = zephyr.uptime(), }; } fn stamp(self: *const Self, message: []const u8) void { const now = zephyr.uptime(); std.log.info("{s}: {}ms", .{ message, now - self.start }); } };
main.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const gui = @import("gui"); const nvg = @import("nanovg"); const geometry = @import("gui/geometry.zig"); const Point = geometry.Point; const Rect = geometry.Rect; const EditorWidget = @import("EditorWidget.zig"); const NewDocumentWidget = @This(); widget: gui.Widget, allocator: *Allocator, editor_widget: *EditorWidget, width_label: *gui.Label, width_spinner: *gui.Spinner(i32), height_label: *gui.Label, height_spinner: *gui.Spinner(i32), ok_button: *gui.Button, cancel_button: *gui.Button, onSelectedFn: ?fn (*Self) void = null, const Self = @This(); pub fn init(allocator: *Allocator, editor_widget: *EditorWidget) !*Self { var self = try allocator.create(Self); self.* = Self{ .widget = gui.Widget.init(allocator, Rect(f32).make(0, 0, 240, 100)), .allocator = allocator, .editor_widget = editor_widget, .width_label = try gui.Label.init(allocator, Rect(f32).make(10, 20, 0, 20), "Width:"), .width_spinner = try gui.Spinner(i32).init(allocator, Rect(f32).make(55, 20, 60, 20)), .height_label = try gui.Label.init(allocator, Rect(f32).make(125, 20, 0, 20), "Height:"), .height_spinner = try gui.Spinner(i32).init(allocator, Rect(f32).make(170, 20, 60, 20)), .ok_button = try gui.Button.init(allocator, Rect(f32).make(240 - 160 - 10 - 10, 100 - 25 - 10, 80, 25), "OK"), .cancel_button = try gui.Button.init(allocator, Rect(f32).make(240 - 80 - 10, 100 - 25 - 10, 80, 25), "Cancel"), }; self.widget.onKeyDownFn = onKeyDown; self.width_spinner.setValue(@intCast(i32, editor_widget.document.width)); self.height_spinner.setValue(@intCast(i32, editor_widget.document.height)); self.width_spinner.min_value = 1; self.height_spinner.min_value = 1; self.width_spinner.max_value = 1 << 14; // 16k self.height_spinner.max_value = 1 << 14; self.ok_button.onClickFn = onOkButtonClick; self.cancel_button.onClickFn = onCancelButtonClick; try self.widget.addChild(&self.width_label.widget); try self.widget.addChild(&self.width_spinner.widget); try self.widget.addChild(&self.height_label.widget); try self.widget.addChild(&self.height_spinner.widget); try self.widget.addChild(&self.ok_button.widget); try self.widget.addChild(&self.cancel_button.widget); self.widget.drawFn = draw; return self; } pub fn deinit(self: *Self) void { self.width_label.deinit(); self.width_spinner.deinit(); self.height_label.deinit(); self.height_spinner.deinit(); self.ok_button.deinit(); self.cancel_button.deinit(); self.widget.deinit(); self.allocator.destroy(self); } fn onKeyDown(widget: *gui.Widget, event: *gui.KeyEvent) void { var self = @fieldParentPtr(Self, "widget", widget); switch (event.key) { .Return => self.accept(), .Escape => self.cancel(), else => event.event.ignore(), } } fn onOkButtonClick(button: *gui.Button) void { if (button.widget.parent) |parent| { var self = @fieldParentPtr(Self, "widget", parent); self.accept(); } } fn onCancelButtonClick(button: *gui.Button) void { if (button.widget.parent) |parent| { var self = @fieldParentPtr(Self, "widget", parent); self.cancel(); } } fn accept(self: *Self) void { self.editor_widget.createNewDocument( @intCast(u32, self.width_spinner.value), @intCast(u32, self.height_spinner.value), ) catch { // TODO: error dialog }; if (self.widget.getWindow()) |window| { window.close(); } } fn cancel(self: *Self) void { if (self.widget.getWindow()) |window| { window.close(); } } pub fn draw(widget: *gui.Widget) void { nvg.beginPath(); nvg.rect(0, 0, 240, 55); nvg.fillColor(nvg.rgbf(1, 1, 1)); nvg.fill(); nvg.beginPath(); nvg.rect(0, 55, 240, 45); nvg.fillColor(gui.theme_colors.background); nvg.fill(); widget.drawChildren(); }
src/NewDocumentWidget.zig
const std = @import("std"); const panic = std.debug.panic; const Allocator = std.mem.Allocator; usingnamespace @import("backend.zig"); const List = std.ArrayList(Node); const Object = std.StringHashMap(Node); const String = []const u8; const ScalarType = enum { String, Integer, Float, Bool, }; const Scalar = union(ScalarType) { String: String, Integer: u64, Float: f64, Bool: bool, pub fn fromString(string: String, typeHint: ?ScalarType) LoaderError!@This() { if (typeHint) |stype| { switch (stype) { .Integer => { if (std.fmt.parseInt(u64, string, 0)) |int| { return Scalar{ .Integer = int }; } else |_| { return LoaderError.UnexpectedType; } }, .Float => { if (std.fmt.parseFloat(f64, string)) |float| { return Scalar{ .Float = float }; } else |_| { return LoaderError.UnexpectedType; } }, .Bool => { if (std.mem.eql(u8, "true", string)) { return Scalar{ .Bool = true }; } else if (std.mem.eql(u8, "false", string)) { return Scalar{ .Bool = false }; } else { return LoaderError.UnexpectedType; } }, else => { return Scalar{ .String = string }; }, } } else { return Scalar{ .String = string }; } } pub fn deinit(self: *@This(), allocator: *Allocator) void { switch(self.*) { .String => |st| allocator.free(st), else => {} } } }; const Node = union(enum) { Scalar: Scalar, List: List, Object: Object, pub fn deinit(self: *@This(), allocator: *Allocator) void { switch(self.*) { .Scalar => |*sc| sc.deinit(allocator), .List => |*ls| { for(ls.items) |*node| { node.deinit(allocator); } ls.deinit(); }, .Object => |*obj| { var iter = obj.iterator(); while(iter.next()) |entry| { var k = entry.key_ptr; var v = entry.value_ptr; allocator.free(k.*); v.deinit(allocator); } obj.deinit(); } } } }; const Command = enum { Mapping, Sequencing, }; const State = union(Command) { Mapping: struct { object: Object, name: ?String, }, Sequencing: List, pub fn addNode(self: *@This(), node: Node) LoaderError!void { switch (self.*) { .Mapping => |*mapping| { if (mapping.name) |name| { try mapping.object.put(name, node); mapping.name = null; } else panic("Expected key but there was none", .{}); }, .Sequencing => |*seq| { try seq.append(node); }, } } }; /// A basic YAML loader. If you just want to parse a string instead, see `stringLoader`. pub fn Loader(comptime Reader: type) type { const Parser = parser.Parser(Reader); return struct { inner: Parser, allocator: *Allocator, nodes: List, const Self = @This(); fn init(allocator: *Allocator, reader: Reader) ParserError!Self { var par = try Parser.init(allocator, reader) ; errdefer par.deinit(); var ndlist = List.init(allocator); return Self{ .allocator = allocator, .inner = par, .nodes = ndlist}; } fn parse(self: *Self, command: ?Command) YamlError!Node { var state: ?State = if (command) |cmd| switch (cmd) { .Mapping => State{ .Mapping = .{ .object = Object.init(self.allocator), .name = null } }, .Sequencing => State{ .Sequencing = List.init(self.allocator) }, } else null; var evt: Event = undefined; while (true) { evt = try self.inner.nextEvent(); switch (evt.etype) { .MappingStartEvent => { const obj = try self.parse(.Mapping); if (state) |*st| { try st.addNode(obj); } else return obj; }, .MappingEndEvent => { if (state) |st| switch (st) { .Mapping => |map| { if (map.name) |name| panic("Mapping stopped before key \'{s}\' could receive a value", .{name}); return Node{ .Object = map.object }; }, else => |cur| panic("Current state is '{s}', expected '{s}'", .{ @tagName(cur), @tagName(.Mapping) }), } else panic("Impossible to end mapping; nothing is supposed to be happening", .{}); }, .SequenceStartEvent => { const seq = try self.parse(.Sequencing); if (state) |*st| { try st.addNode(seq); } else return seq; }, .ScalarEvent => |scalar| { if (state) |*st| { // If we're currently mapping and there is no name yet, // store this scalar to be used as a key. switch (st.*) { .Mapping => |*map| if (map.name == null) { map.name = scalar.value; continue; }, else => {}, } try st.addNode(.{ .Scalar = try Scalar.fromString(scalar.value, null) }); } else return Node{ .Scalar = try Scalar.fromString(scalar.value, null) }; }, .SequenceEndEvent => { if (state) |st| { switch (st) { .Sequencing => |seq| return Node{ .List = seq }, .Mapping => panic("Received sequence stop event while mapping", .{}), } } else panic("Impossible to end sequencing; nothing is supposed to be happening", .{}); }, else => {}, } } unreachable; } /// Returns a dynamic representation of YAML. /// This is useful when you don't know the data beforehand. /// This is freed when `Parser.deinit` is called. pub fn parseDynamic(self: *Self) YamlError!Node { var nd = try self.parse(null); try self.nodes.append(nd); return nd; } pub fn deinit(self: *Self) void { self.inner.deinit(); for(self.nodes.items) |*node| { node.deinit(self.allocator); } self.nodes.deinit(); } }; } pub const StringLoader = Loader(*std.io.FixedBufferStream(String).Reader); test "Load String" { const string = "name: Bob\nage: 100"; var buf = std.io.fixedBufferStream(string); var stringloader = try StringLoader.init(std.testing.allocator, &buf.reader()); defer stringloader.deinit(); const result = try stringloader.parseDynamic(); const name = result.Object.get("name").?.Scalar.String; const age = result.Object.get("age").?.Scalar.String; try std.testing.expectEqualStrings("Bob", name); try std.testing.expectEqualStrings("100", age); } test "Root is List" { const string = \\- apple \\- pear \\- grapes \\- starfruit ; var buf = std.io.fixedBufferStream(string); var stringloader = try StringLoader.init(std.testing.allocator, &buf.reader()); defer stringloader.deinit(); const result = try stringloader.parseDynamic(); try std.testing.expect(result == .List); const fruits = result.List; inline for(.{"apple", "pear", "grapes", "starfruit"}) |name, i| { try std.testing.expectEqualStrings(fruits.items[i].Scalar.String, name); } }
src/yaml.zig
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/day22.txt"); pub fn run(alloc: Allocator, stdout_: anytype) !void { var entries = ArrayList(Cuboid).init(alloc); defer entries.deinit(); var lines = helper.getlines(input); while (lines.next()) |line| { const entry = try Cuboid.parse(line); try entries.append(entry); } var reactor = Reactor.init(alloc); defer reactor.deinit(); var i: usize = 0; while (true) : (i += 1) { const val = entries.items[i].x.low; if (val < -50 or val > 50) break; try reactor.addCuboid(entries.items[i]); } const res1 = reactor.volumeSum(); while (i < entries.items.len) : (i += 1) { try reactor.addCuboid(entries.items[i]); } const res2 = reactor.volumeSum(); if (stdout_) |stdout| { try stdout.print("Part 1: {}\n", .{res1}); try stdout.print("Part 2: {}\n", .{res2}); } } const Reactor = struct { cuboids: ArrayList(Cuboid), buffer: ArrayList(Cuboid), const Self = @This(); pub fn init(alloc: Allocator) Self { return .{ .cuboids = ArrayList(Cuboid).init(alloc), .buffer = ArrayList(Cuboid).init(alloc), }; } pub fn addCuboid(self: *Self, cuboid: Cuboid) !void { self.buffer.clearRetainingCapacity(); for (self.cuboids.items) |victim| { try self.splitAndAddPieces(victim, cuboid); } if (cuboid.on) { try self.buffer.append(cuboid); } std.mem.swap(ArrayList(Cuboid), &self.cuboids, &self.buffer); } fn minimizeFrom(self: *Self, i_: usize) void { var i: usize = i_; while (i < self.buffer.items.len) { const ci = self.buffer.items[i]; var melded: bool = false; var j: usize = i + 1; while (j < self.buffer.items.len) : (j += 1) { const cj = &self.buffer.items[j]; const eqx = ci.x.eq(cj.x); const eqy = ci.y.eq(cj.y); const eqz = ci.z.eq(cj.z); if (eqx and eqy) { if (ci.z.low == cj.z.high + 1) { cj.z.high = ci.z.high; melded = true; } else if (ci.z.high == cj.z.low - 1) { cj.z.low = ci.z.low; melded = true; } } else if (eqy and eqz) { if (ci.x.low == cj.x.high + 1) { cj.x.high = ci.x.high; melded = true; } else if (ci.x.high == cj.x.low - 1) { cj.x.low = ci.x.low; melded = true; } } else if (eqz and eqx) { if (ci.y.low == cj.y.high + 1) { cj.y.high = ci.y.high; melded = true; } else if (ci.y.high == cj.y.low - 1) { cj.y.low = ci.y.low; melded = true; } } if (melded) break; } if (melded) { _ = self.buffer.swapRemove(i); } else { i += 1; } } } fn splitAndAddPieces(self: *Self, victim: Cuboid, splitter: Cuboid) !void { const splitter_ranges: [3]Range(i32) = .{ splitter.x, splitter.y, splitter.z }; const victim_ranges: [3]Range(i32) = .{ victim.x, victim.y, victim.z }; var victim_split_ranges: [3][3]?Range(i32) = undefined; for (splitter_ranges) |srange, i| { const vrange = victim_ranges[i]; victim_split_ranges[i] = splitRange(vrange, srange); } const idx = self.buffer.items.len; for (victim_split_ranges[0]) |xrangen, xi| if (xrangen) |xrange| { for (victim_split_ranges[1]) |yrangen, yi| if (yrangen) |yrange| { for (victim_split_ranges[2]) |zrangen, zi| if (zrangen) |zrange| { if (xi == 1 and yi == 1 and zi == 1) continue; // exactly the intersection of the cuboids try self.buffer.append(Cuboid{ .x = xrange, .y = yrange, .z = zrange, .on = true, }); }; }; }; if (idx < self.buffer.items.len) { self.minimizeFrom(idx); } } fn splitRange(vrange: Range(i32), srange: Range(i32)) [3]?Range(i32) { return .{ Range(i32).init(vrange.low, std.math.min(vrange.high, srange.low - 1)), vrange.intersection(srange), Range(i32).init(std.math.max(vrange.low, srange.high + 1), vrange.high), }; } pub fn volumeSum(self: Self) i64 { var sum: i64 = 0; for (self.cuboids.items) |cuboid| { sum += cuboid.volume(); } return sum; } pub fn deinit(self: Self) void { self.cuboids.deinit(); self.buffer.deinit(); } }; const Point = struct { x: i32, y: i32, z: i32 }; fn Range(comptime T: type) type { return struct { low: T, high: T, const Self = @This(); pub fn init(low: T, high: T) ?Self { if (low > high) return null; return Self{ .low = low, .high = high }; } pub fn contains(self: Self, elem: T) bool { return self.low <= elem and elem <= self.high; } pub fn intersection(self: Self, other: Self) ?Self { const low = std.math.max(self.low, other.low); const high = std.math.min(self.high, other.high); return Self.init(low, high); // automatically handles non-intersecting ranges } pub fn length(self: Self) T { return self.high - self.low + 1; } pub fn eq(self: Self, other: Self) bool { return self.low == other.low and self.high == other.high; } }; } const Cuboid = struct { x: Range(i32), y: Range(i32), z: Range(i32), on: bool, const Self = @This(); pub fn parse(line: []const u8) !Self { const on = std.mem.startsWith(u8, line, "on"); var tokens = tokenize(u8, line, "ofnxyz=., "); var ranges: [3]Range(i32) = undefined; for (ranges) |*range| { const low = try parseInt(i32, tokens.next().?, 10); const high = try parseInt(i32, tokens.next().?, 10); range.* = Range(i32).init(low, high) orelse return error.InvalidRange; } return Self{ .x = ranges[0], .y = ranges[1], .z = ranges[2], .on = on, }; } pub fn volume(self: Self) i64 { var acc: i64 = 1; acc *= self.x.length(); acc *= self.y.length(); acc *= self.z.length(); return acc; } }; const eql = std.mem.eql; 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/day22.zig
const std = @import("std"); const root = @import("main.zig"); const meta = std.meta; const generic_vector = @import("generic_vector.zig"); const mat4 = @import("mat4.zig"); const math = std.math; const eps_value = math.floatEps(f32); const expectApproxEqAbs = std.testing.expectApproxEqAbs; const expectApproxEqRel = std.testing.expectApproxEqRel; const expectEqual = std.testing.expectEqual; const expect = std.testing.expect; const assert = std.debug.assert; const GenericVector = generic_vector.GenericVector; const Vec3 = generic_vector.Vec3; const Vec4 = generic_vector.Vec4; const Mat4x4 = mat4.Mat4x4; pub const Quat = Quaternion(f32); pub const Quat_f64 = Quaternion(f64); /// A Quaternion for 3D rotations. pub fn Quaternion(comptime T: type) type { if (@typeInfo(T) != .Float) { @compileError("Quaternion not implemented for " ++ @typeName(T)); } const Vector3 = GenericVector(3, T); return extern struct { w: T, x: T, y: T, z: T, const Self = @This(); /// Construct new quaternion from floats. pub fn new(w: T, x: T, y: T, z: T) Self { return .{ .w = w, .x = x, .y = y, .z = z, }; } /// Shorthand for (1, 0, 0, 0). pub fn identity() Self { return Self.new(1, 0, 0, 0); } /// Set all components to the same given value. pub fn set(val: T) Self { return Self.new(val, val, val, val); } /// Construct new quaternion from slice. /// Note: Careful, the latest component `slice[3]` is the `W` component. pub fn fromSlice(slice: []const T) Self { return Self.new(slice[3], slice[0], slice[1], slice[2]); } // Construct new quaternion from given `W` component and Vector3. pub fn fromVec3(w: T, axis: Vector3) Self { return Self.new(w, axis.x(), axis.y(), axis.z()); } /// Return true if two quaternions are equal. pub fn eql(left: Self, right: Self) bool { return meta.eql(left, right); } /// Construct new normalized quaternion from a given one. pub fn norm(self: Self) Self { const l = length(self); if (l == 0) { return self; } return Self.new( self.w / l, self.x / l, self.y / l, self.z / l, ); } /// Return the length (magnitude) of quaternion. pub fn length(self: Self) T { return @sqrt(self.dot(self)); } /// Substraction between two quaternions. pub fn sub(left: Self, right: Self) Self { return Self.new( left.w - right.w, left.x - right.x, left.y - right.y, left.z - right.z, ); } /// Addition between two quaternions. pub fn add(left: Self, right: Self) Self { return Self.new( left.w + right.w, left.x + right.x, left.y + right.y, left.z + right.z, ); } /// Quaternions' multiplication. /// Produce a new quaternion from given two quaternions. pub fn mul(left: Self, right: Self) Self { const x = (left.x * right.w) + (left.y * right.z) - (left.z * right.y) + (left.w * right.x); const y = (-left.x * right.z) + (left.y * right.w) + (left.z * right.x) + (left.w * right.y); const z = (left.x * right.y) - (left.y * right.x) + (left.z * right.w) + (left.w * right.z); const w = (-left.x * right.x) - (left.y * right.y) - (left.z * right.z) + (left.w * right.w); return Self.new(w, x, y, z); } /// Multiply each component by the given scalar. pub fn scale(mat: Self, scalar: T) Self { const w = mat.w * scalar; const x = mat.x * scalar; const y = mat.y * scalar; const z = mat.z * scalar; return Self.new(w, x, y, z); } /// Negate the given quaternion pub fn negate(self: Self) Self { return self.scale(-1); } /// Return the dot product between two quaternion. pub fn dot(left: Self, right: Self) T { return (left.x * right.x) + (left.y * right.y) + (left.z * right.z) + (left.w * right.w); } /// Convert given quaternion to rotation 4x4 matrix. /// Mostly taken from https://github.com/HandmadeMath/Handmade-Math. pub fn toMat4(self: Self) Mat4x4(T) { var result: Mat4x4(T) = undefined; const normalized = self.norm(); const xx = normalized.x * normalized.x; const yy = normalized.y * normalized.y; const zz = normalized.z * normalized.z; const xy = normalized.x * normalized.y; const xz = normalized.x * normalized.z; const yz = normalized.y * normalized.z; const wx = normalized.w * normalized.x; const wy = normalized.w * normalized.y; const wz = normalized.w * normalized.z; result.data[0][0] = 1 - 2 * (yy + zz); result.data[0][1] = 2 * (xy + wz); result.data[0][2] = 2 * (xz - wy); result.data[0][3] = 0; result.data[1][0] = 2 * (xy - wz); result.data[1][1] = 1 - 2 * (xx + zz); result.data[1][2] = 2 * (yz + wx); result.data[1][3] = 0; result.data[2][0] = 2 * (xz + wy); result.data[2][1] = 2 * (yz - wx); result.data[2][2] = 1 - 2 * (xx + yy); result.data[2][3] = 0; result.data[3][0] = 0; result.data[3][1] = 0; result.data[3][2] = 0; result.data[3][3] = 1; return result; } /// From <NAME> at Insomniac Games. /// For more details: https://d3cw3dd2w32x2b.cloudfront.net/wp-content/uploads/2015/01/matrix-to-quat.pdf pub fn fromMat4(mat: Mat4x4(T)) Self { var t: T = undefined; var result: Self = undefined; if (mat.data[2][2] < 0) { if (mat.data[0][0] > mat.data[1][1]) { t = 1 + mat.data[0][0] - mat.data[1][1] - mat.data[2][2]; result = Self.new( mat.data[1][2] - mat.data[2][1], t, mat.data[0][1] + mat.data[1][0], mat.data[2][0] + mat.data[0][2], ); } else { t = 1 - mat.data[0][0] + mat.data[1][1] - mat.data[2][2]; result = Self.new( mat.data[2][0] - mat.data[0][2], mat.data[0][1] + mat.data[1][0], t, mat.data[1][2] + mat.data[2][1], ); } } else { if (mat.data[0][0] < -mat.data[1][1]) { t = 1 - mat.data[0][0] - mat.data[1][1] + mat.data[2][2]; result = Self.new( mat.data[0][1] - mat.data[1][0], mat.data[2][0] + mat.data[0][2], mat.data[1][2] + mat.data[2][1], t, ); } else { t = 1 + mat.data[0][0] + mat.data[1][1] + mat.data[2][2]; result = Self.new( t, mat.data[1][2] - mat.data[2][1], mat.data[2][0] - mat.data[0][2], mat.data[0][1] - mat.data[1][0], ); } } return result.scale(0.5 / @sqrt(t)); } /// Convert all Euler angles (in degrees) to quaternion. pub fn fromEulerAngles(axis_in_degrees: Vector3) Self { const x = Self.fromAxis(axis_in_degrees.x(), Vector3.right()); const y = Self.fromAxis(axis_in_degrees.y(), Vector3.up()); const z = Self.fromAxis(axis_in_degrees.z(), Vector3.forward()); return z.mul(y.mul(x)); } /// Convert Euler angle around specified axis to quaternion. pub fn fromAxis(degrees: T, axis: Vector3) Self { const radians = root.toRadians(degrees); const rot_sin = @sin(radians / 2); const quat_axis = axis.norm().data * @splat(3, rot_sin); const w = @cos(radians / 2); return Self.fromVec3(w, .{ .data = quat_axis }); } /// Extract euler angles (degrees) from quaternion. pub fn extractEulerAngles(self: Self) Vector3 { const yaw = math.atan2( T, 2 * (self.y * self.z + self.w * self.x), self.w * self.w - self.x * self.x - self.y * self.y + self.z * self.z, ); const pitch = math.asin( -2 * (self.x * self.z - self.w * self.y), ); const roll = math.atan2( T, 2 * (self.x * self.y + self.w * self.z), self.w * self.w + self.x * self.x - self.y * self.y - self.z * self.z, ); return Vector3.new(root.toDegrees(yaw), root.toDegrees(pitch), root.toDegrees(roll)); } /// Get the rotation angle (degrees) and axis for a given quaternion. // Taken from https://github.com/raysan5/raylib/blob/master/src/raymath.h#L1755 pub fn extractAxisAngle(self: Self) struct { axis: Vector3, angle: T } { var copy = self; if (@fabs(copy.w) > 1) copy = copy.norm(); var res_axis = Vector3.zero(); var res_angle: T = 2 * math.acos(copy.w); const den: T = @sqrt(1 - copy.w * copy.w); if (den > 0.0001) { res_axis.data[0] = copy.x / den; res_axis.data[1] = copy.y / den; res_axis.data[2] = copy.z / den; } else { // This occurs when the angle is zero. // Not a problem: just set an arbitrary normalized axis. res_axis.data[0] = 1; } return .{ .axis = res_axis, .angle = root.toDegrees(res_angle), }; } /// Construct inverse quaternion pub fn inv(self: Self) Self { const res = Self.new(self.w, -self.x, -self.y, -self.z); return res.scale(1 / self.dot(self)); } /// Linear interpolation between two quaternions. pub fn lerp(left: Self, right: Self, t: T) Self { const w = root.lerp(T, left.w, right.w, t); const x = root.lerp(T, left.x, right.x, t); const y = root.lerp(T, left.y, right.y, t); const z = root.lerp(T, left.z, right.z, t); return Self.new(w, x, y, z); } // Shortest path slerp between two quaternions. // Taken from "Physically Based Rendering, 3rd Edition, Chapter 2.9.2" // https://pbr-book.org/3ed-2018/Geometry_and_Transformations/Animating_Transformations#QuaternionInterpolation pub fn slerp(left: Self, right: Self, t: T) Self { const ParallelThreshold = 0.9995; var cos_theta = dot(left, right); var right1 = right; // We need the absolute value of the dot product to take the shortest path if (cos_theta < 0) { cos_theta *= -1; right1 = right.negate(); } if (cos_theta > ParallelThreshold) { // Use regular old lerp to avoid numerical instability return lerp(left, right1, t); } else { var theta = math.acos(math.clamp(cos_theta, -1, 1)); const thetap = theta * t; var qperp = right1.sub(left.scale(cos_theta)).norm(); return left.scale(@cos(thetap)).add(qperp.scale(@sin(thetap))); } } /// Rotate the Vector3 v using the sandwich product. /// Taken from "Foundations of Game Engine Development Vol. 1 Mathematics". pub fn rotateVec(self: Self, v: Vector3) Vector3 { const q = self.norm(); const b = Vector3.new(q.x, q.y, q.z); const b2 = b.dot(b); return v.scale(q.w * q.w - b2).add(b.scale(v.dot(b) * 2)).add(b.cross(v).scale(q.w * 2)); } /// Cast a type to another type. /// It's like builtins: @intCast, @floatCast, @intToFloat, @floatToInt. pub fn cast(self: Self, comptime dest_type: type) Quaternion(dest_type) { const dest_info = @typeInfo(dest_type); if (dest_info != .Float) { std.debug.panic("Error, dest type should be float.\n", .{}); } const w = @floatCast(dest_type, self.w); const x = @floatCast(dest_type, self.x); const y = @floatCast(dest_type, self.y); const z = @floatCast(dest_type, self.z); return Quaternion(dest_type).new(w, x, y, z); } }; } test "zalgebra.Quaternion.new" { const q = Quat.new(1.5, 2.6, 3.7, 4.7); try expectEqual(q.w, 1.5); try expectEqual(q.x, 2.6); try expectEqual(q.y, 3.7); try expectEqual(q.z, 4.7); } test "zalgebra.Quaternion.set" { const a = Quat.set(12); const b = Quat.new(12, 12, 12, 12); try expectEqual(a, b); } test "zalgebra.Quaternion.eql" { const a = Quat.new(1.5, 2.6, 3.7, 4.7); const b = Quat.new(1.5, 2.6, 3.7, 4.7); const c = Quat.new(2.6, 3.7, 4.8, 5.9); try expectEqual(Quat.eql(a, b), true); try expectEqual(Quat.eql(a, c), false); } test "zalgebra.Quaternion.fromSlice" { const array = [4]f32{ 2, 3, 4, 1 }; try expectEqual(Quat.fromSlice(&array), Quat.new(1, 2, 3, 4)); } test "zalgebra.Quaternion.fromVec3" { const q = Quat.fromVec3(1.5, Vec3.new(2.6, 3.7, 4.7)); try expectEqual(q.w, 1.5); try expectEqual(q.x, 2.6); try expectEqual(q.y, 3.7); try expectEqual(q.z, 4.7); } test "zalgebra.Quaternion.fromVec3" { const a = Quat.fromVec3(1.5, Vec3.new(2.6, 3.7, 4.7)); const b = Quat.fromVec3(1.5, Vec3.new(2.6, 3.7, 4.7)); const c = Quat.fromVec3(1, Vec3.new(2.6, 3.7, 4.7)); try expectEqual(a, b); try expectEqual(Quat.eql(a, c), false); } test "zalgebra.Quaternion.norm" { const a = Quat.fromVec3(1, Vec3.new(2, 2, 2)); const b = Quat.fromVec3(0.2773500978946686, Vec3.new(0.5547001957893372, 0.5547001957893372, 0.5547001957893372)); try expectEqual(a.norm(), b); } test "zalgebra.Quaternion.fromEulerAngles" { const a = Quat.fromEulerAngles(Vec3.new(10, 5, 45)); const a_res = a.extractEulerAngles(); const b = Quat.fromEulerAngles(Vec3.new(0, 55, 22)); const b_res = b.toMat4().extractEulerAngles(); try expectEqual(a_res, Vec3.new(9.999999046325684, 5.000000476837158, 45)); try expectEqual(b_res, Vec3.new(0, 47.2450294, 22)); } test "zalgebra.Quaternion.fromAxis" { const q = Quat.fromAxis(45, Vec3.up()); const res_q = q.extractEulerAngles(); try expectEqual(res_q, Vec3.new(0, 45.0000076, 0)); } test "zalgebra.Quaternion.extractAxisAngle" { const axis = Vec3.new(44, 120, 8).norm(); const q = Quat.fromAxis(45, axis); const res = q.extractAxisAngle(); try expectApproxEqRel(axis.x(), res.axis.x(), eps_value); try expectApproxEqRel(axis.y(), res.axis.y(), eps_value); try expectApproxEqRel(axis.z(), res.axis.z(), eps_value); try expectApproxEqRel(res.angle, 45.0000076, eps_value); } test "zalgebra.Quaternion.extractEulerAngles" { const q = Quat.fromVec3(0.5, Vec3.new(0.5, 1, 0.3)); const res_q = q.extractEulerAngles(); try expectEqual(res_q, Vec3.new(129.6000213623047, 44.427005767822266, 114.4107360839843)); } test "zalgebra.Quaternion.rotateVec" { const q = Quat.fromEulerAngles(Vec3.set(45)); const m = q.toMat4(); const v = Vec3.up(); const v1 = q.rotateVec(v); const v2 = m.mulByVec4(Vec4.new(v.x(), v.y(), v.z(), 1)); try expectApproxEqAbs(v1.x(), -1.46446585e-01, eps_value); try expectApproxEqAbs(v1.y(), 8.53553473e-01, eps_value); try expectApproxEqAbs(v1.z(), 0.5, eps_value); try expectApproxEqAbs(v1.x(), v2.data[0], eps_value); try expectApproxEqAbs(v1.y(), v2.data[1], eps_value); try expectApproxEqAbs(v1.z(), v2.data[2], eps_value); } test "zalgebra.Quaternion.lerp" { const a = Quat.identity(); const b = Quat.fromAxis(180, Vec3.up()); try expectEqual(Quat.lerp(a, b, 1), b); const c = Quat.lerp(a, b, 0.5); const d = Quat.new(0.5, 0, 0.5, 0); try expectApproxEqAbs(c.w, d.w, eps_value); try expectApproxEqAbs(c.x, d.x, eps_value); try expectApproxEqAbs(c.y, d.y, eps_value); try expectApproxEqAbs(c.z, d.z, eps_value); } test "zalgebra.Quaternion.slerp" { const a = Quat.identity(); const b = Quat.fromAxis(180, Vec3.up()); try expectEqual(Quat.slerp(a, b, 1), Quat.new(7.54979012e-08, 0, -1, 0)); const c = Quat.slerp(a, b, 0.5); const d = Quat.new(1, 0, -1, 0).norm(); try expectApproxEqAbs(c.w, d.w, eps_value); try expectApproxEqAbs(c.x, d.x, eps_value); try expectApproxEqAbs(c.y, d.y, eps_value); try expectApproxEqAbs(c.z, d.z, eps_value); } test "zalgebra.Quaternion.cast" { const a = Quat.new(3.5, 4.5, 5.5, 6.5); const a_f64 = Quat_f64.new(3.5, 4.5, 5.5, 6.5); try expectEqual(a.cast(f64), a_f64); try expectEqual(a_f64.cast(f32), a); } test "zalgebra.Quaternion.inv" { const out = Quat.new(7, 4, 5, 9).inv(); const answ = Quat.new(0.0409357, -0.0233918, -0.0292398, -0.0526316); try expectApproxEqAbs(out.w, answ.w, eps_value); try expectApproxEqAbs(out.x, answ.x, eps_value); try expectApproxEqAbs(out.y, answ.y, eps_value); try expectApproxEqAbs(out.z, answ.z, eps_value); }
src/quaternion.zig
const std = @import("std"); const hm = std.array_hash_map; const fs = std.fs; const BagFitIn = struct { name: []const u8, times: i32 = 0, }; const BagContains = struct { name: [] const u8, times: i32 = 0 }; const Bag = struct { in: [16]BagFitIn, contains: [16] BagContains, in_count: usize = 0, contain_count: usize = 0, visited: bool = false, }; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = &gpa.allocator; const input = try fs.cwd().readFileAlloc(allocator, "data/input_07_1.txt", std.math.maxInt(usize)); var lines = std.mem.tokenize(input, "\n"); const col_rule_separator = " bags contain "; var map = hm.ArrayHashMap([]const u8, Bag, hm.hashString, hm.eqlString, true) .init(allocator); while (lines.next()) |line| { const trimmed = std.mem.trim(u8, line, " \r\n"); if (trimmed.len == 0) break; const col_last = std.mem.indexOf(u8, trimmed, col_rule_separator).?; const color = trimmed[0..col_last]; const rules = trimmed[col_last+col_rule_separator.len..]; const p_entry = try map.getOrPutValue(color, Bag{ .in = undefined, .contains = undefined }); const p_bag = &p_entry.*.value; if (std.mem.eql(u8, rules, "no other bags.")) continue; //std.debug.print("Color: {}\n", .{color}); var rulesit = std.mem.tokenize(rules, ","); while (rulesit.next()) |rule_untrimmed| { const rule = std.mem.trim(u8, rule_untrimmed, " \r\n"); var rule_it = std.mem.tokenize(rule, " "); const count_txt = rule_it.next().?; const color_bgn = count_txt.len + 1; const color_len = rule_it.next().?.len + 1 + rule_it.next().?.len; const color_txt = rule[color_bgn..color_bgn+color_len]; const count = try std.fmt.parseInt(i32, count_txt, 10); //std.debug.print(" - Rule - Count: {}, Color: \"{}\"\n", .{count, color_txt}); const c_entry = try map.getOrPutValue(color_txt, Bag{ .in = undefined, .contains = undefined }); var c_bag = &c_entry.*.value; c_bag.*.in[c_bag.*.in_count] = BagFitIn{.name = color, .times = count}; c_bag.*.in_count += 1; var paren = &map.getEntry(color).?.*.value; paren.*.contains[paren.*.contain_count] = BagContains{ .name = color_txt, .times = count }; paren.*.contain_count += 1; } } { // Solution 1 var to_visit = std.ArrayList([]const u8).init(allocator); try to_visit.append("shiny gold"); var count: usize = 0; {var to_visit_i: usize = 0; while (to_visit_i < to_visit.items.len) : (to_visit_i += 1) { const bag_name = to_visit.items[to_visit_i]; const bag = &map.getEntry(bag_name).?; if (bag.*.value.visited) continue; count += 1; bag.*.value.visited = true; {var i: usize = 0; while (i < bag.*.value.in_count) : (i += 1) { try to_visit.append(bag.*.value.in[i].name); }} }} std.debug.print("Day 07 - Solution 1: {}\n", .{count - 1}); } { // Solution 2 const Contains = struct { color: []const u8, count: usize }; var to_visit = std.ArrayList(Contains).init(allocator); try to_visit.append(Contains{.color = "shiny gold", .count = 1}); var accum: usize = 0; {var to_visit_i: usize = 0; while (to_visit_i < to_visit.items.len) : (to_visit_i += 1) { const bag_name = to_visit.items[to_visit_i].color; const count = to_visit.items[to_visit_i].count; accum += count; const bag = &map.getEntry(bag_name).?; {var i: usize = 0; while (i < bag.*.value.contain_count) : (i += 1) { const next_name = bag.*.value.contains[i].name; const next_times = @intCast(usize, bag.*.value.contains[i].times) * count; try to_visit.append(Contains{.color = next_name, .count = next_times}); }} }} std.debug.print("Day 07 - Solution 2: {}\n", .{accum - 1}); } }
2020/src/day_07.zig
const std = @import("std"); const sdl = @import("sdl"); const samples_for_avg = 5; pub const Time = struct { fps_frames: u32 = 0, prev_time: u32 = 0, curr_time: u32 = 0, fps_last_update: u32 = 0, frames_per_seconds: u32 = 0, frame_count: u32 = 1, timestep: Timestep = undefined, pub fn init(update_rate: f64) Time { return Time{ .timestep = Timestep.init(update_rate), }; } fn updateFps(self: *Time) void { self.frame_count += 1; self.fps_frames += 1; self.prev_time = self.curr_time; self.curr_time = sdl.SDL_GetTicks(); const time_since_last = self.curr_time - self.fps_last_update; if (self.curr_time > self.fps_last_update + 1000) { self.frames_per_seconds = self.fps_frames * 1000 / time_since_last; self.fps_last_update = self.curr_time; self.fps_frames = 0; } } pub fn tick(self: *Time) void { self.updateFps(); self.timestep.tick(); } pub fn sleep(self: Time, ms: u32) void { _ = self; sdl.SDL_Delay(ms); } pub fn frames(self: Time) u32 { return self.frame_count; } pub fn ticks(self: Time) u32 { _ = self; return sdl.SDL_GetTicks(); } pub fn seconds(self: Time) f32 { _ = self; return @intToFloat(f32, sdl.SDL_GetTicks()) / 1000; } pub fn fps(self: Time) u32 { return self.frames_per_seconds; } pub fn dt(self: Time) f32 { return self.timestep.fixed_deltatime; } pub fn rawDeltaTime(self: Time) f32 { return self.timestep.raw_deltatime; } pub fn now(self: Time) u64 { _ = self; return sdl.SDL_GetPerformanceCounter(); } /// returns the time in milliseconds since the last call pub fn laptime(self: Time, last_time: *f64) f64 { var tmp = last_time; // now const n = self.now(); const curr_dt: f64 = if (tmp.* != 0) { @intToFloat(f64, ((n - tmp.*) * 1000.0) / @intToFloat(f64, sdl.SDL_GetPerformanceFrequency())); } else 0; return curr_dt; } pub fn toSeconds(self: Time, perf_counter_time: u64) f64 { _ = self; return @intToFloat(f64, perf_counter_time) / @intToFloat(f64, sdl.SDL_GetPerformanceFrequency()); } pub fn toMs(self: Time, perf_counter_time: u64) f64 { _ = self; return @intToFloat(f64, perf_counter_time) * 1000 / @intToFloat(f64, sdl.SDL_GetPerformanceFrequency()); } /// forces a resync of the timing code. Useful after some slower operations such as level loads or window resizes pub fn resync(self: *Time) void { self.timestep.resync = true; self.timestep.prev_frame_time = sdl.SDL_GetPerformanceCounter() + @floatToInt(u64, self.timestep.fixed_deltatime); } // converted from <NAME>'s: https://github.com/TylerGlaiel/FrameTimingControl/blob/master/frame_timer.cpp const Timestep = struct { // compute how many ticks one update should be fixed_deltatime: f32, desired_frametime: i32, raw_deltatime: f32 = 0, // these are to snap deltaTime to vsync values if it's close enough vsync_maxerror: u64, snap_frequencies: [5]i32 = undefined, prev_frame_time: u64, frame_accumulator: i64 = 0, resync: bool = false, // time_averager: utils.Ring_Buffer(u64, samples_for_avg), time_averager: [samples_for_avg]i32 = undefined, pub fn init(update_rate: f64) Timestep { var timestep = Timestep{ .fixed_deltatime = 1 / @floatCast(f32, update_rate), .desired_frametime = @floatToInt(i32, @intToFloat(f64, sdl.SDL_GetPerformanceFrequency()) / update_rate), .vsync_maxerror = sdl.SDL_GetPerformanceFrequency() / 5000, .prev_frame_time = sdl.SDL_GetPerformanceCounter(), }; // TODO: // utils.ring_buffer_fill(&timestep.time_averager, timestep.desired_frametime); timestep.time_averager = [samples_for_avg]i32{ timestep.desired_frametime, timestep.desired_frametime, timestep.desired_frametime, timestep.desired_frametime, timestep.desired_frametime }; const time_60hz = @floatToInt(i32, @intToFloat(f64, sdl.SDL_GetPerformanceFrequency()) / 60); timestep.snap_frequencies[0] = time_60hz; // 60fps timestep.snap_frequencies[1] = time_60hz * 2; // 30fps timestep.snap_frequencies[2] = time_60hz * 3; // 20fps timestep.snap_frequencies[3] = time_60hz * 4; // 15fps timestep.snap_frequencies[4] = @divTrunc(time_60hz + 1, 2); // 120fps return timestep; } pub fn tick(self: *Timestep) void { // frame timer const current_frame_time = sdl.SDL_GetPerformanceCounter(); const delta_u32 = @truncate(u32, current_frame_time - self.prev_frame_time); var delta_time = @intCast(i32, delta_u32); self.prev_frame_time = current_frame_time; // handle unexpected timer anomalies (overflow, extra slow frames, etc) if (delta_time > self.desired_frametime * 8) delta_time = self.desired_frametime; if (delta_time < 0) delta_time = 0; // vsync time snapping for (self.snap_frequencies) |snap| { if (std.math.absCast(delta_time - snap) < self.vsync_maxerror) { delta_time = snap; break; } } // delta time averaging var dt_avg = delta_time; var i: usize = 0; while (i < samples_for_avg - 1) : (i += 1) { self.time_averager[i] = self.time_averager[i + 1]; dt_avg += self.time_averager[i]; } self.time_averager[samples_for_avg - 1] = delta_time; delta_time = @divTrunc(dt_avg, samples_for_avg); self.raw_deltatime = @intToFloat(f32, delta_u32) / @intToFloat(f32, sdl.SDL_GetPerformanceFrequency()); // add to the accumulator self.frame_accumulator += delta_time; // spiral of death protection if (self.frame_accumulator > self.desired_frametime * 8) self.resync = true; // TODO: should we zero out the frame_accumulator here? timer resync if requested so reset all state if (self.resync) { self.frame_accumulator = self.desired_frametime; delta_time = self.desired_frametime; self.resync = false; } } }; };
gamekit/time.zig
const std = @import("std"); const ig = @import("imgui"); const zt = @import("../zt.zig"); const math = zt.math; /// Sets imgui style to be compact, does not affect colors. Recommended to follow this up /// with your own custom colors, or one from this file `styleColor*()` pub fn styleSizeCompact() void { var style = ig.igGetStyle(); // Paddings style.*.WindowPadding = .{ .x = 4, .y = 4 }; style.*.FramePadding = .{ .x = 2, .y = 2 }; style.*.CellPadding = .{ .x = 4, .y = 2 }; style.*.ItemSpacing = .{ .x = 10, .y = 2 }; style.*.ItemInnerSpacing = .{ .x = 2, .y = 2 }; style.*.IndentSpacing = 12; style.*.ScrollbarSize = 4; // Borders style.*.TabBorderSize = 0; style.*.ChildBorderSize = 0; style.*.FrameBorderSize = 0; style.*.PopupBorderSize = 0; style.*.WindowBorderSize = 0; // Rounding style.*.TabRounding = 2; style.*.GrabRounding = 0; style.*.ChildRounding = 0; style.*.FrameRounding = 2; style.*.PopupRounding = 0; style.*.WindowRounding = 2; style.*.ScrollbarRounding = 0; // Align style.*.WindowTitleAlign = .{ .x = 0.5, .y = 0.5 }; style.*.WindowMenuButtonPosition = ig.ImGuiDir_None; } /// Provide 4 colors, contrast, and if it is a light theme, and reroute will automatically /// style each of your imgui colors. If you're changing this and re-building often, prefer to use /// styleColorEditor() to toy with this in real time. pub fn styleColorCustom(background: ig.ImVec4, foreground: ig.ImVec4, highlight: ig.ImVec4, special: ig.ImVec4, contrast: f32, isLightTheme: bool) void { const bg0 = if (isLightTheme) background.brighten(contrast) else background.brighten(-contrast); const bg1 = background; const bg2 = if (isLightTheme) background.brighten(-contrast) else background.brighten(contrast); const fg0 = if (isLightTheme) foreground.brighten(contrast) else foreground.brighten(-contrast); const fg1 = foreground; const fg2 = if (isLightTheme) foreground.brighten(-contrast) else foreground.brighten(contrast); const hl0 = if (isLightTheme) highlight.brighten(contrast) else highlight.brighten(-contrast); const hl1 = highlight; const hl2 = if (isLightTheme) highlight.brighten(-contrast) else highlight.brighten(contrast); const sp0 = if (isLightTheme) special.brighten(contrast) else special.brighten(-contrast); const sp1 = special; const sp2 = if (isLightTheme) special.brighten(-contrast) else special.brighten(contrast); var style = ig.igGetStyle(); style.*.Colors[ig.ImGuiCol_Text] = fg1; style.*.Colors[ig.ImGuiCol_TextDisabled] = fg0; style.*.Colors[ig.ImGuiCol_WindowBg] = bg0; style.*.Colors[ig.ImGuiCol_ChildBg] = bg0; style.*.Colors[ig.ImGuiCol_PopupBg] = bg0; style.*.Colors[ig.ImGuiCol_Border] = bg0.brighten(-0.5); style.*.Colors[ig.ImGuiCol_BorderShadow] = bg0.brighten(-0.5); style.*.Colors[ig.ImGuiCol_FrameBg] = if (isLightTheme) bg1.brighten(-0.33) else bg1.brighten(0.33); style.*.Colors[ig.ImGuiCol_FrameBgHovered] = bg2; style.*.Colors[ig.ImGuiCol_FrameBgActive] = bg2.brighten(0.7); style.*.Colors[ig.ImGuiCol_TitleBg] = hl0; style.*.Colors[ig.ImGuiCol_TitleBgActive] = hl1; style.*.Colors[ig.ImGuiCol_TitleBgCollapsed] = hl0; style.*.Colors[ig.ImGuiCol_MenuBarBg] = bg0.brighten(-0.1); style.*.Colors[ig.ImGuiCol_ScrollbarBg] = bg0; style.*.Colors[ig.ImGuiCol_ScrollbarGrab] = fg0; style.*.Colors[ig.ImGuiCol_ScrollbarGrabHovered] = fg1; style.*.Colors[ig.ImGuiCol_ScrollbarGrabActive] = fg2; style.*.Colors[ig.ImGuiCol_CheckMark] = hl0; style.*.Colors[ig.ImGuiCol_SliderGrab] = hl0; style.*.Colors[ig.ImGuiCol_SliderGrabActive] = hl2; style.*.Colors[ig.ImGuiCol_Button] = hl0; style.*.Colors[ig.ImGuiCol_ButtonHovered] = hl1; style.*.Colors[ig.ImGuiCol_ButtonActive] = hl2; style.*.Colors[ig.ImGuiCol_Header] = bg1; style.*.Colors[ig.ImGuiCol_HeaderHovered] = bg1; style.*.Colors[ig.ImGuiCol_HeaderActive] = bg2; style.*.Colors[ig.ImGuiCol_Separator] = bg2; style.*.Colors[ig.ImGuiCol_SeparatorHovered] = sp0; style.*.Colors[ig.ImGuiCol_SeparatorActive] = sp1; style.*.Colors[ig.ImGuiCol_ResizeGrip] = sp0; style.*.Colors[ig.ImGuiCol_ResizeGripHovered] = sp1; style.*.Colors[ig.ImGuiCol_ResizeGripActive] = sp2; style.*.Colors[ig.ImGuiCol_Tab] = bg2; style.*.Colors[ig.ImGuiCol_TabHovered] = bg2; style.*.Colors[ig.ImGuiCol_TabActive] = bg2.brighten(0.3); style.*.Colors[ig.ImGuiCol_TabUnfocused] = bg1; style.*.Colors[ig.ImGuiCol_TabUnfocusedActive] = bg2; style.*.Colors[ig.ImGuiCol_DockingPreview] = hl1; style.*.Colors[ig.ImGuiCol_DockingEmptyBg] = hl0; style.*.Colors[ig.ImGuiCol_PlotLines] = ig.ImVec4{ .x = 0.61, .y = 0.61, .z = 0.61, .w = 1.00 }; style.*.Colors[ig.ImGuiCol_PlotLinesHovered] = ig.ImVec4{ .x = 1.00, .y = 0.43, .z = 0.35, .w = 1.00 }; style.*.Colors[ig.ImGuiCol_PlotHistogram] = ig.ImVec4{ .x = 0.90, .y = 0.70, .z = 0.00, .w = 1.00 }; style.*.Colors[ig.ImGuiCol_PlotHistogramHovered] = ig.ImVec4{ .x = 1.00, .y = 0.60, .z = 0.00, .w = 1.00 }; style.*.Colors[ig.ImGuiCol_TableHeaderBg] = ig.ImVec4{ .x = 0.19, .y = 0.19, .z = 0.20, .w = 1.00 }; style.*.Colors[ig.ImGuiCol_TableBorderStrong] = ig.ImVec4{ .x = 0.31, .y = 0.31, .z = 0.35, .w = 1.00 }; style.*.Colors[ig.ImGuiCol_TableBorderLight] = ig.ImVec4{ .x = 0.23, .y = 0.23, .z = 0.25, .w = 1.00 }; style.*.Colors[ig.ImGuiCol_TableRowBg] = ig.ImVec4{ .x = 0.00, .y = 0.00, .z = 0.00, .w = 0.00 }; style.*.Colors[ig.ImGuiCol_TableRowBgAlt] = ig.ImVec4{ .x = 1.00, .y = 1.00, .z = 1.00, .w = 0.06 }; style.*.Colors[ig.ImGuiCol_TextSelectedBg] = ig.ImVec4{ .x = 0.26, .y = 0.59, .z = 0.98, .w = 0.35 }; style.*.Colors[ig.ImGuiCol_DragDropTarget] = ig.ImVec4{ .x = 1.00, .y = 1.00, .z = 0.00, .w = 0.90 }; style.*.Colors[ig.ImGuiCol_NavHighlight] = ig.ImVec4{ .x = 0.26, .y = 0.59, .z = 0.98, .w = 1.00 }; style.*.Colors[ig.ImGuiCol_NavWindowingHighlight] = ig.ImVec4{ .x = 1.00, .y = 1.00, .z = 1.00, .w = 0.70 }; style.*.Colors[ig.ImGuiCol_NavWindowingDimBg] = ig.ImVec4{ .x = 0.80, .y = 0.80, .z = 0.80, .w = 0.20 }; style.*.Colors[ig.ImGuiCol_ModalWindowDimBg] = ig.ImVec4{ .x = 0.80, .y = 0.80, .z = 0.80, .w = 0.35 }; } var edit_bg: math.Vec4 = math.Vec4.new(0.1, 0.1, 0.15, 1.0); var edit_fg: math.Vec4 = math.Vec4.new(0.89, 0.89, 0.91, 1.0); var edit_sp: math.Vec4 = math.Vec4.new(0.9, 0.34, 0.2, 1.0); var edit_hl: math.Vec4 = math.Vec4.new(0.9, 0.34, 0.2, 1.0); var edit_diff: f32 = 0.2; var edit_isLight: bool = false; fn stringVec(vec: math.Vec4) []const u8 { return zt.custom_components.fmtTextForImgui("reroute.math.Vec4{{.x={d:.2},.y={d:.2},.z={d:.2},.w={d:.2}}}", .{ vec.x, vec.y, vec.z, vec.w }); } /// A slate/orange dark theme pub fn styleColorOrangeSlate() void { styleColorCustom(math.Vec4{ .x = 0.16, .y = 0.19, .z = 0.22, .w = 1.00 }, math.Vec4{ .x = 0.89, .y = 0.89, .z = 0.89, .w = 1.00 }, math.Vec4{ .x = 0.90, .y = 0.34, .z = 0.20, .w = 1.00 }, math.Vec4{ .x = 0.00, .y = 0.00, .z = 0.00, .w = 0.36 }, 0.30, false); }
src/zt/styler.zig
const aoc = @import("../aoc.zig"); const std = @import("std"); const Allocator = std.mem.Allocator; const VACANT: u8 = 'L'; const OCCUPIED: u8 = '#'; const FLOOR: u8 = '.'; const SeatIterator = struct { allocator: Allocator, seats: []u8, follow_blanks: bool, width: usize, height: usize, row: isize = 0, col: isize = -1, fn init(allocator: Allocator, seats: []const u8, follow_blanks: bool) !SeatIterator { const width = std.mem.indexOf(u8, seats, &[_]u8 {'\n'}).?; const height = seats.len / (width + 1); return SeatIterator { .allocator = allocator, .seats = try allocator.dupe(u8, seats), .follow_blanks = follow_blanks, .width = width, .height = height }; } fn deinit(self: *SeatIterator) void { self.allocator.free(self.seats); } fn next(self: *SeatIterator) ?u8 { while (true) { self.col += 1; if (self.col == self.width) { self.col = 0; self.row += 1; if (self.row == self.height) { return null; } } const seat = self.getSeat(self.row, self.col); if (seat != FLOOR) { return seat; } } } fn getIndex(self: *const SeatIterator, row: isize, col: isize) usize { return @intCast(usize, row) * (self.width+1) + @intCast(usize, col); } fn getSeat(self: *const SeatIterator, row: isize, col: isize) u8 { return self.seats[self.getIndex(row, col)]; } fn isOccupied(self: *const SeatIterator, drow: isize, dcol: isize) u8 { var row = self.row + drow; var col = self.col + dcol; while (row >= 0 and row < self.height and col >= 0 and col < self.width) : ({row += drow; col += dcol;}) { switch (self.getSeat(row, col)) { FLOOR => if (!self.follow_blanks) return 0, VACANT => return 0, OCCUPIED => return 1, else => unreachable } } return 0; } fn getOccupiedNeighbors(self: *const SeatIterator) u8 { return self.isOccupied(-1, -1) + self.isOccupied(-1, 0) + self.isOccupied(-1, 1) + self.isOccupied( 0, -1) + self.isOccupied( 0, 1) + self.isOccupied( 1, -1) + self.isOccupied( 1, 0) + self.isOccupied( 1, 1); } fn setSeat(self: *SeatIterator, row: isize, col: isize, new_seat: u8) void { self.seats[self.getIndex(row, col)] = new_seat; } }; pub fn run(problem: *aoc.Problem) !aoc.Solution { const res1 = try getOccupiedSeats(problem.allocator, problem.input, 4, false); const res2 = try getOccupiedSeats(problem.allocator, problem.input, 5, true); return problem.solution(res1, res2); } fn getOccupiedSeats(allocator: Allocator, seats: []const u8, tolerance: u8, follow_blanks: bool) !usize { var prev_arrangement = try SeatIterator.init(allocator, seats, follow_blanks); while (true) { var next_arrangement = try SeatIterator.init(allocator, seats, follow_blanks); while (prev_arrangement.next()) |prev_seat| { const occupiedNeighbors = prev_arrangement.getOccupiedNeighbors(); var next_seat = if (prev_seat == VACANT and occupiedNeighbors == 0) OCCUPIED else if (prev_seat == OCCUPIED and occupiedNeighbors >= tolerance) VACANT else prev_seat; next_arrangement.setSeat(prev_arrangement.row, prev_arrangement.col, next_seat); } if (std.mem.eql(u8, prev_arrangement.seats, next_arrangement.seats)) { const res = std.mem.count(u8, prev_arrangement.seats, &[_]u8 {OCCUPIED}); prev_arrangement.deinit(); next_arrangement.deinit(); return res; } prev_arrangement.deinit(); prev_arrangement = next_arrangement; } }
src/main/zig/2020/day11.zig
const std = @import("../../std.zig"); const builtin = @import("builtin"); const assert = std.debug.assert; const mem = std.mem; const net = std.net; const os = std.os; const linux = os.linux; const testing = std.testing; const Socket = std.x.os.Socket; const io_uring_params = linux.io_uring_params; const io_uring_sqe = linux.io_uring_sqe; const io_uring_cqe = linux.io_uring_cqe; const IO_Uring = linux.IO_Uring; const IORING_OP = linux.IORING_OP; pub const Handle = packed union { op: IORING_OP, // u8 state_type: enum(u8) { fd, fd_and_buf_group }, state: packed union { fd: os.fd_t, fd_and_buf_group: packed struct { fd: os.fd_t, buf_group: u16, }, // for correct size bytes: [@sizeOf(u64) - 2]u8, }, }; pub const Conn = struct { fd: os.fd_t, rx_buf: std.x.os.Buffer }; pub fn StateType(comptime op: IORING_OP) type { switch (op) { .ACCEPT => { return struct { addr: os.sockaddr = undefined, addr_size: os.socklen_t = @sizeOf(os.sockaddr), }; }, } } pub fn Ring() type { return struct { const Self = @This(); ring: *IO_Uring, // not-owned. pub fn init(ring: *IO_Uring) Self { return .{ .ring = ring, }; } const AcceptState = struct { addr: os.sockaddr = undefined, addr_size: os.socklen_t = @sizeOf(os.sockaddr), }; pub fn prep_accept( self: Self, fd: fd_t, flags: u32, state: ?*StateType(.ACCEPT), ) !*io_uring_sqe { var addr_ptr: ?*os.sockaddr = null; var addr_size: ?*os.socklen_t = null; if (state) |s| { addr_ptr = s.addr; s.*.addr_size = @sizeOf(os.sockaddr); addr_size = s.addr_size; } return self.ring.accept(0, fd, addr_ptr, addr_size, flags); } }; } pub const RingPld = struct { const Self = @This(); ring: *IO_Uring, const AcceptOp = struct { pub const Flags = std.enums.EnumFieldStruct(Socket.InitFlags, bool, false); pub const State = struct { sock: os.socket_t, addr: ?*os.sockaddr = null, addr_size: ?*socklen_t = null, }; pub fn prep(ring: *IO_Uring, sock: fd_t, flags: Flags) !*io_uring_sqe { var raw_flags: u32 = 0; const set = std.EnumSet(Socket.InitFlags).init(flags); if (set.contains(.close_on_exec)) raw_flags |= linux.SOCK.CLOEXEC; if (set.contains(.nonblocking)) raw_flags |= linux.SOCK.NONBLOCK; // linux.io_uring_prep_recv // get_accept_state const sqe = try ring.get_sqe(); linux.io_uring_prep_accept(sqe, fd, null, null, raw_flags); sqe.user_data = @bitCast(u64, Handle{ .op = .ACCEPT, .state_type = .fd, .state = .{ .fd = fd, }, }); return sqe; } }; };
src/io_uring-tcp-hasher/ring.zig
const sboxes = @import("sboxes.zig"); pub const InvalidKeySizeError = error{InvalidKeySizeError}; pub const Blowfish = struct { p: [18]u32 = sboxes.P, s: [4][256]u32 = sboxes.S, const Pair = packed struct { l: u32, r: u32 }; pub fn init(key: []const u8) InvalidKeySizeError!Blowfish { if (key.len < 4 or 56 < key.len) { return error.InvalidKeySizeError; } var this = Blowfish{}; expandKey(&this, key); return this; } pub fn encryptBlock(self: *const Blowfish, block: *[8]u8) void { var bpair = @bitCast(Pair, block.*); var out = self.encrypt(bpair); block.* = @bitCast([8]u8, out); } pub fn decryptBlock(self: *const Blowfish, block: *[8]u8) void { var bpair = @bitCast(Pair, block.*); var out = self.decrypt(bpair); block.* = @bitCast([8]u8, out); } fn expandKey(self: *Blowfish, key: []const u8) void { @setEvalBranchQuota(2 << 13); var key_pos: usize = 0; for (self.p) |*val| { val.* ^= nextU32Wrapped(key, &key_pos); } var lr: Pair = .{ .l = 0, .r = 0 }; var i: u8 = 0; while (i < 9) : (i += 1) { lr = self.encrypt(lr); self.p[2 * i] = lr.l; self.p[2 * i + 1] = lr.r; } for (self.s) |*sub| { var k: usize = 0; while (k < 128) : (k += 1) { lr = self.encrypt(lr); sub.*[2 * k] = lr.l; sub.*[2 * k + 1] = lr.r; } } } fn encrypt(self: *const Blowfish, p: Pair) Pair { var l = p.l; var r = p.r; var i: u8 = 0; while (i < 8) : (i += 1) { l ^= self.p[2 * i]; r ^= self.roundFunction(l); r ^= self.p[2 * i + 1]; l ^= self.roundFunction(r); } l ^= self.p[16]; r ^= self.p[17]; return Pair{ .l = r, .r = l }; } fn decrypt(self: *const Blowfish, p: Pair) Pair { var l = p.l; var r = p.r; var i: u8 = 8; while (i > 0) : (i -= 1) { l ^= self.p[2 * i + 1]; r ^= self.roundFunction(l); r ^= self.p[2 * i]; l ^= self.roundFunction(r); } l ^= self.p[1]; r ^= self.p[0]; return Pair{ .l = r, .r = l }; } fn roundFunction(self: *const Blowfish, x: u32) u32 { var a = self.s[0][(x >> 24)]; var b = self.s[1][(x >> 16) & 0xFF]; var c = self.s[2][(x >> 8) & 0xFF]; var d = self.s[3][x & 0xFF]; return ((a +% b) ^ c) +% d; } }; fn nextU32Wrapped(buf: []const u8, offset: *usize) u32 { var v: u32 = 0; var i: u32 = 0; while (i < 4) : (i += 1) { if (offset.* >= buf.len) { offset.* = 0; } v = @intCast(u32, (v << 8) | buf[offset.*]); offset.* += 1; } return v; }
src/lib.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const _p = std.fs.path; fn PackedSlice (comptime T: type, constant: bool) type { const Type = if (constant) [*]const T else [*] T; return packed struct { ptr: Type, len: usize, const Self = @This(); pub fn init(s: if (constant) []const T else []T) Self { return Self { .ptr = s.ptr, .len = s.len, }; } pub fn slice(self: *Self) if (constant) []const T else []T { return self.ptr[0..self.len]; } pub fn advCast(obj: anytype) Self { return Self { .ptr = @field(obj, "ptr"), .len = @field(obj, "len"), }; } }; } /// This is a travsal structure for your package. /// The structure is used to transfer infomation between different autopkg in different import container. pub const AutoPkgI = packed struct { name: PackedSlice(u8, true) = undefined, path: PackedSlice(u8, true) = undefined, rootSrc: PackedSlice(u8, true) = undefined, // Releative to .path dependencies: PackedSlice(AutoPkg, false) = undefined, includeDirs: PackedSlice([]const u8, true) = undefined, cSrcFiles: PackedSlice([]const u8, true) = undefined, ccflags: PackedSlice([]const u8, true) = undefined, linkSystemLibs: PackedSlice([]const u8, true) = undefined, linkLibNames: PackedSlice([]const u8, true) = undefined, libraryPaths: PackedSlice([]const u8, true) = undefined, alloc: usize = 0, linkLibC: bool = false, doNotTest: bool = false, // these placeholders are workaround to aligned pointer...can be used in future. placeholder0: bool = false, placeholder1: bool = false, placeholder2: bool = false, placeholder3: bool = false, placeholder4: bool = false, placeholder5: bool = false, testSrcs: PackedSlice([]const u8, true) = undefined, const Self = @This(); pub fn fromNormal(val: AutoPkg) Self { return AutoPkgI { .name = PackedSlice(u8, true).init(val.name), .path = PackedSlice(u8, true).init(val.path), .rootSrc = PackedSlice(u8, true).init(val.rootSrc), .dependencies = PackedSlice(AutoPkg, false).init(val.dependencies), .includeDirs = PackedSlice([]const u8, true).init(val.includeDirs), .cSrcFiles = PackedSlice([]const u8, true).init(val.cSrcFiles), .ccflags = PackedSlice([]const u8, true).init(val.ccflags), .linkLibC = val.linkLibC, .alloc = if (val.alloc) |alloc| @ptrToInt(alloc) else 0, .linkSystemLibs = PackedSlice([]const u8, true).init(val.linkSystemLibs), .linkLibNames = PackedSlice([]const u8, true).init(val.linkLibNames), .libraryPaths = PackedSlice([]const u8, true).init(val.libraryPaths), .doNotTest = val.doNotTest, .testSrcs = PackedSlice([]const u8, true).init(val.testSrcs), }; } pub fn toNormal(self: *Self) AutoPkg { return AutoPkg { .name = self.name.slice(), .path = self.path.slice(), .rootSrc = self.rootSrc.slice(), .dependencies = self.dependencies.slice(), .includeDirs = self.includeDirs.slice(), .cSrcFiles = self.cSrcFiles.slice(), .ccflags = self.ccflags.slice(), .linkLibC = self.linkLibC, .alloc = if (self.alloc != 0) @intToPtr(*Allocator, self.alloc) else null, .linkSystemLibs = self.linkSystemLibs.slice(), .linkLibNames = self.linkLibNames.slice(), .libraryPaths = self.libraryPaths.slice(), .doNotTest = self.doNotTest, .testSrcs = self.testSrcs.slice(), }; } fn advCast(obj: anytype) Self { const T = @TypeOf(obj); var newObj = Self {}; const requiredFieldList = .{ "name", "path", "rootSrc", "dependencies", "includeDirs", "cSrcFiles", "ccflags", "linkLibC", "linkSystemLibs", "linkLibNames", "libraryPaths", }; inline for (requiredFieldList) |name| { if (@hasField(T, name)) { @field(newObj, name) = @bitCast(@TypeOf(@field(newObj, name)), @field(obj, name)); } else { @compileError("AutoPkgI field '" ++ name ++ "' not found."); } } newObj.alloc = @field(obj, "alloc"); // Optional fields: if (@hasField(T, "doNotTest")){ @field(newObj, "doNotTest") = @as(bool, @field(obj, "doNotTest")); } else { @field(newObj, "doNotTest") = true; } if (@hasField(T, "testSrcs")) { @field(newObj, "testSrcs") = PackedSlice([]const u8, true).advCast(@field(obj, "testSrcs")); } else { @field(newObj, "testSrcs") = PackedSlice([]const u8, true).init(&.{}); } return newObj; } }; pub fn accept(pkg: anytype) AutoPkg { var casted = AutoPkgI.advCast(pkg); return casted.toNormal(); } var generalAllocator = std.heap.GeneralPurposeAllocator(.{}){}; pub fn genExport(pkg: AutoPkg) AutoPkgI { var newPkg = pkg.dupe(pkg.alloc orelse &generalAllocator.allocator) catch unreachable; return AutoPkgI.fromNormal(newPkg); } /// Declare your package. /// `name` is the name. /// `path` is relative path to this library from parent AutoPkg declaration or the file where call .addBuild(). /// `rootSrc` could be "" to tell zig build system building without zig file. /// `dependencies` is dependencies of this package. pub const AutoPkg = struct { name: []const u8, path: []const u8, rootSrc: []const u8 = &.{}, // Releative to .path dependencies: []AutoPkg = &.{}, includeDirs: []const []const u8 = &.{}, cSrcFiles: []const []const u8 = &.{}, ccflags: []const []const u8 = &.{}, linkSystemLibs: []const []const u8 = &.{}, linkLibNames: []const []const u8 = &.{}, libraryPaths: []const []const u8 = &.{}, linkLibC: bool = false, alloc: ?*Allocator = null, doNotTest: bool = false, testSrcs: []const []const u8 = &.{}, // To developers: Once you add new field here, make sure they will be copied in // `.resolve()` and `.dupe()`. Don't forget deinitlise it in `.deinit()` when needed. // And don't forget add them in `AutoPkgI`. const Self = @This(); /// Add to builder as a static library. pub fn addBuild(self: *const Self, b: *std.build.Builder) *std.build.LibExeObjStep { var me = b.addStaticLibrary(self.name, if (self.rootSrc.len != 0) self.rootSrc else null); self.setupBuild(me, b); return me; } fn setupBuild(self: *const Self, me: *std.build.LibExeObjStep, b: *std.build.Builder) void { var dependedSteps = b.allocator.alloc(*std.build.LibExeObjStep, self.dependencies.len) catch unreachable; defer b.allocator.free(dependedSteps); for (self.dependencies) |d, i| { dependedSteps[i] = d.addBuild(b); if (d.rootSrc.len > 0) { me.addPackagePath(d.name, d.rootSrc); } for (d.includeDirs) |dir| { me.addIncludeDir(dir); } me.linkLibrary(dependedSteps[i]); } for (self.includeDirs) |dir| { me.addIncludeDir(dir); } for (self.cSrcFiles) |file| { me.addCSourceFile(file, self.ccflags); } if (self.linkLibC) { me.linkLibC(); } for (self.linkSystemLibs) |l| { me.linkSystemLibrary(l); } for (self.linkLibNames) |l| { me.linkSystemLibraryName(l); } for (self.libraryPaths) |p| { me.addLibPath(p); } } pub fn dependedBy(self: *const Self, step: *std.build.LibExeObjStep) void { var buildStep = self.addBuild(step.builder); step.linkLibrary(buildStep); } fn setupSingleTest(self: *const Self, src: []const u8, b: *std.build.Builder, mode: std.builtin.Mode, target: *const std.zig.CrossTarget) *std.build.LibExeObjStep { var me = b.addTest(src); self.setupBuild(me, b); me.setBuildMode(mode); me.setTarget(target.*); return me; } pub fn addTest(self: *const Self, b: *std.build.Builder, mode: std.builtin.Mode, target: *const std.zig.CrossTarget) *std.build.Step { var dependedTestSteps = b.allocator.alloc(?*std.build.Step, self.dependencies.len) catch unreachable; defer b.allocator.free(dependedTestSteps); for (self.dependencies) |d, i| { dependedTestSteps[i] = d.addTest(b, mode, target); } if (self.rootSrc.len > 0 and !self.doNotTest) { var me = self.setupSingleTest(self.rootSrc, b, mode, target); for (dependedTestSteps) |step| { if (step) |stepnn| { me.step.dependOn(stepnn); } } for (self.testSrcs) |src| { var step = self.setupSingleTest(src, b, mode, target); me.step.dependOn(&step.step); } return &me.step; } else { var me = b.allocator.create(std.build.Step) catch unreachable; me.* = std.build.Step.initNoOp( if(@hasField(std.build.Step.Id, "Custom")) std.build.Step.Id.Custom else std.build.Step.Id.custom, // changed in 0.9.0+dev.1561 or earlier "autopkgTestPlaceHolder", b.allocator); for (dependedTestSteps) |step| { if (step) |stepnn| { me.dependOn(stepnn); } } if (!self.doNotTest) { for (self.testSrcs) |src| { var step = self.setupSingleTest(src, b, mode, target); me.dependOn(&step.step); } } return me; } } /// Resolve all pathes, this method should not be called twice or more. pub fn resolve(self: *const Self, basePath: []const u8, alloc: *Allocator) Allocator.Error!AutoPkg { const rootPathVec = &.{basePath, self.path}; var rootPath = try _p.join(alloc, rootPathVec); // (Rubicon:) above line was "var rootPath = try _p.join(alloc, &.{basePath, self.path});" // , but I got a segfault in zig 0.8.0-600 (Fedora 34 built) without compiling error. // Add std.debug.printf("{s}/{s}", .{basePath, self.path}); before the line then works fine. // Could it caused by the missing data doesn't be stored in stack and be refered // when directly used as &.{} in function argument? Might be a compiler bug, IDK. // Use the original version (it's more clear) if that were fixed. errdefer alloc.free(rootPath); var newDependencies = try alloc.alloc(AutoPkg, self.dependencies.len); errdefer alloc.free(newDependencies); for (self.dependencies) |d, i| { newDependencies[i] = try d.resolve(rootPath, alloc); errdefer d.deinit(); } var newIncludeDirs = try alloc.alloc([]const u8, self.includeDirs.len); errdefer alloc.free(newIncludeDirs); for (self.includeDirs) |dir, i| { newIncludeDirs[i] = try _p.join(alloc, &.{rootPath, dir}); errdefer alloc.free(newIncludeDirs[i]); } var newCSrcFiles = try alloc.alloc([]const u8, self.cSrcFiles.len); errdefer alloc.free(newCSrcFiles); for (self.cSrcFiles) |f, i| { newCSrcFiles[i] = try _p.join(alloc, &.{rootPath, f}); errdefer alloc.free(newCSrcFiles[i]); } var newRootSrc = if (self.rootSrc.len != 0) try _p.join(alloc, &.{rootPath, self.rootSrc}) else try alloc.dupe(u8, self.rootSrc); errdefer alloc.free(newRootSrc); var newSystemLibs = try alloc.alloc([]const u8, self.linkSystemLibs.len); errdefer alloc.free(newSystemLibs); for (self.linkSystemLibs) |l, i| { newSystemLibs[i] = try alloc.dupe(u8, l); errdefer alloc.free(newSystemLibs[i]); } var newLibNames = try alloc.alloc([]const u8, self.linkLibNames.len); errdefer alloc.free(newLibNames); for (self.linkLibNames) |l, i| { newLibNames[i] = try alloc.dupe(u8, l); errdefer alloc.free(newLibNames[i]); } var newLibPaths = try alloc.alloc([]const u8, self.libraryPaths.len); errdefer alloc.free(newLibPaths); for (self.libraryPaths) |l, i| { newLibPaths[i] = try _p.join(alloc, &.{rootPath, l}); errdefer alloc.free(newLibPaths[i]); } var newTestSrcs = try alloc.alloc([]const u8, self.testSrcs.len); errdefer alloc.free(newTestSrcs); for (self.testSrcs) |src, i| { newTestSrcs[i] = try _p.join(alloc, &.{rootPath, src}); errdefer alloc.free(newTestSrcs[i]); } return AutoPkg { .name = try alloc.dupe(u8, self.name), .path = rootPath, .rootSrc = newRootSrc, .dependencies = newDependencies, .includeDirs = newIncludeDirs, .cSrcFiles = newCSrcFiles, .ccflags = self.ccflags, .linkLibC = self.linkLibC, .alloc = alloc, .linkSystemLibs = newSystemLibs, .linkLibNames = newLibNames, .libraryPaths = newLibPaths, .doNotTest = self.doNotTest, .testSrcs = newTestSrcs, }; } pub fn dupe(self: *const Self, alloc: *Allocator) Allocator.Error!Self { var result = Self { .name = &.{}, .path = &.{}, }; inline for (.{"name", "path", "rootSrc", "dependencies"}) |name| { @field(result, name) = try alloc.dupe(@typeInfo(@TypeOf(@field(self, name))).Pointer.child, @field(self, name)); errdefer alloc.free(@field(result, name)); } inline for (.{"includeDirs", "cSrcFiles", "ccflags", "linkSystemLibs", "linkLibNames", "libraryPaths", "testSrcs"}) |name| { @field(result, name) = try alloc.dupe(@typeInfo(@TypeOf(@field(self, name))).Pointer.child, @field(self, name)); errdefer alloc.free(@field(result, name)); } inline for (.{"linkLibC", "doNotTest"}) |name| { @field(result, name) = @field(self, name); } result.alloc = alloc; return result; } pub fn deinit(self: *Self) void { for (self.dependencies) |*d| { d.deinit(); } if (self.alloc) |alloc| { alloc.free(self.name); alloc.free(self.path); alloc.free(self.rootSrc); alloc.free(self.dependencies); inline for (.{"includeDirs", "cSrcFiles", "linkSystemLibs", "linkLibNames", "libraryPaths", "testSrcs"}) |name| { alloc.free(@field(self, name)); } self.alloc = null; } } };
autopkg.zig
usingnamespace @import("zig-pdcurses.zig"); pub const code_yes = c.KEY_CODE_YES; pub const key_break = c.KEY_BREAK; pub const down = c.KEY_DOWN; pub const up = c.KEY_UP; pub const left = c.KEY_LEFT; pub const right = c.KEY_RIGHT; pub const home = c.KEY_HOME; pub const backspace = c.KEY_BACKSPACE; pub const f0 = c.KEY_F0; pub const dl = c.KEY_DL; pub const il = c.KEY_IL; pub const dc = c.KEY_DC; pub const ic = c.KEY_IC; pub const eic = c.KEY_EIC; pub const clear = c.KEY_CLEAR; pub const eos = c.KEY_EOS; pub const eol = c.KEY_EOL; pub const sf = c.KEY_SF; pub const sr = c.KEY_SR; pub const npage = c.KEY_NPAGE; pub const ppage = c.KEY_PPAGE; pub const stab = c.KEY_STAB; pub const ctab = c.KEY_CTAB; pub const catab = c.KEY_CATAB; pub const enter = c.KEY_ENTER; pub const sreset = c.KEY_SRESET; pub const reset = c.KEY_RESET; pub const print = c.KEY_PRINT; pub const ll = c.KEY_LL; pub const abort = c.KEY_ABORT; pub const shelp = c.KEY_SHELP; pub const lhelp = c.KEY_LHELP; pub const btab = c.KEY_BTAB; pub const beg = c.KEY_BEG; pub const cancel = c.KEY_CANCEL; pub const close = c.KEY_CLOSE; pub const command = c.KEY_COMMAND; pub const copy = c.KEY_COPY; pub const create = c.KEY_CREATE; pub const end = c.KEY_END; pub const exit = c.KEY_EXIT; pub const find = c.KEY_FIND; pub const help = c.KEY_HELP; pub const mark = c.KEY_MARK; pub const message = c.KEY_MESSAGE; pub const move = c.KEY_MOVE; pub const next = c.KEY_NEXT; pub const open = c.KEY_OPEN; pub const options = c.KEY_OPTIONS; pub const previous = c.KEY_PREVIOUS; pub const redo = c.KEY_REDO; pub const reference = c.KEY_REFERENCE; pub const refresh = c.KEY_REFRESH; pub const replace = c.KEY_REPLACE; pub const restart = c.KEY_RESTART; pub const key_resume = c.KEY_RESUME; pub const save = c.KEY_SAVE; pub const sbeg = c.KEY_SBEG; pub const scancel = c.KEY_SCANCEL; pub const scommand = c.KEY_SCOMMAND; pub const scopy = c.KEY_SCOPY; pub const screate = c.KEY_SCREATE; pub const sdc = c.KEY_SDC; pub const sdl = c.KEY_SDL; pub const select = c.KEY_SELECT; pub const send = c.KEY_SEND; pub const seol = c.KEY_SEOL; pub const sexit = c.KEY_SEXIT; pub const sfind = c.KEY_SFIND; pub const shome = c.KEY_SHOME; pub const sic = c.KEY_SIC; pub const sleft = c.KEY_SLEFT; pub const smessage = c.KEY_SMESSAGE; pub const smove = c.KEY_SMOVE; pub const snext = c.KEY_SNEXT; pub const soptions = c.KEY_SOPTIONS; pub const sprevious = c.KEY_SPREVIOUS; pub const sprint = c.KEY_SPRINT; pub const sredo = c.KEY_SREDO; pub const sreplace = c.KEY_SREPLACE; pub const sright = c.KEY_SRIGHT; pub const srsume = c.KEY_SRSUME; pub const ssave = c.KEY_SSAVE; pub const ssuspend = c.KEY_SSUSPEND; pub const sundo = c.KEY_SUNDO; pub const key_suspend = c.KEY_SUSPEND; pub const undo = c.KEY_UNDO; pub const alt_0 = c.ALT_0; pub const alt_1 = c.ALT_1; pub const alt_2 = c.ALT_2; pub const alt_3 = c.ALT_3; pub const alt_4 = c.ALT_4; pub const alt_5 = c.ALT_5; pub const alt_6 = c.ALT_6; pub const alt_7 = c.ALT_7; pub const alt_8 = c.ALT_8; pub const alt_9 = c.ALT_9; pub const alt_a = c.ALT_A; pub const alt_b = c.ALT_B; pub const alt_c = c.ALT_C; pub const alt_d = c.ALT_D; pub const alt_e = c.ALT_E; pub const alt_f = c.ALT_F; pub const alt_g = c.ALT_G; pub const alt_h = c.ALT_H; pub const alt_i = c.ALT_I; pub const alt_j = c.ALT_J; pub const alt_k = c.ALT_K; pub const alt_l = c.ALT_L; pub const alt_m = c.ALT_M; pub const alt_n = c.ALT_N; pub const alt_o = c.ALT_O; pub const alt_p = c.ALT_P; pub const alt_q = c.ALT_Q; pub const alt_r = c.ALT_R; pub const alt_s = c.ALT_S; pub const alt_t = c.ALT_T; pub const alt_u = c.ALT_U; pub const alt_v = c.ALT_V; pub const alt_w = c.ALT_W; pub const alt_x = c.ALT_X; pub const alt_y = c.ALT_Y; pub const alt_z = c.ALT_Z; pub const ctl_left = c.CTL_LEFT; pub const ctl_right = c.CTL_RIGHT; pub const ctl_pgup = c.CTL_PGUP; pub const ctl_pgdn = c.CTL_PGDN; pub const ctl_home = c.CTL_HOME; pub const ctl_end = c.CTL_END; pub const a1 = c.KEY_A1; pub const a2 = c.KEY_A2; pub const a3 = c.KEY_A3; pub const b1 = c.KEY_B1; pub const b2 = c.KEY_B2; pub const b3 = c.KEY_B3; pub const c1 = c.KEY_C1; pub const c2 = c.KEY_C2; pub const c3 = c.KEY_C3; pub const padslash = c.PADSLASH; pub const padenter = c.PADENTER; pub const ctl_padenter = c.CTL_PADENTER; pub const alt_padenter = c.ALT_PADENTER; pub const padstop = c.PADSTOP; pub const padstar = c.PADSTAR; pub const padminus = c.PADMINUS; pub const padplus = c.PADPLUS; pub const ctl_padstop = c.CTL_PADSTOP; pub const ctl_padcenter = c.CTL_PADCENTER; pub const ctl_padplus = c.CTL_PADPLUS; pub const ctl_padminus = c.CTL_PADMINUS; pub const ctl_padslash = c.CTL_PADSLASH; pub const ctl_padstar = c.CTL_PADSTAR; pub const alt_padplus = c.ALT_PADPLUS; pub const alt_padminus = c.ALT_PADMINUS; pub const alt_padslash = c.ALT_PADSLASH; pub const alt_padstar = c.ALT_PADSTAR; pub const alt_padstop = c.ALT_PADSTOP; pub const ctl_ins = c.CTL_INS; pub const alt_del = c.ALT_DEL; pub const alt_ins = c.ALT_INS; pub const ctl_up = c.CTL_UP; pub const ctl_down = c.CTL_DOWN; pub const ctl_dn = c.CTL_DN; pub const ctl_tab = c.CTL_TAB; pub const alt_tab = c.ALT_TAB; pub const alt_minus = c.ALT_MINUS; pub const alt_equal = c.ALT_EQUAL; pub const alt_home = c.ALT_HOME; pub const alt_pgup = c.ALT_PGUP; pub const alt_pgdn = c.ALT_PGDN; pub const alt_end = c.ALT_END; pub const alt_up = c.ALT_UP; pub const alt_down = c.ALT_DOWN; pub const alt_right = c.ALT_RIGHT; pub const alt_left = c.ALT_LEFT; pub const alt_enter = c.ALT_ENTER; pub const alt_esc = c.ALT_ESC; pub const alt_bquote = c.ALT_BQUOTE; pub const alt_lbracket = c.ALT_LBRACKET; pub const alt_rbracket = c.ALT_RBRACKET; pub const alt_semicolon = c.ALT_SEMICOLON; pub const alt_fquote = c.ALT_FQUOTE; pub const alt_comma = c.ALT_COMMA; pub const alt_stop = c.ALT_STOP; pub const alt_fslash = c.ALT_FSLASH; pub const alt_bksp = c.ALT_BKSP; pub const ctl_bksp = c.CTL_BKSP; pub const pad0 = c.PAD0; pub const ctl_pad0 = c.CTL_PAD0; pub const ctl_pad1 = c.CTL_PAD1; pub const ctl_pad2 = c.CTL_PAD2; pub const ctl_pad3 = c.CTL_PAD3; pub const ctl_pad4 = c.CTL_PAD4; pub const ctl_pad5 = c.CTL_PAD5; pub const ctl_pad6 = c.CTL_PAD6; pub const ctl_pad7 = c.CTL_PAD7; pub const ctl_pad8 = c.CTL_PAD8; pub const ctl_pad9 = c.CTL_PAD9; pub const alt_pad0 = c.ALT_PAD0; pub const alt_pad1 = c.ALT_PAD1; pub const alt_pad2 = c.ALT_PAD2; pub const alt_pad3 = c.ALT_PAD3; pub const alt_pad4 = c.ALT_PAD4; pub const alt_pad5 = c.ALT_PAD5; pub const alt_pad6 = c.ALT_PAD6; pub const alt_pad7 = c.ALT_PAD7; pub const alt_pad8 = c.ALT_PAD8; pub const alt_pad9 = c.ALT_PAD9; pub const ctl_del = c.CTL_DEL; pub const alt_bslash = c.ALT_BSLASH; pub const ctl_enter = c.CTL_ENTER; pub const shf_padenter = c.SHF_PADENTER; pub const shf_padslash = c.SHF_PADSLASH; pub const shf_padstar = c.SHF_PADSTAR; pub const shf_padplus = c.SHF_PADPLUS; pub const shf_padminus = c.SHF_PADMINUS; pub const shf_up = c.SHF_UP; pub const shf_down = c.SHF_DOWN; pub const shf_ic = c.SHF_IC; pub const shf_dc = c.SHF_DC; pub const mouse = c.KEY_MOUSE; pub const shift_l = c.KEY_SHIFT_L; pub const shift_r = c.KEY_SHIFT_R; pub const control_l = c.KEY_CONTROL_L; pub const control_r = c.KEY_CONTROL_R; pub const key_alt_l = c.KEY_ALT_L; pub const key_alt_r = c.KEY_ALT_R; pub const resize = c.KEY_RESIZE; pub const sup = c.KEY_SUP; pub const sdown = c.KEY_SDOWN; pub const apps = c.KEY_APPS; pub const pause = c.KEY_PAUSE; pub const printscreen = c.KEY_PRINTSCREEN; pub const scrolllock = c.KEY_SCROLLLOCK; pub const browser_back = c.KEY_BROWSER_BACK; pub const browser_fwd = c.KEY_BROWSER_FWD; pub const browser_ref = c.KEY_BROWSER_REF; pub const browser_stop = c.KEY_BROWSER_STOP; pub const search = c.KEY_SEARCH; pub const favorites = c.KEY_FAVORITES; pub const browser_home = c.KEY_BROWSER_HOME; pub const volume_mute = c.KEY_VOLUME_MUTE; pub const volume_down = c.KEY_VOLUME_DOWN; pub const volume_up = c.KEY_VOLUME_UP; pub const next_track = c.KEY_NEXT_TRACK; pub const prev_track = c.KEY_PREV_TRACK; pub const media_stop = c.KEY_MEDIA_STOP; pub const play_pause = c.KEY_PLAY_PAUSE; pub const launch_mail = c.KEY_LAUNCH_MAIL; pub const media_select = c.KEY_MEDIA_SELECT; pub const launch_app1 = c.KEY_LAUNCH_APP1; pub const launch_app2 = c.KEY_LAUNCH_APP2; pub const launch_app3 = c.KEY_LAUNCH_APP3; pub const launch_app4 = c.KEY_LAUNCH_APP4; pub const launch_app5 = c.KEY_LAUNCH_APP5; pub const launch_app6 = c.KEY_LAUNCH_APP6; pub const launch_app7 = c.KEY_LAUNCH_APP7; pub const launch_app8 = c.KEY_LAUNCH_APP8; pub const launch_app9 = c.KEY_LAUNCH_APP9; pub const launch_app10 = c.KEY_LAUNCH_APP10; pub const min = c.KEY_MIN; pub const max = c.KEY_MAX; pub inline fn f(num:i32) i32 { return c.F(num); }
src/keys.zig
const std = @import("std"); const log = std.log; const tokenizer = @import("tokenizer.zig"); const TokenKind = tokenizer.TokenKind; const Language = @import("code_chunks.zig").Language; const builtin = @import("builtin.zig"); const DFS = @import("utils.zig").DepthFirstIterator; const expect = std.testing.expect; // meta.TagType gets union's enum tag type (by using @typeInfo(T).tag_type) pub const NodeKind = std.meta.TagType(Node.NodeData); pub const Node = struct { parent: ?*Node, next: ?*Node, first_child: ?*Node, // TODO @Size @Speed remove last_child and replace with method? last_child: ?*Node, // since a tagged union coerces to their tag type we don't need a // separate kind field data: NodeData, pub const LinkData = struct { label: ?[]const u8, url: ?[]const u8, title: ?[]const u8}; pub const EmphData = struct { opener_token_kind: TokenKind }; pub const ListData = struct { blank_lines: u32, start_num: u16 = 1, ol_type: u8 }; pub const CodeData = struct { language: Language, code: []const u8, run: bool, stdout: ?[]const u8 = null, stderr: ?[]const u8 = null }; /// indent: column that list item startes need to have in order to continue the list /// 1. test /// - sublist /// ^ this is the indent of the sublist // we also need to store the list item starter offset (due to ordered list item // starters being variable) and so users can align the text abritrarily pub const ListItemData = struct { list_item_starter: TokenKind, indent: u16, // offset in bytes from immediate list item starter // to first non-whitespace byte ol_type: u8, li_starter_offset: u8 }; pub const CitationData = struct { id: []const u8 }; // tagged union pub const NodeData = union(enum) { // special Undefined, Document, Import, BuiltinCall: struct { builtin_type: builtin.BuiltinCall, result: ?*builtin.BuiltinResult = null }, PostionalArg, KeywordArg: struct { keyword: []const u8 }, // block // leaf blocks ThematicBreak, Heading: struct { level: u8 }, FencedCode: CodeData, MathMultiline: struct { text: []const u8 }, LinkRef: LinkData, // inline in CommonMark - leaf block here // TODO just store the pointer here and the ImageData just in the same arena // oterwise the union is getting way too big Image: struct { alt: []const u8, label: ?[]const u8, url: ?[]const u8, title: ?[]const u8 }, // TODO add id to generate link to bibentry Citation: CitationData, Bibliography, BibEntry: CitationData, Paragraph, BlankLine, // ? // container blocks BlockQuote, UnorderedList: ListData, UnorderedListItem: ListItemData, OrderedList: ListData, OrderedListItem: ListItemData, // ? Table, TableRow, // inline CodeSpan: CodeData, MathInline: struct { text: []const u8 }, Emphasis: EmphData, StrongEmphasis: EmphData, Strikethrough, Superscript, Subscript, SmallCaps, // TODO add syntax? Underline, Link: LinkData, // add SoftLineBreak ? are basically ignored and are represented by single \n SoftLineBreak, HardLineBreak, Text: struct { text: []const u8 }, pub fn print(self: *@This()) void { const uT = @typeInfo(@This()).Union; inline for (uT.fields) |union_field, enum_i| { // check for active tag if (enum_i == @enumToInt(self.*)) { std.debug.print("{s}{{ ", .{ @tagName(self.*) }); // the union_field is only the active union variant like BuiltinCall or CodeSpan etc. // iter over actual payload type fields (assuming it's a struct) switch (@typeInfo(union_field.field_type)) { .Struct => |fT| { inline for (fT.fields) |ft_field, ft_enum| { std.debug.print(".{s} = ", .{ ft_field.name }); // print as str if type is []const u8 // necessary due to zig's recent change to just print []u8 as actual u8 // unless explicitly specified as {s}, which means every []u8 has // to specified manually with {s} which is a pain in nested structs etc. if (ft_field.field_type == []const u8) { std.debug.print("'{s}', ", .{ @field(@field(self, union_field.name), ft_field.name) }); } else { std.debug.print("{any}, ", .{ @field(@field(self, union_field.name), ft_field.name) }); } } }, .Void => {}, else => {}, } } } std.debug.print("}}\n", .{}); } }; pub inline fn create(allocator: *std.mem.Allocator) !*Node { var new_node = try allocator.create(Node); new_node.* = .{ .parent = null, .next = null, .first_child = null, .last_child = null, .data = .Undefined, }; return new_node; } pub fn append_child(self: *Node, child: *Node) void { std.debug.assert(child.parent == null); if (self.first_child != null) { // .? equals "orelse unreachable" so we crash when last_child is null self.last_child.?.next = child; self.last_child = child; } else { self.first_child = child; self.last_child = child; } child.parent = self; } /// allocator has to be the allocator that node and it's direct children were /// allocated with /// Node's child must not have children of their own, otherwise there will be a leak pub fn delete_direct_children(self: *Node, allocator: *std.mem.Allocator) void { var mb_next = self.first_child; while (mb_next) |next| { mb_next = next.next; std.debug.assert(next.first_child == null); allocator.destroy(next); } self.first_child = null; self.last_child = null; } /// allocator has to be the one that node and it's direct children were allocated with pub fn delete_children(self: *Node, allocator: *std.mem.Allocator) void { var dfs = DFS(Node, true).init(self); while (dfs.next()) |node_info| { if (!node_info.is_end) continue; log.debug("Deleting end {}\n", .{ node_info.data.data }); allocator.destroy(node_info.data); } // !IMPORTANT! mark self as having no children self.first_child = null; self.last_child = null; } /// detaches itself from parent pub fn detach(self: *Node) void { if (self.parent) |parent| { parent.remove_child(self); } } /// assumes that x is a child of self /// does not deallocate x pub fn remove_child(self: *Node, x: *Node) void { if (self.first_child == x) { if (self.last_child == x) { // x is the only child self.first_child = null; self.last_child = null; } else { self.first_child = x.next; } x.parent = null; x.next = null; return; } // find node which is followed by x var prev_child = self.first_child.?; while (prev_child.next != x) { prev_child = prev_child.next.?; } if (self.last_child == x) { self.last_child = prev_child; prev_child.next = null; } else { prev_child.next = x.next; } x.next = null; x.parent = null; } pub fn print_direct_children(self: *Node) void { var mb_next = self.first_child; while (mb_next) |next| { std.debug.print("Child: {}\n", .{ next.data }); mb_next = next.next; } } pub fn print_tree(self: *Node) void { var level: i16 = 0; var mb_current: ?*Node = self; while (mb_current) |current| { // print node var indent_count: u8 = 0; while (indent_count < level) : (indent_count += 1) { if (level - 1 == indent_count) { std.debug.print("|-", .{}); } else { std.debug.print(" ", .{}); } } current.data.print(); const result = current.dfs_next_lvl(); mb_current = result.next; level += result.lvl_delta; } } /// contrary to utils.DepthFirstIterator this iterator does not visit /// nodes twice (start/end) pub fn dfs_next(self: *@This()) ?*Node { var nxt: ?*@This() = null; if (self.first_child) |child| { nxt = child; } else if (self.next) |sibling| { nxt = sibling; } else if (self.parent) |parent| { nxt = parent.next; } return nxt; } pub fn dfs_next_lvl(self: *@This()) struct { next: ?*Node, lvl_delta: i8 } { var nxt: ?*@This() = null; var delta: i8 = 0; if (self.first_child) |child| { nxt = child; delta = 1; } else if (self.next) |sibling| { nxt = sibling; } else if (self.parent) |parent| { nxt = parent.next; delta = -1; } return .{ .next = nxt, .lvl_delta = delta }; } }; test "dfs next" { const alloc = std.testing.allocator; var parent = try Node.create(alloc); defer alloc.destroy(parent); var child1 = try Node.create(alloc); defer alloc.destroy(child1); parent.append_child(child1); var child2 = try Node.create(alloc); defer alloc.destroy(child2); parent.append_child(child2); var child1child1 = try Node.create(alloc); defer alloc.destroy(child1child1); child1.append_child(child1child1); var child1child2 = try Node.create(alloc); defer alloc.destroy(child1child2); child1.append_child(child1child2); var child1child1child1 = try Node.create(alloc); defer alloc.destroy(child1child1child1); child1child1.append_child(child1child1child1); try expect(parent.dfs_next().? == child1); try expect(child1.dfs_next().? == child1child1); try expect(child1child1.dfs_next().? == child1child1child1); try expect(child1child1child1.dfs_next().? == child1child2); try expect(child1child2.dfs_next().? == child2); const order = [6]*Node{ parent, child1, child1child1, child1child1child1, child1child2, child2 }; var mb_current: ?*Node = parent; var i: usize = 0; while (mb_current) |current| : ({ i += 1; mb_current = current.dfs_next(); }) { try expect(current == order[i]); } // with level try expect(parent.dfs_next_lvl().next.? == child1); try expect(parent.dfs_next_lvl().lvl_delta == 1); try expect(child1.dfs_next_lvl().next.? == child1child1); try expect(child1.dfs_next_lvl().lvl_delta == 1); try expect(child1child1.dfs_next_lvl().next.? == child1child1child1); try expect(child1child1.dfs_next_lvl().lvl_delta == 1); try expect(child1child1child1.dfs_next_lvl().next.? == child1child2); try expect(child1child1child1.dfs_next_lvl().lvl_delta == -1); try expect(child1child2.dfs_next_lvl().next.? == child2); try expect(child1child2.dfs_next_lvl().lvl_delta == -1); } test "node remove_child first_child of 3" { const alloc = std.testing.allocator; var parent = try Node.create(alloc); defer alloc.destroy(parent); var child1 = try Node.create(alloc); defer alloc.destroy(child1); var child2 = try Node.create(alloc); defer alloc.destroy(child2); var child3 = try Node.create(alloc); defer alloc.destroy(child3); parent.append_child(child1); parent.append_child(child2); parent.append_child(child3); parent.remove_child(child1); try expect(parent.first_child == child2); try expect(parent.last_child == child3); try expect(child2.next == child3); try expect(child1.next == null); try expect(child1.parent == null); try expect(child3.next == null); } test "node remove_child middle_child of 3" { const alloc = std.testing.allocator; var parent = try Node.create(alloc); defer alloc.destroy(parent); var child1 = try Node.create(alloc); defer alloc.destroy(child1); var child2 = try Node.create(alloc); defer alloc.destroy(child2); var child3 = try Node.create(alloc); defer alloc.destroy(child3); parent.append_child(child1); parent.append_child(child2); parent.append_child(child3); parent.remove_child(child2); try expect(parent.first_child == child1); try expect(parent.last_child == child3); try expect(child2.next == null); try expect(child2.parent == null); try expect(child1.next == child3); try expect(child3.next == null); } test "node remove_child last_child of 3" { const alloc = std.testing.allocator; var parent = try Node.create(alloc); defer alloc.destroy(parent); var child1 = try Node.create(alloc); defer alloc.destroy(child1); var child2 = try Node.create(alloc); defer alloc.destroy(child2); var child3 = try Node.create(alloc); defer alloc.destroy(child3); parent.append_child(child1); parent.append_child(child2); parent.append_child(child3); parent.remove_child(child3); try expect(parent.first_child == child1); try expect(parent.last_child == child2); try expect(child1.next == child2); try expect(child2.next == null); try expect(child3.next == null); try expect(child3.parent == null); } test "node remove_child only_child" { const alloc = std.testing.allocator; var parent = try Node.create(alloc); defer alloc.destroy(parent); var child1 = try Node.create(alloc); defer alloc.destroy(child1); parent.append_child(child1); parent.remove_child(child1); try expect(parent.first_child == null); try expect(parent.last_child == null); try expect(child1.next == null); try expect(child1.parent == null); } pub inline fn is_container_block(self: NodeKind) bool { return switch (self) { .Document, .BlockQuote, .UnorderedList, .UnorderedListItem, .OrderedList, .OrderedListItem => true, else => false, }; } pub inline fn is_leaf_block(self: NodeKind) bool { return switch (self) { .ThematicBreak, .Heading, .FencedCode, .LinkRef, .Paragraph, .BlankLine, .Image, .MathMultiline => true, else => false, }; } pub inline fn is_inline(self: NodeKind) bool { return switch (self) { .CodeSpan, .Emphasis, .StrongEmphasis, .Strikethrough, .Link, .HardLineBreak, .SoftLineBreak, .Text, .Superscript, .Subscript, .MathInline => true, else => false, }; } pub inline fn can_hold(self: NodeKind, other: NodeKind) bool { if (is_container_block(self)) { return true; } else if (other == .PostionalArg or other == .KeywordArg) { if (self == .BuiltinCall) { return true; } else { return false; } } else { return if (is_inline(other)) true else false; } } pub inline fn children_allowed(self: NodeKind) bool { return switch (self) { .Undefined, .CodeSpan, .ThematicBreak, .LinkRef, .BlankLine, .HardLineBreak, .SoftLineBreak, .Text, .MathInline => false, else => true, }; } pub inline fn is_block(self: NodeKind) bool { return is_container_block(self) or is_leaf_block(self); }
src/ast.zig
const std = @import("std"); const tools = @import("tools"); const with_trace = false; const assert = std.debug.assert; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { const Layer = [25 * 6]u8; var all_layers: [500]Layer = undefined; const layers = blk: { var ipix: u32 = 0; var ilayer: u32 = 0; for (input) |c| { if (c < '0' or c > '9') continue; all_layers[ilayer][ipix] = c; ipix += 1; if (ipix >= @typeInfo(Layer).Array.len) { ipix = 0; ilayer += 1; } } assert(ipix == 0); break :blk all_layers[0..ilayer]; }; var best_zeroes: u32 = 99999; var best_result: u32 = undefined; for (layers) |layer| { var digits = [1]u32{0} ** 10; for (layer) |pix| { digits[pix - '0'] += 1; } if (digits[0] < best_zeroes) { best_zeroes = digits[0]; best_result = digits[1] * digits[2]; } } var composite: Layer = undefined; for (composite) |*pix, i| { for (layers) |_, l| { switch (layers[layers.len - 1 - l][i]) { '0' => pix.* = ' ', '1' => pix.* = '*', '2' => continue, else => unreachable, } } } trace("layers = {} , minzero = {}, res = {}\n", .{ layers.len, best_zeroes, best_result }); var buf: [4096]u8 = undefined; var len: usize = 0; var row: u32 = 0; while (row < 6) : (row += 1) { tools.fmt_bufAppend(&buf, &len, "{s}\n", .{composite[row * 25 .. (row + 1) * 25]}); } return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{best_result}), try std.fmt.allocPrint(allocator, "{s}", .{buf[0..len]}), }; } pub const main = tools.defaultMain("2019/day08.txt", run);
2019/day08.zig
const builtin = @import("builtin"); const utils = @import("utils"); const platform = @import("platform.zig"); const vbe = @import("vbe.zig"); const kernel = @import("root").kernel; const print = kernel.print; const Range = kernel.memory.Range; export var multiboot_info: []u32 = undefined; const Error = error { NullMultibootInfoPointer, TagNotFound, }; const TagKind = enum (u32) { End = 0, CmdLine = 1, BootLoaderName = 2, Module = 3, BasicMemInfo = 4, BootDev = 5, Mmap = 6, Vbe = 7, Framebuffer = 8, ElfSections = 9, Apm = 10, Efi32 = 11, Efi64 = 12, Smbios = 13, AcpiOld = 14, AcpiNew = 15, Network = 16, EfiMmap = 17, EfiBs = 18, Efi32Ih = 19, Efi64Ih = 20, LoadBaseAddr = 21, pub fn from_u32(value: u32) ?TagKind { return utils.int_to_enum(TagKind, value); } pub fn to_string(self: TagKind) []const u8 { return switch (self) { .End => "End", .CmdLine => "Boot Command", .BootLoaderName => "Boot Loader Name", .Module => "Modules", .BasicMemInfo => "Basic Memory Info", .BootDev => "BIOS Boot Device", .Mmap => "Memory Map", .Vbe => "VBE Info", .Framebuffer => "Framebuffer Info", .ElfSections => "ELF Symbols", .Apm => "APM Table", .Efi32 => "EFI 32-bit Table Pointer", .Efi64 => "EFI 64-bit Table Pointer", .Smbios => "SMBIOS Tables", .AcpiOld => "ACPI v1 RSDP", .AcpiNew => "ACPI v2 RSDP", .Network => "Networking Info", .EfiMmap => "EFI Memory Map", .EfiBs => "EFI Boot Services Not Terminated", .Efi32Ih => "EFI 32-bit Image Handle Pointer", .Efi64Ih => "EFI 64-bit Image Handle Pointer", .LoadBaseAddr => "Image Load Base Physical Address", }; } }; /// Process part of the Multiboot information given by `find`. If `find` wasn't /// found, returns `Error.TagNotFound`. If `find` is `End`, then just list /// what's in the Multiboot header. pub fn find_tag(find: TagKind) Error!Range { var i = @intCast(usize, @ptrToInt(multiboot_info.ptr)); if (i == 0) { return Error.NullMultibootInfoPointer; } const list = find == .End; if (list) { print.debug_string(" - Multiboot Tags Available:\n"); } var running = true; var tag_count: usize = 0; if (list) { const size = @intToPtr(*u32, i).*; print.debug_format( \\ - Total Size: {} B ({} KiB) \\ - Tags: \\ , .{size, size >> 10}); } i += 8; // Move to first tag while (running) { const kind_raw = @intToPtr(*u32, i).*; const size = @intToPtr(*u32, i + 4).*; const kind_maybe = TagKind.from_u32(kind_raw); if (list) { print.debug_format(" - {}\n", .{ if (kind_maybe) |kind| kind.to_string() else "Unkown"}); } if (kind_maybe) |kind| { if (kind == .End) { running = false; } if (find == kind) { return Range{.start = i, .size = size}; } } // Move to next tag i += utils.align_up(size, 8); tag_count += 1; } if (list) { print.debug_format(" - That was {} tags\n", .{tag_count}); return Range{.start = i, .size = 0}; } return Error.TagNotFound; } const VbeInfo = packed struct { kind: TagKind, size: u32, mode: u16, interface_seg: u16, interface_off: u16, interface_len: u16, control_info: [512]u8, mode_info: [256]u8, }; pub fn get_vbe_info() ?*VbeInfo { const range = find_tag(TagKind.Vbe) catch { return null; }; return range.to_ptr(*VbeInfo); }
kernel/platform/multiboot.zig
const std = @import("std"); const TestContext = @import("../../src/test.zig").TestContext; pub fn addCases(ctx: *TestContext) !void { { var case = addPtx(ctx, "nvptx: simple addition and subtraction"); case.compiles( \\fn add(a: i32, b: i32) i32 { \\ return a + b; \\} \\ \\pub export fn add_and_substract(a: i32, out: *i32) callconv(.PtxKernel) void { \\ const x = add(a, 7); \\ var y = add(2, 0); \\ y -= x; \\ out.* = y; \\} ); } { var case = addPtx(ctx, "nvptx: read special registers"); case.compiles( \\fn threadIdX() usize { \\ var tid = asm volatile ("mov.u32 \t$0, %tid.x;" \\ : [ret] "=r" (-> u32), \\ ); \\ return @as(usize, tid); \\} \\ \\pub export fn special_reg(a: []const i32, out: []i32) callconv(.PtxKernel) void { \\ const i = threadIdX(); \\ out[i] = a[i] + 7; \\} ); } { var case = addPtx(ctx, "nvptx: address spaces"); case.compiles( \\var x: i32 addrspace(.global) = 0; \\ \\pub export fn increment(out: *i32) callconv(.PtxKernel) void { \\ x += 1; \\ out.* = x; \\} ); } } const nvptx_target = std.zig.CrossTarget{ .cpu_arch = .nvptx64, .os_tag = .cuda, }; pub fn addPtx( ctx: *TestContext, name: []const u8, ) *TestContext.Case { ctx.cases.append(TestContext.Case{ .name = name, .target = nvptx_target, .updates = std.ArrayList(TestContext.Update).init(ctx.cases.allocator), .output_mode = .Obj, .files = std.ArrayList(TestContext.File).init(ctx.cases.allocator), .link_libc = false, .backend = .llvm, }) catch @panic("out of memory"); return &ctx.cases.items[ctx.cases.items.len - 1]; }
test/stage2/nvptx.zig
const std = @import("std"); const bits = @import("bits.zig"); const mem = std.mem; const fmt = std.fmt; const debug = std.debug; const io = std.io; const assert = debug.assert; // TODO: Missing a few convinient features // * Short arguments that doesn't take values should probably be able to be // chain like many linux programs: "rm -rf" // * Handle "--something=VALUE" pub fn Arg(comptime T: type) type { return struct { const Self = @This(); pub const Kind = enum { Optional, Required, IgnoresRequired, }; help_message: []const u8, handler: fn (*T, []const u8) anyerror!void, arg_kind: Kind, takes_value: bool, short_arg: ?u8, long_arg: ?[]const u8, pub fn init(handler: fn (*T, []const u8) anyerror!void) Self { return Self{ .help_message = "", .handler = handler, .arg_kind = Kind.Optional, .takes_value = false, .short_arg = null, .long_arg = null, }; } pub fn help(arg: Self, str: []const u8) Self { var res = arg; res.help_message = str; return res; } pub fn short(arg: Self, char: u8) Self { var res = arg; res.short_arg = char; return res; } pub fn long(arg: Self, str: []const u8) Self { var res = arg; res.long_arg = str; return res; } pub fn takesValue(arg: Self, b: bool) Self { var res = arg; res.takes_value = b; return res; } pub fn kind(arg: Self, k: Kind) Self { var res = arg; res.arg_kind = k; return res; } }; } pub fn parse(comptime T: type, options: []const Arg(T), defaults: T, args: []const []const u8) !T { var result = defaults; const Kind = enum { Long, Short, None, }; const ArgKind = struct { arg: []const u8, kind: Kind, }; // NOTE: We avoid allocation here by using a bit field to store the required // arguments that we need to handle. I'll only make this more flexible // if someone finds a usecase for more than 128 required arguments. var required: u128 = 0; if (args.len >= 128) return error.ToManyOptions; { var required_index: usize = 0; for (options) |option, i| { if (option.arg_kind == Arg(T).Kind.Required) { required = bits.set(u128, required, @intCast(u7, required_index), true); required_index += 1; } } } // We assume that the first arg is always the exe path var arg_i = usize(1); while (arg_i < args.len) : (arg_i += 1) { const pair = blk: { const tmp = args[arg_i]; if (mem.startsWith(u8, tmp, "--")) break :blk ArgKind{ .arg = tmp[2..], .kind = Kind.Long }; if (mem.startsWith(u8, tmp, "-")) break :blk ArgKind{ .arg = tmp[1..], .kind = Kind.Short }; break :blk ArgKind{ .arg = tmp, .kind = Kind.None }; }; const arg = pair.arg; const kind = pair.kind; var required_index: usize = 0; loop: for (options) |option, op_i| { switch (kind) { Kind.None => { if (option.short_arg != null) continue :loop; if (option.long_arg != null) continue :loop; try option.handler(&result, arg); switch (option.arg_kind) { Arg(T).Kind.Required => { required = bits.set(u128, required, @intCast(u7, required_index), false); required_index += 1; }, Arg(T).Kind.IgnoresRequired => { required = 0; required_index += 1; }, else => {}, } break :loop; }, Kind.Short => { const short = option.short_arg orelse continue :loop; if (arg.len != 1 or arg[0] != short) continue :loop; }, Kind.Long => { const long = option.long_arg orelse continue :loop; if (!mem.eql(u8, long, arg)) continue :loop; }, } if (option.takes_value) arg_i += 1; if (args.len <= arg_i) return error.MissingValueToArgument; const value = args[arg_i]; try option.handler(&result, value); switch (option.arg_kind) { Arg(T).Kind.Required => { required = bits.set(u128, required, @intCast(u7, required_index), false); required_index += 1; }, Arg(T).Kind.IgnoresRequired => { required = 0; required_index += 1; }, else => {}, } break :loop; } else { return error.InvalidArgument; } } if (required != 0) { return error.RequiredArgumentWasntHandled; } return result; } // TODO: // * Usage // * Description pub fn help(comptime T: type, options: []const Arg(T), out_stream: var) !void { const equal_value: []const u8 = "=OPTION"; var longest_long: usize = 0; for (options) |option| { const long = option.long_arg orelse continue; var len = long.len; if (option.takes_value) len += equal_value.len; if (longest_long < len) longest_long = len; } for (options) |option| { if (option.short_arg == null and option.long_arg == null) continue; try out_stream.print(" "); if (option.short_arg) |short| { try out_stream.print("-{c}", short); } else { try out_stream.print(" "); } if (option.short_arg != null and option.long_arg != null) { try out_stream.print(", "); } else { try out_stream.print(" "); } // We need to ident by: // "--<longest_long> ".len var missing_spaces = longest_long + 3; if (option.long_arg) |long| { try out_stream.print("--{}", long); missing_spaces -= 2 + long.len; if (option.takes_value) { try out_stream.print("{}", equal_value); missing_spaces -= equal_value.len; } } var i: usize = 0; while (i < (missing_spaces + 1)) : (i += 1) { try out_stream.print(" "); } try out_stream.print("{}\n", option.help_message); } } test "clap.parse.Example" { const Color = struct { const Self = @This(); r: u8, g: u8, b: u8, fn rFromStr(color: *Self, str: []const u8) !void { color.r = try fmt.parseInt(u8, str, 10); } fn gFromStr(color: *Self, str: []const u8) !void { color.g = try fmt.parseInt(u8, str, 10); } fn bFromStr(color: *Self, str: []const u8) !void { color.b = try fmt.parseInt(u8, str, 10); } }; const CArg = Arg(Color); // TODO: Format is horrible. Fix const options = []CArg{ CArg.init(Color.rFromStr).help("The amount of red in our color").short('r').long("red").takesValue(true).kind(CArg.Kind.Required), CArg.init(Color.gFromStr).help("The amount of green in our color").short('g').long("green").takesValue(true), CArg.init(Color.bFromStr).help("The amount of blue in our color").short('b').long("blue").takesValue(true), }; const Case = struct { args: []const []const u8, res: Color, err: ?anyerror, }; const cases = []Case{ Case{ .args = [][]const u8{ "color.exe", "-r", "100", "-g", "100", "-b", "100", }, .res = Color{ .r = 100, .g = 100, .b = 100 }, .err = null, }, Case{ .args = [][]const u8{ "color.exe", "--red", "100", "-g", "100", "--blue", "50", }, .res = Color{ .r = 100, .g = 100, .b = 50 }, .err = null, }, Case{ .args = [][]const u8{ "color.exe", "-g", "200", "--blue", "100", "--red", "100", }, .res = Color{ .r = 100, .g = 200, .b = 100 }, .err = null, }, Case{ .args = [][]const u8{ "color.exe", "-r", "200", "-r", "255" }, .res = Color{ .r = 255, .g = 0, .b = 0 }, .err = null, }, Case{ .args = [][]const u8{ "color.exe", "-g", "200", "-b", "255" }, .res = Color{ .r = 0, .g = 0, .b = 0 }, .err = error.RequiredArgumentWasntHandled, }, Case{ .args = [][]const u8{ "color.exe", "-p" }, .res = Color{ .r = 0, .g = 0, .b = 0 }, .err = error.InvalidArgument, }, Case{ .args = [][]const u8{ "color.exe", "-g" }, .res = Color{ .r = 0, .g = 0, .b = 0 }, .err = error.MissingValueToArgument, }, }; for (cases) |case| { const default = Color{ .r = 0, .g = 0, .b = 0 }; if (parse(Color, options, default, case.args)) |res| { assert(res.r == case.res.r); assert(res.g == case.res.g); assert(res.b == case.res.b); } else |err| { assert(err == (case.err orelse unreachable)); } } }
src/clap.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const expectEqual = std.testing.expectEqual; const expectEqualSlices = std.testing.expectEqualSlices; const base_pattern = [_]isize{ 0, 1, 0, -1 }; fn getPattern(output_pos: usize, pos: usize) isize { const real_pos = pos + 1; const multiplier = output_pos + 1; return base_pattern[(real_pos / multiplier) % base_pattern.len]; } test "getPattern first output" { expectEqual(@as(isize, 1), getPattern(0, 0)); expectEqual(@as(isize, 0), getPattern(0, 1)); expectEqual(@as(isize, -1), getPattern(0, 2)); expectEqual(@as(isize, 0), getPattern(0, 3)); expectEqual(@as(isize, 1), getPattern(0, 4)); expectEqual(@as(isize, 0), getPattern(0, 5)); } test "getPattern second output" { expectEqual(@as(isize, 0), getPattern(1, 0)); expectEqual(@as(isize, 1), getPattern(1, 1)); expectEqual(@as(isize, 1), getPattern(1, 2)); expectEqual(@as(isize, 0), getPattern(1, 3)); expectEqual(@as(isize, 0), getPattern(1, 4)); expectEqual(@as(isize, -1), getPattern(1, 5)); } test "getPattern third output" { expectEqual(@as(isize, 0), getPattern(2, 0)); expectEqual(@as(isize, 0), getPattern(2, 1)); expectEqual(@as(isize, 1), getPattern(2, 2)); expectEqual(@as(isize, 1), getPattern(2, 3)); expectEqual(@as(isize, 1), getPattern(2, 4)); expectEqual(@as(isize, 0), getPattern(2, 5)); expectEqual(@as(isize, 0), getPattern(2, 6)); expectEqual(@as(isize, 0), getPattern(2, 7)); expectEqual(@as(isize, -1), getPattern(2, 8)); expectEqual(@as(isize, -1), getPattern(2, 9)); expectEqual(@as(isize, -1), getPattern(2, 10)); } fn fftPhase(input: []const isize, output: []isize) void { for (input) |x, i| { const step_size = i + 1; var new_val: isize = 0; // Optimization: only iterate over fields that are non-null var j: usize = i; while (j < input.len) : (j += 2 * step_size) { var k: usize = 0; while (k < step_size and j + k < input.len) : (k += 1) { new_val += input[j + k] * getPattern(i, j + k); } } output[i] = @mod(std.math.absInt(new_val) catch 0, 10); } } test "first example" { var input: [8]isize = undefined; var output: [8]isize = undefined; var i: usize = 0; while (i < 8) : (i += 1) input[i] = @intCast(isize, i + 1); fftPhase(&input, &output); expectEqualSlices(isize, &[_]isize{ 4, 8, 2, 2, 6, 1, 5, 8 }, &output); std.mem.copy(isize, &input, &output); fftPhase(&input, &output); expectEqualSlices(isize, &[_]isize{ 3, 4, 0, 4, 0, 4, 3, 8 }, &output); std.mem.copy(isize, &input, &output); } test "large example 1" { const input_str = "80871224585914546619083218645595"; var input: [input_str.len]isize = undefined; var output: [input_str.len]isize = undefined; for (input_str) |x, i| { input[i] = @intCast(isize, x - '0'); } var i: usize = 0; while (i < 100) : (i += 1) { fftPhase(&input, &output); std.mem.copy(isize, &input, &output); } expectEqualSlices(isize, &[_]isize{ 2, 4, 1, 7, 6, 1, 7, 6 }, output[0..8]); } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; const input_file = try std.fs.cwd().openFile("input16.txt", .{}); var input_stream = input_file.reader(); var read = ArrayList(isize).init(allocator); while (input_stream.readByte()) |b| { if ('0' <= b and b <= '9') { try read.append(@intCast(isize, b - '0')); } } else |e| switch (e) { error.EndOfStream => {}, else => return e, } var current = read.toOwnedSlice(); var new = try allocator.alloc(isize, current.len); var i: usize = 0; while (i < 100) : (i += 1) { fftPhase(current, new); std.mem.copy(isize, current, new); } var eight_digits: [8]u8 = undefined; for (eight_digits) |*x, j| { x.* = @intCast(u8, current[j] + '0'); } std.debug.warn("first eight digits: {}\n", .{&eight_digits}); }
zig/16.zig
const std = @import("std"); const Entity = @import("./Entity.zig"); const ArrayList = std.ArrayList; const Allocator = std.mem.Allocator; const Bitset = std.bit_set.StaticBitSet(MAX_ENTITIES); const expect = std.testing.expect; const benchmark = @import("benchmark"); const Entities = @This(); const MAX_ENTITIES = @import("./main.zig").MAX_ENTITIES; bitset: Bitset, // Stack bitset = 8KB generation: ArrayList(u32), // Heap generation list = 255KB killed: ArrayList(Entity), next_id: u16 = 0, /// helps to know if we should directly append after /// next_id or if we should look through the bitset. has_deleted: bool = false, const InnerType: type = Entity; /// Allocates a new Entities struct. pub fn init(allocator: *Allocator) !@This() { var gen = try ArrayList(u32).initCapacity(allocator, MAX_ENTITIES); errdefer gen.deinit(); gen.appendNTimesAssumeCapacity(0, MAX_ENTITIES); const killed = ArrayList(Entity).init(allocator); errdefer killed.deinit(); const bitset = Bitset.initEmpty(); return @This(){ .bitset = bitset, .generation = gen, .killed = killed, }; } /// Creates a new `Entity` and returns it. /// This function will not reuse the index of an entity that is still in /// the killed entities. pub fn create(this: *@This()) Entity { if (!this.has_deleted) { const i = this.next_id; this.next_id += 1; this.bitset.set(i); return Entity{ .index = i, .generation = this.generation.items[i] }; } else { var check: u16 = 0; var found = false; while (!found) : (check += 1) { comptime const overflow_check = std.builtin.mode == .Debug or std.builtin.mode == .ReleaseSafe; if (overflow_check and check == MAX_ENTITIES) { @panic("Max entity count reached!"); } if (!this.bitset.isSet(check)) { var in_killed = false; // .any(fn) would reduce this by a lot, but I'm not sure if that's possible // didn't find that in std.mem for (this.killed.items) |k| { if (k.index == check) { in_killed = true; break; } } if (!in_killed) { found = true; } } } check -= 1; this.bitset.set(check); if (check >= this.next_id) { this.next_id = check; this.has_deleted = false; } return Entity{ .index = check, .generation = this.generation.items[check] }; } } /// Checks if the `Entity` is still bitset. /// Returns true if it is bitset. /// Returns false if it has been killed. pub fn is_bitset(this: *@This(), entity: Entity) bool { return this.bitset.isSet(entity.index) and this.generation.items[entity.index] == entity.generation; } /// Kill an entity. pub fn kill(this: *@This(), entity: Entity) !void { if (this.is_bitset(entity)) { this.bitset.unset(entity.index); this.generation.items[entity.index] += 1; try this.killed.append(entity); this.has_deleted = true; } } /// Clears the killed entity list. pub fn clear_killed(this: *@This()) void { this.killed.items.len = 0; } /// Deallocates an Entities struct. pub fn deinit(this: *@This()) void { this.generation.deinit(); this.killed.deinit(); } /// Gets the element immutably pub fn get(this: *const @This(), idx: u32) ?Entity { return Entity{ .index = idx, .generation = this.generation.items[idx], }; } test "Create entity" { var entities = try @This().init(std.testing.allocator); defer entities.deinit(); const entity1 = entities.create(); try expect(entity1.index == 0); try expect(entity1.generation == 0); try expect(entities.bitset.isSet(0)); try expect(!entities.bitset.isSet(1)); const entity2 = entities.create(); try expect(entity2.index == 1); try expect(entity2.generation == 0); try expect(entities.bitset.isSet(0)); try expect(entities.bitset.isSet(1)); } test "Kill create entity" { var entities = try @This().init(std.testing.allocator); defer entities.deinit(); const entity1 = entities.create(); try expect(entity1.index == 0); try expect(entity1.generation == 0); try expect(entities.bitset.isSet(0)); try expect(!entities.bitset.isSet(1)); try expect(!entities.has_deleted); try entities.kill(entity1); try expect(entities.has_deleted); const entity2 = entities.create(); try expect(entity2.index == 1); try expect(entity2.generation == 0); try expect(!entities.bitset.isSet(0)); try expect(entities.bitset.isSet(1)); // This did go all the way to the end to create the entity, so has_deleted should go back to false. try expect(!entities.has_deleted); entities.clear_killed(); // has_deleted is false, so we won't try to reuse index 0 // let's turn has_deleted back to true manually and check if we reuse index 0. entities.has_deleted = true; const entity3 = entities.create(); try expect(entity3.index == 0); try expect(entity3.generation == 1); try expect(entities.bitset.isSet(0)); try expect(entities.bitset.isSet(1)); try expect(!entities.bitset.isSet(2)); try expect(!entities.bitset.isSet(3)); // has_deleted stays to true since we didn't check until the end of the array try expect(entities.has_deleted); const entity4 = entities.create(); try expect(entity4.index == 2); try expect(entity4.generation == 0); try expect(entities.bitset.isSet(0)); try expect(entities.bitset.isSet(1)); try expect(entities.bitset.isSet(2)); try expect(!entities.bitset.isSet(3)); // has_deleted turns back to false try expect(!entities.has_deleted); } test "Benchmark create entity" { const b = struct { fn bench(ctx: *benchmark.Context, count: u32) void { while (ctx.runExplicitTiming()) { var entities = Entities.init(std.testing.allocator) catch unreachable; defer entities.deinit(); var i = @as(u32, 0); ctx.startTimer(); while (i < count) : (i += 1) { const e = entities.create(); benchmark.doNotOptimize(e.index); } ctx.stopTimer(); } } }.bench; benchmark.benchmarkArgs("create Entity", b, &[_]u32{ 1, 100, 10000 }); } test "Benchmark create Entities" { const b = struct { fn bench(ctx: *benchmark.Context) void { // using the arena allocator and -lc (libc) gives the fastest results. //var alloc = std.heap.c_allocator; var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const alloc = &arena.allocator; while (ctx.run()) { var entities = Entities.init(alloc) catch unreachable; defer entities.deinit(); } } }.bench; benchmark.benchmark("create Entities", b); }
src/Entities.zig
const arduino = @import("arduino"); const gpio = arduino.gpio; // Necessary, and has the side effect of pulling in the needed _start method pub const panic = arduino.start.panicLogUart; // display 4 digits // using a kyx-3942bg and a 74hc595 shift register // pins: // 74hc595 pins in: const SHIFTREG_DS = 11; // data const SHIFTREG_STCP = 12; // shift-in clock (up edge) const SHIFTREG_SHCP = 10; // register storage clock (up edge) // out pins Q7..Q0 -> 3942bg in: 16 13 3 5 11 15 7 14 // other 3942bg pins const LED_1 = 4; const LED_2 = 5; const LED_6 = 6; const LED_8 = 7; fn shiftOut(comptime DS_pin: comptime_int, comptime SHC_pin: comptime_int, comptime STC_pin: comptime_int, value: u8) void { gpio.setPin(STC_pin, .low); var v = value; var i: u8 = 0; while (i < 8) : (i += 1) { if (v & 0b1000_0000 != 0) gpio.setPin(DS_pin, .high) else gpio.setPin(DS_pin, .low); gpio.setPin(SHC_pin, .high); v <<= 1; gpio.setPin(SHC_pin, .low); } gpio.setPin(STC_pin, .high); } fn setLCDDigit(comptime sel_pin: comptime_int, digit: u4) void { const digit_segments = [_]u8{ 0b0_0111111, // 0 0b0_0000110, // 1 0b0_1011011, // 2 0b0_1001111, // 3 0b0_1100110, // 4 0b0_1101101, // 5 0b0_1111101, // 6 0b0_0000111, // 7 0b0_1111111, // 8 0b0_1101111, // 9 0b0_1110111, // A 0b0_1111100, // b 0b0_0111001, // C 0b0_1011110, // d 0b0_1111001, // E 0b0_1110001, // F }; shiftOut(SHIFTREG_DS, SHIFTREG_SHCP, SHIFTREG_STCP, ~digit_segments[digit]); gpio.setPin(sel_pin, .high); arduino.cpu.delayMicroseconds(250); gpio.setPin(sel_pin, .low); } pub fn main() void { arduino.uart.init(arduino.cpu.CPU_FREQ, 115200); gpio.setMode(SHIFTREG_DS, .output); gpio.setMode(SHIFTREG_STCP, .output); gpio.setMode(SHIFTREG_SHCP, .output); gpio.setMode(LED_1, .output); gpio.setMode(LED_2, .output); gpio.setMode(LED_6, .output); gpio.setMode(LED_8, .output); // var counter:u16=0; // while (true) { // setLCDDigit(LED_1, 0); // setLCDDigit(LED_2, 0); // setLCDDigit(LED_6, 0); // setLCDDigit(LED_8, @intCast(u4, (counter>>8)&0x0F)); // counter +%= 1; // } // set 4 digits LCD to the analog pin A0 value: const A0 = 14; gpio.setMode(A0, .input); const REDLED = 9; gpio.setMode(REDLED, .output_analog); gpio.setPin(REDLED, .high); while (true) { const potar = gpio.getPinAnalog(0); setLCDDigit(LED_8, @intCast(u4, (potar >> 0) & 0x000F)); setLCDDigit(LED_6, @intCast(u4, (potar >> 4) & 0x000F)); setLCDDigit(LED_2, @intCast(u4, (potar >> 8) & 0x000F)); setLCDDigit(LED_1, @intCast(u4, (potar >> 12) & 0x000F)); gpio.setPinAnalog(REDLED, @intCast(u8, potar & 0xFF)); } }
examples/7seg_display.zig
usingnamespace @import("root").preamble; const rb = lib.containers.rbtree; const platform = os.platform; const PagingContext = platform.paging.PagingContext; const rb_features: rb.Features = .{ .enable_iterators_cache = true, .enable_kth_queries = false, .enable_not_associatve_augment = false, }; const addr_config: rb.Config = .{ .features = rb_features, .augment_callback = null, .comparator = AddressComparator, }; const AddressComparator = struct { pub fn compare(self: *const @This(), left: *const MemoryRegion, right: *const MemoryRegion) bool { return left.base >= right.base; } }; const RbNode = rb.Node(rb_features); const RbTree = rb.Tree(MemoryRegion, "rb_node", addr_config); pub const PageFaultError = error{ RangeRefusedHandling, OutOfMemory, InternalError, }; //pub const DupError = error{ // OutOfMemory, // Refusing, //}; pub const MemoryRegionVtable = struct { /// Call this on a page fault into the region, be it read, write or execute /// returns whether the page fault was handled by the region itself pageFault: fn ( *MemoryRegion, offset: usize, present: bool, fault_type: platform.PageFaultAccess, page_table: *PagingContext, ) PageFaultError!void, // /// Call to duplicate a memory region, for fork or similar // dup: fn (*MemoryRegion) DupError!*MemoryRegion, }; pub const MemoryRegion = struct { // TODO: rbtree node for this memory region rb_node: RbNode = undefined, // vtable with function pointers to implementations vtab: *const MemoryRegionVtable, /// The base address of the region base: usize = undefined, /// The byte size of the region size: usize = undefined, pub fn pageFault( self: *@This(), offset: usize, present: bool, fault_type: platform.PageFaultAccess, page_table: *PagingContext, ) !void { return self.vtab.pageFault( self, offset, present, fault_type, page_table, ); } //pub fn dup(self: *@This()) !*MemoryRegion { // return self.vtab.dup(self); //} pub fn contains(self: @This(), addr: usize) bool { return addr >= self.base and addr < self.base + self.size; } }; fn pageSize() usize { return os.platform.paging.page_sizes[0]; } pub const AddrSpace = struct { emptyRanges: lib.memory.range_alloc.RangeAlloc = .{ .backing_allocator = os.memory.pmm.phys_heap, }, usedRanges: RbTree = RbTree.init(.{}, {}), pub fn init(self: *@This(), base: usize, end: usize) !void { self.* = .{}; try self.emptyRanges.giveRange(.{ .base = base, .size = end - base, }); } pub fn deinit(self: *@This()) !void { // TODO unreachable; } /// Try to allocate space at a specific address pub fn allocateAt(self: *@This(), addr: usize, size_in: usize) !void { if (!lib.util.libalign.isAligned(usize, pageSize(), addr)) return error.AddrNotAligned; const size = lib.util.libalign.alignUp(usize, pageSize(), size_in); _ = try self.emptyRanges.allocateAt(addr, size); } /// Allocates new space anywhere in the address space pub fn allocateAnywhere(self: *@This(), size_in: usize) !usize { const size = lib.util.libalign.alignUp(usize, pageSize(), size_in); const r = try self.emptyRanges.allocateAnywhere(size, pageSize(), pageSize()); return @ptrToInt(r.ptr); } pub fn findRangeAt(self: *@This(), addr: usize) ?*MemoryRegion { const addr_finder: struct { addr: usize, pub fn check(finder: *const @This(), region: *const MemoryRegion) bool { return region.base + region.size >= finder.addr; } } = .{ .addr = addr }; var candidate = self.usedRanges.lowerBound(@TypeOf(addr_finder), &addr_finder); if (candidate) |c| { if (c.contains(addr)) return c; } return null; } pub fn findRangeContaining(self: *@This(), addr: usize, size: usize) ?*MemoryRegion { if (findRangeAt(addr)) |range| { if (range.contains(addr + size - 1)) return range; } return null; } pub fn pageFault(self: *@This(), addr: usize, present: bool, fault_type: platform.PageFaultAccess) !void { const range = self.findRangeAt(addr) orelse return error.NoRangeAtAddress; try range.pageFault(addr - range.base, present, fault_type, self.pageTable()); } pub fn lazyMap(self: *@This(), addr: usize, size: usize, region: *MemoryRegion) !void { region.base = addr; region.size = size; self.usedRanges.insert(region); } pub fn freeAndUnmap(self: *@This(), addr: usize, size: usize) void { // TODO unreachable; } fn pageTable(self: *@This()) *PagingContext { return &@fieldParentPtr(os.kernel.process.Process, "addr_space", self).page_table; } };
subprojects/flork/src/kernel/process/address_space.zig
const std = @import("std"); const s2s = @import("s2s"); const logger = std.log.scoped(.antiphony_rpc); /// The role of an EndPoint. `host` and `client` are arbitrary names that define both ends. /// The `host` role usually calls `EndPoint.acceptCalls()` and waits for incoming calls. pub const Role = enum { host, client }; pub const Config = struct { /// If this is set, a call to `EndPoint.invoke()` will merge the remote error set into /// the error set of `invoke()` itself, so a single `try invoke()` will suffice. /// Otherwise, the return type will be`InvokeError!InvocationResult(RemoteResult)`. merge_error_sets: bool = true, }; /// Returns a wrapper struct that contains the result of a function invocation. /// This is needed as s2s cannot serialize raw top level errors. pub fn InvocationResult(comptime T: type) type { return struct { value: T, fn unwrap(self: @This()) T { return self.value; } }; } /// Use this instead of the usual `Self` parameter when you need to return slices pub fn AllocatingCall(comptime T: type) type { return struct { const Self = @This(); allocator: std.mem.Allocator, value: T, }; } /// Create a new RPC definition that can be used to instantiate end points. pub fn CreateDefinition(comptime spec: anytype) type { const host_spec = spec.host; const client_spec = spec.client; const config: Config = if (@hasField(@TypeOf(spec), "config")) spec.config else Config{}; comptime validateSpec(host_spec); comptime validateSpec(client_spec); return struct { const Self = @This(); pub fn HostEndPoint(comptime Reader: type, comptime Writer: type, comptime Implementation: type) type { return CreateEndPoint(.host, Reader, Writer, Implementation); } pub fn ClientEndPoint(comptime Reader: type, comptime Writer: type, comptime Implementation: type) type { return CreateEndPoint(.client, Reader, Writer, Implementation); } pub fn CreateEndPoint(comptime role: Role, comptime ReaderType: type, comptime WriterType: type, comptime ImplementationType: type) type { const inbound_spec = switch (role) { .host => host_spec, .client => client_spec, }; const outbound_spec = switch (role) { .host => client_spec, .client => host_spec, }; const InboundSpec = @TypeOf(inbound_spec); const max_received_func_name_len = comptime blk: { var len = 0; for (std.meta.fields(InboundSpec)) |fld| { len = std.math.max(fld.name.len, len); } break :blk len; }; return struct { const EndPoint = @This(); pub const Reader = ReaderType; pub const Writer = WriterType; pub const Implementation = ImplementationType; pub const IoError = Reader.Error || Writer.Error || error{EndOfStream}; pub const ProtocolError = error{ ProtocolViolation, InvalidProtocol, ProtocolMismatch }; pub const InvokeError = IoError || ProtocolError || std.mem.Allocator.Error; pub const ConnectError = IoError || ProtocolError; allocator: std.mem.Allocator, reader: Reader, writer: Writer, sequence_id: u32 = 0, impl: ?*Implementation = null, pub fn init(allocator: std.mem.Allocator, reader: Reader, writer: Writer) EndPoint { return EndPoint{ .allocator = allocator, .reader = reader, .writer = writer, }; } pub fn destroy(self: *EndPoint) void { // // make sure the other connection is gracefully shut down in any case // if (self.impl != null) { // self.shutdown() catch |err| logger.warn("failed to shut down remote connection gracefully: {s}", .{@errorName(err)}); // } self.* = undefined; } /// Performs the initial handshake with the remote peer. /// Both agree on the used RPC version and that they use the same protocol. pub fn connect(self: *EndPoint, impl: *Implementation) ConnectError!void { std.debug.assert(self.impl == null); // do not call twice try self.writer.writeAll(&protocol_magic); try self.writer.writeByte(current_version); // version byte var remote_magic: [4]u8 = undefined; try self.reader.readNoEof(&remote_magic); if (!std.mem.eql(u8, &protocol_magic, &remote_magic)) return error.InvalidProtocol; const remote_version = try self.reader.readByte(); if (remote_version != current_version) return error.ProtocolMismatch; self.impl = impl; } /// Shuts down the connection and exits the loop inside `acceptCalls()` on the remote peer. /// /// Must be called only after a successful call to `connect()`. pub fn shutdown(self: *EndPoint) IoError!void { std.debug.assert(self.impl != null); // call these only after a successful connection! try self.writer.writeByte(@enumToInt(CommandId.shutdown)); } /// Waits for incoming calls and handles them till the client shuts down the connection. /// /// Must be called only after a successful call to `connect()`. pub fn acceptCalls(self: *EndPoint) InvokeError!void { std.debug.assert(self.impl != null); // call these only after a successful connection! while (true) { const cmd_id = try self.reader.readByte(); const cmd = std.meta.intToEnum(CommandId, cmd_id) catch return error.ProtocolViolation; switch (cmd) { .call => { try self.processCall(); }, .response => return error.ProtocolViolation, .shutdown => return, } } } pub fn InvokeReturnType(comptime func_name: []const u8) type { const FuncPrototype = @field(outbound_spec, func_name); const func_info = @typeInfo(FuncPrototype).Fn; const FuncReturnType = func_info.return_type.?; if (config.merge_error_sets) { switch (@typeInfo(FuncReturnType)) { // We merge error sets, but still return the original function payload .ErrorUnion => |eu| return (InvokeError || eu.error_set)!eu.payload, // we just merge error sets, the result will be `void` in *no* case (but makes handling easier) .ErrorSet => return (InvokeError || FuncReturnType)!void, // The function doesn't return an error, so we just return InvokeError *or* the function return value. else => return InvokeError!FuncReturnType, } } else { // When not merging error sets, we need to wrap the result into a InvocationResult to handle potential // error unions or sets gracefully in the API. return InvokeError!InvocationResult(FuncReturnType); } } /// Invokes `func_name` on the remote peer with `args`. Returns either an error or the return value of the remote procedure call. /// /// Must be called only after a successful call to `connect()`. pub fn invoke(self: *EndPoint, comptime func_name: []const u8, args: anytype) InvokeReturnType(func_name) { return try self.invokeInternal(false, {}, func_name, args); } /// Invokes `func_name` on the remote peer with `args`. Returns either an error or the return value of the remote procedure call. /// /// Must be called only after a successful call to `connect()`. pub fn invokeAlloc(self: *EndPoint, allocator: std.mem.Allocator, comptime func_name: []const u8, args: anytype) InvokeReturnType(func_name) { return try self.invokeInternal(true, allocator, func_name, args); } /// Frees the result of `invokeAlloc`. pub const free = s2s.free; fn invokeInternal(self: *EndPoint, comptime has_alloc: bool, allocator: if (has_alloc) std.mem.Allocator else void, comptime func_name: []const u8, args: anytype) !InvokeReturnType(func_name) { std.debug.assert(self.impl != null); // call these only after a successful connection! const FuncPrototype = @field(outbound_spec, func_name); const ArgsTuple = std.meta.ArgsTuple(FuncPrototype); const func_info = @typeInfo(FuncPrototype).Fn; var arg_list: ArgsTuple = undefined; if (args.len != arg_list.len) @compileError("Argument mismatch!"); { comptime var i = 0; inline while (i < arg_list.len) : (i += 1) { arg_list[i] = args[i]; } } const sequence_id = self.nextSequenceID(); try self.writer.writeByte(@enumToInt(CommandId.call)); try self.writer.writeIntLittle(u32, @enumToInt(sequence_id)); try self.writer.writeIntLittle(u32, func_name.len); try self.writer.writeAll(func_name); try s2s.serialize(self.writer, ArgsTuple, arg_list); try self.waitForResponse(sequence_id); const FuncReturnType = func_info.return_type.?; if (has_alloc) { var result = s2s.deserializeAlloc(self.reader, InvocationResult(FuncReturnType), allocator) catch return error.ProtocolViolation; errdefer s2s.free(allocator, InvocationResult(FuncReturnType), &result); if (config.merge_error_sets) { if (@typeInfo(FuncReturnType) == .ErrorUnion) { return try result.unwrap(); } else if (@typeInfo(FuncReturnType) == .ErrorSet) { return result.unwrap(); } else { return result.unwrap(); } } else { // when we don't merge error sets, we have to return the wrapper struct itself. return result; } } else { const result = s2s.deserialize(self.reader, InvocationResult(FuncReturnType)) catch return error.ProtocolViolation; if (config.merge_error_sets) { if (@typeInfo(FuncReturnType) == .ErrorUnion) { return try result.unwrap(); } else if (@typeInfo(FuncReturnType) == .ErrorSet) { return result.unwrap(); } else { return result.unwrap(); } } else { // when we don't merge error sets, we have to return the wrapper struct itself. return result; } } } /// Waits until a response comman is received and validates that against the response id. /// Handles in-between calls to other functions. /// Leaves the reader in a state so the response can be deserialized directly from the stream. fn waitForResponse(self: *EndPoint, sequence_id: SequenceID) !void { while (true) { const cmd_id = try self.reader.readByte(); const cmd = std.meta.intToEnum(CommandId, cmd_id) catch return error.ProtocolViolation; switch (cmd) { .call => { try self.processCall(); }, .response => { const seq = @intToEnum(SequenceID, try self.reader.readIntLittle(u32)); if (seq != sequence_id) return error.ProtocolViolation; return; }, .shutdown => return error.ProtocolViolation, } } } /// Deserializes call information fn processCall(self: *EndPoint) !void { const sequence_id = @intToEnum(SequenceID, try self.reader.readIntLittle(u32)); const name_length = try self.reader.readIntLittle(u32); if (name_length > max_received_func_name_len) return error.ProtocolViolation; var name_buffer: [max_received_func_name_len]u8 = undefined; const function_name = name_buffer[0..name_length]; try self.reader.readNoEof(function_name); inline for (std.meta.fields(InboundSpec)) |fld| { if (std.mem.eql(u8, fld.name, function_name)) { try self.processCallTo(fld.name, sequence_id); return; } } // Client invoked unknown function return error.ProtocolViolation; } fn processCallTo(self: *EndPoint, comptime function_name: []const u8, sequence_id: SequenceID) !void { const impl_func = @field(Implementation, function_name); const FuncSpec = @field(inbound_spec, function_name); const FuncArgs = std.meta.ArgsTuple(FuncSpec); const ImplFunc = @TypeOf(impl_func); const SpecReturnType = @typeInfo(FuncSpec).Fn.return_type.?; const impl_func_info = @typeInfo(ImplFunc); if (impl_func_info != .Fn) @compileError(@typeName(Implementation) ++ "." ++ function_name ++ " must be a function with invocable signature " ++ @typeName(FuncSpec)); const impl_func_fn = impl_func_info.Fn; var invocation_args: FuncArgs = s2s.deserializeAlloc(self.reader, FuncArgs, self.allocator) catch |err| switch (err) { error.UnexpectedData => return error.ProtocolViolation, else => |e| return e, }; defer s2s.free(self.allocator, FuncArgs, &invocation_args); // We use the arena for allocating calls, so we don't leak return values var arena = std.heap.ArenaAllocator.init(self.allocator); defer arena.deinit(); const result: SpecReturnType = if (impl_func_fn.args.len == invocation_args.len) // invocation without self @call(.{}, impl_func, invocation_args) else if (impl_func_fn.args.len == invocation_args.len + 1) blk: { const Arg0Type = impl_func_fn.args[0].arg_type.?; // invocation with self and allocation break :blk if (Arg0Type == AllocatingCall(Implementation)) b: { const proxy = AllocatingCall(Implementation){ .value = self.impl.?.*, .allocator = arena.allocator() }; break :b @call(.{}, impl_func, .{proxy} ++ invocation_args); } else if (Arg0Type == AllocatingCall(*Implementation)) b: { const proxy = AllocatingCall(*Implementation){ .value = self.impl.?, .allocator = arena.allocator() }; break :b @call(.{}, impl_func, .{proxy} ++ invocation_args); } else if (Arg0Type == AllocatingCall(*const Implementation)) b: { const proxy = AllocatingCall(*const Implementation){ .value = self.impl.?, .allocator = arena.allocator() }; break :b @call(.{}, impl_func, .{proxy} ++ invocation_args); } // invocation with self else if (@typeInfo(Arg0Type) == .Pointer) @call(.{}, impl_func, .{self.impl.?} ++ invocation_args) else @call(.{}, impl_func, .{self.impl.?.*} ++ invocation_args); } else @compileError("Parameter mismatch for " ++ function_name); try self.writer.writeByte(@enumToInt(CommandId.response)); try self.writer.writeIntLittle(u32, @enumToInt(sequence_id)); try s2s.serialize(self.writer, InvocationResult(SpecReturnType), invocationResult(SpecReturnType, result)); } fn nextSequenceID(self: *EndPoint) SequenceID { const next = self.sequence_id; self.sequence_id += 1; return @intToEnum(SequenceID, next); } }; } }; } const protocol_magic = [4]u8{ 0x34, 0xa3, 0x8a, 0x54 }; const current_version = 0; const CommandId = enum(u8) { /// Begins a function invocation. /// /// message format: /// - sequence id (u32) /// - function name length (u32) /// - function name ([function name length]u8) /// - serialized function arguments call = 1, /// Returns the data for a function invocation. /// /// message format: /// - sequence id (u32) /// - serialized InvocationResult(function return value) response = 2, /// Forces a peer to leave `acceptCalls()`. /// /// message format: /// - (no data) shutdown = 3, }; const SequenceID = enum(u32) { _ }; /// Computes the return type of the given function type. fn ReturnType(comptime Func: type) type { return @typeInfo(Func).Fn.return_type.?; } /// Constructor for InvocationResult fn invocationResult(comptime T: type, value: T) InvocationResult(T) { return .{ .value = value }; } fn validateSpec(comptime funcs: anytype) void { const T = @TypeOf(funcs); inline for (std.meta.fields(T)) |fld| { if (fld.field_type != type) @compileError("All fields of .host or .client must be function types!"); const field_info = @typeInfo(@field(funcs, fld.name)); if (field_info != .Fn) @compileError("All fields of .host or .client must be function types!"); const func_info: std.builtin.TypeInfo.Fn = field_info.Fn; if (func_info.is_generic) @compileError("Cannot handle generic functions"); for (func_info.args) |arg| { if (arg.is_generic) @compileError("Cannot handle generic functions"); if (arg.arg_type == null) @compileError("Cannot handle generic functions"); } if (func_info.return_type == null) @compileError("Cannot handle generic functions"); } } test "CreateDefinition" { const CreateError = error{ OutOfMemory, UnknownCounter }; const UsageError = error{ OutOfMemory, UnknownCounter }; const RcpDefinition = CreateDefinition(.{ .host = .{ .createCounter = fn () CreateError!u32, .destroyCounter = fn (u32) void, .increment = fn (u32, u32) UsageError!u32, .getCount = fn (u32) UsageError!u32, }, .client = .{ .signalError = fn (msg: []const u8) void, }, }); _ = RcpDefinition; } test "invoke function (emulated host)" { const RcpDefinition = CreateDefinition(.{ .host = .{ .some = fn (a: u32, b: f32, c: []const u8) void, }, .client = .{}, }); const ClientImpl = struct {}; var output_stream = std.ArrayList(u8).init(std.testing.allocator); defer output_stream.deinit(); const input_data = comptime blk: { var buffer: [4096]u8 = undefined; var stream = std.io.fixedBufferStream(&buffer); var writer = stream.writer(); try writer.writeAll(&protocol_magic); try writer.writeByte(current_version); try writer.writeByte(@enumToInt(CommandId.response)); try writer.writeIntLittle(u32, 0); // first sequence id try s2s.serialize(writer, InvocationResult(void), invocationResult(void, {})); break :blk stream.getWritten(); }; var input_stream = std.io.fixedBufferStream(@as([]const u8, input_data)); const EndPoint = RcpDefinition.ClientEndPoint(std.io.FixedBufferStream([]const u8).Reader, std.ArrayList(u8).Writer, ClientImpl); var end_point = EndPoint.init(std.testing.allocator, input_stream.reader(), output_stream.writer()); var impl = ClientImpl{}; try end_point.connect(&impl); try end_point.invoke("some", .{ 1, 2, "hello, world!" }); // std.debug.print("host to client: {}\n", .{std.fmt.fmtSliceHexUpper(input_data)}); // std.debug.print("client to host: {}\n", .{std.fmt.fmtSliceHexUpper(output_stream.items)}); } test "invoke function (emulated client, no self parameter)" { const RcpDefinition = CreateDefinition(.{ .host = .{ .some = fn (a: u32, b: f32, c: []const u8) u32, }, .client = .{}, }); const HostImpl = struct { fn some(a: u32, b: f32, c: []const u8) u32 { std.debug.print("some({}, {d}, \"{s}\");\n", .{ a, b, c }); return a + @floatToInt(u32, b); } }; var output_stream = std.ArrayList(u8).init(std.testing.allocator); defer output_stream.deinit(); const input_data = comptime blk: { var buffer: [4096]u8 = undefined; var stream = std.io.fixedBufferStream(&buffer); var writer = stream.writer(); try writer.writeAll(&protocol_magic); try writer.writeByte(current_version); try writer.writeByte(@enumToInt(CommandId.call)); try writer.writeIntLittle(u32, 1337); // first sequence id try writer.writeIntLittle(u32, "some".len); try writer.writeAll("some"); try s2s.serialize(writer, std.meta.Tuple(&.{ u32, f32, []const u8 }), .{ .@"0" = 1334, .@"1" = std.math.pi, .@"2" = "Hello, Host!", }); try writer.writeByte(@enumToInt(CommandId.shutdown)); break :blk stream.getWritten(); }; var input_stream = std.io.fixedBufferStream(@as([]const u8, input_data)); const EndPoint = RcpDefinition.HostEndPoint(std.io.FixedBufferStream([]const u8).Reader, std.ArrayList(u8).Writer, HostImpl); var end_point = EndPoint.init(std.testing.allocator, input_stream.reader(), output_stream.writer()); var impl = HostImpl{}; try end_point.connect(&impl); try end_point.acceptCalls(); // std.debug.print("host to client: {}\n", .{std.fmt.fmtSliceHexUpper(input_data)}); // std.debug.print("client to host: {}\n", .{std.fmt.fmtSliceHexUpper(output_stream.items)}); } test "invoke function (emulated client, with self parameter)" { const RcpDefinition = CreateDefinition(.{ .host = .{ .some = fn (a: u32, b: f32, c: []const u8) u32, }, .client = .{}, }); const HostImpl = struct { dummy: u8 = 0, fn some(self: @This(), a: u32, b: f32, c: []const u8) u32 { std.debug.print("some({}, {}, {d}, \"{s}\");\n", .{ self.dummy, a, b, c }); return a + @floatToInt(u32, b); } }; var output_stream = std.ArrayList(u8).init(std.testing.allocator); defer output_stream.deinit(); const input_data = comptime blk: { var buffer: [4096]u8 = undefined; var stream = std.io.fixedBufferStream(&buffer); var writer = stream.writer(); try writer.writeAll(&protocol_magic); try writer.writeByte(current_version); try writer.writeByte(@enumToInt(CommandId.call)); try writer.writeIntLittle(u32, 1337); // first sequence id try writer.writeIntLittle(u32, "some".len); try writer.writeAll("some"); try s2s.serialize(writer, std.meta.Tuple(&.{ u32, f32, []const u8 }), .{ .@"0" = 1334, .@"1" = std.math.pi, .@"2" = "Hello, Host!", }); try writer.writeByte(@enumToInt(CommandId.shutdown)); break :blk stream.getWritten(); }; var input_stream = std.io.fixedBufferStream(@as([]const u8, input_data)); const EndPoint = RcpDefinition.HostEndPoint(std.io.FixedBufferStream([]const u8).Reader, std.ArrayList(u8).Writer, HostImpl); var end_point = EndPoint.init(std.testing.allocator, input_stream.reader(), output_stream.writer()); var impl = HostImpl{ .dummy = 123 }; try end_point.connect(&impl); try end_point.acceptCalls(); // std.debug.print("host to client: {}\n", .{std.fmt.fmtSliceHexUpper(input_data)}); // std.debug.print("client to host: {}\n", .{std.fmt.fmtSliceHexUpper(output_stream.items)}); } test "invoke function with callback (emulated host, no self parameter)" { const RcpDefinition = CreateDefinition(.{ .host = .{ .some = fn (a: u32, b: f32, c: []const u8) void, }, .client = .{ .callback = fn (msg: []const u8) void, }, }); const ClientImpl = struct { pub fn callback(msg: []const u8) void { std.debug.print("callback(\"{s}\");\n", .{msg}); } }; var output_stream = std.ArrayList(u8).init(std.testing.allocator); defer output_stream.deinit(); const input_data = comptime blk: { var buffer: [4096]u8 = undefined; var stream = std.io.fixedBufferStream(&buffer); var writer = stream.writer(); try writer.writeAll(&protocol_magic); try writer.writeByte(current_version); try writer.writeByte(@enumToInt(CommandId.call)); try writer.writeIntLittle(u32, 1337); // first sequence id try writer.writeIntLittle(u32, "callback".len); try writer.writeAll("callback"); try s2s.serialize(writer, std.meta.Tuple(&.{[]const u8}), .{ .@"0" = "Hello, World!", }); try writer.writeByte(@enumToInt(CommandId.response)); try writer.writeIntLittle(u32, 0); // first sequence id try s2s.serialize(writer, InvocationResult(void), invocationResult(void, {})); break :blk stream.getWritten(); }; var input_stream = std.io.fixedBufferStream(@as([]const u8, input_data)); const EndPoint = RcpDefinition.ClientEndPoint(std.io.FixedBufferStream([]const u8).Reader, std.ArrayList(u8).Writer, ClientImpl); var end_point = EndPoint.init(std.testing.allocator, input_stream.reader(), output_stream.writer()); var impl = ClientImpl{}; try end_point.connect(&impl); try end_point.invoke("some", .{ 1, 2, "hello, world!" }); // std.debug.print("host to client: {}\n", .{std.fmt.fmtSliceHexUpper(input_data)}); // // std.debug.print("client to host: {}\n", .{std.fmt.fmtSliceHexUpper(output_stream.items)}); } test "invoke function with callback (emulated host, with self parameter)" { const RcpDefinition = CreateDefinition(.{ .host = .{ .some = fn (a: u32, b: f32, c: []const u8) void, }, .client = .{ .callback = fn (msg: []const u8) void, }, }); const ClientImpl = struct { dummy: u8 = 0, // required to print pointer pub fn callback(self: *@This(), msg: []const u8) void { std.debug.print("callback({*}, \"{s}\");\n", .{ self, msg }); } }; var output_stream = std.ArrayList(u8).init(std.testing.allocator); defer output_stream.deinit(); const input_data = comptime blk: { var buffer: [4096]u8 = undefined; var stream = std.io.fixedBufferStream(&buffer); var writer = stream.writer(); try writer.writeAll(&protocol_magic); try writer.writeByte(current_version); try writer.writeByte(@enumToInt(CommandId.call)); try writer.writeIntLittle(u32, 1337); // first sequence id try writer.writeIntLittle(u32, "callback".len); try writer.writeAll("callback"); try s2s.serialize(writer, std.meta.Tuple(&.{[]const u8}), .{ .@"0" = "Hello, World!", }); try writer.writeByte(@enumToInt(CommandId.response)); try writer.writeIntLittle(u32, 0); // first sequence id try s2s.serialize(writer, InvocationResult(void), invocationResult(void, {})); break :blk stream.getWritten(); }; var input_stream = std.io.fixedBufferStream(@as([]const u8, input_data)); const EndPoint = RcpDefinition.ClientEndPoint(std.io.FixedBufferStream([]const u8).Reader, std.ArrayList(u8).Writer, ClientImpl); var end_point = EndPoint.init(std.testing.allocator, input_stream.reader(), output_stream.writer()); var impl = ClientImpl{}; try end_point.connect(&impl); try end_point.invoke("some", .{ 1, 2, "hello, world!" }); // std.debug.print("host to client: {}\n", .{std.fmt.fmtSliceHexUpper(input_data)}); // std.debug.print("client to host: {}\n", .{std.fmt.fmtSliceHexUpper(output_stream.items)}); }
src/antiphony.zig
const std = @import("std"); const assert = std.debug.assert; pub usingnamespace @import("bits.zig"); comptime { assert(@alignOf(i8) == 1); assert(@alignOf(u8) == 1); assert(@alignOf(i16) == 2); assert(@alignOf(u16) == 2); assert(@alignOf(i32) == 4); assert(@alignOf(u32) == 4); // assert(@alignOf(i64) == 8); // assert(@alignOf(u64) == 8); } pub const iovec_t = iovec; pub const ciovec_t = iovec_const; pub extern "wasi_unstable" fn args_get(argv: [*][*:0]u8, argv_buf: [*]u8) errno_t; pub extern "wasi_unstable" fn args_sizes_get(argc: *usize, argv_buf_size: *usize) errno_t; pub extern "wasi_unstable" fn clock_res_get(clock_id: clockid_t, resolution: *timestamp_t) errno_t; pub extern "wasi_unstable" fn clock_time_get(clock_id: clockid_t, precision: timestamp_t, timestamp: *timestamp_t) errno_t; pub extern "wasi_unstable" fn environ_get(environ: [*]?[*:0]u8, environ_buf: [*]u8) errno_t; pub extern "wasi_unstable" fn environ_sizes_get(environ_count: *usize, environ_buf_size: *usize) errno_t; pub extern "wasi_unstable" fn fd_advise(fd: fd_t, offset: filesize_t, len: filesize_t, advice: advice_t) errno_t; pub extern "wasi_unstable" fn fd_allocate(fd: fd_t, offset: filesize_t, len: filesize_t) errno_t; pub extern "wasi_unstable" fn fd_close(fd: fd_t) errno_t; pub extern "wasi_unstable" fn fd_datasync(fd: fd_t) errno_t; pub extern "wasi_unstable" fn fd_pread(fd: fd_t, iovs: [*]const iovec_t, iovs_len: usize, offset: filesize_t, nread: *usize) errno_t; pub extern "wasi_unstable" fn fd_pwrite(fd: fd_t, iovs: [*]const ciovec_t, iovs_len: usize, offset: filesize_t, nwritten: *usize) errno_t; pub extern "wasi_unstable" fn fd_read(fd: fd_t, iovs: [*]const iovec_t, iovs_len: usize, nread: *usize) errno_t; pub extern "wasi_unstable" fn fd_readdir(fd: fd_t, buf: [*]u8, buf_len: usize, cookie: dircookie_t, bufused: *usize) errno_t; pub extern "wasi_unstable" fn fd_renumber(from: fd_t, to: fd_t) errno_t; pub extern "wasi_unstable" fn fd_seek(fd: fd_t, offset: filedelta_t, whence: whence_t, newoffset: *filesize_t) errno_t; pub extern "wasi_unstable" fn fd_sync(fd: fd_t) errno_t; pub extern "wasi_unstable" fn fd_tell(fd: fd_t, newoffset: *filesize_t) errno_t; pub extern "wasi_unstable" fn fd_write(fd: fd_t, iovs: [*]const ciovec_t, iovs_len: usize, nwritten: *usize) errno_t; pub extern "wasi_unstable" fn fd_fdstat_get(fd: fd_t, buf: *fdstat_t) errno_t; pub extern "wasi_unstable" fn fd_fdstat_set_flags(fd: fd_t, flags: fdflags_t) errno_t; pub extern "wasi_unstable" fn fd_fdstat_set_rights(fd: fd_t, fs_rights_base: rights_t, fs_rights_inheriting: rights_t) errno_t; pub extern "wasi_unstable" fn fd_filestat_get(fd: fd_t, buf: *filestat_t) errno_t; pub extern "wasi_unstable" fn fd_filestat_set_size(fd: fd_t, st_size: filesize_t) errno_t; pub extern "wasi_unstable" fn fd_filestat_set_times(fd: fd_t, st_atim: timestamp_t, st_mtim: timestamp_t, fstflags: fstflags_t) errno_t; pub extern "wasi_unstable" fn fd_prestat_get(fd: fd_t, buf: *prestat_t) errno_t; pub extern "wasi_unstable" fn fd_prestat_dir_name(fd: fd_t, path: [*]u8, path_len: usize) errno_t; pub extern "wasi_unstable" fn path_create_directory(fd: fd_t, path: [*]const u8, path_len: usize) errno_t; pub extern "wasi_unstable" fn path_filestat_get(fd: fd_t, flags: lookupflags_t, path: [*]const u8, path_len: usize, buf: *filestat_t) errno_t; pub extern "wasi_unstable" fn path_filestat_set_times(fd: fd_t, flags: lookupflags_t, path: [*]const u8, path_len: usize, st_atim: timestamp_t, st_mtim: timestamp_t, fstflags: fstflags_t) errno_t; pub extern "wasi_unstable" fn path_link(old_fd: fd_t, old_flags: lookupflags_t, old_path: [*]const u8, old_path_len: usize, new_fd: fd_t, new_path: [*]const u8, new_path_len: usize) errno_t; pub extern "wasi_unstable" fn path_open(dirfd: fd_t, dirflags: lookupflags_t, path: [*]const u8, path_len: usize, oflags: oflags_t, fs_rights_base: rights_t, fs_rights_inheriting: rights_t, fs_flags: fdflags_t, fd: *fd_t) errno_t; pub extern "wasi_unstable" fn path_readlink(fd: fd_t, path: [*]const u8, path_len: usize, buf: [*]u8, buf_len: usize, bufused: *usize) errno_t; pub extern "wasi_unstable" fn path_remove_directory(fd: fd_t, path: [*]const u8, path_len: usize) errno_t; pub extern "wasi_unstable" fn path_rename(old_fd: fd_t, old_path: [*]const u8, old_path_len: usize, new_fd: fd_t, new_path: [*]const u8, new_path_len: usize) errno_t; pub extern "wasi_unstable" fn path_symlink(old_path: [*]const u8, old_path_len: usize, fd: fd_t, new_path: [*]const u8, new_path_len: usize) errno_t; pub extern "wasi_unstable" fn path_unlink_file(fd: fd_t, path: [*]const u8, path_len: usize) errno_t; pub extern "wasi_unstable" fn poll_oneoff(in: *const subscription_t, out: *event_t, nsubscriptions: usize, nevents: *usize) errno_t; pub extern "wasi_unstable" fn proc_exit(rval: exitcode_t) noreturn; pub extern "wasi_unstable" fn proc_raise(sig: signal_t) errno_t; pub extern "wasi_unstable" fn random_get(buf: [*]u8, buf_len: usize) errno_t; pub extern "wasi_unstable" fn sched_yield() errno_t; pub extern "wasi_unstable" fn sock_recv(sock: fd_t, ri_data: *const iovec_t, ri_data_len: usize, ri_flags: riflags_t, ro_datalen: *usize, ro_flags: *roflags_t) errno_t; pub extern "wasi_unstable" fn sock_send(sock: fd_t, si_data: *const ciovec_t, si_data_len: usize, si_flags: siflags_t, so_datalen: *usize) errno_t; pub extern "wasi_unstable" fn sock_shutdown(sock: fd_t, how: sdflags_t) errno_t; /// Get the errno from a syscall return value, or 0 for no error. pub fn getErrno(r: errno_t) usize { return r; }
lib/std/os/wasi.zig
const std = @import("std"); const arm_m = @import("arm_m"); const timer = @import("ports/" ++ @import("build_options").BOARD ++ "/timer.zig").timer0; const tzmcfi = @cImport(@cInclude("TZmCFI/Gateway.h")); const warn = @import("nonsecure-common/debug.zig").warn; const port = @import("ports/" ++ @import("build_options").BOARD ++ "/nonsecure.zig"); const nonsecure_init = @import("nonsecure-common/init.zig"); const gateways = @import("common/gateways.zig"); // FreeRTOS-related thingy const os = @cImport({ @cInclude("FreeRTOS.h"); @cInclude("task.h"); @cInclude("timers.h"); @cInclude("semphr.h"); }); comptime { _ = @import("nonsecure-common/oshooks.zig"); } // The (unprocessed) Non-Secure exception vector table. export const raw_exception_vectors linksection(".text.raw_isr_vector") = @import("nonsecure-common/excvector.zig").getDefaultFreertos(); // The entry point. The reset handler transfers the control to this function // after initializing data sections. export fn main() void { port.init(); nonsecure_init.disableNestedExceptionIfDisallowed(); warn("%output-start\r\n", .{}); warn("[\r\n", .{}); seqmon.mark(0); global_mutex1.* = xSemaphoreCreateBinary(); global_mutex2.* = xSemaphoreCreateBinary(); _ = xSemaphoreGive(global_mutex1.*); _ = os.xTaskCreateRestricted(&task1_params, 0); os.vTaskStartScheduler(); unreachable; } var task1_stack align(32) = [1]u32{0} ** 192; const regions_with_peripheral_access = [3]os.MemoryRegion_t{ // TODO: It seems that this is actually not needed for measurements to work. // Investigate why os.MemoryRegion_t{ .pvBaseAddress = @intToPtr(*c_void, 0x40000000), .ulLengthInBytes = 0x10000000, .ulParameters = 0, }, os.MemoryRegion_t{ .pvBaseAddress = @ptrCast(*c_void, &unpriv_state), .ulLengthInBytes = @sizeOf(@TypeOf(unpriv_state)) + 32, .ulParameters = 0, }, os.MemoryRegion_t{ .pvBaseAddress = null, .ulLengthInBytes = 0, .ulParameters = 0, }, }; const task1_params = os.TaskParameters_t{ .pvTaskCode = task1Main, .pcName = "task1", .usStackDepth = task1_stack.len, .pvParameters = null, .uxPriority = 2 | os.portPRIVILEGE_BIT, .puxStackBuffer = &task1_stack, .xRegions = regions_with_peripheral_access, .pxTaskBuffer = null, }; var task2_stack align(32) = [1]u32{0} ** 192; const task2b_params = os.TaskParameters_t{ .pvTaskCode = task2bMain, .pcName = "task2b", .usStackDepth = task2_stack.len, .pvParameters = null, .uxPriority = 4, // > task1 .puxStackBuffer = &task2_stack, .xRegions = regions_with_peripheral_access, .pxTaskBuffer = null, }; const global_mutex1 = &unpriv_state.global_mutex1; const global_mutex2 = &unpriv_state.global_mutex2; fn task1Main(_arg: ?*c_void) callconv(.C) void { // Disable SysTick arm_m.sys_tick.regCsr().* = 0; // Make us unprivileged os.vResetPrivilege(); // Create a high-priority task `task2b` to be dispatched on `xSemaphoreGive` var task2_handle: os.TaskHandle_t = undefined; _ = os.xTaskCreateRestricted(&task2b_params, &task2_handle); // ----------------------------------------------------------------------- var sample_time: u32 = 1; while (sample_time < 10000) : (sample_time += 1) { // Sample the program counter after `i` cycles _ = gateways.scheduleSamplePc(@as(usize, sample_time), 0, 0, 0); unpriv_state.next_ordinal = 2; seqmon.mark(2); // `xSemaphoreTake` without dispatch _ = xSemaphoreTake(global_mutex1.*, portMAX_DELAY); // `xSemaphoreGive` with dispatch _ = xSemaphoreGive(global_mutex2.*); seqmon.mark(5); // Get the sampled PC const sampled_pc = gateways.getSampledPc(0, 0, 0, 0); if (sampled_pc == 0) { // PC hasn't been sampled yet; `i` is too large. Break the loop. break; } // Output in the JSON5 format warn(" {{ \"cycles\": {}, \"pc\": {}, \"pc_hex\": \"0x{x}\" }},\r\n", .{ sample_time, sampled_pc, sampled_pc }); } warn("]\r\n", .{}); warn("%output-end\r\n", .{}); warn("Done!\r\n", .{}); while (true) {} } fn task2bMain(_arg: ?*c_void) callconv(.C) void { seqmon.mark(1); // This will block and gives the control back to task1 _ = xSemaphoreTake(global_mutex2.*, portMAX_DELAY); while (true) { seqmon.mark(3); _ = xSemaphoreGive(global_mutex1.*); seqmon.mark(4); // This will block and gives the control back to task1 _ = xSemaphoreTake(global_mutex2.*, portMAX_DELAY); } unreachable; } /// unprivilileged state data var unpriv_state align(32) = struct { next_ordinal: u32 = 0, global_mutex1: os.SemaphoreHandle_t = undefined, global_mutex2: os.SemaphoreHandle_t = undefined, }{}; /// Execution sequence monitoring const seqmon = struct { const next_ordinal = &unpriv_state.next_ordinal; /// Declare a checkpoint. `ordinal` is a sequence number that starts at /// `0`. Aborts the execution on a sequence violation. fn mark(ordinal: u32) void { if (ordinal != next_ordinal.*) { warn("execution sequence violation: expected {}, got {}\r\n", .{ ordinal, next_ordinal.* }); @panic("execution sequence violation"); } next_ordinal.* += 1; } }; // FreeRTOS wrapper const queueQUEUE_TYPE_MUTEX = 1; const queueQUEUE_TYPE_BINARY_SEMAPHORE = 3; const semGIVE_BLOCK_TIME = 0; const semSEMAPHORE_QUEUE_ITEM_LENGTH = 0; const portMAX_DELAY = 0xffffffff; fn xSemaphoreCreateBinary() os.SemaphoreHandle_t { return os.xQueueGenericCreate(1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE); } const xSemaphoreTake = os.xQueueSemaphoreTake; fn xSemaphoreGive(semaphore: os.SemaphoreHandle_t) @TypeOf(os.xQueueGenericSend).ReturnType { return os.xQueueGenericSend(semaphore, null, semGIVE_BLOCK_TIME, os.queueSEND_TO_BACK); } // Zig panic handler. See `panicking.zig` for details. const panicking = @import("nonsecure-common/panicking.zig"); pub fn panic(msg: []const u8, error_return_trace: ?*panicking.StackTrace) noreturn { panicking.panic(msg, error_return_trace); }
examples/nonsecure-profile-rtos.zig
const format = @import("std").fmt.format; const OutStream = @import("std").io.OutStream; const arm_m = @import("arm_m"); const arm_cmse = @import("arm_cmse"); const an505 = @import("../../drivers/an505.zig"); pub const VTOR_NS = 0x00200000; extern var __nsc_start: usize; extern var __nsc_end: usize; /// Perform the board-specific initialization. pub fn init() void { // :( <https://github.com/ziglang/zig/issues/504> an505.uart0_s.configure(25e6, 115200); // Configure SAU // ----------------------------------------------------------------------- const Region = arm_cmse.SauRegion; // AN505 ZBT SRAM (SSRAM1) Non-Secure alias arm_cmse.sau.setRegion(0, Region{ .start = 0x00200000, .end = 0x00400000 }); // AN505 ZBT SRAM (SSRAM3) Non-Secure alias arm_cmse.sau.setRegion(1, Region{ .start = 0x28200000, .end = 0x28400000 }); // The Non-Secure callable region arm_cmse.sau.setRegion(2, Region{ .start = @ptrToInt(&__nsc_start), .end = @ptrToInt(&__nsc_end), .nsc = true, }); // Peripherals arm_cmse.sau.setRegion(3, Region{ .start = 0x40000000, .end = 0x50000000 }); // Configure MPCs and IDAU // ----------------------------------------------------------------------- // Enable Non-Secure access to SSRAM1 (`0x[01]0200000`) // for the range `[0x200000, 0x3fffff]`. an505.ssram1_mpc.setEnableBusError(true); an505.ssram1_mpc.assignRangeToNonSecure(0x200000, 0x400000); // Enable Non-Secure access to SSRAM3 (`0x[23]8200000`) // for the range `[0, 0x1fffff]`. // - It seems that the range SSRAM3's MPC encompasses actually starts at // `0x[23]8000000`. // - We actually use only the first `0x4000` bytes. However the hardware // block size is larger than that and the rounding behavior of // `tz_mpc.zig` is unspecified, so specify the larger range. an505.ssram3_mpc.setEnableBusError(true); an505.ssram3_mpc.assignRangeToNonSecure(0x200000, 0x400000); // Configure IDAU to enable Non-Secure Callable regions // for the code memory `[0x10000000, 0x1dffffff]` an505.spcb.regNsccfg().* |= an505.Spcb.NSCCFG_CODENSC; // Allow non-Secure unprivileged access to the timers // ----------------------------------------------------------------------- arm_m.nvic.targetIrqToNonSecure(an505.irqs.Timer0_IRQn - 16); arm_m.nvic.targetIrqToNonSecure(an505.irqs.Timer1_IRQn - 16); arm_m.nvic.targetIrqToNonSecure(an505.irqs.DualTimer_IRQn - 16); an505.spcb.setPpcAccess(an505.ppc.timer0_, .NonSecure, true); an505.spcb.setPpcAccess(an505.ppc.timer1_, .NonSecure, true); an505.spcb.setPpcAccess(an505.ppc.dual_timer_, .NonSecure, true); an505.nspcb.setPpcAccess(an505.ppc.timer0_, true); an505.nspcb.setPpcAccess(an505.ppc.timer1_, true); an505.nspcb.setPpcAccess(an505.ppc.dual_timer_, true); } /// Render the format string `fmt` with `args` and transmit the output. pub fn print(comptime fmt: []const u8, args: var) void { const out_stream = OutStream(void, error{}, printInner){ .context = {} }; format(out_stream, fmt, args) catch unreachable; } fn printInner(ctx: void, data: []const u8) error{}!usize { an505.uart0_s.writeSlice(data); return data.len; } pub fn printByte(b: u8) void { an505.uart0_s.write(b); }
examples/ports/an505/secure.zig
const std = @import("../../std.zig"); const iovec = std.os.iovec; const iovec_const = std.os.iovec_const; const linux = std.os.linux; const SYS = linux.SYS; const uid_t = std.os.linux.uid_t; const gid_t = std.os.linux.gid_t; const pid_t = std.os.linux.pid_t; const sockaddr = linux.sockaddr; const socklen_t = linux.socklen_t; const timespec = std.os.linux.timespec; pub fn syscall0(number: SYS) usize { return asm volatile ("ecall" : [ret] "={x10}" (-> usize), : [number] "{x17}" (@enumToInt(number)), : "memory" ); } pub fn syscall1(number: SYS, arg1: usize) usize { return asm volatile ("ecall" : [ret] "={x10}" (-> usize), : [number] "{x17}" (@enumToInt(number)), [arg1] "{x10}" (arg1), : "memory" ); } pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize { return asm volatile ("ecall" : [ret] "={x10}" (-> usize), : [number] "{x17}" (@enumToInt(number)), [arg1] "{x10}" (arg1), [arg2] "{x11}" (arg2), : "memory" ); } pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("ecall" : [ret] "={x10}" (-> usize), : [number] "{x17}" (@enumToInt(number)), [arg1] "{x10}" (arg1), [arg2] "{x11}" (arg2), [arg3] "{x12}" (arg3), : "memory" ); } pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ("ecall" : [ret] "={x10}" (-> usize), : [number] "{x17}" (@enumToInt(number)), [arg1] "{x10}" (arg1), [arg2] "{x11}" (arg2), [arg3] "{x12}" (arg3), [arg4] "{x13}" (arg4), : "memory" ); } pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { return asm volatile ("ecall" : [ret] "={x10}" (-> usize), : [number] "{x17}" (@enumToInt(number)), [arg1] "{x10}" (arg1), [arg2] "{x11}" (arg2), [arg3] "{x12}" (arg3), [arg4] "{x13}" (arg4), [arg5] "{x14}" (arg5), : "memory" ); } pub fn syscall6( number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize, arg6: usize, ) usize { return asm volatile ("ecall" : [ret] "={x10}" (-> usize), : [number] "{x17}" (@enumToInt(number)), [arg1] "{x10}" (arg1), [arg2] "{x11}" (arg2), [arg3] "{x12}" (arg3), [arg4] "{x13}" (arg4), [arg5] "{x14}" (arg5), [arg6] "{x15}" (arg6), : "memory" ); } pub extern fn clone(func: fn (arg: usize) callconv(.C) u8, stack: usize, flags: u32, arg: usize, ptid: *i32, tls: usize, ctid: *i32) usize; pub const restore = restore_rt; pub fn restore_rt() callconv(.Naked) void { return asm volatile ("ecall" : : [number] "{x17}" (@enumToInt(SYS.rt_sigreturn)), : "memory" ); } pub const O = struct { pub const CREAT = 0o100; pub const EXCL = 0o200; pub const NOCTTY = 0o400; pub const TRUNC = 0o1000; pub const APPEND = 0o2000; pub const NONBLOCK = 0o4000; pub const DSYNC = 0o10000; pub const SYNC = 0o4010000; pub const RSYNC = 0o4010000; pub const DIRECTORY = 0o200000; pub const NOFOLLOW = 0o400000; pub const CLOEXEC = 0o2000000; pub const ASYNC = 0o20000; pub const DIRECT = 0o40000; pub const LARGEFILE = 0o100000; pub const NOATIME = 0o1000000; pub const PATH = 0o10000000; pub const TMPFILE = 0o20200000; pub const NDELAY = NONBLOCK; }; pub const F = struct { pub const DUPFD = 0; pub const GETFD = 1; pub const SETFD = 2; pub const GETFL = 3; pub const SETFL = 4; pub const GETLK = 5; pub const SETLK = 6; pub const SETLKW = 7; pub const SETOWN = 8; pub const GETOWN = 9; pub const SETSIG = 10; pub const GETSIG = 11; pub const RDLCK = 0; pub const WRLCK = 1; pub const UNLCK = 2; pub const SETOWN_EX = 15; pub const GETOWN_EX = 16; pub const GETOWNER_UIDS = 17; }; pub const LOCK = struct { pub const SH = 1; pub const EX = 2; pub const UN = 8; pub const NB = 4; }; pub const blksize_t = i32; pub const nlink_t = u32; pub const time_t = isize; pub const mode_t = u32; pub const off_t = isize; pub const ino_t = usize; pub const dev_t = usize; pub const blkcnt_t = isize; pub const timeval = extern struct { tv_sec: time_t, tv_usec: i64, }; pub const Flock = extern struct { type: i16, whence: i16, start: off_t, len: off_t, pid: pid_t, __unused: [4]u8, }; pub const msghdr = extern struct { name: ?*sockaddr, namelen: socklen_t, iov: [*]iovec, iovlen: i32, __pad1: i32 = 0, control: ?*anyopaque, controllen: socklen_t, __pad2: socklen_t = 0, flags: i32, }; pub const msghdr_const = extern struct { name: ?*const sockaddr, namelen: socklen_t, iov: [*]const iovec_const, iovlen: i32, __pad1: i32 = 0, control: ?*const anyopaque, controllen: socklen_t, __pad2: socklen_t = 0, flags: i32, }; // The `stat` definition used by the Linux kernel. pub const Stat = extern struct { dev: dev_t, ino: ino_t, mode: mode_t, nlink: nlink_t, uid: uid_t, gid: gid_t, rdev: dev_t, __pad: usize, size: off_t, blksize: blksize_t, __pad2: i32, blocks: blkcnt_t, atim: timespec, mtim: timespec, ctim: timespec, __unused: [2]u32, pub fn atime(self: @This()) timespec { return self.atim; } pub fn mtime(self: @This()) timespec { return self.mtim; } pub fn ctime(self: @This()) timespec { return self.ctim; } }; pub const Elf_Symndx = u32; pub const VDSO = struct {}; pub const MAP = struct {};
lib/std/os/linux/riscv64.zig
const std = @import("std"); const net = std.net; const Allocator = std.mem.Allocator; /// HTTP Status codes according to `rfc7231` /// https://tools.ietf.org/html/rfc7231#section-6 pub const StatusCode = enum(u16) { // Informational 1xx @"continue" = 100, // Successful 2xx switching_protocols = 101, ok = 200, created = 201, accepted = 202, non_authoritative_information = 203, no_content = 204, reset_content = 205, // redirections 3xx partial_content = 206, multiple_choices = 300, moved_permanently = 301, found = 302, see_other = 303, not_modified = 304, use_proxy = 305, temporary_redirect = 307, // client errors 4xx bad_request = 400, unauthorized = 401, payment_required = 402, forbidden = 403, not_found = 404, method_not_allowed = 405, not_acceptable = 406, proxy_authentication_required = 407, request_timeout = 408, conflict = 409, gone = 410, length_required = 411, precondition_failed = 412, request_entity_too_large = 413, request_uri_too_long = 414, unsupported_mediatype = 415, requested_range_not_satisfiable = 416, expectation_failed = 417, /// teapot is an extension status code and not required for clients to support teapot = 418, upgrade_required = 426, /// extra status code according to `https://tools.ietf.org/html/rfc6585#section-5` request_header_fields_too_large = 431, // server errors 5xx internal_server_error = 500, not_implemented = 501, bad_gateway = 502, service_unavailable = 503, gateway_timeout = 504, http_version_not_supported = 505, _, /// Returns the string value of a `StatusCode` /// for example: .ResetContent returns "Returns Content". pub fn toString(self: StatusCode) []const u8 { return switch (self) { .@"continue" => "Continue", .switching_protocols => "Switching Protocols", .ok => "Ok", .created => "Created", .accepted => "Accepted", .non_authoritative_information => "Non Authoritative Information", .no_content => "No Content", .reset_content => "Reset Content", .partial_content => "Partial Content", .multiple_choices => "Multiple Choices", .moved_permanently => "Moved Permanently", .found => "Found", .see_other => "See Other", .not_modified => "Not Modified", .use_proxy => "Use Proxy", .temporary_redirect => "Temporary Redirect", .bad_request => "Bad Request", .unauthorized => "Unauthorized", .payment_required => "Payment Required", .forbidden => "Forbidden", .not_found => "Not Found", .method_not_allowed => "Method Not Allowed", .not_acceptable => "Not Acceptable", .proxy_authentication_required => "Proxy Authentication Required", .request_timeout => "Request Timeout", .conflict => "Conflict", .gone => "Gone", .length_required => "Length Required", .precondition_failed => "Precondition Failed", .request_entity_too_large => "Request Entity Too Large", .request_uri_too_long => "Request-URI Too Long", .unsupported_mediatype => "Unsupported Media Type", .requested_range_not_satisfiable => "Requested Range Not Satisfiable", .teapot => "I'm a Teapot", .upgrade_required => "Upgrade Required", .request_header_fields_too_large => "Request Header Fields Too Large", .expectation_failed => "Expectation Failed", .internal_server_error => "Internal Server Error", .not_implemented => "Not Implemented", .bad_gateway => "Bad Gateway", .service_unavailable => "Service Unavailable", .gateway_timeout => "Gateway Timeout", .http_version_not_supported => "HTTP Version Not Supported", _ => "", }; } }; /// Headers is an alias to `std.StringHashMap([]const u8)` pub const Headers = std.StringArrayHashMap([]const u8); /// Response allows to set the status code and content of the response pub const Response = struct { /// status code of the response, 200 by default status_code: StatusCode = .ok, /// StringHashMap([]const u8) with key and value of headers headers: Headers, /// Buffered writer that writes to our socket buffered_writer: std.io.BufferedWriter(4096, net.Stream.Writer), /// True when write() has been called is_flushed: bool, /// Response body, can be written to through the writer interface body: std.ArrayList(u8).Writer, pub const Error = net.Stream.WriteError || error{OutOfMemory}; pub const Writer = std.io.Writer(*Response, Error, write); /// Returns a writer interface, any data written to the writer /// will be appended to the response's body pub fn writer(self: *Response) Writer { return .{ .context = self }; } /// Appends the buffer to the body of the response fn write(self: *Response, buffer: []const u8) Error!usize { return self.body.write(buffer); } /// Sends a status code with an empty body and the current headers to the client /// Note that this will complete the response and any further writes are illegal. pub fn writeHeader(self: *Response, status_code: StatusCode) Error!void { self.status_code = status_code; try self.body.print("{s}", .{self.status_code.toString()}); try self.flush(); } /// Sends the response to the client, can only be called once /// Any further calls is a panic pub fn flush(self: *Response) Error!void { std.debug.assert(!self.is_flushed); self.is_flushed = true; const body = self.body.context.items; var socket = self.buffered_writer.writer(); // Print the status line, we only support HTTP/1.1 for now try socket.print("HTTP/1.1 {d} {s}\r\n", .{ @enumToInt(self.status_code), self.status_code.toString() }); // write headers for (self.headers.items()) |header| { try socket.print("{s}: {s}\r\n", .{ header.key, header.value }); } // If user has not set content-length, we add it calculated by the length of the body if (body.len > 0 and !self.headers.contains("Content-Length")) { try socket.print("Content-Length: {d}\r\n", .{body.len}); } // set default Content-Type. // Adding headers is expensive so add it as default when we write to the socket if (!self.headers.contains("Content-Type")) { try socket.writeAll("Content-Type: text/plain; charset=utf-8\r\n"); } try socket.writeAll("Connection: keep-alive\r\n"); try socket.writeAll("\r\n"); if (body.len > 0) try socket.writeAll(body); try self.buffered_writer.flush(); // ensure everything is written } /// Sends a `404 - Resource not found` response pub fn notFound(self: *Response) Error!void { self.status_code = .not_found; try self.body.writeAll("Resource not found\n"); } };
src/response.zig
const std = @import("std"); pub const pkg = std.build.Pkg{ .name = "zenet", .path = .{ .path = thisDir() ++ "/src/zenet.zig" }, }; pub fn build(b: *std.build.Builder) void { const build_mode = b.standardReleaseOptions(); const target = b.standardTargetOptions(.{}); const tests = buildTests(b, build_mode, target); const test_step = b.step("test", "Run zenet tests"); test_step.dependOn(&tests.step); } pub fn buildTests( b: *std.build.Builder, build_mode: std.builtin.Mode, target: std.zig.CrossTarget, ) *std.build.LibExeObjStep { const tests = b.addTest(comptime thisDir() ++ "/src/zenet.zig"); tests.setBuildMode(build_mode); tests.setTarget(target); link(tests); return tests; } fn buildLibrary(exe: *std.build.LibExeObjStep) *std.build.LibExeObjStep { const lib = exe.builder.addStaticLibrary("zenet", comptime thisDir() ++ "/src/zenet.zig"); lib.setBuildMode(exe.build_mode); lib.setTarget(exe.target); lib.want_lto = false; lib.addIncludeDir(comptime thisDir() ++ "/libs/enet/include"); lib.linkSystemLibrary("c"); if (exe.target.isWindows()) { lib.linkSystemLibrary("ws2_32"); lib.linkSystemLibrary("winmm"); } const defines = .{ "-DHAS_FCNTL=1", "-DHAS_POLL=1", "-DHAS_GETNAMEINFO=1", "-DHAS_GETADDRINFO=1", "-DHAS_GETHOSTBYNAME_R=1", "-DHAS_GETHOSTBYADDR_R=1", "-DHAS_INET_PTON=1", "-DHAS_INET_NTOP=1", "-DHAS_MSGHDR_FLAGS=1", "-DHAS_SOCKLEN_T=1", "-fno-sanitize=undefined", }; lib.addCSourceFile(comptime thisDir() ++ "/libs/enet/callbacks.c", &defines); lib.addCSourceFile(comptime thisDir() ++ "/libs/enet/compress.c", &defines); lib.addCSourceFile(comptime thisDir() ++ "/libs/enet/host.c", &defines); lib.addCSourceFile(comptime thisDir() ++ "/libs/enet/list.c", &defines); lib.addCSourceFile(comptime thisDir() ++ "/libs/enet/packet.c", &defines); lib.addCSourceFile(comptime thisDir() ++ "/libs/enet/peer.c", &defines); lib.addCSourceFile(comptime thisDir() ++ "/libs/enet/protocol.c", &defines); lib.addCSourceFile(comptime thisDir() ++ "/libs/enet/unix.c", &defines); lib.addCSourceFile(comptime thisDir() ++ "/libs/enet/win32.c", &defines); return lib; } pub fn link(exe: *std.build.LibExeObjStep) void { const lib = buildLibrary(exe); exe.linkLibrary(lib); } fn thisDir() []const u8 { return std.fs.path.dirname(@src().file) orelse "."; }
libs/zenet/build.zig
const std = @import("std"); const helper = @import("helper.zig"); const Allocator = std.mem.Allocator; const HashMap = std.AutoHashMap; const input = @embedFile("../inputs/day23.txt"); pub fn run(alloc: Allocator, stdout_: anytype) !void { const start2: State(2) = State(2).parse(input); const res1 = try findDist(2, alloc, start2, final_state2); const rooms2 = start2.rooms; const start4: State(4) = .{ .hallway = start2.hallway, .rooms = .{ .{ rooms2[0][0], .desert, .desert, rooms2[0][1] }, .{ rooms2[1][0], .copper, .bronze, rooms2[1][1] }, .{ rooms2[2][0], .bronze, .amber, rooms2[2][1] }, .{ rooms2[3][0], .amber, .copper, rooms2[3][1] }, }, }; const res2 = try findDist(4, alloc, start4, final_state4); if (stdout_) |stdout| { try stdout.print("Part 1: {}\n", .{res1}); try stdout.print("Part 2: {}\n", .{res2}); } } const Amphipod = enum { amber, bronze, copper, desert, const Self = @This(); pub fn roomnum(self: Self) u2 { return switch (self) { .amber => 0, .bronze => 1, .copper => 2, .desert => 3, }; } pub fn multiplier(self: Self) i32 { return switch (self) { .amber => 1, .bronze => 10, .copper => 100, .desert => 1000, }; } pub fn fromLetter(ch: u8) ?Self { return switch (ch) { 'A' => .amber, 'B' => .bronze, 'C' => .copper, 'D' => .desert, else => null, }; } pub fn getLetter(self: Self) u8 { return switch (self) { .amber => 'A', .bronze => 'B', .copper => 'C', .desert => 'D', }; } }; fn aeq(a1: ?Amphipod, a2: ?Amphipod) bool { if (a1 == null and a2 != null) return false; if (a1 != null and a2 == null) return false; if (a1 == null and a2 == null) return true; return a1.? == a2.?; } fn State(comptime roomsize: comptime_int) type { return struct { hallway: [11]?Amphipod, rooms: [4][roomsize]?Amphipod, // room[0] is closer to the hallway const Self = @This(); pub fn parse(inp: []const u8) Self { var tokens = tokenize(u8, inp, "# \r\n."); var rooms: [4][roomsize]?Amphipod = undefined; var i: usize = 0; var j: usize = 0; while (tokens.next()) |token| { rooms[i][j] = Amphipod.fromLetter(token[0]).?; i += 1; if (i >= rooms.len) { i = 0; j += 1; } } return Self{ .hallway = .{null} ** 11, .rooms = rooms, }; } pub fn neighbors(self: Self) NeighborIterator { return .{ .outer = self }; } pub fn eq(self: Self, other: Self) bool { for (self.hallway) |amph, i| { if (!aeq(amph, other.hallway[i])) return false; } for (self.rooms) |room, i| { for (room) |amph, j| { if (!aeq(amph, other.rooms[i][j])) return false; } } return true; } const NeighborIterator = struct { outer: Self, iter_state: IteratorState = .hallway, idx: usize = 0, had_room_insertion: bool = false, const IteratorState = union(enum) { hallway, room: u2, done }; const StateCost = struct { state: Self, cost: i32 }; pub fn next(self: *@This()) ?StateCost { while (true) : (self.advanceState()) { switch (self.iter_state) { .done => return null, .hallway => if (self.nextHallway()) |state| return state, .room => |roomnum| if (self.nextRoom(roomnum)) |state| return state, } } } fn nextHallway(self: *@This()) ?StateCost { const hallway = self.outer.hallway; if (self.idx >= hallway.len) return null; const amphi = hallway[self.idx] orelse return null; const roomnum = amphi.roomnum(); const roomidx = idxOfRoom(roomnum); if (!self.routeEmpty(self.idx, roomidx)) return null; if (self.hasForeignAmphipods(roomnum)) return null; const vacant = self.getVacantIdx(roomnum) orelse return null; const routelen = routeLen(self.idx, roomidx); var new_state = self.outer; new_state.hallway[self.idx] = null; new_state.rooms[@intCast(usize, roomnum)][vacant] = amphi; self.had_room_insertion = true; self.advanceState(); return StateCost{ .state = new_state, .cost = (@intCast(i32, vacant) + 1 + routelen) * amphi.multiplier(), }; } fn nextRoom(self: *@This(), roomnum: u2) ?StateCost { const hallway = self.outer.hallway; if (self.idx >= hallway.len or hallway[self.idx] != null) return null; if (self.isPartiallySolved(roomnum)) return null; const outermost = self.getOutermostIdx(roomnum) orelse return null; const roomusize = @intCast(usize, roomnum); const amphi = self.outer.rooms[roomusize][outermost].?; const roomidx = idxOfRoom(roomnum); if (!self.routeEmpty(roomidx, self.idx)) return null; const routelen = routeLen(roomidx, self.idx); var new_state = self.outer; new_state.hallway[self.idx] = amphi; new_state.rooms[roomusize][outermost] = null; self.advanceState(); return StateCost{ .state = new_state, .cost = (@intCast(i32, outermost) + 1 + routelen) * amphi.multiplier(), }; } fn routeEmpty(self: @This(), start: usize, finish: usize) bool { const hallway = self.outer.hallway; if (hallway[finish] != null) return false; const min = std.math.min(start, finish); const max = std.math.max(start, finish); var i: usize = min + 1; while (i < max) : (i += 1) { if (hallway[i] != null) return false; } return true; } fn hasForeignAmphipods(self: @This(), roomnum: u2) bool { const room = self.outer.rooms[@intCast(usize, roomnum)]; for (room) |amphin| { const amphi = amphin orelse continue; if (amphi.roomnum() != roomnum) return true; } return false; } fn getVacantIdx(self: @This(), roomnum: u2) ?usize { const room = self.outer.rooms[@intCast(usize, roomnum)]; var i: usize = 0; while (i < room.len) : (i += 1) { if (room[room.len - i - 1] == null) return room.len - i - 1; } return null; } fn getOutermostIdx(self: @This(), roomnum: u2) ?usize { const room = self.outer.rooms[@intCast(usize, roomnum)]; var i: usize = 0; while (i < room.len) : (i += 1) { if (room[i] != null) return i; } return null; } fn routeLen(idx1: usize, idx2: usize) i32 { const x1 = @intCast(i32, idx1); const x2 = @intCast(i32, idx2); return std.math.absInt(x1 - x2) catch unreachable; } fn isPartiallySolved(self: @This(), roomnum: u2) bool { const room = self.outer.rooms[@intCast(usize, roomnum)]; for (room) |amphin| { const amphi = amphin orelse continue; if (amphi.roomnum() != roomnum) return false; } return true; } fn advanceState(self: *@This()) void { switch (self.iter_state) { .done => unreachable, .hallway => self.advanceHallway(), .room => |roomnum| self.advanceRoom(roomnum), } } fn advanceHallway(self: *@This()) void { const hallway = self.outer.hallway; self.idx += 1; while (self.idx < hallway.len and hallway[self.idx] == null) { self.idx += 1; } if (self.idx >= hallway.len) { if (self.had_room_insertion) { self.iter_state = .done; } else { self.iter_state = .{ .room = 0 }; self.makeIdxFirstAvailableForRoom(); } } } fn advanceRoom(self: *@This(), roomnum: u2) void { const hallway = self.outer.hallway; self.idx += 1; if (inFrontOfRoom(self.idx)) self.idx += 1; if (self.idx >= hallway.len or hallway[self.idx] != null) { if (roomnum == 3) { self.iter_state = .done; } else { self.iter_state = .{ .room = roomnum + 1 }; self.makeIdxFirstAvailableForRoom(); } } } fn makeIdxFirstAvailableForRoom(self: *@This()) void { const hallway = self.outer.hallway; self.idx = idxOfRoom(self.iter_state.room); while (self.idx > 0 and hallway[self.idx - 1] == null) { self.idx -= 1; } if (inFrontOfRoom(self.idx)) self.idx += 1; } fn inFrontOfRoom(idx: usize) bool { return (idx == 2) or (idx == 4) or (idx == 6) or (idx == 8); } fn idxOfRoom(roomnum: u2) usize { return (@intCast(usize, roomnum) + 1) * 2; } }; }; } const final_state2 = State(2){ .hallway = .{null} ** 11, .rooms = .{ .{ .amber, .amber }, .{ .bronze, .bronze }, .{ .copper, .copper }, .{ .desert, .desert }, }, }; const final_state4 = State(4){ .hallway = .{null} ** 11, .rooms = .{ .{ .amber, .amber, .amber, .amber }, .{ .bronze, .bronze, .bronze, .bronze }, .{ .copper, .copper, .copper, .copper }, .{ .desert, .desert, .desert, .desert }, }, }; fn findDist( comptime roomsize: comptime_int, alloc: Allocator, begin_state: State(roomsize), end_state: State(roomsize), ) !i32 { var visited = HashMap(State(roomsize), void).init(alloc); var pqueue = helper.BinaryHashHeap(State(roomsize)).init(alloc); defer visited.deinit(); defer pqueue.deinit(); try pqueue.add(begin_state, 0); while (pqueue.heap.items.len > 0) { const min = pqueue.pop(); // try min.state.print(); if (min.data.eq(end_state)) return min.priority; var neighbors = min.data.neighbors(); while (neighbors.next()) |neighbor| { if (visited.contains(neighbor.state)) continue; const state = neighbor.state; const cost = neighbor.cost; const alt = min.priority + cost; if (pqueue.getPriority(state)) |distv| { if (alt < distv) { pqueue.changePriority(state, alt); } } else { try pqueue.add(state, alt); } } try visited.put(min.data, {}); } return error.EndUnreachable; } const eql = std.mem.eql; 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/day23.zig
const std = @import("std"); const fs = std.fs; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = &gpa.allocator; const input = try fs.cwd().readFileAlloc(allocator, "data/input_04_1.txt", std.math.maxInt(usize)); { // Solution 1 var lines = std.mem.tokenize(input, "\n"); var passport_count: i32 = 0; var completed = false; while (!completed) { const PassportField = struct { byr: u1 = 0, iyr: u1 = 0, eyr: u1 = 0, hgt: u1 = 0, hcl: u1 = 0, ecl: u1 = 0, pid: u1 = 0, cid: u1 = 0, }; var has_fields = PassportField{}; while (true) { const line = lines.next(); if (line == null) { completed = true; break; } const trimmed = std.mem.trim(u8, line.?, " \r\n"); if (trimmed.len == 0) break; var fields_it = std.mem.tokenize(trimmed, " "); while (fields_it.next()) |field| { var key_val_it = std.mem.tokenize(field, ":"); var key = key_val_it.next().?; if (std.mem.eql(u8, key, "byr")) { has_fields.byr = 1; } else if (std.mem.eql(u8, key, "iyr")) { has_fields.iyr = 1; } else if (std.mem.eql(u8, key, "eyr")) { has_fields.eyr = 1; } else if (std.mem.eql(u8, key, "hgt")) { has_fields.hgt = 1; } else if (std.mem.eql(u8, key, "hcl")) { has_fields.hcl = 1; } else if (std.mem.eql(u8, key, "ecl")) { has_fields.ecl = 1; } else if (std.mem.eql(u8, key, "pid")) { has_fields.pid = 1; } else if (std.mem.eql(u8, key, "cid")) { has_fields.cid = 1; } } } if (has_fields.byr == 1 and has_fields.iyr == 1 and has_fields.eyr == 1 and has_fields.hgt == 1 and has_fields.hcl == 1 and has_fields.ecl == 1 and has_fields.pid == 1) {// and has_fields.cid == 1) passport_count += 1; } } std.debug.print("Day 04 - Solution 1: {}\n", .{passport_count}); } { // Solution 2 var lines = std.mem.tokenize(input, "\n"); var passport_count: i32 = 0; var completed = false; while (!completed) { const PassportField = struct { byr: u1 = 0, iyr: u1 = 0, eyr: u1 = 0, hgt: u1 = 0, hcl: u1 = 0, ecl: u1 = 0, pid: u1 = 0, cid: u1 = 0, }; var has_fields = PassportField{}; while (true) { const line = lines.next(); if (line == null) { completed = true; break; } const trimmed = std.mem.trim(u8, line.?, " \r\n"); if (trimmed.len == 0) break; var fields_it = std.mem.tokenize(trimmed, " "); while (fields_it.next()) |field| { var key_val_it = std.mem.tokenize(field, ":"); var key = key_val_it.next().?; var val = key_val_it.next().?; if (std.mem.eql(u8, key, "byr")) { const year = std.fmt.parseInt(i32, val, 10) catch 0; if (year >= 1920 and year <= 2002) has_fields.byr = 1; } else if (std.mem.eql(u8, key, "iyr")) { const year = std.fmt.parseInt(i32, val, 10) catch 0; if (year >= 2010 and year <= 2020) has_fields.iyr = 1; } else if (std.mem.eql(u8, key, "eyr")) { const year = std.fmt.parseInt(i32, val, 10) catch 0; if (year >= 2020 and year <= 2030) has_fields.eyr = 1; } else if (std.mem.eql(u8, key, "hgt")) { if (val.len > 2) { if (val[val.len - 2] == 'c' and val[val.len - 1] == 'm') { const cm = std.fmt.parseInt(i32, val[0..val.len-2], 10) catch 0; if (cm >= 150 and cm <= 193) has_fields.hgt = 1; } else if (val[val.len - 2] == 'i' and val[val.len - 1] == 'n') { const in = std.fmt.parseInt(i32, val[0..val.len-2], 10) catch 0; if (in >= 59 and in <= 76) has_fields.hgt = 1; } } } else if (std.mem.eql(u8, key, "hcl")) { if (val.len == 7 and val[0] == '#') { if (std.fmt.parseInt(i32, val[1..], 16)) |_| { has_fields.hcl = 1; } else |_| {} } } else if (std.mem.eql(u8, key, "ecl")) { const colors = [_][] const u8{"amb", "blu", "brn", "gry", "grn", "hzl", "oth"}; inline for (colors) |color| { if (std.mem.eql(u8, val, color)) { has_fields.ecl = 1; break; } } } else if (std.mem.eql(u8, key, "pid")) { if (val.len == 9) { if (std.fmt.parseInt(u64, val, 10)) |_| { has_fields.pid = 1; } else |_| {} } } else if (std.mem.eql(u8, key, "cid")) { has_fields.cid = 1; } } } if (has_fields.byr == 1 and has_fields.iyr == 1 and has_fields.eyr == 1 and has_fields.hgt == 1 and has_fields.hcl == 1 and has_fields.ecl == 1 and has_fields.pid == 1) {// and has_fields.cid == 1) passport_count += 1; } } std.debug.print("Day 04 - Solution 2: {}\n", .{passport_count}); } }
2020/src/day_04.zig
const builtin = @import("builtin"); const std = @import("std"); const math = std.math; // mulo - multiplication overflow // * return a*%b. // * return if a*b overflows => 1 else => 0 // - muloXi4_genericSmall as default // - muloXi4_genericFast for 2*bitsize <= usize inline fn muloXi4_genericSmall(comptime ST: type, a: ST, b: ST, overflow: *c_int) ST { @setRuntimeSafety(builtin.is_test); overflow.* = 0; const min = math.minInt(ST); var res: ST = a *% b; // Hacker's Delight section Overflow subsection Multiplication // case a=-2^{31}, b=-1 problem, because // on some machines a*b = -2^{31} with overflow // Then -2^{31}/-1 overflows and any result is possible. // => check with a<0 and b=-2^{31} if ((a < 0 and b == min) or (a != 0 and @divTrunc(res, a) != b)) overflow.* = 1; return res; } inline fn muloXi4_genericFast(comptime ST: type, a: ST, b: ST, overflow: *c_int) ST { @setRuntimeSafety(builtin.is_test); overflow.* = 0; const EST = switch (ST) { i32 => i64, i64 => i128, i128 => i256, else => unreachable, }; const min = math.minInt(ST); const max = math.maxInt(ST); var res: EST = @as(EST, a) * @as(EST, b); //invariant: -2^{bitwidth(EST)} < res < 2^{bitwidth(EST)-1} if (res < min or max < res) overflow.* = 1; return @truncate(ST, res); } pub fn __mulosi4(a: i32, b: i32, overflow: *c_int) callconv(.C) i32 { if (2 * @bitSizeOf(i32) <= @bitSizeOf(usize)) { return muloXi4_genericFast(i32, a, b, overflow); } else { return muloXi4_genericSmall(i32, a, b, overflow); } } pub fn __mulodi4(a: i64, b: i64, overflow: *c_int) callconv(.C) i64 { if (2 * @bitSizeOf(i64) <= @bitSizeOf(usize)) { return muloXi4_genericFast(i64, a, b, overflow); } else { return muloXi4_genericSmall(i64, a, b, overflow); } } pub fn __muloti4(a: i128, b: i128, overflow: *c_int) callconv(.C) i128 { if (2 * @bitSizeOf(i128) <= @bitSizeOf(usize)) { return muloXi4_genericFast(i128, a, b, overflow); } else { return muloXi4_genericSmall(i128, a, b, overflow); } } test { _ = @import("mulosi4_test.zig"); _ = @import("mulodi4_test.zig"); _ = @import("muloti4_test.zig"); }
lib/std/special/compiler_rt/mulo.zig
const GBA = @import("gba").GBA; const Input = @import("gba").Input; const LCD = @import("gba").LCD; const Background = @import("gba").Background; export var gameHeader linksection(".gbaheader") = GBA.Header.setup("SCREENBLOCK", "ASBE", "00", 0); const CrossTX = 15; const CrossTY = 10; fn screenIndex(tx: u32, ty: u32, pitch: u32) u32 { var sbb: u32 = ((tx >> 5) + (ty >> 5) * (pitch >> 5)); return sbb * 1024 + ((tx & 31) + (ty & 31) * 32); } fn initMap() void { // Init background Background.setupBackground(Background.Background0Control, .{ .characterBaseBlock = 0, .screenBaseBlock = 28, .paletteMode = .Color16, .screenSize = .Text64x64, }); Background.Background0Scroll.setPosition(0, 0); // create the tiles: basic tile and a cross Background.TileMemory[0][0] = .{ .data = [_]u32{ 0x11111111, 0x01111111, 0x01111111, 0x01111111, 0x01111111, 0x01111111, 0x01111111, 0x00000001 }, }; Background.TileMemory[0][1] = .{ .data = [_]u32{ 0x00000000, 0x00100100, 0x01100110, 0x00011000, 0x00011000, 0x01100110, 0x00100100, 0x00000000 }, }; // Create the background palette Background.Palette[0][1] = GBA.toNativeColor(31, 0, 0); Background.Palette[1][1] = GBA.toNativeColor(0, 31, 0); Background.Palette[2][1] = GBA.toNativeColor(0, 0, 31); Background.Palette[3][1] = GBA.toNativeColor(16, 16, 16); const bg0_map = @ptrCast([*]volatile Background.TextScreenEntry, &Background.ScreenBlockMemory[28]); // Create the map: four contigent blocks of 0x0000, 0x1000, 0x2000, 0x3000 var paletteIndex: usize = 0; var mapIndex: usize = 0; while (paletteIndex < 4) : (paletteIndex += 1) { var blockCount: usize = 0; while (blockCount < 32 * 32) : ({ blockCount += 1; mapIndex += 1; }) { bg0_map[mapIndex].paletteIndex = @intCast(u4, paletteIndex); } } } pub fn main() noreturn { initMap(); LCD.setupDisplayControl(.{ .mode = .Mode0, .backgroundLayer0 = .Show, .objectLayer = .Show, }); var x: i32 = 0; var y: i32 = 0; var tx: u32 = 0; var ty: u32 = 0; var screenBlockCurrent: usize = 0; var screenBlockPrevious: usize = CrossTY * 32 + CrossTX; const bg0_map = @ptrCast([*]volatile Background.TextScreenEntry, &Background.ScreenBlockMemory[28]); bg0_map[screenBlockPrevious].tileIndex += 1; while (true) { LCD.naiveVSync(); Input.readInput(); x += Input.getHorizontal(); y += Input.getVertical(); tx = ((@bitCast(u32, x) >> 3) + CrossTX) & 0x3F; ty = ((@bitCast(u32, y) >> 3) + CrossTY) & 0x3F; screenBlockCurrent = screenIndex(tx, ty, 64); if (screenBlockPrevious != screenBlockCurrent) { bg0_map[screenBlockPrevious].tileIndex -= 1; bg0_map[screenBlockCurrent].tileIndex += 1; screenBlockPrevious = screenBlockCurrent; } Background.Background0Scroll.setPosition(x, y); } }
examples/screenBlock/screenBlock.zig
const builtin = @import("builtin"); const std = @import("std"); const Builder = @import("std").build.Builder; // Mostly based on <https://github.com/andrewrk/clashos/blob/master/build.zig> pub fn build(b: *Builder) !void { const mode = b.standardReleaseOptions(); const want_gdb = b.option(bool, "gdb", "Build for using gdb with qemu") orelse false; const arch = builtin.Arch{ .thumb = .v8m_mainline }; // The utility program for creating a CMSE import library // ------------------------------------------------------- const mkimplib = b.addExecutable("mkimplib", "tools/mkimplib.zig"); mkimplib.setOutputDir("zig-cache"); // The Secure part // ------------------------------------------------------- const exe_s_name = if (want_gdb) "secure-dbg" else "secure"; const exe_s = b.addExecutable(exe_s_name, "src/secure.zig"); exe_s.setLinkerScriptPath("src/secure/linker.ld"); exe_s.setTarget(arch, .freestanding, .eabi); exe_s.setBuildMode(mode); exe_s.addAssemblyFile("src/common/startup.s"); exe_s.setOutputDir("zig-cache"); // TODO: "-mthumb -mfloat-abi=soft -msoft-float -march=armv8-m.main"); // CMSE import library (generated from the Secure binary) // ------------------------------------------------------- // It includes the absolute addresses of Non-Secure-callable functions // exported by the Secure code. Usually it's generated by passing the // `--cmse-implib` option to a supported version of `arm-none-eabi-gcc`, but // since it might not be available, we use a custom tool to do that. const implib_path = "zig-cache/secure_implib.s"; var implib_args = std.ArrayList([]const u8).init(b.allocator); try implib_args.appendSlice([_][]const u8{ mkimplib.getOutputPath(), exe_s.getOutputPath(), implib_path, }); const implib = b.addSystemCommand(implib_args.toSliceConst()); implib.step.dependOn(&exe_s.step); implib.step.dependOn(&mkimplib.step); const implib_step = b.step("implib", "Create a CMSE import library"); implib_step.dependOn(&implib.step); // The Non-Secure part // ------------------------------------------------------- const exe_ns_name = if (want_gdb) "nonsecure-dbg" else "nonsecure"; const exe_ns = b.addExecutable(exe_ns_name, "src/nonsecure.zig"); exe_ns.setLinkerScriptPath("src/nonsecure/linker.ld"); exe_ns.setTarget(arch, .freestanding, .eabi); exe_ns.setBuildMode(mode); exe_ns.addAssemblyFile("src/common/startup.s"); exe_ns.addAssemblyFile(implib_path); exe_ns.setOutputDir("zig-cache"); exe_ns.step.dependOn(&implib.step); const exe_both = b.step("build", "Build Secure and Non-Secure executables"); exe_both.dependOn(&exe_s.step); exe_both.dependOn(&exe_ns.step); // Launch QEMU // ------------------------------------------------------- const qemu = b.step("qemu", "Run the program in qemu"); var qemu_args = std.ArrayList([]const u8).init(b.allocator); const qemu_device_arg = try std.fmt.allocPrint( b.allocator, "loader,file={}", exe_ns.getOutputPath(), ); try qemu_args.appendSlice([_][]const u8{ "qemu-system-arm", "-kernel", exe_s.getOutputPath(), "-device", qemu_device_arg, "-machine", "mps2-an505", "-nographic", "-d", "guest_errors", }); if (want_gdb) { try qemu_args.appendSlice([_][]const u8{ "-S", "-s" }); } const run_qemu = b.addSystemCommand(qemu_args.toSliceConst()); qemu.dependOn(&run_qemu.step); run_qemu.step.dependOn(exe_both); // Default Rule // ------------------------------------------------------- b.default_step.dependOn(exe_both); }
build.zig
const std = @import("std"); const expect = std.testing.expect; const assert = std.debug.assert; ///References: https://en.wikipedia.org/wiki/Merge_sort ///A is the array to be sorted and B is extra storage required by merge sort. ///Responsibility for initialization of B is left to the calling side pub fn sort(A: []i32, B: []i32) void { assert(A.len == B.len); copy_array(A, 0, A.len, B); split_merge(B, 0, A.len, A); } fn split_merge(B: []i32, begin: usize, end: usize, A: []i32) void { if (end - begin <= 1) { return; } var middle = (end + begin) / 2; split_merge(A, begin, middle, B); split_merge(A, middle, end, B); merge(B, begin, middle, end, A); } fn merge(A: []i32, begin: usize, middle: usize, end: usize, B: []i32) void { var i = begin; var k = begin; var j = middle; while (k < end) : (k += 1) { if (i < middle and (j >= end or A[i] <= A[j])) { B[k] = A[i]; i = i + 1; } else { B[k] = A[j]; j = j + 1; } } } fn copy_array(A: []i32, begin: usize, end: usize, B: []i32) void { var k = begin; while (k < end) : (k += 1) { B[k] = A[k]; } } pub fn main() !void {} test "empty array" { var array: []i32 = &.{}; var work_array: []i32 = &.{}; sort(array, work_array); const a = array.len; try expect(a == 0); } test "array with one element" { var array: [1]i32 = .{5}; var work_array: [1]i32 = .{0}; sort(&array, &work_array); const a = array.len; try expect(a == 1); try expect(array[0] == 5); } test "sorted array" { var array: [10]i32 = .{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var work_array: [10]i32 = .{0} ** 10; sort(&array, &work_array); for (array) |value, i| { try expect(value == (i + 1)); } } test "reverse order" { var array: [10]i32 = .{ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; var work_array: [10]i32 = .{0} ** 10; sort(&array, &work_array); for (array) |value, i| { try expect(value == (i + 1)); } } test "unsorted array" { var array: [5]i32 = .{ 5, 3, 4, 1, 2 }; var work_array: [5]i32 = .{0} ** 5; sort(&array, &work_array); for (array) |value, i| { try expect(value == (i + 1)); } } test "two last unordered" { var array: [10]i32 = .{ 1, 2, 3, 4, 5, 6, 7, 8, 10, 9 }; var work_array: [10]i32 = .{0} ** 10; sort(&array, &work_array); for (array) |value, i| { try expect(value == (i + 1)); } } test "two first unordered" { var array: [10]i32 = .{ 2, 1, 3, 4, 5, 6, 7, 8, 9, 10 }; var work_array: [10]i32 = .{0} ** 10; sort(&array, &work_array); for (array) |value, i| { try expect(value == (i + 1)); } }
sorting/merge_sort.zig
pub const va_list = __builtin_va_list; pub const __gnuc_va_list = __builtin_va_list; pub const ptrdiff_t = c_long; pub const wchar_t = c_int; const struct_unnamed_1 = extern struct { __clang_max_align_nonce1: c_longlong, __clang_max_align_nonce2: c_longdouble, }; pub const max_align_t = struct_unnamed_1; pub const int_least64_t = i64; pub const uint_least64_t = u64; pub const int_fast64_t = i64; pub const uint_fast64_t = u64; pub const int_least32_t = i32; pub const uint_least32_t = u32; pub const int_fast32_t = i32; pub const uint_fast32_t = u32; pub const int_least16_t = i16; pub const uint_least16_t = u16; pub const int_fast16_t = i16; pub const uint_fast16_t = u16; pub const int_least8_t = i8; pub const uint_least8_t = u8; pub const int_fast8_t = i8; pub const uint_fast8_t = u8; pub const intmax_t = c_long; pub const uintmax_t = c_ulong; pub const struct_leveldb_t = @OpaqueType(); pub const leveldb_t = struct_leveldb_t; pub const struct_leveldb_cache_t = @OpaqueType(); pub const leveldb_cache_t = struct_leveldb_cache_t; pub const struct_leveldb_comparator_t = @OpaqueType(); pub const leveldb_comparator_t = struct_leveldb_comparator_t; pub const struct_leveldb_env_t = @OpaqueType(); pub const leveldb_env_t = struct_leveldb_env_t; pub const struct_leveldb_filelock_t = @OpaqueType(); pub const leveldb_filelock_t = struct_leveldb_filelock_t; pub const struct_leveldb_filterpolicy_t = @OpaqueType(); pub const leveldb_filterpolicy_t = struct_leveldb_filterpolicy_t; pub const struct_leveldb_iterator_t = @OpaqueType(); pub const leveldb_iterator_t = struct_leveldb_iterator_t; pub const struct_leveldb_logger_t = @OpaqueType(); pub const leveldb_logger_t = struct_leveldb_logger_t; pub const struct_leveldb_options_t = @OpaqueType(); pub const leveldb_options_t = struct_leveldb_options_t; pub const struct_leveldb_randomfile_t = @OpaqueType(); pub const leveldb_randomfile_t = struct_leveldb_randomfile_t; pub const struct_leveldb_readoptions_t = @OpaqueType(); pub const leveldb_readoptions_t = struct_leveldb_readoptions_t; pub const struct_leveldb_seqfile_t = @OpaqueType(); pub const leveldb_seqfile_t = struct_leveldb_seqfile_t; pub const struct_leveldb_snapshot_t = @OpaqueType(); pub const leveldb_snapshot_t = struct_leveldb_snapshot_t; pub const struct_leveldb_writablefile_t = @OpaqueType(); pub const leveldb_writablefile_t = struct_leveldb_writablefile_t; pub const struct_leveldb_writebatch_t = @OpaqueType(); pub const leveldb_writebatch_t = struct_leveldb_writebatch_t; pub const struct_leveldb_writeoptions_t = @OpaqueType(); pub const leveldb_writeoptions_t = struct_leveldb_writeoptions_t; pub extern fn leveldb_open(options: ?*const leveldb_options_t, name: [*c]const u8, errptr: [*c][*c]u8) ?*leveldb_t; pub extern fn leveldb_close(db: ?*leveldb_t) void; pub extern fn leveldb_put(db: ?*leveldb_t, options: ?*const leveldb_writeoptions_t, key: [*c]const u8, keylen: usize, val: [*c]const u8, vallen: usize, errptr: [*c][*c]u8) void; pub extern fn leveldb_delete(db: ?*leveldb_t, options: ?*const leveldb_writeoptions_t, key: [*c]const u8, keylen: usize, errptr: [*c][*c]u8) void; pub extern fn leveldb_write(db: ?*leveldb_t, options: ?*const leveldb_writeoptions_t, batch: ?*leveldb_writebatch_t, errptr: [*c][*c]u8) void; pub extern fn leveldb_get(db: ?*leveldb_t, options: ?*const leveldb_readoptions_t, key: [*]const u8, keylen: usize, vallen: [*c]usize, errptr: [*c][*c]u8) [*c]u8; pub extern fn leveldb_create_iterator(db: ?*leveldb_t, options: ?*const leveldb_readoptions_t) ?*leveldb_iterator_t; pub extern fn leveldb_create_snapshot(db: ?*leveldb_t) ?*const leveldb_snapshot_t; pub extern fn leveldb_release_snapshot(db: ?*leveldb_t, snapshot: ?*const leveldb_snapshot_t) void; pub extern fn leveldb_property_value(db: ?*leveldb_t, propname: [*c]const u8) [*c]u8; pub extern fn leveldb_approximate_sizes(db: ?*leveldb_t, num_ranges: c_int, range_start_key: [*c]const [*c]const u8, range_start_key_len: [*c]const usize, range_limit_key: [*c]const [*c]const u8, range_limit_key_len: [*c]const usize, sizes: [*c]u64) void; pub extern fn leveldb_compact_range(db: ?*leveldb_t, start_key: [*c]const u8, start_key_len: usize, limit_key: [*c]const u8, limit_key_len: usize) void; pub extern fn leveldb_destroy_db(options: ?*const leveldb_options_t, name: [*c]const u8, errptr: [*c][*c]u8) void; pub extern fn leveldb_repair_db(options: ?*const leveldb_options_t, name: [*c]const u8, errptr: [*c][*c]u8) void; pub extern fn leveldb_iter_destroy(?*leveldb_iterator_t) void; pub extern fn leveldb_iter_valid(?*const leveldb_iterator_t) u8; pub extern fn leveldb_iter_seek_to_first(?*leveldb_iterator_t) void; pub extern fn leveldb_iter_seek_to_last(?*leveldb_iterator_t) void; pub extern fn leveldb_iter_seek(?*leveldb_iterator_t, k: [*c]const u8, klen: usize) void; pub extern fn leveldb_iter_next(?*leveldb_iterator_t) void; pub extern fn leveldb_iter_prev(?*leveldb_iterator_t) void; pub extern fn leveldb_iter_key(?*const leveldb_iterator_t, klen: [*c]usize) [*c]const u8; pub extern fn leveldb_iter_value(?*const leveldb_iterator_t, vlen: [*c]usize) [*c]const u8; pub extern fn leveldb_iter_get_error(?*const leveldb_iterator_t, errptr: [*c][*c]u8) void; pub extern fn leveldb_writebatch_create() ?*leveldb_writebatch_t; pub extern fn leveldb_writebatch_destroy(?*leveldb_writebatch_t) void; pub extern fn leveldb_writebatch_clear(?*leveldb_writebatch_t) void; pub extern fn leveldb_writebatch_put(?*leveldb_writebatch_t, key: [*c]const u8, klen: usize, val: [*c]const u8, vlen: usize) void; pub extern fn leveldb_writebatch_delete(?*leveldb_writebatch_t, key: [*c]const u8, klen: usize) void; pub extern fn leveldb_writebatch_iterate(?*const leveldb_writebatch_t, state: ?*c_void, put: ?fn (?*c_void, [*c]const u8, usize, [*c]const u8, usize) callconv(.C) void, deleted: ?fn (?*c_void, [*c]const u8, usize) callconv(.C) void) void; pub extern fn leveldb_writebatch_append(destination: ?*leveldb_writebatch_t, source: ?*const leveldb_writebatch_t) void; pub extern fn leveldb_options_create() ?*leveldb_options_t; pub extern fn leveldb_options_destroy(?*leveldb_options_t) void; pub extern fn leveldb_options_set_comparator(?*leveldb_options_t, ?*leveldb_comparator_t) void; pub extern fn leveldb_options_set_filter_policy(?*leveldb_options_t, ?*leveldb_filterpolicy_t) void; pub extern fn leveldb_options_set_create_if_missing(?*leveldb_options_t, u8) void; pub extern fn leveldb_options_set_error_if_exists(?*leveldb_options_t, u8) void; pub extern fn leveldb_options_set_paranoid_checks(?*leveldb_options_t, u8) void; pub extern fn leveldb_options_set_env(?*leveldb_options_t, ?*leveldb_env_t) void; pub extern fn leveldb_options_set_info_log(?*leveldb_options_t, ?*leveldb_logger_t) void; pub extern fn leveldb_options_set_write_buffer_size(?*leveldb_options_t, usize) void; pub extern fn leveldb_options_set_max_open_files(?*leveldb_options_t, c_int) void; pub extern fn leveldb_options_set_cache(?*leveldb_options_t, ?*leveldb_cache_t) void; pub extern fn leveldb_options_set_block_size(?*leveldb_options_t, usize) void; pub extern fn leveldb_options_set_block_restart_interval(?*leveldb_options_t, c_int) void; pub extern fn leveldb_options_set_max_file_size(?*leveldb_options_t, usize) void; pub const leveldb_no_compression = @enumToInt(enum_unnamed_2.leveldb_no_compression); pub const leveldb_snappy_compression = @enumToInt(enum_unnamed_2.leveldb_snappy_compression); const enum_unnamed_2 = extern enum(c_int) { leveldb_no_compression = 0, leveldb_snappy_compression = 1, _, }; pub extern fn leveldb_options_set_compression(?*leveldb_options_t, c_int) void; pub extern fn leveldb_comparator_create(state: ?*c_void, destructor: ?fn (?*c_void) callconv(.C) void, compare: ?fn (?*c_void, [*c]const u8, usize, [*c]const u8, usize) callconv(.C) c_int, name: ?fn (?*c_void) callconv(.C) [*c]const u8) ?*leveldb_comparator_t; pub extern fn leveldb_comparator_destroy(?*leveldb_comparator_t) void; pub extern fn leveldb_filterpolicy_create(state: ?*c_void, destructor: ?fn (?*c_void) callconv(.C) void, create_filter: ?fn (?*c_void, [*c]const [*c]const u8, [*c]const usize, c_int, [*c]usize) callconv(.C) [*c]u8, key_may_match: ?fn (?*c_void, [*c]const u8, usize, [*c]const u8, usize) callconv(.C) u8, name: ?fn (?*c_void) callconv(.C) [*c]const u8) ?*leveldb_filterpolicy_t; pub extern fn leveldb_filterpolicy_destroy(?*leveldb_filterpolicy_t) void; pub extern fn leveldb_filterpolicy_create_bloom(bits_per_key: c_int) ?*leveldb_filterpolicy_t; pub extern fn leveldb_readoptions_create() ?*leveldb_readoptions_t; pub extern fn leveldb_readoptions_destroy(?*leveldb_readoptions_t) void; pub extern fn leveldb_readoptions_set_verify_checksums(?*leveldb_readoptions_t, u8) void; pub extern fn leveldb_readoptions_set_fill_cache(?*leveldb_readoptions_t, u8) void; pub extern fn leveldb_readoptions_set_snapshot(?*leveldb_readoptions_t, ?*const leveldb_snapshot_t) void; pub extern fn leveldb_writeoptions_create() ?*leveldb_writeoptions_t; pub extern fn leveldb_writeoptions_destroy(?*leveldb_writeoptions_t) void; pub extern fn leveldb_writeoptions_set_sync(?*leveldb_writeoptions_t, u8) void; pub extern fn leveldb_cache_create_lru(capacity: usize) ?*leveldb_cache_t; pub extern fn leveldb_cache_destroy(cache: ?*leveldb_cache_t) void; pub extern fn leveldb_create_default_env() ?*leveldb_env_t; pub extern fn leveldb_env_destroy(?*leveldb_env_t) void; pub extern fn leveldb_env_get_test_directory(?*leveldb_env_t) [*c]u8; pub extern fn leveldb_free(ptr: ?*c_void) void; pub extern fn leveldb_major_version() c_int; pub extern fn leveldb_minor_version() c_int; pub const __INTMAX_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __UINTMAX_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_unsigned = void }"); pub const __PTRDIFF_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __INTPTR_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __SIZE_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_unsigned = void }"); pub const __WINT_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __CHAR16_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_short = void }"); pub const __CHAR32_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __UINTPTR_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_unsigned = void }"); pub const __INT8_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_signed = void }"); pub const __INT64_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __UINT8_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_char = void }"); pub const __UINT16_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_short = void }"); pub const __UINT32_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __UINT64_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_unsigned = void }"); pub const __INT_LEAST8_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_signed = void }"); pub const __UINT_LEAST8_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_char = void }"); pub const __UINT_LEAST16_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_short = void }"); pub const __UINT_LEAST32_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __INT_LEAST64_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __UINT_LEAST64_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_unsigned = void }"); pub const __INT_FAST8_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_signed = void }"); pub const __UINT_FAST8_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_char = void }"); pub const __UINT_FAST16_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_short = void }"); pub const __UINT_FAST32_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __INT_FAST64_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __UINT_FAST64_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_unsigned = void }"); pub const NULL = @compileError("unable to translate C expr: expected ')'' here"); pub const __stdint_join3 = @compileError("unable to translate C expr: unexpected token Id{ .HashHash = void }"); pub const __int_c_join = @compileError("unable to translate C expr: unexpected token Id{ .HashHash = void }"); pub const __uint_c = @compileError("unable to translate C expr: expected ',' or ')'"); pub const __UINT64_MAX__ = @as(c_ulong, 18446744073709551615); pub const __FINITE_MATH_ONLY__ = 0; pub const __SIZEOF_FLOAT__ = 4; pub const __SEG_GS = 1; pub const INT_FAST64_MAX = __INT_LEAST64_MAX; pub const __UINT_LEAST64_FMTX__ = "lX"; pub const __INT_FAST8_MAX__ = 127; pub const __OBJC_BOOL_IS_BOOL = 0; pub const __INT_LEAST8_FMTi__ = "hhi"; pub const __UINT64_FMTX__ = "lX"; pub inline fn va_start(ap: var, param: var) @TypeOf(__builtin_va_start(ap, param)) { return __builtin_va_start(ap, param); } pub const __SIG_ATOMIC_MAX__ = 2147483647; pub const __SSE__ = 1; pub const __INT_LEAST16_MIN = INT64_MIN; pub const __BYTE_ORDER__ = __ORDER_LITTLE_ENDIAN__; pub const __NO_MATH_INLINES = 1; pub const __SIZEOF_FLOAT128__ = 16; pub const __INT_FAST32_FMTd__ = "d"; pub const __STDC_UTF_16__ = 1; pub const __UINT_FAST16_MAX__ = 65535; pub const __ATOMIC_ACQUIRE = 2; pub const __LDBL_HAS_DENORM__ = 1; pub const __INTMAX_FMTi__ = "li"; pub const __FLT_EPSILON__ = @as(f32, 1.19209290e-7); pub const __UINT_FAST32_FMTo__ = "o"; pub const __UINT32_MAX__ = @as(c_uint, 4294967295); pub const INT_FAST8_MIN = __INT_LEAST8_MIN; pub const __INT_MAX__ = 2147483647; pub const __INT_LEAST64_MAX__ = @as(c_long, 9223372036854775807); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 = 1; pub const __SIZEOF_INT128__ = 16; pub const __INT64_MAX__ = @as(c_long, 9223372036854775807); pub const __DBL_MIN_10_EXP__ = -307; pub const __INT_LEAST32_MAX__ = 2147483647; pub const __INT_FAST16_FMTd__ = "hd"; pub const __UINT_LEAST64_FMTu__ = "lu"; pub inline fn INT64_C(v: var) @TypeOf(__int_c(v, __int64_c_suffix)) { return __int_c(v, __int64_c_suffix); } pub const __DBL_DENORM_MIN__ = 4.9406564584124654e-324; pub const __UINT8_FMTu__ = "hhu"; pub const __INT_FAST16_MAX__ = 32767; pub const __LP64__ = 1; pub const __SIZE_FMTx__ = "lx"; pub const __ORDER_PDP_ENDIAN__ = 3412; pub const __UINT8_FMTX__ = "hhX"; pub const __LDBL_MIN_10_EXP__ = -4931; pub const __LDBL_MAX_10_EXP__ = 4932; pub const __DBL_MAX_10_EXP__ = 308; pub const __PTRDIFF_FMTi__ = "li"; pub const INT_FAST32_MAX = __INT_LEAST32_MAX; pub const __FLT_MIN_EXP__ = -125; pub const __SIZEOF_LONG__ = 8; pub const INT_FAST16_MAX = __INT_LEAST16_MAX; pub const __FLT_MIN__ = @as(f32, 1.17549435e-38); pub const __FLT_EVAL_METHOD__ = 0; pub const __UINTMAX_FMTx__ = "lx"; pub const __UINT_LEAST8_FMTo__ = "hho"; pub const __code_model_small_ = 1; pub const __ELF__ = 1; pub const __UINT_FAST8_FMTu__ = "hhu"; pub const _LP64 = 1; pub const __FLT_MAX_EXP__ = 128; pub const UINT8_MAX = UINT8_C(255); pub const __DBL_HAS_DENORM__ = 1; pub const __WINT_UNSIGNED__ = 1; pub const __INT_LEAST64_FMTd__ = "ld"; pub const SIZE_MAX = __SIZE_MAX__; pub const __UINT_LEAST8_FMTu__ = "hhu"; pub const __FLT_MAX__ = @as(f32, 3.40282347e+38); pub const __UINT_FAST8_FMTX__ = "hhX"; pub const __UINT_FAST16_FMTu__ = "hu"; pub const __amdfam10 = 1; pub const __UINT_FAST32_FMTX__ = "X"; pub const __DECIMAL_DIG__ = __LDBL_DECIMAL_DIG__; pub const __LZCNT__ = 1; pub const __int64_c_suffix = __INT64_C_SUFFIX__; pub const WCHAR_MAX = __WCHAR_MAX__; pub const __clang_patchlevel__ = 0; pub const __UINT64_FMTu__ = "lu"; pub inline fn __INTN_MAX(n: var) @TypeOf(__stdint_join3(INT, n, _MAX)) { return __stdint_join3(INT, n, _MAX); } pub const UINT_FAST64_MAX = __UINT_LEAST64_MAX; pub const INT_FAST32_MIN = __INT_LEAST32_MIN; pub const __SIZEOF_SHORT__ = 2; pub const __LDBL_DIG__ = 18; pub const __OPENCL_MEMORY_SCOPE_DEVICE = 2; pub const __INT_FAST8_FMTd__ = "hhd"; pub const __int_least8_t = int64_t; pub const __FLT_DENORM_MIN__ = @as(f32, 1.40129846e-45); pub const __MMX__ = 1; pub const __NO_INLINE__ = 1; pub const __SIZEOF_WINT_T__ = 4; pub const __CLANG_ATOMIC_POINTER_LOCK_FREE = 2; pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 = 1; pub const __INTMAX_C_SUFFIX__ = L; pub const __UINT_LEAST32_FMTu__ = "u"; pub const __INT_LEAST16_FMTi__ = "hi"; pub const __LITTLE_ENDIAN__ = 1; pub const __UINTMAX_C_SUFFIX__ = UL; pub const __OPENCL_MEMORY_SCOPE_WORK_ITEM = 0; pub const __VERSION__ = "Clang 9.0.0 (tags/RELEASE_900/final)"; pub const __DBL_HAS_INFINITY__ = 1; pub const __INT_LEAST16_MAX__ = 32767; pub const INT16_MAX = INT16_C(32767); pub const __SCHAR_MAX__ = 127; pub const __GNUC_MINOR__ = 2; pub const __UINT32_FMTx__ = "x"; pub const __LDBL_HAS_QUIET_NAN__ = 1; pub const __UINT_FAST32_FMTu__ = "u"; pub const INT_LEAST16_MAX = __INT_LEAST16_MAX; pub const WINT_MIN = __UINTN_C(__WINT_WIDTH__, 0); pub const __UINT8_FMTx__ = "hhx"; pub const WCHAR_MIN = __INTN_MIN(__WCHAR_WIDTH__); pub const __UINT_LEAST8_FMTX__ = "hhX"; pub const __UINT_LEAST64_FMTx__ = "lx"; pub const __UINT_LEAST64_MAX__ = @as(c_ulong, 18446744073709551615); pub const INT64_MIN = -INT64_C(9223372036854775807) - 1; pub const __GCC_ATOMIC_CHAR16_T_LOCK_FREE = 2; pub const __clang__ = 1; pub const __INT_LEAST32_MAX = INT64_MAX; pub const __FLT_HAS_INFINITY__ = 1; pub const __UINTPTR_FMTu__ = "lu"; pub const UINT_FAST32_MAX = __UINT_LEAST32_MAX; pub const __3dNOW__ = 1; pub const __unix__ = 1; pub const __INT_FAST32_TYPE__ = c_int; pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 = 1; pub const UINTPTR_MAX = __UINTPTR_MAX__; pub inline fn __va_copy(d: var, s: var) @TypeOf(__builtin_va_copy(d, s)) { return __builtin_va_copy(d, s); } pub const __UINT16_FMTx__ = "hx"; pub const INT8_MAX = INT8_C(127); pub const __UINT_LEAST32_FMTo__ = "o"; pub inline fn __INTN_MIN(n: var) @TypeOf(__stdint_join3(INT, n, _MIN)) { return __stdint_join3(INT, n, _MIN); } pub const __FLT_MIN_10_EXP__ = -37; pub const __int_least32_t = int64_t; pub const __UINT_LEAST16_FMTX__ = "hX"; pub const __UINT_LEAST32_MAX__ = @as(c_uint, 4294967295); pub const UINT_FAST8_MAX = __UINT_LEAST8_MAX; pub const __GNUC_VA_LIST = 1; pub const __uint_least16_t = uint64_t; pub const __UINT_FAST8_FMTx__ = "hhx"; pub const __SIZE_FMTu__ = "lu"; pub const __SIZEOF_POINTER__ = 8; pub const __SIZE_FMTX__ = "lX"; pub inline fn UINT32_C(v: var) @TypeOf(__uint_c(v, __int32_c_suffix)) { return __uint_c(v, __int32_c_suffix); } pub const __INT16_FMTd__ = "hd"; pub const __clang_version__ = "9.0.0 (tags/RELEASE_900/final)"; pub const __ATOMIC_RELEASE = 3; pub const __UINT_FAST64_FMTX__ = "lX"; pub const WINT_MAX = __UINTN_MAX(__WINT_WIDTH__); pub const __INTMAX_FMTd__ = "ld"; pub const INT_FAST16_MIN = __INT_LEAST16_MIN; pub const __SEG_FS = 1; pub const __UINT_FAST8_FMTo__ = "hho"; pub const INT32_MIN = -INT32_C(2147483647) - 1; pub inline fn __INTN_C(n: var, v: var) @TypeOf(__stdint_join3(INT, n, _C(v))) { return __stdint_join3(INT, n, _C(v)); } pub const __WINT_WIDTH__ = 32; pub const __FLT_MAX_10_EXP__ = 38; pub const __LDBL_MAX__ = @as(c_longdouble, 1.18973149535723176502e+4932); pub const __GCC_ATOMIC_LONG_LOCK_FREE = 2; pub const __gnu_linux__ = 1; pub const _DEBUG = 1; pub const __UINTPTR_WIDTH__ = 64; pub const __INT_LEAST32_FMTi__ = "i"; pub const INTMAX_MIN = -__INTMAX_MAX__ - 1; pub const PTRDIFF_MIN = -__PTRDIFF_MAX__ - 1; pub const __WCHAR_WIDTH__ = 32; pub const __UINT16_FMTX__ = "hX"; pub const UINT_LEAST8_MAX = __UINT_LEAST8_MAX; pub const unix = 1; pub const INT64_MAX = INT64_C(9223372036854775807); pub const __GNUC_PATCHLEVEL__ = 1; pub const __INT_LEAST16_TYPE__ = c_short; pub const __INT64_FMTd__ = "ld"; pub const __SSE3__ = 1; pub const __UINT16_MAX__ = 65535; pub const __ATOMIC_RELAXED = 0; pub const __UINT_LEAST32_MAX = UINT64_MAX; pub const __SSE4A__ = 1; pub const INT32_MAX = INT32_C(2147483647); pub const INT_FAST8_MAX = __INT_LEAST8_MAX; pub const __GCC_ATOMIC_CHAR_LOCK_FREE = 2; pub const __UINT_LEAST16_FMTx__ = "hx"; pub const __UINT_FAST64_FMTu__ = "lu"; pub const INT16_MIN = -INT16_C(32767) - 1; pub const __CLANG_ATOMIC_CHAR16_T_LOCK_FREE = 2; pub const __SSE2__ = 1; pub const __STDC__ = 1; pub const __UINT_LEAST16_MAX = UINT64_MAX; pub const __INT_FAST16_TYPE__ = c_short; pub const __UINT64_C_SUFFIX__ = UL; pub const __LONG_MAX__ = @as(c_long, 9223372036854775807); pub const __DBL_MAX__ = 1.7976931348623157e+308; pub const __CHAR_BIT__ = 8; pub const __DBL_DECIMAL_DIG__ = 17; pub const __UINT_LEAST8_FMTx__ = "hhx"; pub const linux = 1; pub const __ORDER_BIG_ENDIAN__ = 4321; pub const __INTPTR_MAX__ = @as(c_long, 9223372036854775807); pub const __INT_LEAST8_FMTd__ = "hhd"; pub const __INTMAX_WIDTH__ = 64; pub const __CLANG_ATOMIC_SHORT_LOCK_FREE = 2; pub const __FLOAT128__ = 1; pub const __LDBL_DENORM_MIN__ = @as(c_longdouble, 3.64519953188247460253e-4951); pub const UINT_LEAST64_MAX = __UINT_LEAST64_MAX; pub const __x86_64 = 1; pub const __CLANG_ATOMIC_LONG_LOCK_FREE = 2; pub const __INTMAX_MAX__ = @as(c_long, 9223372036854775807); pub const __INT8_FMTd__ = "hhd"; pub const __UINTMAX_WIDTH__ = 64; pub const __UINT8_MAX__ = 255; pub const __DBL_MIN__ = 2.2250738585072014e-308; pub const __PRAGMA_REDEFINE_EXTNAME = 1; pub const __DBL_HAS_QUIET_NAN__ = 1; pub const __clang_minor__ = 0; pub const __LDBL_DECIMAL_DIG__ = 21; pub const __WCHAR_TYPE__ = c_int; pub const __INT_FAST64_FMTd__ = "ld"; pub const INT_LEAST64_MIN = __INT_LEAST64_MIN; pub const __GCC_ATOMIC_WCHAR_T_LOCK_FREE = 2; pub const __seg_fs = __attribute__(address_space(257)); pub const __UINTMAX_FMTX__ = "lX"; pub const __INT16_FMTi__ = "hi"; pub const __INT_LEAST16_MAX = INT64_MAX; pub const __LDBL_MIN_EXP__ = -16381; pub const __PRFCHW__ = 1; pub const __UINTMAX_FMTu__ = "lu"; pub const __UINT_LEAST16_FMTo__ = "ho"; pub const __uint_least32_t = uint64_t; pub const INTPTR_MIN = -__INTPTR_MAX__ - 1; pub const UINT64_MAX = UINT64_C(18446744073709551615); pub const __UINT32_FMTu__ = "u"; pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 = 1; pub const __SIG_ATOMIC_WIDTH__ = 32; pub const __uint_least8_t = uint64_t; pub const __amd64__ = 1; pub const __INT64_C_SUFFIX__ = L; pub inline fn INT16_C(v: var) @TypeOf(__int_c(v, __int16_c_suffix)) { return __int_c(v, __int16_c_suffix); } pub const __LDBL_EPSILON__ = @as(c_longdouble, 1.08420217248550443401e-19); pub const __INT_LEAST8_MIN = INT64_MIN; pub const __CLANG_ATOMIC_INT_LOCK_FREE = 2; pub const __SSE2_MATH__ = 1; pub const __GCC_ATOMIC_SHORT_LOCK_FREE = 2; pub const __POPCNT__ = 1; pub const __POINTER_WIDTH__ = 64; pub const __UINT64_FMTx__ = "lx"; pub const __ATOMIC_ACQ_REL = 4; pub const __UINT_LEAST32_FMTx__ = "x"; pub const __STDC_HOSTED__ = 1; pub const __GNUC__ = 4; pub const __INT_FAST32_FMTi__ = "i"; pub const __GCC_ATOMIC_BOOL_LOCK_FREE = 2; pub const __seg_gs = __attribute__(address_space(256)); pub const __FXSR__ = 1; pub const __UINT64_FMTo__ = "lo"; pub const __int_least16_t = int64_t; pub const __UINT_FAST16_FMTx__ = "hx"; pub const __INT_LEAST8_MAX = INT64_MAX; pub const UINT_FAST16_MAX = __UINT_LEAST16_MAX; pub const __uint_least64_t = uint64_t; pub const __UINT_LEAST64_FMTo__ = "lo"; pub inline fn INT32_C(v: var) @TypeOf(__int_c(v, __int32_c_suffix)) { return __int_c(v, __int32_c_suffix); } pub const __STDC_UTF_32__ = 1; pub const __PTRDIFF_WIDTH__ = 64; pub const __SIZE_WIDTH__ = 64; pub const __INT_LEAST32_MIN = INT64_MIN; pub const __LDBL_MIN__ = @as(c_longdouble, 3.36210314311209350626e-4932); pub const __UINTMAX_MAX__ = @as(c_ulong, 18446744073709551615); pub const __INT_LEAST16_FMTd__ = "hd"; pub inline fn __int_c(v: var, suffix: var) @TypeOf(__int_c_join(v, suffix)) { return __int_c_join(v, suffix); } pub const __SIZEOF_PTRDIFF_T__ = 8; pub const __UINT_LEAST16_FMTu__ = "hu"; pub const UINT32_MAX = UINT32_C(4294967295); pub const __UINT16_FMTu__ = "hu"; pub const __DBL_MANT_DIG__ = 53; pub const __CLANG_ATOMIC_WCHAR_T_LOCK_FREE = 2; pub const INT_LEAST8_MIN = __INT_LEAST8_MIN; pub const __INT_LEAST64_FMTi__ = "li"; pub const __GNUC_STDC_INLINE__ = 1; pub const __UINT32_FMTX__ = "X"; pub const __DBL_DIG__ = 15; pub const __SHRT_MAX__ = 32767; pub inline fn va_copy(dest: var, src: var) @TypeOf(__builtin_va_copy(dest, src)) { return __builtin_va_copy(dest, src); } pub const __ATOMIC_CONSUME = 1; pub const __UINT_FAST16_FMTX__ = "hX"; pub const __INT_FAST16_FMTi__ = "hi"; pub const __INT32_FMTd__ = "d"; pub const __INT8_MAX__ = 127; pub const __FLT_DECIMAL_DIG__ = 9; pub inline fn UINT64_C(v: var) @TypeOf(__uint_c(v, __int64_c_suffix)) { return __uint_c(v, __int64_c_suffix); } pub const __INT_LEAST32_FMTd__ = "d"; pub const __UINT8_FMTo__ = "hho"; pub const __amdfam10__ = 1; pub const __FLT_HAS_DENORM__ = 1; pub const __FLT_DIG__ = 6; pub const __INTPTR_FMTi__ = "li"; pub const __UINT32_FMTo__ = "o"; pub const __UINT_FAST64_MAX__ = @as(c_ulong, 18446744073709551615); pub const __UINT_FAST64_FMTo__ = "lo"; pub const __GXX_ABI_VERSION = 1002; pub const __tune_amdfam10__ = 1; pub const INTMAX_MAX = __INTMAX_MAX__; pub const __SIZEOF_LONG_LONG__ = 8; pub const INT_LEAST64_MAX = __INT_LEAST64_MAX; pub const INT_LEAST16_MIN = __INT_LEAST16_MIN; pub const __int_least64_t = int64_t; pub const __INT32_TYPE__ = c_int; pub const __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES = 3; pub const __UINTPTR_FMTX__ = "lX"; pub const __INT8_FMTi__ = "hhi"; pub const __SIZEOF_LONG_DOUBLE__ = 16; pub inline fn UINTMAX_C(v: var) @TypeOf(__int_c(v, __UINTMAX_C_SUFFIX__)) { return __int_c(v, __UINTMAX_C_SUFFIX__); } pub const __DBL_MIN_EXP__ = -1021; pub const __INT_LEAST64_MIN = INT64_MIN; pub const __INT64_FMTi__ = "li"; pub const __INT_FAST64_FMTi__ = "li"; pub const __GCC_ATOMIC_TEST_AND_SET_TRUEVAL = 1; pub const __OPENCL_MEMORY_SCOPE_SUB_GROUP = 4; pub const __clang_major__ = 9; pub const __INT16_MAX__ = 32767; pub const __linux = 1; pub const __GCC_ATOMIC_LLONG_LOCK_FREE = 2; pub const INT_LEAST32_MAX = __INT_LEAST32_MAX; pub const __UINT16_FMTo__ = "ho"; pub const __INT_LEAST64_MAX = INT64_MAX; pub const __INT_FAST8_FMTi__ = "hhi"; pub const __UINT_FAST64_FMTx__ = "lx"; pub const INTPTR_MAX = __INTPTR_MAX__; pub const __UINT_LEAST8_MAX__ = 255; pub const UINT16_MAX = UINT16_C(65535); pub const __LDBL_HAS_INFINITY__ = 1; pub const INT_FAST64_MIN = __INT_LEAST64_MIN; pub const __UINT_LEAST32_FMTX__ = "X"; pub const __UINT_LEAST16_MAX__ = 65535; pub const __unix = 1; pub const __CONSTANT_CFSTRINGS__ = 1; pub const __SSE_MATH__ = 1; pub const __DBL_EPSILON__ = 2.2204460492503131e-16; pub const __llvm__ = 1; pub const __DBL_MAX_EXP__ = 1024; pub const __CLANG_ATOMIC_CHAR_LOCK_FREE = 2; pub const SIG_ATOMIC_MAX = __INTN_MAX(__SIG_ATOMIC_WIDTH__); pub const __CLANG_ATOMIC_CHAR32_T_LOCK_FREE = 2; pub const __GCC_ASM_FLAG_OUTPUTS__ = 1; pub const __PTRDIFF_MAX__ = @as(c_long, 9223372036854775807); pub const __ORDER_LITTLE_ENDIAN__ = 1234; pub const __linux__ = 1; pub const __INT16_TYPE__ = c_short; pub const __UINTPTR_FMTx__ = "lx"; pub const __UINT_LEAST64_MAX = UINT64_MAX; pub const __LDBL_MAX_EXP__ = 16384; pub const __UINT_FAST32_MAX__ = @as(c_uint, 4294967295); pub const __3dNOW_A__ = 1; pub const __FLT_RADIX__ = 2; pub const __amd64 = 1; pub const INT_LEAST8_MAX = __INT_LEAST8_MAX; pub const __WINT_MAX__ = @as(c_uint, 4294967295); pub const __int8_c_suffix = __INT64_C_SUFFIX__; pub const __UINTPTR_FMTo__ = "lo"; pub const __INT32_MAX__ = 2147483647; pub const __UINT_LEAST8_MAX = UINT64_MAX; pub const __INTPTR_FMTd__ = "ld"; pub inline fn va_arg(ap: var, type_1: var) @TypeOf(__builtin_va_arg(ap, type_1)) { return __builtin_va_arg(ap, type_1); } pub inline fn __UINTN_C(n: var, v: var) @TypeOf(__stdint_join3(UINT, n, _C(v))) { return __stdint_join3(UINT, n, _C(v)); } pub const __INTPTR_WIDTH__ = 64; pub const __int16_c_suffix = __INT64_C_SUFFIX__; pub const __INT_FAST32_MAX__ = 2147483647; pub const __INT32_FMTi__ = "i"; pub const __GCC_ATOMIC_CHAR32_T_LOCK_FREE = 2; pub const __UINT_FAST16_FMTo__ = "ho"; pub inline fn __UINTN_MAX(n: var) @TypeOf(__stdint_join3(UINT, n, _MAX)) { return __stdint_join3(UINT, n, _MAX); } pub const __GCC_ATOMIC_INT_LOCK_FREE = 2; pub inline fn UINT16_C(v: var) @TypeOf(__uint_c(v, __int16_c_suffix)) { return __uint_c(v, __int16_c_suffix); } pub const PTRDIFF_MAX = __PTRDIFF_MAX__; pub const __FLT_HAS_QUIET_NAN__ = 1; pub inline fn INTMAX_C(v: var) @TypeOf(__int_c(v, __INTMAX_C_SUFFIX__)) { return __int_c(v, __INTMAX_C_SUFFIX__); } pub inline fn offsetof(t: var, d: var) @TypeOf(__builtin_offsetof(t, d)) { return __builtin_offsetof(t, d); } pub const __INT_LEAST32_TYPE__ = c_int; pub const __BIGGEST_ALIGNMENT__ = 16; pub const UINT_LEAST16_MAX = __UINT_LEAST16_MAX; pub const INT_LEAST32_MIN = __INT_LEAST32_MIN; pub const __GCC_ATOMIC_POINTER_LOCK_FREE = 2; pub const __SIZE_MAX__ = @as(c_ulong, 18446744073709551615); pub const __INT_FAST64_MAX__ = @as(c_long, 9223372036854775807); pub const SIG_ATOMIC_MIN = __INTN_MIN(__SIG_ATOMIC_WIDTH__); pub const __CLANG_ATOMIC_LLONG_LOCK_FREE = 2; pub const __UINTPTR_MAX__ = @as(c_ulong, 18446744073709551615); pub const __UINT_FAST32_FMTx__ = "x"; pub const __PTRDIFF_FMTd__ = "ld"; pub const INT8_MIN = -INT8_C(127) - 1; pub const __LONG_LONG_MAX__ = @as(c_longlong, 9223372036854775807); pub const __CLANG_ATOMIC_BOOL_LOCK_FREE = 2; pub const __WCHAR_MAX__ = 2147483647; pub const __ATOMIC_SEQ_CST = 5; pub inline fn UINT8_C(v: var) @TypeOf(__uint_c(v, __int8_c_suffix)) { return __uint_c(v, __int8_c_suffix); } pub const __LDBL_MANT_DIG__ = 64; pub const UINT_LEAST32_MAX = __UINT_LEAST32_MAX; pub const __UINT_FAST8_MAX__ = 255; pub const __SIZEOF_SIZE_T__ = 8; pub const __STDC_VERSION__ = @as(c_long, 201112); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_16 = 1; pub const __OPENCL_MEMORY_SCOPE_WORK_GROUP = 1; pub const __SIZEOF_INT__ = 4; pub const UINTMAX_MAX = __UINTMAX_MAX__; pub const __UINT32_C_SUFFIX__ = U; pub const __x86_64__ = 1; pub inline fn va_end(ap: var) @TypeOf(__builtin_va_end(ap)) { return __builtin_va_end(ap); } pub const __FLT_MANT_DIG__ = 24; pub const __INT_LEAST8_MAX__ = 127; pub inline fn INT8_C(v: var) @TypeOf(__int_c(v, __int8_c_suffix)) { return __int_c(v, __int8_c_suffix); } pub const __UINTMAX_FMTo__ = "lo"; pub const __SIZE_FMTo__ = "lo"; pub const __SIZEOF_DOUBLE__ = 8; pub const __int32_c_suffix = __INT64_C_SUFFIX__; pub const __SIZEOF_WCHAR_T__ = 4;
c_leveldb.zig
const std = @import("std"); const time = std.time; const math = std.math; const memory = @import("memory.zig"); const pressure = @import("pressure.zig"); const process = @import("process.zig"); const config = @import("config.zig"); const MemoryStatusTag = enum { ok, near_terminal, }; const MemoryStatus = union(MemoryStatusTag) { /// Memory is "okay": basically no risk of memory thrashing ok: void, /// Nearing the terminal PSI cutoff: memory thrashing is occurring or close to it. Holds the current PSI value. near_terminal: f32 }; pub const Monitor = struct { mem_info: memory.MemoryInfo, /// Memory status as of last checked status: MemoryStatus, /// A pointer to a buffer of at least 128 bytes buffer: []u8, const Self = @This(); pub fn new(buffer: []u8) !Self { var self = Self{ .mem_info = undefined, .status = undefined, .buffer = buffer, }; try self.updateMemoryStats(); return self; } pub fn updateMemoryStats(self: *Self) !void { self.mem_info = try memory.MemoryInfo.new(); self.status = blk: { if (self.mem_info.available_ram_percent <= config.free_ram_threshold) { const psi = try pressure.pressureSomeAvg10(self.buffer); std.log.warn("read avg10: {}", .{psi}); break :blk MemoryStatus{ .near_terminal = psi }; } else { break :blk MemoryStatus.ok; } }; } fn freeUpMemory(self: *Self) !void { const victim_process = try process.findVictimProcess(self.buffer); // Check for memory stats again to see if the // low-memory situation was solved while // we were searching for our victim try self.updateMemoryStats(); if (self.isMemoryLow()) { try victim_process.terminateSelf(); } } pub fn poll(self: *Self) !void { while (true) { if (self.isMemoryLow()) { try self.freeUpMemory(); } try self.updateMemoryStats(); const sleep_time = self.sleepTimeNs(); std.log.warn("sleeping for {}ms, {}% of RAM is free", .{sleep_time, self.mem_info.available_ram_percent}); // Convert ms to ns time.sleep(sleep_time * 1000000); } } /// Determines for how long buztd should sleep /// This function is essentially a copy of how earlyoom calculates its sleep time /// /// Credits: https://github.com/rfjakob/earlyoom/blob/dea92ae67997fcb1a0664489c13d49d09d472d40/main.c#L365 /// MIT Licensed fn sleepTimeNs(self: *const Self) u64 { // Maximum expected memory fill rate as seen // with `stress -m 4 --vm-bytes 4G` const ram_fill_rate: i64 = 6000; // Maximum expected swap fill rate as seen // with membomb on zRAM const swap_fill_rate: i64 = 800; // Maximum and minimum sleep times (in ms) const min_sleep: i64 = 100; const max_sleep: i64 = 1000; // TODO: make these percentages configurable by args./config. file const ram_terminal_percent: f64 = 10.0; const swap_terminal_percent: f64 = 10.0; const f_ram_headroom_kib = (@intToFloat(f64, self.mem_info.available_ram_percent) - ram_terminal_percent) * (@intToFloat(f64, self.mem_info.total_ram_mb) * 10.0); const f_swap_headroom_kib = (@intToFloat(f64, self.mem_info.available_swap_percent) - swap_terminal_percent) * (@intToFloat(f64, self.mem_info.total_swap_mb) * 10.0); const i_ram_headroom_kib = math.max(0, @floatToInt(i64, f_ram_headroom_kib)); const i_swap_headroom_kib = math.max(0, @floatToInt(i64, f_swap_headroom_kib)); var time_to_sleep = @divFloor(i_ram_headroom_kib, ram_fill_rate) + @divFloor(i_swap_headroom_kib, swap_fill_rate); time_to_sleep = math.min(time_to_sleep, max_sleep); time_to_sleep = math.max(time_to_sleep, min_sleep); return @intCast(u64, time_to_sleep); } fn isMemoryLow(self: *const Self) bool { return switch (self.status) { MemoryStatusTag.ok => false, MemoryStatusTag.near_terminal => |psi| psi >= config.cutoff_psi, }; } };
src/monitor.zig
const std = @import("std"); const tvg = @import("tinyvg.zig"); pub fn create(writer: anytype) Builder(@TypeOf(writer)) { return .{ .writer = writer }; } // normal types: // style.type // uint(length - 1) // style // (line_width) // // outline types: // fill_style.type // line_style.type // // uint(length - 1) // // fill_style // line_style // line_width pub fn Builder(comptime Writer: type) type { return struct { const Self = @This(); pub const Error = Writer.Error || error{OutOfRange}; writer: Writer, state: State = .initial, scale: tvg.Scale = undefined, range: tvg.Range = undefined, color_encoding: tvg.ColorEncoding = undefined, pub fn writeHeader(self: *Self, width: u32, height: u32, scale: tvg.Scale, color_encoding: tvg.ColorEncoding, range: tvg.Range) Error!void { errdefer self.state = .faulted; std.debug.assert(self.state == .initial); try self.writer.writeAll(&[_]u8{ 0x72, 0x56, // magic tvg.current_version, // version @enumToInt(scale) | (@as(u8, @enumToInt(color_encoding)) << 4) | (@as(u8, @enumToInt(range)) << 6), }); switch (range) { .reduced => { const rwidth = mapSizeToType(u8, width) catch return error.OutOfRange; const rheight = mapSizeToType(u8, height) catch return error.OutOfRange; try self.writer.writeIntLittle(u8, rwidth); try self.writer.writeIntLittle(u8, rheight); }, .default => { const rwidth = mapSizeToType(u16, width) catch return error.OutOfRange; const rheight = mapSizeToType(u16, height) catch return error.OutOfRange; try self.writer.writeIntLittle(u16, rwidth); try self.writer.writeIntLittle(u16, rheight); }, .enhanced => { try self.writer.writeIntLittle(u32, width); try self.writer.writeIntLittle(u32, height); }, } self.color_encoding = color_encoding; self.scale = scale; self.range = range; self.state = .color_table; } pub fn writeColorTable(self: *Self, colors: []const tvg.Color) (error{UnsupportedColorEncoding} || Error)!void { errdefer self.state = .faulted; std.debug.assert(self.state == .color_table); const count = std.math.cast(u32, colors.len) catch return error.OutOfRange; try self.writeUint(count); switch (self.color_encoding) { .u565 => for (colors) |c| { const rgb8 = c.toRgba8(); const value: u16 = (@as(u16, ((rgb8[0] >> 3) & 0x1F)) << 0) | (@as(u16, ((rgb8[1] >> 2) & 0x2F)) << 5) | (@as(u16, ((rgb8[2] >> 3) & 0x1F)) << 11); try self.writer.writeIntLittle(u16, value); }, .u8888 => for (colors) |c| { var rgba = c.toRgba8(); try self.writer.writeIntLittle(u8, rgba[0]); try self.writer.writeIntLittle(u8, rgba[1]); try self.writer.writeIntLittle(u8, rgba[2]); try self.writer.writeIntLittle(u8, rgba[3]); }, .f32 => for (colors) |c| { try self.writer.writeIntLittle(u32, @bitCast(u32, c.r)); try self.writer.writeIntLittle(u32, @bitCast(u32, c.g)); try self.writer.writeIntLittle(u32, @bitCast(u32, c.b)); try self.writer.writeIntLittle(u32, @bitCast(u32, c.a)); }, .custom => return error.UnsupportedColorEncoding, } self.state = .body; } pub fn writeCustomColorTable(self: *Self) (error{UnsupportedColorEncoding} || Error)!void { errdefer self.state = .faulted; std.debug.assert(self.state == .color_table); if (self.color_encoding != .custom) { return error.UnsupportedColorEncoding; } self.state = .body; } pub fn writeFillPolygon(self: *Self, style: tvg.Style, points: []const tvg.Point) Error!void { try self.writeFillHeader(.fill_polygon, style, points.len); for (points) |pt| { try self.writePoint(pt); } } pub fn writeFillRectangles(self: *Self, style: tvg.Style, rectangles: []const tvg.Rectangle) Error!void { try self.writeFillHeader(.fill_rectangles, style, rectangles.len); for (rectangles) |rect| { try self.writeRectangle(rect); } } pub fn writeDrawLines(self: *Self, style: tvg.Style, line_width: f32, lines: []const tvg.Line) Error!void { try self.writeLineHeader(.draw_lines, style, line_width, lines.len); for (lines) |line| { try self.writePoint(line.start); try self.writePoint(line.end); } } pub fn writeDrawLineLoop(self: *Self, style: tvg.Style, line_width: f32, points: []const tvg.Point) Error!void { try self.writeLineHeader(.draw_line_loop, style, line_width, points.len); for (points) |pt| { try self.writePoint(pt); } } pub fn writeDrawLineStrip(self: *Self, style: tvg.Style, line_width: f32, points: []const tvg.Point) Error!void { try self.writeLineHeader(.draw_line_strip, style, line_width, points.len); for (points) |pt| { try self.writePoint(pt); } } pub fn writeOutlineFillPolygon(self: *Self, fill_style: tvg.Style, line_style: tvg.Style, line_width: f32, points: []const tvg.Point) Error!void { try self.writeOutlineFillHeader(.outline_fill_polygon, fill_style, line_style, line_width, points.len); for (points) |pt| { try self.writePoint(pt); } } pub fn writeOutlineFillRectangles(self: *Self, fill_style: tvg.Style, line_style: tvg.Style, line_width: f32, rectangles: []const tvg.Rectangle) Error!void { try self.writeOutlineFillHeader(.outline_fill_rectangles, fill_style, line_style, line_width, rectangles.len); for (rectangles) |rect| { try self.writeRectangle(rect); } } pub fn writeFillPath(self: *Self, style: tvg.Style, path: []const tvg.Path.Segment) Error!void { try validatePath(path); try self.writeFillHeader(.fill_path, style, path.len); try self.writePath(path); } pub fn writeDrawPath(self: *Self, style: tvg.Style, line_width: f32, path: []const tvg.Path.Segment) Error!void { try validatePath(path); try self.writeLineHeader(.draw_line_path, style, line_width, path.len); try self.writePath(path); } pub fn writeOutlineFillPath(self: *Self, fill_style: tvg.Style, line_style: tvg.Style, line_width: f32, path: []const tvg.Path.Segment) Error!void { try validatePath(path); try self.writeOutlineFillHeader(.outline_fill_path, fill_style, line_style, line_width, path.len); try self.writePath(path); } pub fn writeEndOfFile(self: *Self) Error!void { errdefer self.state = .faulted; std.debug.assert(self.state == .body); try self.writeCommandAndStyleType(.end_of_document, .flat); self.state = .end_of_file; } /// Writes the preamble for a `draw_*` command fn writeFillHeader(self: *Self, command: tvg.Command, style: tvg.Style, count: usize) Error!void { const actual_len = try validateLength(count); try self.writeCommandAndStyleType(command, style); try self.writeUint(actual_len); try self.writeStyle(style); } /// Writes the preamble for a `draw_*` command fn writeLineHeader(self: *Self, command: tvg.Command, style: tvg.Style, line_width: f32, count: usize) Error!void { const actual_len = try validateLength(count); try self.writeCommandAndStyleType(command, style); try self.writeUint(actual_len); try self.writeStyle(style); try self.writeUnit(line_width); } /// Writes the preamble for a `outline_fill_*` command fn writeOutlineFillHeader(self: *Self, command: tvg.Command, fill_style: tvg.Style, line_style: tvg.Style, line_width: f32, length: usize) Error!void { const total_count = try validateLength(length); const reduced_count = if (total_count < std.math.maxInt(u6)) @intToEnum(ReducedCount, @truncate(u6, total_count)) else return error.OutOfRange; try self.writeCommandAndStyleType(command, fill_style); try self.writeStyleTypeAndCount(line_style, reduced_count); try self.writeStyle(fill_style); try self.writeStyle(line_style); try self.writeUnit(line_width); } fn validateLength(count: usize) Error!u32 { if (count == 0) return error.OutOfRange; return std.math.cast(u32, count - 1) catch return error.OutOfRange; } fn validatePath(segments: []const tvg.Path.Segment) Error!void { _ = try validateLength(segments.len); for (segments) |segment| { _ = try validateLength(segment.commands.len); } } fn writeCommandAndStyleType(self: *Self, cmd: tvg.Command, style_type: tvg.StyleType) Error!void { try self.writer.writeByte((@as(u8, @enumToInt(style_type)) << 6) | @enumToInt(cmd)); } /// Encodes a 6 bit count as well as a 2 bit style type. fn writeStyleTypeAndCount(self: *Self, style: tvg.StyleType, mapped_count: ReducedCount) !void { const data = (@as(u8, @enumToInt(style)) << 6) | @enumToInt(mapped_count); try self.writer.writeByte(data); } /// Writes a Style without encoding the type. This must be done via a second channel. fn writeStyle(self: *Self, style: tvg.Style) Error!void { return switch (style) { .flat => |value| try self.writeUint(value), .linear, .radial => |grad| { try self.writePoint(grad.point_0); try self.writePoint(grad.point_1); try self.writeUint(grad.color_0); try self.writeUint(grad.color_1); }, }; } fn writePath(self: *Self, path: []const tvg.Path.Segment) !void { for (path) |item| { std.debug.assert(item.commands.len > 0); try self.writeUint(@intCast(u32, item.commands.len - 1)); } for (path) |item| { try self.writePoint(item.start); for (item.commands) |node| { const kind: u8 = @enumToInt(std.meta.activeTag(node)); const line_width = switch (node) { .line => |data| data.line_width, .horiz => |data| data.line_width, .vert => |data| data.line_width, .bezier => |data| data.line_width, .arc_circle => |data| data.line_width, .arc_ellipse => |data| data.line_width, .close => |data| data.line_width, .quadratic_bezier => |data| data.line_width, }; const tag: u8 = kind | if (line_width != null) @as(u8, 0x10) else 0; try self.writer.writeByte(tag); if (line_width) |width| { try self.writeUnit(width); } switch (node) { .line => |data| try self.writePoint(data.data), .horiz => |data| try self.writeUnit(data.data), .vert => |data| try self.writeUnit(data.data), .bezier => |data| { try self.writePoint(data.data.c0); try self.writePoint(data.data.c1); try self.writePoint(data.data.p1); }, .arc_circle => |data| { const flags: u8 = 0 | (@as(u8, @boolToInt(data.data.sweep)) << 1) | (@as(u8, @boolToInt(data.data.large_arc)) << 0); try self.writer.writeByte(flags); try self.writeUnit(data.data.radius); try self.writePoint(data.data.target); }, .arc_ellipse => |data| { const flags: u8 = 0 | (@as(u8, @boolToInt(data.data.sweep)) << 1) | (@as(u8, @boolToInt(data.data.large_arc)) << 0); try self.writer.writeByte(flags); try self.writeUnit(data.data.radius_x); try self.writeUnit(data.data.radius_y); try self.writeUnit(data.data.rotation); try self.writePoint(data.data.target); }, .quadratic_bezier => |data| { try self.writePoint(data.data.c); try self.writePoint(data.data.p1); }, .close => {}, } } } } fn writeUint(self: *Self, value: u32) Error!void { var iter = value; while (iter >= 0x80) { try self.writer.writeByte(@as(u8, 0x80) | @truncate(u7, iter)); iter >>= 7; } try self.writer.writeByte(@truncate(u7, iter)); } fn writeUnit(self: *Self, value: f32) Error!void { const val = self.scale.map(value).raw(); switch (self.range) { .reduced => { const reduced_val = std.math.cast(i8, val) catch return error.OutOfRange; try self.writer.writeIntLittle(i8, reduced_val); }, .default => { const reduced_val = std.math.cast(i16, val) catch return error.OutOfRange; try self.writer.writeIntLittle(i16, reduced_val); }, .enhanced => { try self.writer.writeIntLittle(i32, val); }, } } fn writePoint(self: *Self, point: tvg.Point) Error!void { try self.writeUnit(point.x); try self.writeUnit(point.y); } fn writeRectangle(self: *Self, rect: tvg.Rectangle) Error!void { try self.writeUnit(rect.x); try self.writeUnit(rect.y); try self.writeUnit(rect.width); try self.writeUnit(rect.height); } const State = enum { initial, color_table, body, end_of_file, faulted, }; }; } fn mapSizeToType(comptime Dest: type, value: usize) error{OutOfRange}!Dest { if (value == 0 or value > std.math.maxInt(Dest) + 1) { return error.OutOfRange; } if (value == std.math.maxInt(Dest)) return 0; return @intCast(Dest, value); } const ReducedCount = enum(u6) { // 0 = 64, everything else is equivalent _, }; const ground_truth = @import("ground-truth"); test "encode shield (default range, scale 1/256)" { var buffer: [1024]u8 = undefined; var stream = std.io.fixedBufferStream(&buffer); var writer = create(stream.writer()); try writer.writeHeader(24, 24, .@"1/256", .u8888, .default); try ground_truth.renderShield(&writer); } test "encode shield (reduced range, scale 1/4)" { var buffer: [1024]u8 = undefined; var stream = std.io.fixedBufferStream(&buffer); var writer = create(stream.writer()); try writer.writeHeader(24, 24, .@"1/4", .u8888, .reduced); try ground_truth.renderShield(&writer); } test "encode app_menu (default range, scale 1/256)" { var buffer: [1024]u8 = undefined; var stream = std.io.fixedBufferStream(&buffer); var writer = create(stream.writer()); try writer.writeHeader(48, 48, .@"1/256", .u8888, .default); try writer.writeColorTable(&[_]tvg.Color{ try tvg.Color.fromString("000000"), }); try writer.writeFillRectangles(tvg.Style{ .flat = 0 }, &[_]tvg.Rectangle{ tvg.rectangle(6, 12, 36, 4), tvg.rectangle(6, 22, 36, 4), tvg.rectangle(6, 32, 36, 4), }); try writer.writeEndOfFile(); } test "encode workspace (default range, scale 1/256)" { var buffer: [1024]u8 = undefined; var stream = std.io.fixedBufferStream(&buffer); var writer = create(stream.writer()); try writer.writeHeader(48, 48, .@"1/256", .u8888, .default); try writer.writeColorTable(&[_]tvg.Color{ try tvg.Color.fromString("008751"), try tvg.Color.fromString("83769c"), try tvg.Color.fromString("1d2b53"), }); try writer.writeFillRectangles(tvg.Style{ .flat = 0 }, &[_]tvg.Rectangle{tvg.rectangle(6, 6, 16, 36)}); try writer.writeFillRectangles(tvg.Style{ .flat = 1 }, &[_]tvg.Rectangle{tvg.rectangle(26, 6, 16, 16)}); try writer.writeFillRectangles(tvg.Style{ .flat = 2 }, &[_]tvg.Rectangle{tvg.rectangle(26, 26, 16, 16)}); try writer.writeEndOfFile(); } test "encode workspace_add (default range, scale 1/256)" { const Node = tvg.Path.Node; var buffer: [1024]u8 = undefined; var stream = std.io.fixedBufferStream(&buffer); var writer = create(stream.writer()); try writer.writeHeader(48, 48, .@"1/256", .u8888, .default); try writer.writeColorTable(&[_]tvg.Color{ try tvg.Color.fromString("008751"), try tvg.Color.fromString("83769c"), try tvg.Color.fromString("ff004d"), }); try writer.writeFillRectangles(tvg.Style{ .flat = 0 }, &[_]tvg.Rectangle{tvg.rectangle(6, 6, 16, 36)}); try writer.writeFillRectangles(tvg.Style{ .flat = 1 }, &[_]tvg.Rectangle{tvg.rectangle(26, 6, 16, 16)}); try writer.writeFillPath(tvg.Style{ .flat = 2 }, &[_]tvg.Path.Segment{ tvg.Path.Segment{ .start = tvg.point(26, 32), .commands = &[_]Node{ Node{ .horiz = .{ .data = 32 } }, Node{ .vert = .{ .data = 26 } }, Node{ .horiz = .{ .data = 36 } }, Node{ .vert = .{ .data = 32 } }, Node{ .horiz = .{ .data = 42 } }, Node{ .vert = .{ .data = 36 } }, Node{ .horiz = .{ .data = 36 } }, Node{ .vert = .{ .data = 42 } }, Node{ .horiz = .{ .data = 32 } }, Node{ .vert = .{ .data = 36 } }, Node{ .horiz = .{ .data = 26 } }, }, }, }); try writer.writeEndOfFile(); } test "encode arc_variants (default range, scale 1/256)" { const Node = tvg.Path.Node; var buffer: [1024]u8 = undefined; var stream = std.io.fixedBufferStream(&buffer); var writer = create(stream.writer()); try writer.writeHeader(92, 92, .@"1/256", .u8888, .default); try writer.writeColorTable(&[_]tvg.Color{ try tvg.Color.fromString("40ff00"), }); try writer.writeFillPath(tvg.Style{ .flat = 0 }, &[_]tvg.Path.Segment{ tvg.Path.Segment{ .start = tvg.point(48, 32), .commands = &[_]Node{ Node{ .horiz = .{ .data = 64 } }, Node{ .arc_ellipse = .{ .data = .{ .radius_x = 18.5, .radius_y = 18.5, .rotation = 0, .large_arc = false, .sweep = true, .target = tvg.point(80, 48) } } }, Node{ .vert = .{ .data = 64 } }, Node{ .arc_ellipse = .{ .data = .{ .radius_x = 18.5, .radius_y = 18.5, .rotation = 0, .large_arc = false, .sweep = false, .target = tvg.point(64, 80) } } }, Node{ .horiz = .{ .data = 48 } }, Node{ .arc_ellipse = .{ .data = .{ .radius_x = 18.5, .radius_y = 18.5, .rotation = 0, .large_arc = true, .sweep = true, .target = tvg.point(32, 64) } } }, Node{ .vert = .{ .data = 64 } }, Node{ .arc_ellipse = .{ .data = .{ .radius_x = 18.5, .radius_y = 18.5, .rotation = 0, .large_arc = true, .sweep = false, .target = tvg.point(48, 32) } } }, }, }, }); try writer.writeEndOfFile(); }
src/lib/builder.zig
//! PCG32 - http://www.pcg-random.org/ //! //! PRNG const std = @import("std"); const Random = std.rand.Random; const Pcg = @This(); const default_multiplier = 6364136223846793005; random: Random, s: u64, i: u64, pub fn init(init_s: u64) Pcg { var pcg = Pcg{ .random = Random{ .fillFn = fill }, .s = undefined, .i = undefined, }; pcg.seed(init_s); return pcg; } fn next(self: *Pcg) u32 { const l = self.s; self.s = l *% default_multiplier +% (self.i | 1); const xor_s = @truncate(u32, ((l >> 18) ^ l) >> 27); const rot = @intCast(u32, l >> 59); return (xor_s >> @intCast(u5, rot)) | (xor_s << @intCast(u5, (0 -% rot) & 31)); } fn seed(self: *Pcg, init_s: u64) void { // Pcg requires 128-bits of seed. var gen = std.rand.SplitMix64.init(init_s); self.seedTwo(gen.next(), gen.next()); } fn seedTwo(self: *Pcg, init_s: u64, init_i: u64) void { self.s = 0; self.i = (init_s << 1) | 1; self.s = self.s *% default_multiplier +% self.i; self.s +%= init_i; self.s = self.s *% default_multiplier +% self.i; } fn fill(r: *Random, buf: []u8) void { const self = @fieldParentPtr(Pcg, "random", r); var i: usize = 0; const aligned_len = buf.len - (buf.len & 7); // Complete 4 byte segments. while (i < aligned_len) : (i += 4) { var n = self.next(); comptime var j: usize = 0; inline while (j < 4) : (j += 1) { buf[i + j] = @truncate(u8, n); n >>= 8; } } // Remaining. (cuts the stream) if (i != buf.len) { var n = self.next(); while (i < buf.len) : (i += 1) { buf[i] = @truncate(u8, n); n >>= 4; } } } test "pcg sequence" { var r = Pcg.init(0); const s0: u64 = 0x9394bf54ce5d79de; const s1: u64 = 0x84e9c579ef59bbf7; r.seedTwo(s0, s1); const seq = [_]u32{ 2881561918, 3063928540, 1199791034, 2487695858, 1479648952, 3247963454, }; for (seq) |s| { std.testing.expect(s == r.next()); } }
lib/std/rand/Pcg.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day02.txt"); const Direction = enum { forward, up, down }; const uint = uint; const split = std.mem.split; const print = std.debug.print; const parseInt = std.fmt.parseInt; pub fn main() !void { { // part 1 var lines = util.strtok(data, "\n"); var x: uint = 0; var y: uint = 0; while (lines.next()) |line| { var splitter = split(u8, line, " "); var direction = std.meta.stringToEnum(Direction, splitter.next().?).?; var distance = try parseInt(uint, splitter.next().?, 10); switch (direction) { .forward => { x += distance; }, .up => { y -= distance; }, .down => { y += distance; }, } } print("{d}, {d} -> {d}\n", .{ x, y, x * y }); } { // part 2 var lines = util.strtok(data, "\n"); var x: i128 = 0; var y: i128 = 0; var aim: i128 = 0; while (lines.next()) |line| { var splitter = split(u8, line, " "); var direction = std.meta.stringToEnum(Direction, splitter.next().?).?; var distance = try parseInt(i128, splitter.next().?, 10); switch (direction) { .forward => { x += distance; y += (aim * distance); }, .up => { aim -= distance; }, .down => { aim += distance; }, } } print("{d}, {d} -> {d}\n", .{ x, y, x * y }); } }
src/day02.zig
const std = @import("std"); const ArenaAllocator = std.heap.ArenaAllocator; const xml = @import("lib.zig"); const Writer = @This(); const logger = std.log.scoped(.@"xml.Writer"); usingnamespace @import("traverser.zig").StructTraverser(Writer); arena: ArenaAllocator, doc: xml.Document = undefined, pub fn init(allocator: std.mem.Allocator) Writer { return .{ .arena = ArenaAllocator.init(allocator) }; } pub fn deinit(self: *Writer) void { self.arena.deinit(); } pub fn writeStructToDocument(self: *Writer, input: anytype) !xml.Document { self.doc = try xml.Document.new(); try self.traverseStruct(&input, try self.doc.toNode()); return self.doc; } pub fn handleSubStruct(self: *Writer, comptime name: []const u8, input: anytype, parent: xml.Node) !void { var sub_parent = try self.doc.createElement(name ++ "\x00"); try self.traverseStruct(input, try sub_parent.toNode()); switch (parent) { .Document => |d| try d.appendChild(sub_parent), .Element => |e| try e.appendChild(sub_parent), else => { logger.warn("Invalid node type for node named {s}", .{name}); return xml.Error; } } } pub fn handlePointer(self: *Writer, comptime name: []const u8, input: anytype, parent: xml.Element) !void { for (input.*) |subinput| { try self.traverseField(&subinput, name, try parent.toNode()); } } pub fn handleOptional(self: *Writer, comptime name: []const u8, input: anytype, parent: xml.Element) !void { if (input.*) |i| { try self.traverseField(&i, name, try parent.toNode()); } } pub fn handleString(self: *Writer, comptime _: []const u8, input: anytype, parent: xml.Element) !void { var text = try self.doc.createTextNode(try self.arena.allocator().dupeZ(u8, input.*)); try parent.appendChild(text); } pub fn handleInt(self: *Writer, comptime _: []const u8, input: anytype, parent: xml.Element) !void { var text = try self.doc.createTextNode(try std.fmt.allocPrintZ(self.arena.allocator(), "{d}", .{input.*})); try parent.appendChild(text); } pub fn handleBool(self: *Writer, comptime _: []const u8, input: anytype, parent: xml.Element) !void { var text = try self.doc.createTextNode(if (input.*) "1" else "0"); try parent.appendChild(text); } pub fn handleAttributes(self: *Writer, input: anytype, parent: xml.Element) !void { inline for (@typeInfo(@TypeOf(input.*)).Struct.fields) |field| { const field_value_opt: ?[]const u8 = @field(input.*, field.name); if (field_value_opt) |field_value| { try parent.setAttribute(field.name ++ "\x00", try self.arena.allocator().dupeZ(u8, field_value)); } } } pub fn handleSingleItem(self: *Writer, comptime name: []const u8, input: anytype, parent: xml.Element) !void { var node = try self.doc.createElement(name ++ "\x00"); try self.traverseField(input, "__item__", try node.toNode()); try parent.appendChild(node); }
src/writer.zig
const std = @import("std"); const mem = std.mem; const math = std.math; const meta = std.meta; const trait = std.meta.trait; pub fn typed(comptime val_t: type) type { return struct { pub const func = @import("fn_deriv.zig"); pub const Float = val_t; // const LayerType = enum { // Input, // Output, // FeedForward, // }; // pub fn Layer(comptime neurons_: usize, comptime weigts_per_neuron_: usize, comptime activation_: anytype) type { // return struct { // const Self = @This(); // pub const neurons_len = neurons_; // pub const weights_per_neuron = weigts_per_neuron_; // pub const bisases_len = biases_; // either 0 or neurons_len // pub const activation = activation_; // out: ?@Vector(neurons_len, Float) = null, // bias: ?@Vector(neurons_len, Float) = null, // weights: ?[neurons]@Vector(weights_per_neuron, Float) = null, // pub fn empty() Self { // return .{ null, null, null }; // } // }; // } pub fn TestCase(comptime input_len_: usize, comptime output_len_: usize) type { return struct { pub const input_len = input_len_; pub const output_len = output_len_; input: @Vector(input_len, Float), answer: @Vector(output_len, Float) }; } pub fn TestAccessor(comptime test_case_t : type) type { return struct { const Self = @This(); countFn: fn (s: *Self) usize, grabFn: fn (s: *Self, idx: usize) *const test_case_t, freeFn: ?fn (s: *Self, tc: *const test_case_t) void = null, pub fn testCount(self: *Self) usize { return self.countFn(self); } // call freeTest to release data (for loaders that support it) pub fn grabTest(self: *Self, idx: usize) * const test_case_t { return self.grabFn(self, idx); } pub fn freeTest(self: *Self, tc: *const test_case_t) void { if (self.freeFn) |f| return f(self, tc); } }; } // Feed-Forward // takes current neurons throught weights propogates it forward to next layer neurons `out`, then activates the neurons to `out_activated` // `out` can be void - activation will be done (if its not void) however un-activated output won't be stored and will be discarded // `out_activated` can be void - activation will be skipped pub fn forward(neurons: anytype, weights: anytype, next_activation: anytype, next_biases: anytype, out_activated: anytype) void { @setFloatMode(std.builtin.FloatMode.Optimized); // comptime checks const do_activate: bool = comptime ablk: { if (@TypeOf(out_activated) != @TypeOf(void)) { if (@typeInfo(@TypeOf(out_activated)) != .Pointer) @compileError("output_values has to be writeable pointer!"); if (@typeInfo(@TypeOf(out_activated.*)) != .Vector) @compileError("output_values must be pointer to vector!"); break :ablk true; } else break :ablk false; }; const olen: u32 = comptime @typeInfo(@TypeOf(weights[0])).Vector.len; const nlen: u32 = comptime @typeInfo(@TypeOf(neurons)).Vector.len; comptime if (@typeInfo(@TypeOf(neurons)) != .Vector) @compileError("neurons must be vector!"); comptime if (@typeInfo(@TypeOf(weights)) != .Array and @typeInfo(@TypeOf(weights)) != .Pointer and @typeInfo(@TypeOf(weights[0])) != .Vector) @compileError("weights have to be array or slice of vectors!"); comptime if (nlen != weights.len or olen != @typeInfo(@TypeOf(weights[0])).Vector.len) @compileError("weights have to be array of [neurons.len] of @vectors(output.len)!"); // Compute var nidx: u32 = 0; var res = next_biases; while (nidx < nlen) : (nidx += 1) { res += @splat(olen, neurons[nidx]) * weights[nidx]; } if (do_activate) { assertFinite(res, "feedforward: res"); out_activated.* = next_activation.f(res); assertFinite(out_activated.*, "feedforward: out_activated"); } } // d_oerr_o_na = 𝝏err_total / 𝝏h = how much Output error for {layer + 1} changes with respect to output (non activated) // // pub fn backpropHidden(d_oerr_o_na : anytype, ) void { // } pub fn randomArray(rnd: *std.rand.Random, comptime t: type, comptime len: usize) [len]t { @setFloatMode(std.builtin.FloatMode.Optimized); var rv: [len]Float = undefined; const coef = 1 / @as(Float, len); for (rv) |*v| { v.* = @floatCast(Float, rnd.floatNorm(f64)) * coef; } return rv; } pub fn randomize(rnd: *std.rand.Random, out: anytype) void { comptime if (@typeInfo(@TypeOf(out)) != .Pointer) @compileError("out must be pointer!"); const tinfo = @typeInfo(@TypeOf(out.*)); if (tinfo == .Vector) { const arr = randomArray(rnd, tinfo.Vector.child, tinfo.Vector.len); out.* = arr; } else if (tinfo == .Array) { const cinfo = @typeInfo(tinfo.Array.child); if (cinfo == .Array or cinfo == .Vector) { for (out.*) |*o| { randomize(rnd, o); } } else { out.* = randomArray(rnd, tinfo.Vector.child, tinfo.Vector.len); @compileError("unexpected!"); } } } pub fn isFinite(v: anytype) bool { const ti = @typeInfo(@TypeOf(v)); if (ti == .Vector) { const len = ti.Vector.len; var i: usize = 0; while (i < len) : (i += 1) { if (!std.math.isFinite(v[i])) return false; } } else { for (v) |vi| { if (!std.math.isFinite(vi)) return false; } } return true; } pub fn assertFinite(v: anytype, msg: []const u8) void { if (std.builtin.mode != .Debug and std.builtin.mode != .ReleaseSafe) return; if (!isFinite(v)) { std.debug.panic("Values aren't finite!\n{s}\n{}", .{ msg, v }); } } }; }
src/nnet.zig
const ArgvIterator = @This(); const std = @import("std"); const mem = std.mem; const testing = std.testing; pub const RawArg = struct { name: []const u8, pub fn init(name: []const u8) RawArg { return RawArg{ .name = name }; } pub fn isShort(self: *RawArg) bool { return (mem.startsWith(u8, self.name, "-") and mem.count(u8, self.name, "-") == 1); } pub fn isLong(self: *RawArg) bool { return (mem.startsWith(u8, self.name, "--")); } pub fn toShort(self: *RawArg) ?ShortFlags { const trimmed_name = mem.trim(u8, self.name, "-"); if (trimmed_name.len == 0) { return null; } else { return ShortFlags.init(trimmed_name); } } pub fn toLong(self: *RawArg) ?LongFlag { const trimmed_name = mem.trim(u8, self.name, "--"); if (trimmed_name.len == 0) return null; // Extract value if passed as like '--flag=value' if (mem.indexOfScalar(u8, trimmed_name, '=')) |delimiter_pos| { const flag_name = trimmed_name[0..delimiter_pos]; const flag_value = trimmed_name[delimiter_pos + 1 ..]; if (flag_value.len == 0) { return LongFlag.init(flag_name, null); } else { return LongFlag.init(flag_name, flag_value); } } else { return LongFlag.init(trimmed_name, null); } } }; pub const ShortFlags = struct { name: []const u8, /// Any value after the '=' sign fixed_value: ?[]const u8, /// Will be use to iterate chained flags (if have) /// or to consume rest of the values next_index: usize, current_index: usize, pub fn init(name: []const u8) ShortFlags { var self = ShortFlags{ .name = name, .fixed_value = null, .next_index = 0, .current_index = 0, }; self.checkAndSetFixedValue(); return self; } fn checkAndSetFixedValue(self: *ShortFlags) void { if (self.name.len >= 2 and self.name[1] == '=') { self.fixed_value = self.name[2..]; self.name = self.name[0..1]; } } pub fn nextFlag(self: *ShortFlags) ?u8 { if (self.next_index >= self.name.len) return null; defer self.next_index += 1; self.current_index = self.next_index; return self.name[self.current_index]; } /// Return remaining items as value pub fn nextValue(self: *ShortFlags) ?[]const u8 { if (self.fixed_value) |v| return v; if (self.next_index >= self.name.len) return null; defer self.next_index = self.name.len; return self.name[self.next_index..]; } pub fn rollbackValue(self: *ShortFlags) void { if ((self.current_index + 1) >= self.name.len) { self.next_index = self.current_index; } else { self.next_index = self.current_index + 1; } } }; pub const LongFlag = struct { name: []const u8, value: ?[]const u8, pub fn init(name: []const u8, value: ?[]const u8) LongFlag { return LongFlag{ .name = name, .value = value }; } }; argv: []const [:0]const u8, current_index: usize, pub fn init(argv: []const [:0]const u8) ArgvIterator { return ArgvIterator{ .argv = argv, .current_index = 0, }; } pub fn next(self: *ArgvIterator) ?RawArg { defer self.current_index += 1; if (self.current_index >= self.argv.len) return null; const value = @as([]const u8, self.argv[self.current_index]); return RawArg.init(value); } pub fn nextValue(self: *ArgvIterator) ?[]const u8 { var next_value = self.next() orelse return null; if (next_value.isShort() or next_value.isLong()) { // Rollback value to prevent it from skipping while parsing self.current_index -= 1; return null; } else { return next_value.name; } } pub fn rest(self: *ArgvIterator) ?[]const [:0]const u8 { defer self.current_index = self.argv.len; if (self.current_index >= self.argv.len) return null; return self.argv[self.current_index..]; } test "ArgvIterator" { const argv: []const [:0]const u8 = &.{ "cmd", "--long-bool-flag", "--long-arg-flag=value1", "--long-arg-flag2", "value2", "-a", "-b=value3", "-cvalue4", "-d", "value5", "-abcd", }; var iter = ArgvIterator.init(argv); try testing.expectEqualStrings("cmd", iter.nextValue().?); var arg1 = iter.next().?; try testing.expectEqual(true, arg1.isLong()); var arg2 = iter.next().?; try testing.expectEqual(true, arg2.isLong()); var arg2_long = arg2.toLong().?; try testing.expectEqualStrings("long-arg-flag", arg2_long.name); try testing.expectEqualStrings("value1", arg2_long.value.?); var arg3 = iter.next().?; try testing.expectEqual(true, arg3.isLong()); var arg3_long = arg3.toLong().?; try testing.expectEqualStrings("long-arg-flag2", arg3_long.name); try testing.expect(arg3_long.value == null); try testing.expectEqualStrings("value2", iter.nextValue().?); var arg4 = iter.next().?; try testing.expectEqual(true, arg4.isShort()); var arg5 = iter.next().?; try testing.expectEqual(true, arg5.isShort()); var arg5_short = arg5.toShort().?; try testing.expect('b' == arg5_short.nextFlag().?); try testing.expectEqualStrings("value3", arg5_short.nextValue().?); var arg6 = iter.next().?; try testing.expectEqual(true, arg6.isShort()); var arg6_short = arg6.toShort().?; try testing.expect('c' == arg6_short.nextFlag().?); try testing.expectEqualStrings("value4", arg6_short.nextValue().?); var arg7 = iter.next().?; try testing.expectEqual(true, arg7.isShort()); var arg7_short = arg7.toShort().?; try testing.expect('d' == arg7_short.nextFlag().?); try testing.expect(null == arg7_short.nextValue()); try testing.expectEqualStrings("value5", iter.nextValue().?); var arg8 = iter.next().?; try testing.expectEqual(true, arg8.isShort()); var arg8_short = arg8.toShort().?; try testing.expect('a' == arg8_short.nextFlag().?); try testing.expect('b' == arg8_short.nextFlag().?); try testing.expect('c' == arg8_short.nextFlag().?); try testing.expect('d' == arg8_short.nextFlag().?); } test "ShortFlags" { const ex_flag = "fvalue"; var short_flag = ShortFlags.init(ex_flag); try testing.expect(short_flag.nextFlag().? == 'f'); try testing.expectEqualStrings("value", short_flag.nextValue().?); try testing.expect(short_flag.nextValue() == null); short_flag.rollbackValue(); try testing.expectEqualStrings("value", short_flag.nextValue().?); }
src/ArgvIterator.zig
const std = @import("std"); const testing = std.testing; const allocator = std.heap.page_allocator; pub const Map = struct { const Color = enum { White, Black, pub fn flip(color: Color) Color { return switch (color) { Color.White => Color.Black, Color.Black => Color.White, }; } }; const Dir = enum { E, SE, SW, W, NW, NE, }; // These are Cube Coordinates in a hexagonal grid. // Basically a 3D coordinate system with one additional restriction: // // x + y + z = 0 // // This makes it into an effective way of representing the hex grid on a 2D // surface. // https://www.redblobgames.com/grids/hexagons/ const Pos = struct { x: isize, y: isize, z: isize, pub fn init(x: isize, y: isize, z: isize) Pos { var self = Pos{ .x = x, .y = y, .z = z, }; return self; } pub fn is_valid(self: Pos) bool { return self.x + self.y + self.z == 0; } pub fn move(self: *Pos, dir: Dir) void { // Notice how the hex invariant is maintained in each case, since // we always add 1 and subtract 1. switch (dir) { Dir.E => { self.x += 1; self.y += -1; self.z += 0; }, Dir.SE => { self.x += 0; self.y += -1; self.z += 1; }, Dir.SW => { self.x += -1; self.y += 0; self.z += 1; }, Dir.W => { self.x += -1; self.y += 1; self.z += 0; }, Dir.NW => { self.x += 0; self.y += 1; self.z += -1; }, Dir.NE => { self.x += 1; self.y += 0; self.z += -1; }, } } }; min: Pos, max: Pos, tiles: [2]std.AutoHashMap(Pos, Color), curr: usize, pub fn init() Map { var self = Map{ .min = Pos.init(std.math.maxInt(isize), std.math.maxInt(isize), std.math.maxInt(isize)), .max = Pos.init(std.math.minInt(isize), std.math.minInt(isize), std.math.minInt(isize)), .tiles = undefined, .curr = 0, }; self.tiles[0] = std.AutoHashMap(Pos, Color).init(allocator); self.tiles[1] = std.AutoHashMap(Pos, Color).init(allocator); return self; } pub fn deinit(self: *Map) void { self.tiles[1].deinit(); self.tiles[0].deinit(); } pub fn process_tile(self: *Map, line: []const u8) void { // std.debug.warn("TILE [{}]\n", .{line}); var pos = Pos.init(0, 0, 0); var p: u8 = 0; for (line) |c| { // std.debug.warn(" c [{c}]\n", .{c}); switch (c) { 'e' => { switch (p) { 0 => pos.move(Dir.E), 'n' => pos.move(Dir.NE), 's' => pos.move(Dir.SE), else => @panic("E"), } p = 0; }, 'w' => { switch (p) { 0 => pos.move(Dir.W), 'n' => pos.move(Dir.NW), 's' => pos.move(Dir.SW), else => @panic("W"), } p = 0; }, 's' => p = c, 'n' => p = c, else => @panic("DIR"), } } const current = self.get_color(pos); const next = current.flip(); // std.debug.warn("FLIP {} -> {}\n", .{ current, next }); _ = self.tiles[self.curr].put(pos, next) catch unreachable; self.update_bounday(pos); } pub fn get_color(self: Map, pos: Pos) Color { return if (self.tiles[self.curr].contains(pos)) self.tiles[self.curr].get(pos).? else Color.White; } pub fn count_black(self: Map) usize { return self.count_color(Color.Black); } fn count_color(self: Map, color: Color) usize { var count: usize = 0; var it = self.tiles[self.curr].iterator(); while (it.next()) |kv| { if (kv.value_ptr.* != color) continue; count += 1; } return count; } pub fn run(self: *Map, turns: usize) void { var t: usize = 0; while (t < turns) : (t += 1) { // if (t % 10 == 0) std.debug.warn("Run {}/{}\n", .{ t, turns }); self.step(); } } fn update_bounday(self: *Map, pos: Pos) void { if (self.min.x > pos.x) self.min.x = pos.x; if (self.min.y > pos.y) self.min.y = pos.y; if (self.min.z > pos.z) self.min.z = pos.z; if (self.max.x < pos.x) self.max.x = pos.x; if (self.max.y < pos.y) self.max.y = pos.y; if (self.max.z < pos.z) self.max.z = pos.z; } fn step(self: *Map) void { var ops: usize = 0; var next = 1 - self.curr; const min = self.min; const max = self.max; // std.debug.warn("STEP {} {}\n", .{ min, max }); var z: isize = min.z - 1; while (z <= max.z + 1) : (z += 1) { var y: isize = min.y - 1; while (y <= max.y + 1) : (y += 1) { var x: isize = min.x - 1; while (x <= max.x + 1) : (x += 1) { const pos = Pos.init(x, y, z); if (!pos.is_valid()) continue; _ = self.tiles[next].remove(pos); const adjacent = self.count_adjacent(pos); const color = self.get_color(pos); var new = color; switch (color) { Color.Black => { if (adjacent == 0 or adjacent > 2) new = color.flip(); }, Color.White => { if (adjacent == 2) new = color.flip(); }, } _ = self.tiles[next].put(pos, new) catch unreachable; self.update_bounday(pos); ops += 1; } } } self.curr = next; // std.debug.warn("OPS: {}\n", .{ops}); } fn count_adjacent(self: Map, pos: Pos) usize { var count: usize = 0; var c: usize = 0; while (c < 6) : (c += 1) { var neighbor = pos; switch (c) { 0 => neighbor.move(Dir.E), 1 => neighbor.move(Dir.SE), 2 => neighbor.move(Dir.SW), 3 => neighbor.move(Dir.W), 4 => neighbor.move(Dir.NW), 5 => neighbor.move(Dir.NE), else => @panic("ADJACENT"), } const color = self.get_color(neighbor); if (color != Color.Black) continue; count += 1; } return count; } }; test "sample part a" { const data: []const u8 = \\sesenwnenenewseeswwswswwnenewsewsw \\neeenesenwnwwswnenewnwwsewnenwseswesw \\seswneswswsenwwnwse \\nwnwneseeswswnenewneswwnewseswneseene \\swweswneswnenwsewnwneneseenw \\eesenwseswswnenwswnwnwsewwnwsene \\sewnenenenesenwsewnenwwwse \\wenwwweseeeweswwwnwwe \\wsweesenenewnwwnwsenewsenwwsesesenwne \\neeswseenwwswnwswswnw \\nenwswwsewswnenenewsenwsenwnesesenew \\enewnwewneswsewnwswenweswnenwsenwsw \\sweneswneswneneenwnewenewwneswswnese \\swwesenesewenwneswnwwneseswwne \\enesenwswwswneneswsenwnewswseenwsese \\wnwnesenesenenwwnenwsewesewsesesew \\nenewswnwewswnenesenwnesewesw \\eneswnwswnwsenenwnwnwwseeswneewsenese \\neswnwewnwnwseenwseesewsenwsweewe \\wseweeenwnesenwwwswnew ; var map = Map.init(); defer map.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { map.process_tile(line); } const black = map.count_black(); try testing.expect(black == 10); } test "sample part b" { const data: []const u8 = \\sesenwnenenewseeswwswswwnenewsewsw \\neeenesenwnwwswnenewnwwsewnenwseswesw \\seswneswswsenwwnwse \\nwnwneseeswswnenewneswwnewseswneseene \\swweswneswnenwsewnwneneseenw \\eesenwseswswnenwswnwnwsewwnwsene \\sewnenenenesenwsewnenwwwse \\wenwwweseeeweswwwnwwe \\wsweesenenewnwwnwsenewsenwwsesesenwne \\neeswseenwwswnwswswnw \\nenwswwsewswnenenewsenwsenwnesesenew \\enewnwewneswsewnwswenweswnenwsenwsw \\sweneswneswneneenwnewenewwneswswnese \\swwesenesewenwneswnwwneseswwne \\enesenwswwswneneswsenwnewswseenwsese \\wnwnesenesenenwwnenwsewesewsesesew \\nenewswnwewswnenesenwnesewesw \\eneswnwswnwsenenwnwnwwseeswneewsenese \\neswnwewnwnwseenwseesewsenwsweewe \\wseweeenwnesenwwwswnew ; var map = Map.init(); defer map.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { map.process_tile(line); } try testing.expect(map.count_black() == 10); map.run(1); try testing.expect(map.count_black() == 15); map.run(1); try testing.expect(map.count_black() == 12); map.run(1); try testing.expect(map.count_black() == 25); map.run(1); try testing.expect(map.count_black() == 14); map.run(1); try testing.expect(map.count_black() == 23); map.run(1); try testing.expect(map.count_black() == 28); map.run(1); try testing.expect(map.count_black() == 41); map.run(1); try testing.expect(map.count_black() == 37); map.run(1); try testing.expect(map.count_black() == 49); map.run(1); try testing.expect(map.count_black() == 37); map.run(10); try testing.expect(map.count_black() == 132); map.run(10); try testing.expect(map.count_black() == 259); map.run(10); try testing.expect(map.count_black() == 406); map.run(10); try testing.expect(map.count_black() == 566); map.run(10); try testing.expect(map.count_black() == 788); map.run(10); try testing.expect(map.count_black() == 1106); map.run(10); try testing.expect(map.count_black() == 1373); map.run(10); try testing.expect(map.count_black() == 1844); map.run(10); try testing.expect(map.count_black() == 2208); }
2020/p24/map.zig
const std = @import("std"); const with_trace = true; const assert = std.debug.assert; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } pub fn main() anyerror!void { const stdout = std.io.getStdOut().writer(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const limit = 1 * 1024 * 1024 * 1024; const text = try std.fs.cwd().readFileAlloc(allocator, "day7.txt", limit); defer allocator.free(text); var count: u32 = 0; { var it = std.mem.tokenize(u8, text, "\n"); while (it.next()) |line_full| { const line = std.mem.trim(u8, line_full, " \n\r\t"); if (line.len == 0) continue; var bracket: u32 = 0; var BAB: [100][3]u8 = undefined; var ABA: [100][3]u8 = undefined; var BAB_count: u32 = 0; var ABA_count: u32 = 0; var queue = [3]u8{ 0, 1, 2 }; for (line) |c| { if (c == '[') { bracket += 1; queue = [3]u8{ 0, 1, 2 }; } else if (c == ']') { bracket -= 1; queue = [3]u8{ 0, 1, 2 }; } else { queue[0] = queue[1]; queue[1] = queue[2]; queue[2] = c; if (queue[0] == queue[2] and queue[1] != queue[0]) { if (bracket > 0) { BAB[BAB_count] = queue; BAB_count += 1; } else { ABA[ABA_count] = queue; ABA_count += 1; } } } } const found = blk: { for (BAB[0..BAB_count]) |bab| { for (ABA[0..ABA_count]) |aba| { if (aba[0] == bab[1] and aba[1] == bab[0]) { break :blk true; } } } break :blk false; }; if (found) { trace("ssl={}\n", .{line}); count += 1; } } } try stdout.print("answer='{}'\n", .{count}); }
2016/day7.zig
const std = @import("std"); const expect = std.testing.expect; pub const Value = union(enum) { int: i64, uint: u64, nil, bool: bool, float: f64, string: []const u8, binary: []const u8, array: std.ArrayList(Value), map: std.StringHashMap(Value), pub fn fromInt(val: i64) Value { return .{ .int = val }; } pub fn fromUint(val: u64) Value { return .{ .uint = val }; } pub fn fromBool(val: bool) Value { return .{ .bool = val }; } pub fn fromFloat(val: float) Value { return .{ .float = val }; } pub fn fromString(val: []const u8) Value { return .{ .string = val }; } pub fn fromBinary(val: []const u8) Value { return .{ .bool = val }; } pub fn fromArray(val: []Value) Value { return .{ .array = val }; } pub fn fromMap(val: std.StringHashMap(Value)) Value { return .{ .map = val }; } pub fn equal(self: Value, oth: Value) bool { return switch (self) { .int => |val| oth.equalInt(val), .uint => |val| oth.equalUint(val), .nil => oth.isNil(), .bool => |val| oth.equalBool(val), .float => |val| oth.equalFloat(val), .string => |val| oth.equalString(val), .binary => |val| oth.equalBinary(val), .array => |val| oth.equalArray(val), .map => |val| oth.equalMap(val), }; } pub fn free(self: *Value) void { switch (self.*) { .array => { for (self.array.items) |*v| { v.free(); } self.array.deinit(); }, .map => { var it = self.map.iterator(); while (it.next()) |i| { i.value.free(); } self.map.deinit(); }, else => {}, } } pub fn dump(self: Value) void { self.dumpImpl(0); std.debug.print("\n", .{}); } fn dumpImpl(self: Value, indent: u8) void { switch (self) { .int => |val| std.debug.print("{}", .{val}), .uint => |val| std.debug.print("{}", .{val}), .nil => std.debug.print("null", .{}), .bool => |val| std.debug.print("{}", .{val}), .float => |val| std.debug.print("{}", .{val}), .string => |val| std.debug.print("\"{}\"", .{val}), .binary => |val| dumpBinary(val, indent), .array => |val| dumpArray(val, indent), .map => |val| dumpMap(val, indent), } } fn dumpMap(map: std.StringHashMap(Value), indent: u8) void { std.debug.print("{}\n", .{"{"}); var i: usize = 0; var it = map.iterator(); while (it.next()) |entry| { dumpIndent(indent + 1); std.debug.print("\"{}\": ", .{entry.key}); entry.value.dumpImpl(indent + 1); if (i + 1 != map.count()) { std.debug.print(",\n", .{}); } else { std.debug.print("\n", .{}); } i += 1; } dumpIndent(indent); std.debug.print("{}", .{"}"}); } fn dumpArray(array: std.ArrayList(Value), indent: u8) void { std.debug.print("[\n", .{}); var i: usize = 0; while (i < array.items.len) { dumpIndent(indent + 1); array.items[i].dumpImpl(indent); if (i + 1 != array.items.len) { std.debug.print(",\n", .{}); } else { std.debug.print("\n", .{}); } i += 1; } dumpIndent(indent); std.debug.print("]", .{}); } fn dumpBinary(bin: []const u8, indent: u8) void { std.debug.print("[", .{}); var i: usize = 0; while (i < bin.len) { std.debug.print("{}", .{bin[i]}); i += 1; if (i != bin.len) { std.debug.print(", ", .{}); } } std.debug.print("]", .{}); } fn dumpIndent(indent: u8) void { var i: usize = 0; while (i < indent * 2) { std.debug.print(" ", .{}); i += 1; } } fn equalInt(self: Value, oth: i64) bool { return switch (self) { .int => |val| val == oth, else => false, }; } fn equalUint(self: Value, oth: u64) bool { return switch (self) { .uint => |val| val == oth, else => false, }; } fn isNil(self: Value) bool { return switch (self) { .nil => true, else => false, }; } fn equalBool(self: Value, oth: bool) bool { return switch (self) { .bool => |val| val == oth, else => false, }; } fn equalFloat(self: Value, oth: f64) bool { return switch (self) { .float => |val| val == oth, else => false, }; } fn equalString(self: Value, oth: []const u8) bool { return switch (self) { .string => |val| std.mem.eql(u8, val, oth), else => false, }; } fn equalBinary(self: Value, oth: []const u8) bool { return switch (self) { .binary => |val| std.mem.eql(u8, val, oth), else => false, }; } fn equalArray(self: Value, oth: std.ArrayList(Value)) bool { return switch (self) { .array => |val| { if (val.items.len != oth.items.len) { return false; } var i: usize = 0; while (i < val.items.len) { if (!val.items[i].equal(oth.items[i])) { return false; } i += 1; } return true; }, else => false, }; } fn equalMap(self: Value, oth: std.StringHashMap(Value)) bool { return switch (self) { .map => |val| { if (val.count() != oth.count()) { return false; } var it = self.map.iterator(); while (it.next()) |i| { if (oth.get(i.key)) |v| { if (!i.value.equal(v)) { return false; } } else { return false; } } return true; }, else => false, }; } }; test "equal int" { expect(!(Value{ .int = 42 }).equal(.nil)); expect(!(Value{ .int = 42 }).equal(Value{ .int = 84 })); expect((Value{ .int = 42 }).equal(Value{ .int = 42 })); } test "equal uint" { expect(!(Value{ .uint = 42 }).equal(.nil)); expect(!(Value{ .uint = 42 }).equal(Value{ .uint = 84 })); expect((Value{ .uint = 42 }).equal(Value{ .uint = 42 })); } test "equal float" { expect(!(Value{ .float = 42 }).equal(.nil)); expect(!(Value{ .float = 42 }).equal(Value{ .float = 84 })); expect((Value{ .float = 42 }).equal(Value{ .float = 42 })); } test "equal bool" { expect(!(Value{ .bool = true }).equal(.nil)); expect(!(Value{ .bool = true }).equal(Value{ .bool = false })); expect((Value{ .bool = true }).equal(Value{ .bool = true })); } test "equal string" { expect(!(Value{ .string = "hello world" }).equal(.nil)); expect(!(Value{ .string = "hello world" }).equal(Value{ .string = "hello" })); expect((Value{ .string = "hello world" }).equal(Value{ .string = "hello world" })); }
src/value.zig
const std = @import("std"); const tvg = @import("tvg"); const args = @import("args"); pub fn main() !u8 { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; const cli = args.parseForCurrentProcess(CliOptions, allocator) catch return 1; defer cli.deinit(); const stdin = std.io.getStdIn().reader(); const stdout = std.io.getStdOut().writer(); const stderr = std.io.getStdErr().writer(); if (cli.options.help) { try printUsage(stdout); return 0; } if (cli.positionals.len != 1) { try stderr.writeAll("Expected exactly one positional argument!\n"); try printUsage(stderr); return 1; } const read_stdin = std.mem.eql(u8, cli.positionals[0], "-"); const write_stdout = if (cli.options.output) |o| std.mem.eql(u8, o, "-") else false; if (read_stdin and cli.options.output == null) { try stderr.writeAll("Requires --output file name set when reading from stdin!\n"); try printUsage(stderr); return 1; } var source_file: std.fs.File = if (read_stdin) std.io.getStdIn() else try std.fs.cwd().openFile(cli.positionals[0], .{}); defer if (!read_stdin) source_file.close(); var parser = try tvg.parse(allocator, source_file.reader()); defer parser.deinit(); var geometry = cli.options.geometry orelse Geometry{ .width = @floatToInt(u16, std.math.ceil(parser.header.width)), .height = @floatToInt(u16, std.math.ceil(parser.header.height)), }; const pixel_count = @as(usize, geometry.width) * @as(usize, geometry.height); var backing_buffer = try allocator.alloc(u8, ImgFormat.bytesRequired(pixel_count)); defer allocator.free(backing_buffer); var slice = ImgFormat.init(backing_buffer, pixel_count); { const color: u24 = cli.options.background.toInt(); var i: usize = 0; while (i < slice.int_count) : (i += 1) { slice.set(i, color); } } var fb = Framebuffer{ .slice = slice, .stride = geometry.width, .width = geometry.width, .height = geometry.height, }; while (try parser.next()) |cmd| { try tvg.rendering.render(&fb, parser.header, parser.color_table, cmd); } { var dest_file: std.fs.File = if (write_stdout) std.io.getStdIn() else blk: { var out_name = cli.options.output orelse try std.mem.concat(allocator, u8, &[_][]const u8{ cli.positionals[0][0..(cli.positionals[0].len - std.fs.path.extension(cli.positionals[0]).len)], ".ppm", }); break :blk try std.fs.cwd().createFile(out_name, .{}); }; defer if (!read_stdin) dest_file.close(); var writer = dest_file.writer(); try writer.print("P6 {} {} 255\n", .{ geometry.width, geometry.height }); try writer.writeAll(backing_buffer[0 .. 3 * pixel_count]); } return 0; } const Framebuffer = struct { const Self = @This(); // private API slice: ImgFormat, stride: usize, // public API width: usize, height: usize, pub fn setPixel(self: *Self, x: isize, y: isize, color: [4]u8) void { const offset = (std.math.cast(usize, y) catch return) * self.stride + (std.math.cast(usize, x) catch return); // std.debug.print("{} {} => {any}\n", .{ x, y, color }); self.slice.set(offset, (Color{ .r = color[0], .g = color[1], .b = color[2] }).toInt()); } }; const ImgFormat = std.PackedIntSliceEndian(u24, .Little); const Color = struct { r: u8, g: u8, b: u8, pub fn parse(str: []const u8) !Color { switch (str.len) { 3 => { const r = try std.fmt.parseInt(u8, str[0..1], 16); const g = try std.fmt.parseInt(u8, str[0..1], 16); const b = try std.fmt.parseInt(u8, str[0..1], 16); return Color{ .r = r | r << 4, .g = g | g << 4, .b = b | b << 4, }; }, 6 => { const r = try std.fmt.parseInt(u8, str[0..2], 16); const g = try std.fmt.parseInt(u8, str[2..4], 16); const b = try std.fmt.parseInt(u8, str[4..6], 16); return Color{ .r = r | r << 4, .g = g | g << 4, .b = b | b << 4, }; }, else => return error.InvalidColor, } } pub fn toInt(self: Color) u24 { return @as(u24, self.r) | (@as(u24, self.g) << 8) | (@as(u24, self.b) << 16); } }; const CliOptions = struct { help: bool = false, output: ?[]const u8 = null, geometry: ?Geometry = null, background: Color = Color{ .r = 0xAA, .g = 0xAA, .b = 0xAA }, pub const shorthands = .{ .o = "output", .g = "geometry", .h = "help", .b = "background", }; }; const Geometry = struct { const Self = @This(); width: u16, height: u16, pub fn parse(str: []const u8) !Self { if (std.mem.indexOfScalar(u8, str, 'x')) |index| { return Geometry{ .width = try std.fmt.parseInt(u16, str[0..index], 10), .height = try std.fmt.parseInt(u16, str[index + 1 ..], 10), }; } else { const v = try std.fmt.parseInt(u16, str, 10); return Geometry{ .width = v, .height = v, }; } } }; fn printUsage(stream: anytype) !void { try stream.writeAll( \\tvg-render [-o file] [-g geometry] source.tvg \\ ); }
src/tools/render.zig
const x86_64 = @import("../../../index.zig"); const bitjuggle = @import("bitjuggle"); const std = @import("std"); const paging = x86_64.structures.paging; const mapping = paging.mapping; const Mapper = mapping.Mapper; /// A recursive page table is a last level page table with an entry mapped to the table itself. /// /// This recursive mapping allows accessing all page tables in the hierarchy: /// /// - To access the level 4 page table, we “loop“ (i.e. follow the recursively mapped entry) four /// times. /// - To access a level 3 page table, we “loop” three times and then use the level 4 index. /// - To access a level 2 page table, we “loop” two times, then use the level 4 index, then the /// level 3 index. /// - To access a level 1 page table, we “loop” once, then use the level 4 index, then the /// level 3 index, then the level 2 index. /// /// This struct implements the `Mapper` trait. /// /// The page table flags `PRESENT` and `WRITABLE` are always set for higher level page table /// entries, even if not specified, because the design of the recursive page table requires it. pub const RecursivePageTable = struct { pub const InvalidPageTable = error{ /// The given page table was not at an recursive address. /// /// The page table address must be of the form `0o_xxx_xxx_xxx_xxx_0000` where `xxx` /// is the recursive entry. NotRecursive, /// The given page table was not active on the CPU. /// /// The recursive page table design requires that the given level 4 table is active /// on the CPU because otherwise it's not possible to access the other page tables /// through recursive memory addresses. NotActive, }; mapper: Mapper, level_4_table: *paging.PageTable, recursive_index: paging.PageTableIndex, /// Creates a new RecursivePageTable from the passed level 4 PageTable. /// /// The page table must be recursively mapped, that means: /// /// - The page table must have one recursive entry, i.e. an entry that points to the table /// itself. /// - The reference must use that “loop”, i.e. be of the form `0o_xxx_xxx_xxx_xxx_0000` /// where `xxx` is the recursive entry. /// - The page table must be active, i.e. the CR3 register must contain its physical address. /// /// Otherwise a `RecursivePageTableCreationError` is returned. pub fn init(table: *paging.PageTable) InvalidPageTable!RecursivePageTable { const page = paging.Page.containingAddress(x86_64.VirtAddr.initPanic(@ptrToInt(table))); const recursive_index = page.p4Index(); const recursive_index_value = recursive_index.value; if (page.p3Index().value != recursive_index_value or page.p2Index().value != recursive_index_value or page.p1Index().value != recursive_index_value) { return InvalidPageTable.NotRecursive; } const recursive_index_frame = table.getAtIndex(recursive_index).getFrame() catch return InvalidPageTable.NotRecursive; if (x86_64.registers.control.Cr3.read().phys_frame.start_address.value != recursive_index_frame.start_address.value) { return InvalidPageTable.NotActive; } return RecursivePageTable{ .mapper = makeMapper(), .level_4_table = table, .recursive_index = recursive_index, }; } /// Creates a new RecursivePageTable without performing any checks. /// /// ## Safety /// /// The given page table must be a level 4 page table that is active in the /// CPU (i.e. loaded in the CR3 register). The `recursive_index` parameter /// must be the index of the recursively mapped entry of that page table. pub fn initUnchecked(table: *paging.PageTable, recursive_index: paging.PageTableIndex) RecursivePageTable { return .{ .mapper = makeMapper(), .level_4_table = table, .recursive_index = recursive_index, }; } inline fn getSelfPtr(mapper: *Mapper) *RecursivePageTable { return @fieldParentPtr(RecursivePageTable, "mapper", mapper); } fn mapToWithTableFlags1GiB( mapper: *Mapper, page: paging.Page1GiB, frame: paging.PhysFrame1GiB, flags: paging.PageTableFlags, parent_table_flags: paging.PageTableFlags, frame_allocator: *paging.FrameAllocator, ) mapping.MapToError!mapping.MapperFlush1GiB { var self = getSelfPtr(mapper); const parent_flags = parent_table_flags.sanitizeForParent(); const p3 = try createNextTable( self.level_4_table.getAtIndex(page.p4Index()), p3Page( .Size1GiB, page, self.recursive_index, ), parent_flags, frame_allocator, ); var entry = p3.getAtIndex(page.p3Index()); if (!entry.isUnused()) return mapping.MapToError.PageAlreadyMapped; entry.setAddr(frame.start_address); var new_flags = flags; new_flags.huge = true; entry.setFlags(new_flags); return mapping.MapperFlush1GiB.init(page); } fn unmap1GiB( mapper: *Mapper, page: paging.Page1GiB, ) mapping.UnmapError!mapping.UnmapResult1GiB { var self = getSelfPtr(mapper); _ = self.level_4_table.getAtIndex(page.p4Index()).getFrame() catch |err| switch (err) { paging.FrameError.FrameNotPresent => return mapping.UnmapError.PageNotMapped, paging.FrameError.HugeFrame => return mapping.UnmapError.ParentEntryHugePage, }; const p3 = p3Ptr(.Size1GiB, page, self.recursive_index); const p3_entry = p3.getAtIndex(page.p3Index()); const flags = p3_entry.getFlags(); if (!flags.present) return mapping.UnmapError.PageNotMapped; if (!flags.huge) return mapping.UnmapError.ParentEntryHugePage; const frame = paging.PhysFrame1GiB.fromStartAddress(p3_entry.getAddr()) catch return mapping.UnmapError.InvalidFrameAddress; p3_entry.setUnused(); return mapping.UnmapResult1GiB{ .frame = frame, .flush = mapping.MapperFlush1GiB.init(page), }; } fn updateFlags1GiB( mapper: *Mapper, page: paging.Page1GiB, flags: paging.PageTableFlags, ) mapping.FlagUpdateError!mapping.MapperFlush1GiB { var self = getSelfPtr(mapper); if (self.level_4_table.getAtIndex(page.p4Index()).isUnused()) { return mapping.FlagUpdateError.PageNotMapped; } const p3 = p3Ptr(.Size1GiB, page, self.recursive_index); var p3_entry = p3.getAtIndex(page.p3Index()); if (p3_entry.isUnused()) return mapping.FlagUpdateError.PageNotMapped; var new_flags = flags; new_flags.huge = true; p3_entry.setFlags(new_flags); return mapping.MapperFlush1GiB.init(page); } fn setFlagsP4Entry1GiB( mapper: *Mapper, page: paging.Page1GiB, flags: paging.PageTableFlags, ) mapping.FlagUpdateError!mapping.MapperFlushAll { var self = getSelfPtr(mapper); const p4_entry = self.level_4_table.getAtIndex(page.p4Index()); if (p4_entry.isUnused()) return mapping.FlagUpdateError.PageNotMapped; p4_entry.setFlags(flags); return mapping.MapperFlushAll{}; } fn translatePage1GiB( mapper: *Mapper, page: paging.Page1GiB, ) mapping.TranslateError!paging.PhysFrame1GiB { var self = getSelfPtr(mapper); if (self.level_4_table.getAtIndex(page.p4Index()).isUnused()) { return mapping.TranslateError.NotMapped; } const p3 = p3Ptr(.Size1GiB, page, self.recursive_index); const p3_entry = p3.getAtIndex(page.p3Index()); if (p3_entry.isUnused()) return mapping.TranslateError.NotMapped; return paging.PhysFrame1GiB.fromStartAddress(p3_entry.getAddr()) catch return mapping.TranslateError.InvalidFrameAddress; } fn mapToWithTableFlags2MiB( mapper: *Mapper, page: paging.Page2MiB, frame: paging.PhysFrame2MiB, flags: paging.PageTableFlags, parent_table_flags: paging.PageTableFlags, frame_allocator: *paging.FrameAllocator, ) mapping.MapToError!mapping.MapperFlush2MiB { var self = getSelfPtr(mapper); const parent_flags = parent_table_flags.sanitizeForParent(); const p3 = try createNextTable( self.level_4_table.getAtIndex(page.p4Index()), p3Page( .Size2MiB, page, self.recursive_index, ), parent_flags, frame_allocator, ); const p2 = try createNextTable( p3.getAtIndex(page.p3Index()), p2Page( .Size2MiB, page, self.recursive_index, ), parent_flags, frame_allocator, ); var entry = p2.getAtIndex(page.p2Index()); if (!entry.isUnused()) return mapping.MapToError.PageAlreadyMapped; entry.setAddr(frame.start_address); var new_flags = flags; new_flags.huge = true; entry.setFlags(new_flags); return mapping.MapperFlush2MiB.init(page); } fn unmap2MiB( mapper: *Mapper, page: paging.Page2MiB, ) mapping.UnmapError!mapping.UnmapResult2MiB { var self = getSelfPtr(mapper); _ = self.level_4_table.getAtIndex(page.p4Index()).getFrame() catch |err| switch (err) { paging.FrameError.FrameNotPresent => return mapping.UnmapError.PageNotMapped, paging.FrameError.HugeFrame => return mapping.UnmapError.ParentEntryHugePage, }; const p3 = p3Ptr(.Size2MiB, page, self.recursive_index); const p3_entry = p3.getAtIndex(page.p3Index()); _ = p3_entry.getFrame() catch |err| switch (err) { paging.FrameError.FrameNotPresent => return mapping.UnmapError.PageNotMapped, paging.FrameError.HugeFrame => return mapping.UnmapError.ParentEntryHugePage, }; const p2 = p2Ptr(.Size2MiB, page, self.recursive_index); const p2_entry = p2.getAtIndex(page.p2Index()); const flags = p2_entry.getFlags(); if (!flags.present) return mapping.UnmapError.PageNotMapped; if (!flags.huge) return mapping.UnmapError.ParentEntryHugePage; const frame = paging.PhysFrame2MiB.fromStartAddress(p2_entry.getAddr()) catch return mapping.UnmapError.InvalidFrameAddress; p2_entry.setUnused(); return mapping.UnmapResult2MiB{ .frame = frame, .flush = mapping.MapperFlush2MiB.init(page), }; } fn updateFlags2MiB( mapper: *Mapper, page: paging.Page2MiB, flags: paging.PageTableFlags, ) mapping.FlagUpdateError!mapping.MapperFlush2MiB { var self = getSelfPtr(mapper); if (self.level_4_table.getAtIndex(page.p4Index()).isUnused()) { return mapping.FlagUpdateError.PageNotMapped; } const p3 = p3Ptr(.Size2MiB, page, self.recursive_index); var p3_entry = p3.getAtIndex(page.p3Index()); if (p3_entry.isUnused()) return mapping.FlagUpdateError.PageNotMapped; const p2 = p2Ptr(.Size2MiB, page, self.recursive_index); var p2_entry = p2.getAtIndex(page.p2Index()); if (p2_entry.isUnused()) return mapping.FlagUpdateError.PageNotMapped; var new_flags = flags; new_flags.huge = true; p2_entry.setFlags(new_flags); return mapping.MapperFlush2MiB.init(page); } fn setFlagsP4Entry2MiB( mapper: *Mapper, page: paging.Page2MiB, flags: paging.PageTableFlags, ) mapping.FlagUpdateError!mapping.MapperFlushAll { var self = getSelfPtr(mapper); const p4_entry = self.level_4_table.getAtIndex(page.p4Index()); if (p4_entry.isUnused()) return mapping.FlagUpdateError.PageNotMapped; p4_entry.setFlags(flags); return mapping.MapperFlushAll{}; } fn setFlagsP3Entry2MiB( mapper: *Mapper, page: paging.Page2MiB, flags: paging.PageTableFlags, ) mapping.FlagUpdateError!mapping.MapperFlushAll { var self = getSelfPtr(mapper); if (self.level_4_table.getAtIndex(page.p4Index()).isUnused()) { return mapping.FlagUpdateError.PageNotMapped; } const p3 = p3Ptr(.Size2MiB, page, self.recursive_index); const p3_entry = p3.getAtIndex(page.p3Index()); if (p3_entry.isUnused()) return mapping.FlagUpdateError.PageNotMapped; p3_entry.setFlags(flags); return mapping.MapperFlushAll{}; } fn translatePage2MiB( mapper: *Mapper, page: paging.Page2MiB, ) mapping.TranslateError!paging.PhysFrame2MiB { var self = getSelfPtr(mapper); if (self.level_4_table.getAtIndex(page.p4Index()).isUnused()) { return mapping.TranslateError.NotMapped; } const p3 = p3Ptr(.Size2MiB, page, self.recursive_index); const p3_entry = p3.getAtIndex(page.p3Index()); if (p3_entry.isUnused()) return mapping.TranslateError.NotMapped; const p2 = p2Ptr(.Size2MiB, page, self.recursive_index); const p2_entry = p2.getAtIndex(page.p2Index()); if (p2_entry.isUnused()) return mapping.TranslateError.NotMapped; return paging.PhysFrame2MiB.fromStartAddress(p2_entry.getAddr()) catch return mapping.TranslateError.InvalidFrameAddress; } fn mapToWithTableFlags( mapper: *Mapper, page: paging.Page, frame: paging.PhysFrame, flags: paging.PageTableFlags, parent_table_flags: paging.PageTableFlags, frame_allocator: *paging.FrameAllocator, ) mapping.MapToError!mapping.MapperFlush { var self = getSelfPtr(mapper); const parent_flags = parent_table_flags.sanitizeForParent(); const p3 = try createNextTable( self.level_4_table.getAtIndex(page.p4Index()), p3Page( .Size4KiB, page, self.recursive_index, ), parent_flags, frame_allocator, ); const p2 = try createNextTable( p3.getAtIndex(page.p3Index()), p2Page( .Size4KiB, page, self.recursive_index, ), parent_flags, frame_allocator, ); const p1 = try createNextTable( p2.getAtIndex(page.p2Index()), p1Page( .Size4KiB, page, self.recursive_index, ), parent_flags, frame_allocator, ); var entry = p1.getAtIndex(page.p1Index()); if (!entry.isUnused()) return mapping.MapToError.PageAlreadyMapped; entry.setAddr(frame.start_address); entry.setFlags(flags); return mapping.MapperFlush.init(page); } fn unmap( mapper: *Mapper, page: paging.Page, ) mapping.UnmapError!mapping.UnmapResult { var self = getSelfPtr(mapper); _ = self.level_4_table.getAtIndex(page.p4Index()).getFrame() catch |err| switch (err) { paging.FrameError.FrameNotPresent => return mapping.UnmapError.PageNotMapped, paging.FrameError.HugeFrame => return mapping.UnmapError.ParentEntryHugePage, }; const p3 = p3Ptr(.Size4KiB, page, self.recursive_index); const p3_entry = p3.getAtIndex(page.p3Index()); _ = p3_entry.getFrame() catch |err| switch (err) { paging.FrameError.FrameNotPresent => return mapping.UnmapError.PageNotMapped, paging.FrameError.HugeFrame => return mapping.UnmapError.ParentEntryHugePage, }; const p2 = p2Ptr(.Size4KiB, page, self.recursive_index); const p2_entry = p2.getAtIndex(page.p2Index()); _ = p2_entry.getFrame() catch |err| switch (err) { paging.FrameError.FrameNotPresent => return mapping.UnmapError.PageNotMapped, paging.FrameError.HugeFrame => return mapping.UnmapError.ParentEntryHugePage, }; const p1 = p2Ptr(.Size4KiB, page, self.recursive_index); const p1_entry = p1.getAtIndex(page.p1Index()); const frame = p1_entry.getFrame() catch |err| switch (err) { paging.FrameError.FrameNotPresent => return mapping.UnmapError.PageNotMapped, paging.FrameError.HugeFrame => return mapping.UnmapError.ParentEntryHugePage, }; p1_entry.setUnused(); return mapping.UnmapResult{ .frame = frame, .flush = mapping.MapperFlush.init(page), }; } fn updateFlags( mapper: *Mapper, page: paging.Page, flags: paging.PageTableFlags, ) mapping.FlagUpdateError!mapping.MapperFlush { var self = getSelfPtr(mapper); if (self.level_4_table.getAtIndex(page.p4Index()).isUnused()) { return mapping.FlagUpdateError.PageNotMapped; } const p3 = p3Ptr(.Size4KiB, page, self.recursive_index); var p3_entry = p3.getAtIndex(page.p3Index()); if (p3_entry.isUnused()) return mapping.FlagUpdateError.PageNotMapped; const p2 = p2Ptr(.Size4KiB, page, self.recursive_index); var p2_entry = p2.getAtIndex(page.p2Index()); if (p2_entry.isUnused()) return mapping.FlagUpdateError.PageNotMapped; const p1 = p1Ptr(.Size4KiB, page, self.recursive_index); var p1_entry = p1.getAtIndex(page.p1Index()); if (p1_entry.isUnused()) return mapping.FlagUpdateError.PageNotMapped; p1_entry.setFlags(flags); return mapping.MapperFlush.init(page); } fn setFlagsP4Entry( mapper: *Mapper, page: paging.Page, flags: paging.PageTableFlags, ) mapping.FlagUpdateError!mapping.MapperFlushAll { var self = getSelfPtr(mapper); const p4_entry = self.level_4_table.getAtIndex(page.p4Index()); if (p4_entry.isUnused()) return mapping.FlagUpdateError.PageNotMapped; p4_entry.setFlags(flags); return mapping.MapperFlushAll{}; } fn setFlagsP3Entry( mapper: *Mapper, page: paging.Page, flags: paging.PageTableFlags, ) mapping.FlagUpdateError!mapping.MapperFlushAll { var self = getSelfPtr(mapper); if (self.level_4_table.getAtIndex(page.p4Index()).isUnused()) { return mapping.FlagUpdateError.PageNotMapped; } const p3 = p3Ptr(.Size4KiB, page, self.recursive_index); const p3_entry = p3.getAtIndex(page.p3Index()); if (p3_entry.isUnused()) return mapping.FlagUpdateError.PageNotMapped; p3_entry.setFlags(flags); return mapping.MapperFlushAll{}; } fn setFlagsP2Entry( mapper: *Mapper, page: paging.Page, flags: paging.PageTableFlags, ) mapping.FlagUpdateError!mapping.MapperFlushAll { var self = getSelfPtr(mapper); if (self.level_4_table.getAtIndex(page.p4Index()).isUnused()) { return mapping.FlagUpdateError.PageNotMapped; } const p3 = p3Ptr(.Size4KiB, page, self.recursive_index); const p3_entry = p3.getAtIndex(page.p3Index()); if (p3_entry.isUnused()) return mapping.FlagUpdateError.PageNotMapped; const p2 = p2Ptr(.Size4KiB, page, self.recursive_index); const p2_entry = p2.getAtIndex(page.p2Index()); if (p2_entry.isUnused()) return mapping.FlagUpdateError.PageNotMapped; p2_entry.setFlags(flags); return mapping.MapperFlushAll{}; } fn translatePage( mapper: *Mapper, page: paging.Page, ) mapping.TranslateError!paging.PhysFrame { var self = getSelfPtr(mapper); if (self.level_4_table.getAtIndex(page.p4Index()).isUnused()) { return mapping.TranslateError.NotMapped; } const p3 = p3Ptr(.Size4KiB, page, self.recursive_index); const p3_entry = p3.getAtIndex(page.p3Index()); if (p3_entry.isUnused()) return mapping.TranslateError.NotMapped; const p2 = p2Ptr(.Size4KiB, page, self.recursive_index); const p2_entry = p2.getAtIndex(page.p2Index()); if (p2_entry.isUnused()) return mapping.TranslateError.NotMapped; const p1 = p1Ptr(.Size4KiB, page, self.recursive_index); const p1_entry = p1.getAtIndex(page.p1Index()); if (p1_entry.isUnused()) return mapping.TranslateError.NotMapped; return paging.PhysFrame.fromStartAddress(p1_entry.getAddr()) catch return mapping.TranslateError.InvalidFrameAddress; } fn translate( mapper: *Mapper, addr: x86_64.VirtAddr, ) mapping.TranslateError!mapping.TranslateResult { var self = getSelfPtr(mapper); const page = paging.Page.containingAddress(addr); const p4_entry = self.level_4_table.getAtIndex(addr.p4Index()); if (p4_entry.isUnused()) { return mapping.TranslateError.NotMapped; } if (p4_entry.getFlags().huge) { @panic("level 4 entry has huge page bit set"); } const p3 = p3Ptr(.Size4KiB, page, self.recursive_index); const p3_entry = p3.getAtIndex(page.p3Index()); if (p3_entry.isUnused()) return mapping.TranslateError.NotMapped; const p3_flags = p3_entry.getFlags(); if (p3_flags.huge) { return mapping.TranslateResult{ .Frame1GiB = .{ .frame = paging.PhysFrame1GiB.containingAddress(p3_entry.getAddr()), .offset = addr.value & 0o777_777_7777, .flags = p3_flags, }, }; } const p2 = p2Ptr(.Size4KiB, page, self.recursive_index); const p2_entry = p2.getAtIndex(addr.p2Index()); if (p2_entry.isUnused()) return mapping.TranslateError.NotMapped; const p2_flags = p2_entry.getFlags(); if (p2_flags.huge) { return mapping.TranslateResult{ .Frame2MiB = .{ .frame = paging.PhysFrame2MiB.containingAddress(p2_entry.getAddr()), .offset = addr.value & 0o777_7777, .flags = p2_flags, }, }; } const p1 = p2Ptr(.Size4KiB, page, self.recursive_index); const p1_entry = p1.getAtIndex(addr.p1Index()); if (p1_entry.isUnused()) return mapping.TranslateError.NotMapped; const p1_flags = p1_entry.getFlags(); if (p1_flags.huge) { @panic("level 1 entry has huge page bit set"); } const frame = paging.PhysFrame.fromStartAddress(p1_entry.getAddr()) catch return mapping.TranslateError.InvalidFrameAddress; return mapping.TranslateResult{ .Frame4KiB = .{ .frame = frame, .offset = @as(u64, addr.pageOffset().value), .flags = p1_flags, }, }; } fn makeMapper() Mapper { return .{ .z_impl_mapToWithTableFlags1GiB = mapToWithTableFlags1GiB, .z_impl_unmap1GiB = unmap1GiB, .z_impl_updateFlags1GiB = updateFlags1GiB, .z_impl_setFlagsP4Entry1GiB = setFlagsP4Entry1GiB, .z_impl_translatePage1GiB = translatePage1GiB, .z_impl_mapToWithTableFlags2MiB = mapToWithTableFlags2MiB, .z_impl_unmap2MiB = unmap2MiB, .z_impl_updateFlags2MiB = updateFlags2MiB, .z_impl_setFlagsP4Entry2MiB = setFlagsP4Entry2MiB, .z_impl_setFlagsP3Entry2MiB = setFlagsP3Entry2MiB, .z_impl_translatePage2MiB = translatePage2MiB, .z_impl_mapToWithTableFlags = mapToWithTableFlags, .z_impl_unmap = unmap, .z_impl_updateFlags = updateFlags, .z_impl_setFlagsP4Entry = setFlagsP4Entry, .z_impl_setFlagsP3Entry = setFlagsP3Entry, .z_impl_setFlagsP2Entry = setFlagsP2Entry, .z_impl_translatePage = translatePage, .z_impl_translate = translate, }; } comptime { std.testing.refAllDecls(@This()); } }; /// Internal helper function to create the page table of the next level if needed. /// /// If the passed entry is unused, a new frame is allocated from the given allocator, zeroed, /// and the entry is updated to that address. If the passed entry is already mapped, the next /// table is returned directly. /// /// The page table flags `PRESENT` and `WRITABLE` are always set for higher level page table /// entries, even if not specified in the `insert_flags`, because the design of the /// recursive page table requires it. /// /// The `next_page_table` page must be the page of the next page table in the hierarchy. /// /// Returns `MapToError::FrameAllocationFailed` if the entry is unused and the allocator /// returned `None`. Returns `MapToError::ParentEntryHugePage` if the `HUGE_PAGE` flag is set /// in the passed entry. fn createNextTable( entry: *paging.PageTableEntry, nextTablePage: paging.Page, insertFlags: paging.PageTableFlags, frameAllocator: *paging.FrameAllocator, ) mapping.MapToError!*paging.PageTable { var created = false; if (entry.isUnused()) { if (frameAllocator.allocate4KiB()) |frame| { entry.setAddr(frame.start_address); var flags = insertFlags; flags.present = true; flags.writeable = true; entry.setFlags(flags); created = true; } else { return mapping.MapToError.FrameAllocationFailed; } } else { const raw_insert_flags = insertFlags.toU64(); const raw_entry_flags = entry.getFlags().toU64(); const combined_raw_flags = raw_insert_flags | raw_entry_flags; if (raw_insert_flags != 0 and combined_raw_flags != raw_insert_flags) { entry.setFlags(paging.PageTableFlags.fromU64(combined_raw_flags)); } } const page_table = nextTablePage.start_address.toPtr(*paging.PageTable); if (created) page_table.zero(); return page_table; } fn getPageFromSize(comptime page_size: paging.PageSize) type { return switch (page_size) { .Size4KiB => paging.Page, .Size2MiB => paging.Page2MiB, .Size1GiB => paging.Page1GiB, }; } fn p3Ptr( comptime size: paging.PageSize, page: getPageFromSize(size), recursive_index: paging.PageTableIndex, ) *paging.PageTable { return p3Page(size, page, recursive_index).start_address.toPtr(*paging.PageTable); } fn p3Page( comptime size: paging.PageSize, page: getPageFromSize(size), recursive_index: paging.PageTableIndex, ) paging.Page { return paging.pageFromTableIndices( recursive_index, recursive_index, recursive_index, page.p4Index(), ); } fn p2Ptr( comptime size: paging.PageSize, page: getPageFromSize(size), recursive_index: paging.PageTableIndex, ) *paging.PageTable { return p2Page(size, page, recursive_index).start_address.toPtr(*paging.PageTable); } fn p2Page( comptime size: paging.PageSize, page: getPageFromSize(size), recursive_index: paging.PageTableIndex, ) paging.Page { return paging.pageFromTableIndices( recursive_index, recursive_index, page.p4Index(), page.p3Index(), ); } fn p1Ptr( comptime size: paging.PageSize, page: getPageFromSize(size), recursive_index: paging.PageTableIndex, ) *paging.PageTable { return p1Page(size, page, recursive_index).start_address.toPtr(*paging.PageTable); } fn p1Page( comptime size: paging.PageSize, page: getPageFromSize(size), recursive_index: paging.PageTableIndex, ) paging.Page { return paging.pageFromTableIndices( recursive_index, page.p4Index(), page.p3Index(), page.p2Index(), ); } comptime { std.testing.refAllDecls(@This()); }
src/structures/paging/mapping/recursive_page_table.zig
const common = @import("../common.zig"); pub const StarterLocation = union(enum) { arm9: usize, overlay9: Overlay, pub const Overlay = struct { offset: usize, file: usize, }; }; pub const Info = struct { game_title: [11:0]u8, gamecode: [4]u8, version: common.Version, arm9_is_encoded: bool, starters: StarterLocation, instant_text_patch: []const common.Patch, hm_tm_prefix: []const u8, pokemons: []const u8, level_up_moves: []const u8, moves: []const u8, trainers: []const u8, parties: []const u8, evolutions: []const u8, wild_pokemons: []const u8, scripts: []const u8, itemdata: []const u8, pokedex: []const u8, pokedex_heights: u16, pokedex_weights: u16, species_to_national_dex: u16, text: []const u8, pokemon_names: u16, trainer_names: u16, move_names: u16, move_descriptions: u16, ability_names: u16, item_names: u16, item_descriptions: u16, type_names: u16, }; pub const infos = [_]Info{ hg_info, ss_info, diamond_info, pearl_info, platinum_info, }; const hg_info = Info{ .game_title = "POKEMON HG\x00".*, .gamecode = "IPKE".*, .version = .heart_gold, .arm9_is_encoded = true, .starters = StarterLocation{ .arm9 = 0x00108514 }, .instant_text_patch = &[_]common.Patch{ .{ .offset = 0x002346, .replacement = "\x00\x21" }, .{ .offset = 0x0202ee, .replacement = "\x0c\x1c\x18\x48" }, .{ .offset = 0x02031e, .replacement = "\x10\xbd\x2d\x3c\xe5\xe7" }, .{ .offset = 0x02032e, .replacement = "\xdf\xd0" }, .{ .offset = 0x02033a, .replacement = "\xf1\xe7" }, }, .hm_tm_prefix = "\x1E\x00\x32\x00", .pokemons = "/a/0/0/2", .level_up_moves = "/a/0/3/3", .moves = "/a/0/1/1", .trainers = "/a/0/5/5", .parties = "/a/0/5/6", .evolutions = "/a/0/3/4", .wild_pokemons = "/a/0/3/7", .scripts = "/a/0/1/2", .itemdata = "/a/0/1/7", .pokedex = "/a/0/7/4", .pokedex_heights = 0, .pokedex_weights = 1, .species_to_national_dex = 11, .text = "/a/0/2/7", .pokemon_names = 237, .trainer_names = 729, .move_names = 750, .move_descriptions = 749, .ability_names = 720, .item_names = 222, .item_descriptions = 221, .type_names = 735, }; const ss_info = Info{ .game_title = "POKEMON SS\x00".*, .gamecode = "IPGE".*, .version = .soul_silver, .arm9_is_encoded = true, .starters = hg_info.starters, .instant_text_patch = hg_info.instant_text_patch, .hm_tm_prefix = hg_info.hm_tm_prefix, .pokemons = hg_info.pokemons, .level_up_moves = hg_info.level_up_moves, .moves = hg_info.moves, .trainers = hg_info.trainers, .parties = hg_info.parties, .evolutions = hg_info.evolutions, .wild_pokemons = "/a/1/3/6", .scripts = hg_info.scripts, .itemdata = hg_info.itemdata, .pokedex = hg_info.pokedex, .pokedex_heights = hg_info.pokedex_heights, .pokedex_weights = hg_info.pokedex_weights, .species_to_national_dex = hg_info.species_to_national_dex, .text = hg_info.text, .pokemon_names = hg_info.pokemon_names, .trainer_names = hg_info.trainer_names, .move_names = hg_info.move_names, .move_descriptions = hg_info.move_descriptions, .ability_names = hg_info.ability_names, .item_names = hg_info.item_names, .item_descriptions = hg_info.item_descriptions, .type_names = hg_info.type_names, }; const diamond_info = Info{ .game_title = "POKEMON D\x00\x00".*, .gamecode = "ADAE".*, .version = .diamond, .arm9_is_encoded = false, .starters = StarterLocation{ .overlay9 = StarterLocation.Overlay{ .offset = 0x1B88, .file = 64, }, }, .instant_text_patch = &[_]common.Patch{}, .hm_tm_prefix = "\xD1\x00\xD2\x00\xD3\x00\xD4\x00", .pokemons = "/poketool/personal/personal.narc", .level_up_moves = "/poketool/personal/wotbl.narc", .moves = "/poketool/waza/waza_tbl.narc", .trainers = "/poketool/trainer/trdata.narc", .parties = "/poketool/trainer/trpoke.narc", .evolutions = "/poketool/personal/evo.narc", .wild_pokemons = "/fielddata/encountdata/d_enc_data.narc", .scripts = "/fielddata/script/scr_seq_release.narc", .itemdata = "/itemtool/itemdata/item_data.narc", .pokedex = "application/zukanlist/zkn_data/zukan_data.narc", .pokedex_heights = 0, .pokedex_weights = 1, .species_to_national_dex = 11, .text = "/msgdata/msg.narc", .pokemon_names = 362, .trainer_names = 559, .move_names = 588, .move_descriptions = 587, .ability_names = 552, .item_names = 344, .item_descriptions = 343, .type_names = 565, }; const pearl_info = Info{ .game_title = "POKEMON P\x00\x00".*, .gamecode = "APAE".*, .version = .pearl, .arm9_is_encoded = false, .starters = diamond_info.starters, .instant_text_patch = diamond_info.instant_text_patch, .hm_tm_prefix = diamond_info.hm_tm_prefix, .pokemons = "/poketool/personal_pearl/personal.narc", .level_up_moves = diamond_info.level_up_moves, .moves = diamond_info.moves, .trainers = diamond_info.trainers, .parties = diamond_info.parties, .evolutions = diamond_info.evolutions, .wild_pokemons = "/fielddata/encountdata/p_enc_data.narc", .scripts = diamond_info.scripts, .itemdata = diamond_info.itemdata, .pokedex = diamond_info.pokedex, .pokedex_heights = diamond_info.pokedex_heights, .pokedex_weights = diamond_info.pokedex_weights, .species_to_national_dex = diamond_info.species_to_national_dex, .text = diamond_info.text, .pokemon_names = diamond_info.pokemon_names, .trainer_names = diamond_info.trainer_names, .move_names = diamond_info.move_names, .move_descriptions = diamond_info.move_descriptions, .ability_names = diamond_info.ability_names, .item_names = diamond_info.item_names, .item_descriptions = diamond_info.item_descriptions, .type_names = diamond_info.type_names, }; const platinum_info = Info{ .game_title = "POKEMON PL\x00".*, .gamecode = "CPUE".*, .version = .platinum, .arm9_is_encoded = false, .starters = StarterLocation{ .overlay9 = StarterLocation.Overlay{ .offset = 0x1BC0, .file = 78, }, }, .instant_text_patch = &[_]common.Patch{ .{ .offset = 0x0023fc, .replacement = "\x00\x21" }, .{ .offset = 0x01d97e, .replacement = "\x0c\x1c\x18\x48" }, .{ .offset = 0x01d9ae, .replacement = "\x10\xbd\x2d\x3c\xe5\xe7" }, .{ .offset = 0x01d9be, .replacement = "\xdf\xd0" }, .{ .offset = 0x01d9ca, .replacement = "\xf1\xe7" }, }, .hm_tm_prefix = diamond_info.hm_tm_prefix, .pokemons = "/poketool/personal/pl_personal.narc", .level_up_moves = diamond_info.level_up_moves, .moves = "/poketool/waza/pl_waza_tbl.narc", .trainers = diamond_info.trainers, .parties = diamond_info.parties, .evolutions = diamond_info.evolutions, .wild_pokemons = "/fielddata/encountdata/pl_enc_data.narc", .scripts = "/fielddata/script/scr_seq.narc", .itemdata = "/itemtool/itemdata/pl_item_data.narc", .pokedex = "application/zukanlist/zkn_data/zukan_data_gira.narc", .pokedex_heights = 0, .pokedex_weights = 1, .species_to_national_dex = 11, .text = "/msgdata/pl_msg.narc", .pokemon_names = 412, .trainer_names = 618, .move_names = 647, .move_descriptions = 646, .ability_names = 610, .item_names = 392, .item_descriptions = 391, .type_names = 624, }; pub const hm_count = 8; pub const starters_len = 12; pub const tm_count = 92;
src/core/gen4/offsets.zig
const std = @import("std"); const assert = std.debug.assert; const mem = std.mem; const parser = @import("parser.zig"); const tokenizer = @import("tokenizer.zig"); const Allocator = mem.Allocator; const Token = tokenizer.Token; const ParseNode = parser.Node; const ParseScope = parser.Scope; const ErrorMsg = struct { msg: []const u8, // loc: usize, }; const GenResult = union(enum) { ok: void, err: *ErrorMsg, }; const GenError = error{ OutOfMemory, GenFail, } || std.fmt.ParseIntError; pub const Generator = struct { arena: Allocator, buffer: []const u8, tokens: []const Token, parse_scope: *ParseScope, err_msg: ?*ErrorMsg = null, fn fail(gen: *Generator, comptime format: []const u8, args: anytype) GenError { assert(gen.err_msg == null); const err_msg = try gen.arena.create(ErrorMsg); err_msg.* = .{ .msg = try std.fmt.allocPrint(gen.arena, format, args) }; gen.err_msg = err_msg; return error.GenFail; } pub fn generate(gen: *Generator, code: *std.ArrayList(u8)) !GenResult { gen.generateInternal(code) catch |err| switch (err) { error.GenFail => { return GenResult{ .err = gen.err_msg.? }; }, else => |e| return e, }; return GenResult{ .ok = {} }; } fn generateInternal(gen: *Generator, code: *std.ArrayList(u8)) GenError!void { for (gen.parse_scope.nodes.items) |node| { switch (node) { .@"enum" => { // TODO verify at global scope that it wasn't redefined by any chance try gen.generateEnum(node, code); }, // else => { // return gen.fail("TODO unhandled node type: {s}", .{@tagName(node)}); // }, } } } fn generateEnum(gen: *Generator, node: ParseNode, code: *std.ArrayList(u8)) GenError!void { // TODO these should be methods on respective wrapper structs like `Ast` in zig, etc. const enum_name_tok = gen.tokens[node.@"enum".name]; const enum_name = gen.buffer[enum_name_tok.loc.start..enum_name_tok.loc.end]; const writer = code.writer(); try writer.print("pub const {s} = enum {{\n", .{enum_name}); var field_names = std.StringHashMap(void).init(gen.arena); var field_values = std.AutoHashMap(usize, void).init(gen.arena); for (node.@"enum".fields.items) |field| { const field_name_tok = gen.tokens[field[0]]; const field_name = gen.buffer[field_name_tok.loc.start..field_name_tok.loc.end]; if (field_names.contains(field_name)) { return gen.fail("variant '{s}' already defined", .{field_name}); } try field_names.putNoClobber(field_name, {}); const field_value_tok = gen.tokens[field[1]]; const field_value = try std.fmt.parseInt( usize, gen.buffer[field_value_tok.loc.start..field_value_tok.loc.end], 10, ); if (field_values.contains(field_value)) { return gen.fail("value '{d}' already assigned to a variant", .{field_value}); } try field_values.putNoClobber(field_value, {}); try writer.print(" {s} = {d},\n", .{ field_name, field_value }); } try writer.writeAll("};"); } };
src/generator.zig
const c = @cImport({ @cInclude("cfl_browser.h"); }); const widget = @import("widget.zig"); const valuator = @import("valuator.zig"); const enums = @import("enums.zig"); pub const Browser = struct { inner: ?*c.Fl_Browser, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Browser { const ptr = c.Fl_Browser_new(x, y, w, h, title); if (ptr == null) unreachable; return Browser{ .inner = ptr, }; } pub fn raw(self: *Browser) ?*c.Fl_Browser { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_Browser) Browser { return Browser{ .inner = ptr, }; } pub fn fromWidgetPtr(w: widget.WidgetPtr) Browser { return Browser{ .inner = @ptrCast(?*c.Fl_Browser, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) Browser { return Browser{ .inner = @ptrCast(?*c.Fl_Browser, ptr), }; } pub fn toVoidPtr(self: *Browser) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const Browser) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn handle(self: *Browser, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_Browser_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *Browser, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Browser_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } pub fn remove(self: *Browser, line: u32) void { return c.Fl_Browser_remove(self.inner, line); } pub fn add(self: *Browser, item: [*c]const u8) void { return c.Fl_Browser_add(self.inner, item); } pub fn insert(self: *Browser, line: u32, item: [*c]const u8) void { return c.Fl_Browser_insert(self.inner, line, item); } pub fn moveItem(self: *Browser, to: u32, from: u32) void { return c.Fl_Browser_move_item(self.inner, to, from); } pub fn swap(self: *Browser, a: u32, b: u32) void { return c.Fl_Browser_swap(self.inner, a, b); } pub fn clear(self: *Browser) void { return c.Fl_Browser_clear(self.inner); } pub fn size(self: *const Browser) u32 { return c.Fl_Browser_size(self.inner); } pub fn setSize(self: *Browser, w: i32, h: i32) void { return c.Fl_Browser_set_size(self.inner, w, h); } pub fn select(self: *Browser, line: u32) void { if (line <= self.size()) return c.Fl_Browser_select(self.inner, line); } pub fn selected(self: *const Browser, line: u32) bool { return c.Fl_Browser_selected(self.inner, line) != 0; } pub fn text(self: *const Browser, line: u32) [*c]const u8 { return c.Fl_Browser_text(self.inner, line); } pub fn setText(self: *Browser, line: u32, txt: [*c]const u8) void { return c.Fl_Browser_set_text(self.inner, line, txt); } pub fn load(self: *Browser, path: [*c]const u8) void { return c.Fl_Browser_load_file(self.inner, path); } pub fn textSize(self: *const Browser) u32 { return c.Fl_Browser_text_size(self.inner); } pub fn setTextSize(self: *Browser, val: u32) void { return c.Fl_Browser_set_text_size(self.inner, val); } pub fn topline(self: *Browser, line: u32) void { return c.Fl_Browser_topline(self.inner, line); } pub fn bottomline(self: *Browser, line: u32) void { return c.Fl_Browser_bottomline(self.inner, line); } pub fn middleline(self: *Browser, line: u32) void { return c.Fl_Browser_middleline(self.inner, line); } pub fn formatChar(self: *const Browser) u8 { return c.Fl_Browser_format_char(self.inner); } pub fn setFormatChar(self: *Browser, char: u8) void { return c.Fl_Browser_set_format_char(self.inner, char); } pub fn columnChar(self: *const Browser) u8 { return c.Fl_Browser_column_char(self.inner); } pub fn setColumnChar(self: *Browser, char: u8) void { return c.Fl_Browser_set_column_char(self.inner, char); } pub fn setColumnWidths(self: *Browser, arr: [:0]const i32) void { return c.Fl_Browser_set_column_widths(self.inner, arr); } pub fn displayed(self: *const Browser, line: u32) bool { return c.Fl_Browser_displayed(self.inner, line) != 0; } pub fn makeVisible(self: *Browser, line: u32) void { return c.Fl_Browser_make_visible(self.inner, line); } pub fn position(self: *const Browser) u32 { return c.Fl_Browser_position(self.inner); } pub fn setPosition(self: *Browser, pos: u32) void { return c.Fl_Browser_set_position(self.inner, pos); } pub fn hposition(self: *const Browser) u32 { return c.Fl_Browser_hposition(self.inner); } pub fn setHposition(self: *Browser, pos: u32) void { return c.Fl_Browser_set_hposition(self.inner, pos); } pub fn hasScrollbar(self: *const Browser) enums.BrowserScrollbar { return c.Fl_Browser_has_scrollbar(self.inner); } pub fn setHasScrollbar(self: *Browser, mode: enums.BrowserScrollbar) void { return c.Fl_Browser_set_has_scrollbar(self.inner, mode); } pub fn scrollbarSize(self: *const Browser) u32 { return c.Fl_Browser_scrollbar_size(self.inner); } pub fn setScrollbarSize(self: *Browser, new_size: u32) void { return c.Fl_Browser_set_scrollbar_size(self.inner, new_size); } pub fn sort(self: *Browser) void { return c.Fl_Browser_sort(self.inner); } pub fn scrollbar(self: *const Browser) valuator.Valuator { return valuator.Valuator{ .inner = c.Fl_Browser_scrollbar(self.inner) }; } pub fn hscrollbar(self: *const Browser) valuator.Valuator { return valuator.Valuator{ .inner = c.Fl_Browser_hscrollbar(self.inner) }; } }; pub const SelectBrowser = struct { inner: ?*c.Fl_Select_Browser, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) SelectBrowser { const ptr = c.Fl_Select_Browser_new(x, y, w, h, title); if (ptr == null) unreachable; return SelectBrowser{ .inner = ptr, }; } pub fn raw(self: *SelectBrowser) ?*c.Fl_Select_Browser { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_Select_Browser) SelectBrowser { return SelectBrowser{ .inner = ptr, }; } pub fn fromWidgetPtr(w: widget.WidgetPtr) SelectBrowser { return SelectBrowser{ .inner = @ptrCast(?*c.Fl_Select_Browser, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) SelectBrowser { return SelectBrowser{ .inner = @ptrCast(?*c.Fl_Select_Browser, ptr), }; } pub fn toVoidPtr(self: *SelectBrowser) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const SelectBrowser) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn asBrowser(self: *const SelectBrowser) Browser { return Browser{ .inner = @ptrCast(?*c.Fl_Browser, self.inner), }; } pub fn handle(self: *SelectBrowser, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_Select_Browser_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *SelectBrowser, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Select_Browser_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } }; pub const HoldBrowser = struct { inner: ?*c.Fl_Hold_Browser, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) HoldBrowser { const ptr = c.Fl_Hold_Browser_new(x, y, w, h, title); if (ptr == null) unreachable; return HoldBrowser{ .inner = ptr, }; } pub fn raw(self: *HoldBrowser) ?*c.Fl_Hold_Browser { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_Hold_Browser) HoldBrowser { return HoldBrowser{ .inner = ptr, }; } pub fn fromWidgetPtr(w: widget.WidgetPtr) HoldBrowser { return HoldBrowser{ .inner = @ptrCast(?*c.Fl_Hold_Browser, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) HoldBrowser { return HoldBrowser{ .inner = @ptrCast(?*c.Fl_Hold_Browser, ptr), }; } pub fn toVoidPtr(self: *HoldBrowser) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const HoldBrowser) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn asBrowser(self: *const HoldBrowser) Browser { return Browser{ .inner = @ptrCast(?*c.Fl_Browser, self.inner), }; } pub fn handle(self: *HoldBrowser, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_Hold_Browser_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *HoldBrowser, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Hold_Browser_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } }; pub const MultiBrowser = struct { inner: ?*c.Fl_Multi_Browser, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) MultiBrowser { const ptr = c.Fl_Multi_Browser_new(x, y, w, h, title); if (ptr == null) unreachable; return MultiBrowser{ .inner = ptr, }; } pub fn raw(self: *MultiBrowser) ?*c.Fl_Multi_Browser { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_Multi_Browser) MultiBrowser { return MultiBrowser{ .inner = ptr, }; } pub fn fromWidgetPtr(w: widget.WidgetPtr) MultiBrowser { return MultiBrowser{ .inner = @ptrCast(?*c.Fl_Multi_Browser, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) MultiBrowser { return MultiBrowser{ .inner = @ptrCast(?*c.Fl_Multi_Browser, ptr), }; } pub fn toVoidPtr(self: *MultiBrowser) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const MultiBrowser) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn asBrowser(self: *const MultiBrowser) Browser { return Browser{ .inner = @ptrCast(?*c.Fl_Browser, self.inner), }; } pub fn handle(self: *MultiBrowser, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_Multi_Browser_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *MultiBrowser, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Multi_Browser_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } }; pub const FileBrowser = struct { inner: ?*c.Fl_File_Browser, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) FileBrowser { const ptr = c.Fl_File_Browser_new(x, y, w, h, title); if (ptr == null) unreachable; return FileBrowser{ .inner = ptr, }; } pub fn raw(self: *FileBrowser) ?*c.Fl_File_Browser { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_File_Browser) FileBrowser { return FileBrowser{ .inner = ptr, }; } pub fn fromWidgetPtr(w: widget.WidgetPtr) FileBrowser { return FileBrowser{ .inner = @ptrCast(?*c.Fl_File_Browser, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) FileBrowser { return FileBrowser{ .inner = @ptrCast(?*c.Fl_File_Browser, ptr), }; } pub fn toVoidPtr(self: *FileBrowser) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const FileBrowser) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn asBrowser(self: *const FileBrowser) Browser { return Browser{ .inner = @ptrCast(?*c.Fl_Browser, self.inner), }; } pub fn handle(self: *FileBrowser, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_File_Browser_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *FileBrowser, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_File_Browser_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } }; test "" { @import("std").testing.refAllDecls(@This()); }
src/browser.zig
const std = @import("std"); const epsilonEq = @import("utils.zig").epsilonEq; pub fn initPoint(x: f64, y: f64, z: f64) Vec4 { return Vec4.init(x, y, z, 1.0); } pub fn initVector(x: f64, y: f64, z: f64) Vec4 { return Vec4.init(x, y, z, 0.0); } pub fn isPoint(vec: Vec4) bool { return epsilonEq(vec.w, 1.0); } pub fn isVector(vec: Vec4) bool { return epsilonEq(vec.w, 0.0); } pub const Vec4 = struct { const Self = @This(); x: f64, y: f64, z: f64, w: f64, pub fn init(x: f64, y: f64, z: f64, w: f64) Self { return .{ .x = x, .y = y, .z = z, .w = w, }; } pub fn eql(self: Self, other: Self) bool { return epsilonEq(self.x, other.x) and epsilonEq(self.y, other.y) and epsilonEq(self.z, other.z) and epsilonEq(self.w, other.w); } pub fn add(self: Self, other: Self) Self { return .{ .x = self.x + other.x, .y = self.y + other.y, .z = self.z + other.z, .w = self.w + other.w, }; } pub fn sub(self: Self, other: Self) Self { return .{ .x = self.x - other.x, .y = self.y - other.y, .z = self.z - other.z, .w = self.w - other.w, }; } pub fn negate(self: Self) Self { return .{ .x = -self.x, .y = -self.y, .z = -self.z, .w = -self.w, }; } pub fn scale(self: Self, scalar: f64) Self { return .{ .x = scalar * self.x, .y = scalar * self.y, .z = scalar * self.z, .w = scalar * self.w, }; } pub fn div(self: Self, scalar: f64) Self { return self.scale(1.0 / scalar); } pub fn length(self: Self) f64 { return std.math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z + self.w * self.w); } pub fn normalize(self: Self) Self { const len = self.length(); return .{ .x = self.x / len, .y = self.y / len, .z = self.z / len, .w = self.w / len, }; } pub fn dot(self: Self, other: Self) f64 { return self.x * other.x + self.y * other.y + self.z * other.z + self.w * other.w; } pub fn cross(self: Self, other: Self) Self { return initVector( self.y * other.z - self.z * other.y, self.z * other.x - self.x * other.z, self.x * other.y - self.y * other.x, ); } pub fn reflect(self: Self, normal: Self) Self { const dp = self.dot(normal); return self.sub(normal.scale(2.0 * dp)); } }; test "point / vector" { const a = Vec4.init(4.3, -4.2, 3.1, 1.0); try std.testing.expect(isPoint(a) == true); try std.testing.expect(isVector(a) == false); const b = Vec4.init(4.3, -4.2, 3.1, 0.0); try std.testing.expect(isPoint(b) == false); try std.testing.expect(isVector(b) == true); } test "init" { const p = initPoint(4, -4, 3); try std.testing.expect(epsilonEq(p.w, 1.0)); const v = initVector(4, -4, 3); try std.testing.expect(epsilonEq(v.w, 0.0)); } test "equality" { const p = initPoint(4, -4, 3); const v = initVector(4, -4, 3); try std.testing.expect(p.eql(initPoint(4, -4, 3)) == true); try std.testing.expect(p.eql(initPoint(4, -4, 3.01)) == false); try std.testing.expect(p.eql(initPoint(4, -4.01, 3)) == false); try std.testing.expect(p.eql(initPoint(4.01, -4, 3)) == false); try std.testing.expect(p.eql(p) == true); try std.testing.expect(p.eql(v) == false); try std.testing.expect(v.eql(initVector(4, -4, 3)) == true); } test "adding two tuples" { const a1 = Vec4.init(3, -2, 5, 1); const a2 = Vec4.init(-2, 3, 1, 0); const result = a1.add(a2); try std.testing.expect(result.eql(Vec4.init(1, 1, 6, 1)) == true); } test "subtracting a vector from a point" { const p = initPoint(3, 2, 1); const v = initVector(5, 6, 7); const result = p.sub(v); try std.testing.expect(result.eql(initPoint(-2, -4, -6))); } test "subtracting two vectors" { const v1 = initVector(3, 2, 1); const v2 = initVector(5, 6, 7); const result = v1.sub(v2); try std.testing.expect(result.eql(initVector(-2, -4, -6))); } test "subtracting a vector from the zeor vector" { const zero = initVector(0, 0, 0); const v = initVector(1, -2, 3); const result = zero.sub(v); try std.testing.expect(result.eql(initVector(-1, 2, -3))); } test "negating a tuple" { const a = Vec4.init(1, -2, 3, -4); const result = a.negate(); try std.testing.expect(result.eql(Vec4.init(-1, 2, -3, 4))); } test "multiplying a tuple by a scalar" { const a = Vec4.init(1, -2, 3, -4); const result = a.scale(0.5); try std.testing.expect(result.eql(Vec4.init(0.5, -1, 1.5, -2))); } test "dividing a tuple by a scalar" { const a = Vec4.init(1, -2, 3, -4); const result = a.div(2); try std.testing.expect(result.eql(Vec4.init(0.5, -1, 1.5, -2))); } test "length of vectors" { const v1 = initVector(1, 0, 0); try std.testing.expect(epsilonEq(v1.length(), 1.0)); const v2 = initVector(0, 0, 1); try std.testing.expect(epsilonEq(v2.length(), 1.0)); const v3 = initVector(1, 2, 3); try std.testing.expect(epsilonEq(v3.length(), std.math.sqrt(14.0))); const v4 = initVector(-1, -2, -3); try std.testing.expect(epsilonEq(v4.length(), std.math.sqrt(14.0))); } test "normalize" { const v1 = initVector(4, 0, 0); try std.testing.expect(v1.normalize().eql(initVector(1, 0, 0))); const v2 = initVector(1, 2, 3); const len = std.math.sqrt(14.0); try std.testing.expect(v2.normalize().eql(initVector(1.0 / len, 2.0 / len, 3.0 / len))); try std.testing.expect(epsilonEq(v2.normalize().length(), 1.0)); } test "dot product" { const a = initVector(1, 2, 3); const b = initVector(2, 3, 4); try std.testing.expect(epsilonEq(a.dot(b), 20.0)); } test "cross product" { const a = initVector(1, 2, 3); const b = initVector(2, 3, 4); try std.testing.expect(a.cross(b).eql(initVector(-1, 2, -1))); try std.testing.expect(b.cross(a).eql(initVector(1, -2, 1))); } test "reflecting a vector approaching 45°" { const v = initVector(1, -1, 0); const n = initVector(0, 1, 0); const r = v.reflect(n); try std.testing.expect(r.eql(initVector(1, 1, 0))); } test "reflecting a vector off a slanted surface" { const v = initVector(0, -1, 0); const n = initVector(1, 1, 0).normalize(); const r = v.reflect(n); try std.testing.expect(r.eql(initVector(1, 0, 0))); }
vector.zig
const std = @import("std"); const print = std.debug.print; usingnamespace @import("value.zig"); usingnamespace @import("chunk.zig"); usingnamespace @import("scanner.zig"); usingnamespace @import("compiler.zig"); usingnamespace @import("heap.zig"); pub var parser: Parser = undefined; // Lox’s precedence levels in order from lowest to highest. 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 ParseRule = struct { prefix: ?ParseFn, infix: ?ParseFn, precedence: Precedence, }; const ParseFn = fn (self: *Parser, canAssing: bool) anyerror!void; pub const Parser = struct { current: Token, previous: Token, hadError: bool, panicMode: bool, pub fn init() Parser { return Parser{ .current = undefined, .previous = undefined, .hadError = false, .panicMode = false, }; } const rules = [_]ParseRule{ .{ .prefix = grouping, .infix = call, .precedence = .PREC_CALL }, // 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 = unary, .infix = binary, .precedence = .PREC_TERM }, // TOKEN_MINUS .{ .prefix = null, .infix = binary, .precedence = .PREC_TERM }, // TOKEN_PLUS .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, // TOKEN_SEMICOLON .{ .prefix = null, .infix = binary, .precedence = .PREC_FACTOR }, // TOKEN_SLASH .{ .prefix = null, .infix = binary, .precedence = .PREC_FACTOR }, // TOKEN_STAR .{ .prefix = unary, .infix = null, .precedence = .PREC_NONE }, // TOKEN_BANG .{ .prefix = null, .infix = binary, .precedence = .PREC_EQUALITY }, // TOKEN_BANG_EQUAL .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, // TOKEN_EQUAL .{ .prefix = null, .infix = binary, .precedence = .PREC_EQUALITY }, // TOKEN_EQUAL_EQUAL .{ .prefix = null, .infix = binary, .precedence = .PREC_COMPARISON }, // TOKEN_GREATER .{ .prefix = null, .infix = binary, .precedence = .PREC_COMPARISON }, // TOKEN_GREATER_EQUAL .{ .prefix = null, .infix = binary, .precedence = .PREC_COMPARISON }, // TOKEN_LESS .{ .prefix = null, .infix = binary, .precedence = .PREC_COMPARISON }, // TOKEN_LESS_EQUAL .{ .prefix = variable, .infix = null, .precedence = .PREC_NONE }, // TOKEN_IDENTIFIER .{ .prefix = string, .infix = null, .precedence = .PREC_NONE }, // TOKEN_STRING .{ .prefix = number, .infix = null, .precedence = .PREC_NONE }, // TOKEN_NUMBER .{ .prefix = null, .infix = and_, .precedence = .PREC_AND }, // TOKEN_AND .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, // TOKEN_CLASS .{ .prefix = null, .infix = null, .precedence = .PREC_NONE }, // TOKEN_ELSE .{ .prefix = 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 = 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 = 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 advance(self: *Parser) void { self.previous = self.current; while (true) { self.current = sacnner.scanToken(); if (self.current.tokenType != TokenType.TOKEN_ERROR) { break; } self.errorAtCurrent(self.current.literal); } } fn errorAtCurrent(self: *Parser, message: []const u8) void { self.errorAt(&self.current, message); } pub 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; } print("[line {}] Error", .{token.line}); if (token.tokenType == TokenType.TOKEN_EOF) { print(" at end", .{}); } else if (token.tokenType == TokenType.TOKEN_ERROR) { // Nothing } else { print(" at '{}'", .{token.literal}); } print(": {}\n", .{message}); self.hadError = true; } pub fn consume(self: *Parser, tokenType: TokenType, message: []const u8) void { if (self.current.tokenType == tokenType) { self.advance(); return; } self.errorAtCurrent(message); } fn check(self: *Parser, tt: TokenType) bool { return self.current.tokenType == tt; } pub fn match(self: *Parser, tt: TokenType) bool { if (!self.check(tt)) return false; self.advance(); return true; } fn emitByte(self: *Parser, byte: u8) !void { try currentChunk().writeByte(byte, self.previous.line); } pub fn emitOpCode(self: *Parser, opCode: OpCode) !void { try self.emitByte(@enumToInt(opCode)); } pub fn emitReturn(self: *Parser) !void { try self.emitOpCode(OpCode.OP_NIL); try self.emitOpCode(OpCode.OP_RETURN); } fn makeConstant(self: *Parser, value: Value) !u8 { const constant = try currentChunk().addConstant(value); if (constant > std.math.maxInt(u8)) { self.error0("Too many constant in one chunk."); return 0; } return @intCast(u8, constant); } fn emitConstant(self: *Parser, value: Value) !void { try self.emitOpCode(OpCode.OP_CONSTANT); const constant = try self.makeConstant(value); try self.emitByte(constant); } fn emitBytes(self: *Parser, byte1: u8, byte2: u8) !void { try self.emitByte(byte1); try self.emitByte(byte2); } fn emitOpCodes(self: *Parser, opCode1: OpCode, opCode2: OpCode) !void { try self.emitOpCode(opCode1); try self.emitOpCode(opCode2); } fn emitJump(self: *Parser, opCode: OpCode) !usize { try self.emitOpCode(opCode); try self.emitByte(0xff); try self.emitByte(0xff); return currentChunk().code.items.len - 2; } fn emitLoop(self: *Parser, loopStart: usize) !void { try self.emitOpCode(OpCode.OP_LOOP); const offset = currentChunk().code.items.len - loopStart + 2; if (offset > std.math.maxInt(u16)) self.error0("Loop body to large."); try self.emitByte(@intCast(u8, (offset >> 8) & 0xff)); try self.emitByte(@intCast(u8, offset & 0xff)); } // 写入需要跳过的字节码个数 fn patchJump(self: *Parser, offset: usize) !void { const jump = currentChunk().code.items.len - offset - 2; if (jump > std.math.maxInt(u16)) { self.error0("Too much code jump over."); } currentChunk().code.items[offset] = @intCast(u8, (jump >> 8) & 0xff); currentChunk().code.items[offset + 1] = @intCast(u8, jump & 0xff); } fn binary(self: *Parser, canAssing: bool) !void { // Remember the operator const operatorType = self.previous.tokenType; // Compile the right operand. const rule = self.getRule(operatorType); try self.parsePrecedence(@intToEnum(Precedence, @enumToInt(rule.precedence) + 1)); // Emit the operator instruction. switch (operatorType) { TokenType.TOKEN_MINUS => try self.emitOpCode(OpCode.OP_SUBTRACT), TokenType.TOKEN_PLUS => try self.emitOpCode(OpCode.OP_ADD), TokenType.TOKEN_STAR => try self.emitOpCode(OpCode.OP_MULTIPLY), TokenType.TOKEN_SLASH => try self.emitOpCode(OpCode.OP_DIVIDE), // 比较操作 TokenType.TOKEN_BANG_EQUAL => try self.emitOpCodes(OpCode.OP_EQUAL, OpCode.OP_NOT), TokenType.TOKEN_EQUAL_EQUAL => try self.emitOpCode(OpCode.OP_EQUAL), TokenType.TOKEN_GREATER => try self.emitOpCode(OpCode.OP_GREATER), TokenType.TOKEN_GREATER_EQUAL => try self.emitOpCodes(OpCode.OP_LESS, OpCode.OP_NOT), TokenType.TOKEN_LESS => try self.emitOpCode(OpCode.OP_LESS), TokenType.TOKEN_LESS_EQUAL => try self.emitOpCodes(OpCode.OP_GREATER, OpCode.OP_NOT), else => unreachable, } } fn call(self: *Parser, canAssign: bool) !void { const argCount = try self.argumentList(); try self.emitBytes(@enumToInt(OpCode.OP_CALL), argCount); } fn literal(self: *Parser, canAssing: bool) !void { switch (parser.previous.tokenType) { TokenType.TOKEN_FALSE => try self.emitOpCode(OpCode.OP_FALSE), TokenType.TOKEN_TRUE => try self.emitOpCode(OpCode.OP_TRUE), TokenType.TOKEN_NIL => try self.emitOpCode(OpCode.OP_NIL), else => unreachable, } } fn grouping(self: *Parser, canAssing: bool) !void { try self.expression(); self.consume(TokenType.TOKEN_RIGHT_PAREN, "Expect ')' after expression."); } fn number(self: *Parser, canAssing: bool) !void { const value = try std.fmt.parseFloat(f64, self.previous.literal); try self.emitConstant(number2Value(value)); } fn string(self: *Parser, canAssing: bool) !void { try self.emitConstant(objString2Value(try heap.copyString(parser.previous.literal[1 .. parser.previous.literal.len - 1]))); } // 获取变量 fn nameVariable(self: *Parser, name: Token, canAssing: bool) !void { var getOp: OpCode = undefined; var setOp: OpCode = undefined; var arg = current.?.resolveLocal(name); if (arg != -1) { getOp = OpCode.OP_GET_LOCAL; setOp = OpCode.OP_SET_LOCAL; } else { arg = try current.?.resolveUpvalue(name); if (arg != -1) { getOp = OpCode.OP_GET_UPVALUE; setOp = OpCode.OP_SET_UPVALUE; } else { arg = try self.identifierConstant(&name); getOp = OpCode.OP_GET_GLOBAL; setOp = OpCode.OP_SET_GLOBAL; } } if (self.match(TokenType.TOKEN_EQUAL) and canAssing) { try self.expression(); try self.emitBytes(@enumToInt(setOp), @intCast(u8, arg)); } else try self.emitBytes(@enumToInt(getOp), @intCast(u8, arg)); } fn variable(self: *Parser, canAssing: bool) !void { try self.nameVariable(parser.previous, canAssing); } fn unary(self: *Parser, canAssing: bool) !void { const operatorType = parser.previous.tokenType; // Compile the operand. try self.parsePrecedence(Precedence.PREC_UNARY); // Emit the operator instruction. switch (operatorType) { TokenType.TOKEN_MINUS => try self.emitOpCode(OpCode.OP_NEGATE), TokenType.TOKEN_BANG => try self.emitOpCode(OpCode.OP_NOT), else => unreachable, } } fn parsePrecedence(self: *Parser, precedence: Precedence) !void { self.advance(); const prefixRule = self.getRule(self.previous.tokenType).prefix; if (prefixRule) |prefixFn| { const canAssign = @enumToInt(precedence) <= @enumToInt(Precedence.PREC_ASSIGNMENT); try prefixFn(self, canAssign); while (@enumToInt(precedence) <= @enumToInt(self.getRule(self.current.tokenType).precedence)) { self.advance(); const infixRule = self.getRule(self.previous.tokenType).infix; if (infixRule) |infixFn| { try infixFn(self, canAssign); } else { self.error0("Expect expression"); return; } } if (canAssign and self.match(TokenType.TOKEN_EQUAL)) { self.error0("Invalid assignment target"); } } else { self.error0("Expect expression"); return; } } fn identifierConstant(self: *Parser, name: *const Token) !u8 { return try self.makeConstant(objString2Value(try heap.copyString(name.literal))); } // declare local variable fn declareVariable(self: *Parser) !void { if (current.?.scopeDepth == 0) return; const name = self.previous; if (current.?.locals.items.len > 0) { var i: usize = current.?.locals.items.len - 1; while (i >= 0) { const local = current.?.locals.items[i]; if (local.depth != -1 and local.depth < current.?.scopeDepth) { break; } if (Token.equal(name, local.name)) { self.error0("Already variable with this name in this scope"); } if (@subWithOverflow(usize, i, 1, &i)) { break; } } } try current.?.addLocal(name); } fn parseVariable(self: *Parser, errorMessage: []const u8) !u8 { self.consume(TokenType.TOKEN_IDENTIFIER, errorMessage); // declare local variable try self.declareVariable(); // local aren't looked up by name if (current.?.scopeDepth > 0) return 0; return try self.identifierConstant(&self.previous); } fn defineVariable(self: *Parser, global: u8) !void { // 本地变量已经在栈上面了,不需要定义变量了 if (current.?.scopeDepth > 0) { current.?.makeInitialized(); return; } try self.emitBytes(@enumToInt(OpCode.OP_DEFINE_GLOBAL), global); } fn argumentList(self: *Parser) !u8 { var argCount: u8 = 0; if (!self.check(TokenType.TOKEN_RIGHT_PAREN)) { try self.expression(); argCount += 1; while (self.match(TokenType.TOKEN_COMMA)) { try self.expression(); argCount += 1; } } self.consume(TokenType.TOKEN_RIGHT_PAREN, "Expect ')' after arguments"); return argCount; } fn and_(self: *Parser, canAssign: bool) !void { const endJump = try self.emitJump(OpCode.OP_JUMP_IF_FALSE); try self.emitOpCode(OpCode.OP_POP); try self.parsePrecedence(Precedence.PREC_AND); try self.patchJump(endJump); } fn getRule(self: *Parser, tokenType: TokenType) *const ParseRule { return &rules[@enumToInt(tokenType)]; } pub fn expression(self: *Parser) !void { try self.parsePrecedence(Precedence.PREC_ASSIGNMENT); } fn block(self: *Parser) !void { while (!self.check(TokenType.TOKEN_RIGHT_BRACE) and !self.check(TokenType.TOKEN_EOF)) { try self.declaration(); } self.consume(TokenType.TOKEN_RIGHT_BRACE, "Expect '}' after block."); } fn functionParam(self: *Parser) !void { current.?.function.?.arity += 1; const paramConstant = try self.parseVariable("Expect parameter name."); try self.defineVariable(paramConstant); } fn function(self: *Parser, ft: FunctionType) !void { try initCompiler(heap.allocator, ft); const compiler = current; current.?.beginScope(); // Compile the parameter list. self.consume(TokenType.TOKEN_LEFT_PAREN, "Expect '(' after function name."); if (!self.check(TokenType.TOKEN_RIGHT_PAREN)) { try self.functionParam(); while (self.match(TokenType.TOKEN_COMMA)) { try self.functionParam(); } } self.consume(TokenType.TOKEN_RIGHT_PAREN, "Expect ')' after parameters."); // The body. self.consume(TokenType.TOKEN_LEFT_BRACE, "Expect '{' before function body."); try self.block(); // all byte emit to fun's chunk // Create the function object const fun = try current.?.endCompiler(); // switch to current outside compiler try self.emitBytes(@enumToInt(OpCode.OP_CLOSURE), try self.makeConstant(objFunction2Value(fun))); var i: usize = 0; while (i < fun.upvalueCount) : (i += 1) { try self.emitByte(if (compiler.?.upvalues.items[i].isLocal) 1 else 0); try self.emitByte(@intCast(u8, compiler.?.upvalues.items[i].index)); } } fn funDeclaration(self: *Parser) !void { const global = try self.parseVariable("Expect function name."); current.?.makeInitialized(); try self.function(FunctionType.TYPE_FUNCTION); try self.defineVariable(global); } // 变量定义: 全局变量需要OpCode.OP_DEFINE_GLOBAL指令, 本地变量仅需要将Token存储到Complier locals变量中 // 后面在需要使用的时候,根据locals中的索引直接从栈中,获取到对应位置的常量 fn varDeclaration(self: *Parser) !void { const global = try self.parseVariable("Expect variable name"); if (self.match(TokenType.TOKEN_EQUAL)) { try self.expression(); } else { try self.emitOpCode(OpCode.OP_NIL); } self.consume(TokenType.TOKEN_SEMICOLON, "Expect ';' after variable declaration."); try self.defineVariable(global); } fn expressionStatement(self: *Parser) !void { try self.expression(); self.consume(TokenType.TOKEN_SEMICOLON, "Expect ';' after expression."); try self.emitOpCode(OpCode.OP_POP); } fn ifStatement(self: *Parser) !void { self.consume(TokenType.TOKEN_LEFT_PAREN, "Expect '(' after 'if'."); try self.expression(); self.consume(TokenType.TOKEN_RIGHT_PAREN, "Expect ')' after condition."); const thenJump = try self.emitJump(OpCode.OP_JUMP_IF_FALSE); try self.emitOpCode(OpCode.OP_POP); try self.statement(); const elseJump = try self.emitJump(OpCode.OP_JUMP); try self.patchJump(thenJump); try self.emitOpCode(OpCode.OP_POP); if (self.match(TokenType.TOKEN_ELSE)) try self.statement(); try self.patchJump(elseJump); } fn printStatement(self: *Parser) !void { try self.expression(); self.consume(TokenType.TOKEN_SEMICOLON, "Expect ';' after value."); try self.emitOpCode(OpCode.OP_PRINT); } fn returnStatement(self: *Parser) !void { if (self.match(TokenType.TOKEN_SEMICOLON)) { try self.emitReturn(); } else { try self.expression(); self.consume(TokenType.TOKEN_SEMICOLON, "Expect ';' after return value."); try self.emitOpCode(OpCode.OP_RETURN); } } fn whileStatement(self: *Parser) !void { const loopStart = currentChunk().code.items.len; self.consume(TokenType.TOKEN_LEFT_PAREN, "Expect '(' after 'while'."); try self.expression(); self.consume(TokenType.TOKEN_RIGHT_PAREN, "Expect ')' after condition."); const exitJump = try self.emitJump(OpCode.OP_JUMP_IF_FALSE); try self.emitOpCode(OpCode.OP_POP); try self.statement(); try self.emitLoop(loopStart); try self.patchJump(exitJump); try self.emitOpCode(OpCode.OP_POP); } fn synchronize(self: *Parser) void { self.panicMode = false; while (parser.current.tokenType != TokenType.TOKEN_EOF) { if (parser.previous.tokenType == TokenType.TOKEN_SEMICOLON) return; switch (parser.current.tokenType) { TokenType.TOKEN_CLASS, TokenType.TOKEN_FUN, TokenType.TOKEN_VAR, TokenType.TOKEN_FOR, TokenType.TOKEN_IF, TokenType.TOKEN_WHILE, TokenType.TOKEN_PRINT, TokenType.TOKEN_RETURN => return, else => break, } self.advance(); } } pub fn declaration(self: *Parser) anyerror!void { if (self.match(TokenType.TOKEN_VAR)) { try self.varDeclaration(); } else if (self.match(TokenType.TOKEN_FUN)) { try self.funDeclaration(); } else { try self.statement(); } if (self.panicMode) self.synchronize(); } pub fn statement(self: *Parser) anyerror!void { if (self.match(TokenType.TOKEN_PRINT)) { try self.printStatement(); } else if (self.match(TokenType.TOKEN_IF)) { try self.ifStatement(); } else if (self.match(TokenType.TOKEN_RETURN)) { try self.returnStatement(); } else if (self.match(TokenType.TOKEN_LEFT_BRACE)) { current.?.beginScope(); try self.block(); try current.?.endScope(); } else if (self.match(TokenType.TOKEN_WHILE)) { try self.whileStatement(); } else { try self.expressionStatement(); } } };
zvm/src/parser.zig
const std = @import("std"); // this delay module is not able to handle changes in sample rate, or changes // in the delay time, so it's not quite ready for prime time. i need to figure // out how to deal with reallocating(?) the delay buffer when the sample rate // or delay time changes. pub fn Delay(comptime delay_samples: usize) type { return struct { delay_buffer: [delay_samples]f32, delay_buffer_index: usize, // this wraps around. always < delay_samples pub fn init() @This() { return @This() { .delay_buffer = [1]f32{0.0} ** delay_samples, .delay_buffer_index = 0, }; } pub fn reset(self: *@This()) void { std.mem.set(f32, self.delay_buffer[0..], 0.0); self.delay_buffer_index = 0.0; } // caller calls this first. returns the number of samples actually // written, which might be less than out.len. caller is responsible for // calling this function repeatedly with the remaining parts of `out`, // until the function returns out.len. pub fn readDelayBuffer(self: *@This(), out: []f32) usize { const actual_out = if (out.len > delay_samples) out[0..delay_samples] else out; const index = self.delay_buffer_index; const len = std.math.min(delay_samples - index, actual_out.len); const delay_slice = self.delay_buffer[index .. index + len]; // paint from delay buffer to output var i: usize = 0; while (i < len) : (i += 1) { actual_out[i] += delay_slice[i]; } if (len < actual_out.len) { // wrap around to the start of the delay buffer, and // perform the same operations as above with the remaining // part of the input/output const b_len = actual_out.len - len; i = 0; while (i < b_len) : (i += 1) { actual_out[len + i] += self.delay_buffer[i]; } } return actual_out.len; } // each time readDelayBuffer is called, this must be called after, with // a slice corresponding to the number of samples returned by // readDelayBuffer. pub fn writeDelayBuffer(self: *@This(), input: []const f32) void { std.debug.assert(input.len <= delay_samples); // copy input to delay buffer and increment delay_buffer_index. // we'll have to do this in up to two steps (in case we are // wrapping around the delay buffer) const index = self.delay_buffer_index; const len = std.math.min(delay_samples - index, input.len); const delay_slice = self.delay_buffer[index .. index + len]; // paint from input into delay buffer std.mem.copy(f32, delay_slice, input[0..len]); if (len < input.len) { // wrap around to the start of the delay buffer, and // perform the same operations as above with the remaining // part of the input/output const b_len = input.len - len; std.mem.copy(f32, self.delay_buffer[0..b_len], input[len..]); self.delay_buffer_index = b_len; } else { // wrapping not needed self.delay_buffer_index += len; if (self.delay_buffer_index == delay_samples) { self.delay_buffer_index = 0; } } } }; }
src/zang/delay.zig
const std = @import("std"); const util = @import("util.zig"); fn abs(n: i32) i32 { if (n < 0) { return -n; } else { return n; } } pub fn part1(input: []const u8) !u64 { var positions = std.ArrayList(i32).init(std.heap.page_allocator); defer positions.deinit(); var numbers = std.mem.split(u8, std.mem.trimRight(u8, input, "\n"), ","); while (numbers.next()) |n| { const position = util.parseInt(i32, n); try positions.append(position); } std.sort.sort(i32, positions.items, {}, comptime std.sort.asc(i32)); var median: i32 = undefined; if (positions.items.len % 2 == 0) { const idx = positions.items.len / 2 - 1; median = @divFloor(positions.items[idx] + positions.items[idx + 1], 2); } else { const idx = (positions.items.len + 1) / 2 - 1; median = positions.items[idx]; } var optimal_fuel_use: u64 = 0; for (positions.items) |pos| { optimal_fuel_use += @intCast(u64, abs(pos - median)); } return optimal_fuel_use; } pub fn part2(input: []const u8) !u64 { var positions = std.ArrayList(i32).init(std.heap.page_allocator); defer positions.deinit(); var numbers = std.mem.split(u8, std.mem.trimRight(u8, input, "\n"), ","); while (numbers.next()) |n| { const position = util.parseInt(i32, n); try positions.append(position); } std.sort.sort(i32, positions.items, {}, comptime std.sort.asc(i32)); var optimal_fuel_use: u64 = std.math.maxInt(u64); const min = positions.items[0]; const max = positions.items[positions.items.len - 1]; var target: i32 = min; while (target <= max) : (target += 1) { var fuel_use: u64 = 0; for (positions.items) |pos| { const d = abs(pos - target); fuel_use += @intCast(u64, @divFloor(d * (d + 1), 2)); } if (fuel_use < optimal_fuel_use) { optimal_fuel_use = fuel_use; } } return optimal_fuel_use; } test "day 7 part 1" { const test_input = \\16,1,2,0,4,2,7,1,2,14 ; try std.testing.expectEqual(part1(test_input), 37); } test "day 7 part 2" { const test_input = \\16,1,2,0,4,2,7,1,2,14 ; try std.testing.expectEqual(part2(test_input), 168); }
zig/src/day7.zig
const std = @import("std"); const indexOf = std.mem.indexOf; const indexOfScalar = std.mem.indexOfScalar; const tokenize = std.mem.tokenize; const SEP = " | "; pub fn main() !void { const file = try std.fs.cwd().openFile("../inputs/08.txt", .{}); defer file.close(); const reader = file.reader(); var buf: [256]u8 = undefined; var unique_lengths: u32 = 0; var outputs_total: usize = 0; while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| { const sep_idx = indexOf(u8, line, SEP) orelse return error.InvalidSignals; const patterns = line[0..sep_idx]; var digits = [_]?[]const u8{null} ** 10; // unique signal appearances: 4 => e, 6 => b, 9 => f var signals = [_]u32{0} ** 7; var patterns_iter = tokenize(u8, patterns, " "); // len 5 => 2, 3, 5 var five_lens = [_]?[]const u8{null} ** 3; var five_lens_i: usize = 0; // len 6 => 0, 6, 9 var six_lens = [_]?[]const u8{null} ** 3; var six_lens_i: usize = 0; while (patterns_iter.next()) |pattern| { switch (pattern.len) { 2 => digits[1] = pattern, 3 => digits[7] = pattern, 4 => digits[4] = pattern, 7 => digits[8] = pattern, 5 => { five_lens[five_lens_i] = pattern; five_lens_i += 1; }, 6 => { six_lens[six_lens_i] = pattern; six_lens_i += 1; }, else => {}, } for (pattern) |signal| { // lowercase ascii values signals[signal - 97] += 1; } } next_five_len: for (five_lens) |pattern| { for (pattern.?) |signal| { switch (signals[signal - 97]) { 4 => { digits[2] = pattern; continue :next_five_len; }, 6 => { digits[5] = pattern; continue :next_five_len; }, else => {}, } } digits[3] = pattern; } for (six_lens) |pattern| { for ("abcdefg") |signal| { if (indexOfScalar(u8, pattern.?, signal) == null) { switch (signals[signal - 97]) { 4 => digits[9] = pattern, 7 => digits[0] = pattern, 8 => digits[6] = pattern, else => {}, } break; } } } const output = line[sep_idx + SEP.len ..]; var output_iter = tokenize(u8, output, " "); var coefficient: u32 = 1000; while (output_iter.next()) |v| { switch (v.len) { 2...4 | 7 => unique_lengths += 1, else => {}, } outputs_total += coefficient * findDigit(digits, v).?; coefficient /= 10; } } std.log.info("part 1: {d}", .{unique_lengths}); std.log.info("part 2: {d}", .{outputs_total}); } fn findDigit(digits: [10]?[]const u8, pattern: []const u8) ?usize { next_digit: for (digits) |digit, i| { if (digit.?.len != pattern.len) continue; for (pattern) |signal| { if (indexOfScalar(u8, digit.?, signal) == null) continue :next_digit; } return i; } return null; }
2021/zig/08.zig
const std = @import("std"); const Answer = struct { @"0": u32, @"1": u32 }; const V2 = [2]i32; const LineSeg = [2]V2; fn sign(x: i32) i32 { if (x > 0) { return 1; } else if (x < 0) { return -1; } else { return 0; } } // Direction of v from u fn dirV2(u: V2, v: V2) V2 { return V2{ sign(v[0] - u[0]), sign(v[1] - u[1]) }; } fn addV2(u: V2, v: V2) V2 { return V2{ u[0] + v[0], u[1] + v[1] }; } fn eqV2(u: V2, v: V2) bool { return u[0] == v[0] and u[1] == v[1]; } const Grid = struct { const Self = @This(); items: []u32, dim: usize, allocator: *std.mem.Allocator, pub fn init(n: usize, allocator: *std.mem.Allocator) !Self { const items = try allocator.alloc(u32, n * n); std.mem.set(u32, items, 0); return Self{ .items = items, .dim = n, .allocator = allocator, }; } pub fn deinit(self: Self) void { self.allocator.free(self.items); } pub fn ix(self: Self, row: usize, col: usize) *u32 { return &self.items[row * self.dim + col]; } }; fn solve(grid: Grid, vents: []LineSeg, count_diags: bool) u32 { for (vents) |line_seg| { const dir = dirV2(line_seg[0], line_seg[1]); if (dir[0] * dir[1] != 0 and !count_diags) { continue; } var pos = line_seg[0]; grid.ix(@intCast(usize, pos[1]), @intCast(usize, pos[0])).* += 1; while (!eqV2(pos, line_seg[1])) { pos = addV2(pos, dir); grid.ix(@intCast(usize, pos[1]), @intCast(usize, pos[0])).* += 1; } } var num_multi_covers: u32 = 0; for (grid.items) |num_covers| { if (num_covers >= 2) { num_multi_covers += 1; } } return num_multi_covers; } fn run(filename: []const u8) !Answer { const file = try std.fs.cwd().openFile(filename, .{ .read = true }); defer file.close(); var reader = std.io.bufferedReader(file.reader()).reader(); var buffer: [1024]u8 = undefined; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var vents = std.ArrayList(LineSeg).init(&gpa.allocator); defer vents.deinit(); while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| { var endpoints = std.mem.tokenize(u8, line, " ->"); var coords1 = std.mem.tokenize(u8, endpoints.next().?, ","); const x1 = try std.fmt.parseInt(i32, coords1.next().?, 10); const y1 = try std.fmt.parseInt(i32, coords1.next().?, 10); var coords2 = std.mem.tokenize(u8, endpoints.next().?, ","); const x2 = try std.fmt.parseInt(i32, coords2.next().?, 10); const y2 = try std.fmt.parseInt(i32, coords2.next().?, 10); try vents.append(LineSeg{ V2{ x1, y1 }, V2{ x2, y2 } }); } var max_dim: usize = 0; for (vents.items) |line_seg| { max_dim = @maximum(max_dim, @intCast(usize, line_seg[0][0])); max_dim = @maximum(max_dim, @intCast(usize, line_seg[0][1])); max_dim = @maximum(max_dim, @intCast(usize, line_seg[1][0])); max_dim = @maximum(max_dim, @intCast(usize, line_seg[1][1])); } var grid1 = try Grid.init(max_dim + 1, &gpa.allocator); defer grid1.deinit(); var grid2 = try Grid.init(max_dim + 1, &gpa.allocator); defer grid2.deinit(); return Answer{ .@"0" = solve(grid1, vents.items, false), .@"1" = solve(grid2, vents.items, true) }; } pub fn main() !void { const answer = try run("inputs/" ++ @typeName(@This()) ++ ".txt"); std.debug.print("{d}\n", .{answer.@"0"}); std.debug.print("{d}\n", .{answer.@"1"}); } test { const answer = try run("test-inputs/" ++ @typeName(@This()) ++ ".txt"); try std.testing.expectEqual(answer.@"0", 5); try std.testing.expectEqual(answer.@"1", 12); }
src/day05.zig
const std = @import("std"); const Mmu = @import("mmu.zig").Mmu; const assert = std.debug.assert; // 4.194304Mhz pub const clock_speed = 4194304; pub const FlagZ: u8 = 0x80; pub const FlagS: u8 = 0x40; pub const FlagH: u8 = 0x20; pub const FlagC: u8 = 0x10; pub const A = 0; pub const F = 1; pub const B = 2; pub const C = 3; pub const D = 4; pub const E = 5; pub const H = 6; pub const L = 7; pub const AF = 0; pub const BC = 1; pub const DE = 2; pub const HL = 3; pub const SP = 4; pub const PC = 5; const trace = false; pub const Z80 = struct { // A, F, B, C, D, E, H, L, PC, SP r: [12]u8, r1: []u8, r2: []u16, total_ticks: usize, ticks: usize, // Communication mmu: *Mmu, pub fn init(mmu: *Mmu) Z80 { var z = Z80{ .r = []u8{0} ** 12, .r1 = undefined, .r2 = undefined, .total_ticks = 0, .ticks = 0, .mmu = mmu, }; // Allow accessing half/whole registers somewhwat similar to anonymous unions z.r1 = z.r[0..8]; z.r2 = @alignCast(@alignOf(u16), @bytesToSlice(u16, z.r[0..12])); return z; } pub fn step(self: *Z80, opcode: u8) usize { instruction_table[opcode](self); if (trace) { if (opcode != 0xcb) { std.debug.warn("\n : {} [{x}]\n", instruction_names_table[opcode], opcode); } else { const cb_opcode = self.mmu.read(self.r2[PC] + 1); std.debug.warn("\n : {} [{x}]\n", cb_instruction_names_table[cb_opcode], cb_opcode); } self.dump(); var stdin_file = std.io.getStdIn() catch unreachable; var stdin = stdin_file.inStream(); _ = stdin.stream.readByte(); } const r = self.ticks; self.total_ticks += r; self.ticks = 0; return r; } pub fn dump(self: *Z80) void { std.debug.warn( \\ SP:{x} PC:{x} AF:{x} BC:{x} DE:{x} ({}) \\ [{x}, {x}, ... ] \\ , self.r2[SP], self.r2[PC], self.r2[AF], self.r2[BC], self.r2[DE], self.total_ticks, self.mmu.read(self.r2[PC]), self.mmu.read(self.r2[PC] + 1), ); } // Read a byte from memory in 4 cycles fn read8(self: *Z80, address: u16) u8 { self.ticks += 4; return self.mmu.read(address); } // Read a word from memory in 8 cycles fn read16(self: *Z80, address: u16) u16 { return u16(self.read8(address)) | (u16(self.read8(address + 1)) << 8); } // Write a byte to memory in 4 cycles fn write8(self: *Z80, address: u16, byte: u8) void { self.ticks += 4; self.mmu.write(address, byte); } // Write a word to memory in 8 cycles fn write16(self: *Z80, address: u16, word: u16) void { self.write8(address, @truncate(u8, word)); self.write8(address + 1, @intCast(u8, word >> 8)); } // Cycle the cpu with no other side-effects. fn cycle(self: *Z80) void { self.ticks += 4; } }; // See: http://www.pastraiser.com/cpu/gameboy/gameboy_opcodes.html const Instruction = fn (z: *Z80) void; const instruction_table = [256]Instruction{ // X0, X1, X2, X3, X4, X5, X6, X7, // X8, X9, Xa, Xb, Xc, Xd, Xe, Xf, nop_____, ld16(BC), ldXa(BC), incw(BC), inc__(B), dec__(B), ld8__(B), rlca____, // 0X ld_d16sp, adhl(BC), ldaX(BC), decw(BC), inc__(C), dec__(C), ld8__(C), rrca____, stop____, ld16(DE), ldXa(DE), incw(DE), inc__(D), dec__(D), ld8__(D), rla_____, // 1X jr______, adhl(DE), ldaX(DE), decw(DE), inc__(E), dec__(E), ld8__(E), rra_____, jr_nz___, ld16(HL), ld_hli_a, incw(HL), inc__(H), dec__(H), ld8__(H), ________, // 2X jr_z____, adhl(HL), ld_a_hli, decw(HL), inc__(L), dec__(L), ld8__(L), ________, jr_nc___, ld16(SP), ld_hld_a, incw(SP), inc_hl__, dec_hl__, ld_hl_d8, ________, // 3X jr_c____, adhl(SP), ld_a_hld, decw(SP), inc__(A), dec__(A), ld8__(A), ________, ld(B, B), ld(B, C), ld(B, D), ld(B, E), ld(B, H), ld(B, L), ldXhl(B), ld(B, A), // 4X ld(C, B), ld(C, C), ld(C, D), ld(C, E), ld(C, H), ld(C, L), ldXhl(C), ld(C, A), ld(D, B), ld(D, C), ld(D, D), ld(D, E), ld(D, H), ld(D, L), ldXhl(D), ld(D, A), // 5X ld(E, B), ld(E, C), ld(E, D), ld(E, E), ld(E, H), ld(E, L), ldXhl(E), ld(E, A), ld(H, B), ld(H, C), ld(H, D), ld(H, E), ld(H, H), ld(H, L), ldXhl(H), ld(H, A), // 6X ld(L, B), ld(L, C), ld(L, D), ld(L, E), ld(L, H), ld(L, L), ldXhl(L), ld(L, A), ldhlY(B), ldhlY(C), ldhlY(D), ldhlY(E), ldhlY(H), ldhlY(L), halt____, ldhlY(A), // 7X ld(A, B), ld(A, C), ld(A, D), ld(A, E), ld(A, H), ld(A, L), ldXhl(A), ld(A, A), add__(B), add__(C), add__(D), add__(E), add__(H), add__(L), addhl___, add__(A), // 8X adc__(B), adc__(C), adc__(D), adc__(E), adc__(H), adc__(L), adchl___, adc__(A), sub__(B), sub__(C), sub__(D), sub__(E), sub__(H), sub__(L), subhl___, sub__(A), // 9X sbc__(B), sbc__(C), sbc__(D), sbc__(E), sbc__(H), sbc__(L), sbchl___, sbc__(A), and__(B), and__(C), and__(D), and__(E), and__(H), and__(L), andhl___, and__(A), // aX xor__(B), xor__(C), xor__(D), xor__(E), xor__(H), xor__(L), xorhl___, xor__(A), or___(B), or___(C), or___(D), or___(E), or___(H), or___(L), orhl____, or___(A), // bX cp___(B), cp___(C), cp___(D), cp___(E), cp___(H), cp___(L), cphl____, cp___(A), ret_nz__, pop_(BC), jp_nz___, jp_nn___, call_nz_, push(BC), add_a_d8, rst__(0), // cX ret_z___, ret_____, jp_z____, cb______, call_z__, call____, adc_a_d8, rst__(8), ret_nc__, pop_(DE), jp_nc___, illegal_, call_nc_, push(DE), sub_a_d8, rst_(16), // dX ret_c___, ________, jp_c____, illegal_, call_c__, illegal_, sbc_a_d8, rst_(24), ldh_a8_a, pop_(HL), ld_uc_a_, illegal_, illegal_, push(HL), and_a_d8, rst_(32), // eX ________, ________, ld_a16_a, illegal_, illegal_, illegal_, xor_a_d8, rst_(40), ldh_a_a8, pop_(AF), ld_a_uc_, di______, illegal_, push(AF), or_a_d8_, rst_(48), // fX ________, ________, ld_a_a16, ei______, illegal_, illegal_, cp_a_d8_, rst_(56), }; const instruction_names_table = [256][11]u8{ "NOP ", "LD BC,d16 ", "LD (BC),A ", "INC BC ", "INC B ", "DEC B ", "LD B,d8 ", "RLCA ", "LD (a16),SP", "ADD HL,BC ", "LD A,(BC) ", "DEC BC ", "INC C ", "DEC C ", "LD C,d8 ", "RRCA ", "STOP ", "LD DE,d16 ", "LD (DE),A ", "INC DE ", "INC D ", "DEC D ", "LD D,d8 ", "RLA ", "JR r8 ", "ADD HL,DE ", "LD A,(DE) ", "DEC DE ", "INC E ", "DEC E ", "LD E,d8 ", "RRA ", "JR NZ,r8 ", "LD HL,d16 ", "LD (HL+),A ", "INC HL ", "INC H ", "DEC H ", "LD H,d8 ", "DAA ", "JR Z,r8 ", "ADD HL,HL ", "LD A,(HL+) ", "DEC HL ", "INC L ", "DEC L ", "LD L,d8 ", "CPL ", "JR NC,r8 ", "LD SP,d16 ", "LD (HL-),A ", "INC SP ", "INC (HL) ", "DEC (HL) ", "LD (HL),d8 ", "SCF ", "JR C,r8 ", "ADD HL,SP ", "LD A,(HL-) ", "DEC SP ", "INC A ", "DEC A ", "LD A,d8 ", "CCF ", "LD B,B ", "LD B,C ", "LD B,D ", "LD B,E ", "LD B,H ", "LD B,L ", "LD B,(HL) ", "LD B,A ", "LD C,B ", "LD C,C ", "LD C,D ", "LD C,E ", "LD C,H ", "LD C,L ", "LD C,(HL) ", "LD C,A ", "LD D,B ", "LD D,C ", "LD D,D ", "LD D,E ", "LD D,H ", "LD D,L ", "LD D,(HL) ", "LD D,A ", "LD E,B ", "LD E,C ", "LD E,D ", "LD E,E ", "LD E,H ", "LD E,L ", "LD E,(HL) ", "LD E,A ", "LD H,B ", "LD H,C ", "LD H,D ", "LD H,E ", "LD H,H ", "LD H,L ", "LD H,(HL) ", "LD H,A ", "LD L,B ", "LD L,C ", "LD L,D ", "LD L,E ", "LD L,H ", "LD L,L ", "LD L,(HL) ", "LD L,A ", "LD (HL),B ", "LD (HL),C ", "LD (HL),D ", "LD (HL),E ", "LD (HL),H ", "LD (HL),L ", "HALT ", "LD (HL),A ", "LD A,B ", "LD A,C ", "LD A,D ", "LD A,E ", "LD A,H ", "LD A,L ", "LD A,(HL) ", "LD A,A ", "ADD A,B ", "ADD A,C ", "ADD A,D ", "ADD A,E ", "ADD A,H ", "ADD A,L ", "ADD A,(HL) ", "ADD A,A ", "ADC A,B ", "ADC A,C ", "ADC A,D ", "ADC A,E ", "ADC A,H ", "ADC A,L ", "ADC A,(HL) ", "ADC A,A ", "SUB B ", "SUB C ", "SUB D ", "SUB E ", "SUB H ", "SUB L ", "SUB (HL) ", "SUB A ", "SBC A,B ", "SBC A,C ", "SBC A,D ", "SBC A,E ", "SBC A,H ", "SBC A,L ", "SBC A,(HL) ", "SBC A,A ", "AND B ", "AND C ", "AND D ", "AND E ", "AND H ", "AND L ", "AND (HL) ", "AND A ", "XOR B ", "XOR C ", "XOR D ", "XOR E ", "XOR H ", "XOR L ", "XOR (HL) ", "XOR A ", "OR B ", "OR C ", "OR D ", "OR E ", "OR H ", "OR L ", "OR (HL) ", "OR A ", "CP B ", "CP C ", "CP D ", "CP E ", "CP H ", "CP L ", "CP (HL) ", "CP A ", "RET NZ ", "POP BC ", "JP NZ,a16 ", "JP a16 ", "CALL NZ,a16", "PUSH BC ", "ADD A,d8 ", "RST 00h ", "RET Z ", "RET ", "JP Z,a16 ", "PREFIX CB ", "CALL Z,a16 ", "CALL a16 ", "ADC A,d8 ", "RST 08h ", "RET NC ", "POP DE ", "JP NC,a16 ", "ILLEGAL ", "CALL NC,a16", "PUSH DE ", "SUB d8 ", "RST 10h ", "RET C ", "RETI ", "JP C,a16 ", "ILLEGAL ", "CALL C,a16 ", "ILLEGAL ", "SBC A,d8 ", "RST 18h ", "LDH (a8),A ", "POP HL ", "LD (C),A ", "ILLEGAL ", "ILLEGAL ", "PUSH HL ", "AND d8 ", "RST 20h ", "ADD SP,r8 ", "JP (HL) ", "LD (a16),A ", "ILLEGAL ", "ILLEGAL ", "ILLEGAL ", "XOR d8 ", "RST 28h ", "LDH A,(a8) ", "POP AF ", "LD A,(C) ", "DI ", "ILLEGAL ", "PUSH AF ", "OR d8 ", "RST 30h ", "LD HL,SP+r8", "LD SP,HL ", "LD A,(a16) ", "EI ", "ILLEGAL ", "ILLEGAL ", "CP d8 ", "RST 38h ", }; fn ld_d16sp(z: *Z80) void { const address = z.read16(z.r2[PC]); z.r2[PC] += 2; z.write16(address, z.r2[SP]); assert(z.ticks == 20); } fn ________(z: *Z80) void { const opcode = z.mmu.read(z.r2[PC] -% 1); std.debug.warn( \\!!> UNIMPLEMENTED OPCODE: {} [{x}] \\ , instruction_names_table[opcode], opcode, ); z.dump(); std.os.exit(1); } fn nop_____(z: *Z80) void { assert(z.ticks == 4); } fn stop____(z: *Z80) void { assert(z.ticks == 4); } fn di______(z: *Z80) void { // TODO: Set flag assert(z.ticks == 4); } fn ei______(z: *Z80) void { // TODO: Set flag assert(z.ticks == 4); } // PC = (PC + 1) fn jp_nn___(z: *Z80) void { const address = z.read16(z.r2[PC]); z.cycle(); z.r2[PC] = address; assert(z.ticks == 16); } fn flagCondition(z: *Z80, comptime flag: comptime_int, comptime invert: bool) bool { const r = (z.r1[F] & flag) != 0; return if (invert) !r else r; } // PC += (PC + 1) if condition fn jr_c(comptime flag: comptime_int, comptime invert: bool) Instruction { return struct { fn impl(z: *Z80) void { const offset = z.read8(z.r2[PC]); z.r2[PC] += 1; if (flagCondition(z, flag, invert)) { z.cycle(); z.r2[PC] += offset; assert(z.ticks == 12); } else { assert(z.ticks == 8); } } }.impl; } const jr_nz___ = jr_c(FlagZ, false); const jr_nc___ = jr_c(FlagC, false); const jr_z____ = jr_c(FlagZ, true); const jr_c____ = jr_c(FlagC, true); fn jr______(z: *Z80) void { const offset = z.read8(z.r2[PC]); z.r2[PC] += 1; z.cycle(); z.r2[PC] += offset; assert(z.ticks == 12); } // PC += (PC + 1) if condition fn jp_c(comptime flag: comptime_int, comptime invert: bool) Instruction { return struct { fn impl(z: *Z80) void { const address = z.read16(z.r2[PC]); z.r2[PC] += 2; if (flagCondition(z, flag, invert)) { z.cycle(); z.r2[PC] = address; assert(z.ticks == 16); } else { assert(z.ticks == 12); } } }.impl; } const jp_nz___ = jp_c(FlagZ, false); const jp_nc___ = jp_c(FlagC, false); const jp_z____ = jp_c(FlagZ, true); const jp_c____ = jp_c(FlagC, true); // PC = (SP) if condition fn ret_c(comptime flag: comptime_int, comptime invert: bool) Instruction { return struct { fn impl(z: *Z80) void { const address = z.read16(z.r2[SP]); z.cycle(); z.r2[PC] += 2; if (flagCondition(z, flag, invert)) { z.r2[PC] = address; assert(z.ticks == 16); } else { assert(z.ticks == 12); } } }.impl; } const ret_nz__ = ret_c(FlagZ, false); const ret_nc__ = ret_c(FlagC, false); const ret_z___ = ret_c(FlagZ, true); const ret_c___ = ret_c(FlagC, true); const rst__ = rst_; fn rst_(comptime address: u8) Instruction { return struct { fn impl(z: *Z80) void { z.cycle(); z.write16(z.r2[SP] - 2, z.r2[PC]); z.r2[PC] = address; } }.impl; } fn call_c(comptime flag: comptime_int, comptime invert: bool) Instruction { return struct { fn impl(z: *Z80) void { const address = z.read16(z.r2[PC]); z.r2[PC] += 2; if (flagCondition(z, flag, invert)) { z.cycle(); z.write16(z.r2[SP] - 2, z.r2[PC]); z.r2[PC] = address; assert(z.ticks == 24); } else { assert(z.ticks == 12); } } }.impl; } const call_nz_ = call_c(FlagZ, false); const call_nc_ = call_c(FlagC, false); const call_z__ = call_c(FlagZ, true); const call_c__ = call_c(FlagC, true); fn call____(z: *Z80) void { const address = z.read16(z.r2[PC]); z.r2[PC] +%= 2; z.cycle(); z.write16(z.r2[SP] - 2, z.r2[PC]); z.r2[SP] -%= 2; z.r2[PC] = address; assert(z.ticks == 24); } fn ret_____(z: *Z80) void { // TODO: const address = z.read16(z.r2[SP]); z.cycle(); z.r2[SP] +%= 2; z.r2[PC] = address; } // Pop stack into rr register fn pop_(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { z.r2[X] = z.read16(z.r2[SP]); z.r2[SP] +%= 2; z.r1[F] &= 0xf0; assert(z.ticks == 12); } }.impl; } // Push rr register onto stack fn push(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { z.cycle(); z.write16(z.r2[SP] - 2, z.r2[X]); z.r2[SP] -%= 2; assert(z.ticks == 16); } }.impl; } fn illegal_(z: *Z80) void { const opcode = z.mmu.read(z.r2[PC] -% 1); std.debug.warn( \\ \\ILLEGAL OPCODE: {x} \\ , opcode); std.os.exit(1); } fn halt____(z: *Z80) void { // TODO: Update cycles } fn adhl(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { z.cycle(); const r = z.r2[HL]; const u = z.r2[X]; z.r2[HL] +%= z.r2[X]; assert(z.ticks == 8); z.r1[F] &= ~(FlagS | FlagC | FlagH); if (((r & 0xfff) + (u & 0xfff)) & 0x1000 != 0) { z.r1[F] |= FlagH; } if (usize(r) + usize(u) & 0x10000 != 0) { z.r1[F] |= FlagC; } } }.impl; } // rX = d8 fn ldd8(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { const r = z.read8(z.r2[PC]); z.r2[PC] += 1; z.r1[X] = r; assert(z.ticks == 8); } }.impl; } fn ld_hl_d8(z: *Z80) void { const r = z.read8(z.r2[PC]); z.r2[PC] += 1; z.write8(z.r2[HL], r); assert(z.ticks == 12); } // (0xff00 + a8) = A fn ldh_a8_a(z: *Z80) void { const address = z.read8(z.r2[PC]); z.r2[PC] += 1; z.write8(0xff00 + u16(address), z.r1[A]); assert(z.ticks == 12); } // A = (0xff00 + a8) fn ldh_a_a8(z: *Z80) void { const address = z.read8(z.r2[PC]); z.r2[PC] += 1; z.r1[A] = z.read8(0xff00 + u16(address)); assert(z.ticks == 12); } // (0xff00 + C) = A fn ld_uc_a_(z: *Z80) void { z.write8(0xff00 + u16(z.r1[C]), z.r1[A]); assert(z.ticks == 8); } // A = (0xff00 + C) fn ld_a_uc_(z: *Z80) void { z.r1[A] = z.read8(0xff00 + u16(z.r1[C])); assert(z.ticks == 8); } // (X) = A fn ldXa(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { z.write8(z.r2[X], z.r1[A]); assert(z.ticks == 4); } }.impl; } // A = (X) fn ldaX(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { z.r1[A] = z.read8(z.r2[X]); assert(z.ticks == 8); } }.impl; } // (HL) = A, HL += 1 fn ld_hli_a(z: *Z80) void { z.write8(z.r2[HL], z.r1[A]); z.r2[HL] +%= 1; assert(z.ticks == 8); } // A = (HL), HL += 1 fn ld_a_hli(z: *Z80) void { z.r1[A] = z.read8(z.r2[HL]); z.r2[HL] +%= 1; assert(z.ticks == 8); } // (HL) = A, HL -= 1 fn ld_hld_a(z: *Z80) void { z.write8(z.r2[HL], z.r1[A]); z.r2[HL] -%= 1; assert(z.ticks == 8); } // A = (HL), HL -= 1 fn ld_a_hld(z: *Z80) void { z.r1[A] = z.read8(z.r2[HL]); z.r2[HL] -%= 1; assert(z.ticks == 8); } // rX = (PC) fn ld16(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { z.r2[X] = z.read16(z.r2[PC]); z.r2[PC] += 2; assert(z.ticks == 12); } }.impl; } // A = (PC) fn ld_a_a16(z: *Z80) void { const address = z.read16(z.r2[PC]); z.r2[PC] += 2; z.r1[A] = z.read8(address); assert(z.ticks == 16); } // (PC) = A fn ld_a16_a(z: *Z80) void { const address = z.read16(z.r2[PC]); z.r2[PC] += 2; z.write8(address, z.r1[A]); assert(z.ticks == 16); } // rX = (PC) fn ld8__(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { z.r1[X] = z.read8(z.r2[PC]); z.r2[PC] += 1; assert(z.ticks == 8); } }.impl; } // rX = rY fn ld(comptime X: comptime_int, comptime Y: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { if (X != Y) { z.r1[X] = z.r1[Y]; } assert(z.ticks == 4); } }.impl; } // rX = (HL) fn ldXhl(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { z.r1[X] = z.read8(z.r2[HL]); assert(z.ticks == 8); } }.impl; } // (HL) = rY fn ldhlY(comptime Y: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { z.write8(z.r2[HL], z.r1[Y]); assert(z.ticks == 8); } }.impl; } // rX += 1, no flags set fn incw(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { z.r2[X] +%= 1; z.cycle(); assert(z.ticks == 8); } }.impl; } // rX = rX + 1 fn inc__(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { z.r1[X] +%= 1; z.r1[F] &= ~(FlagS | FlagZ | FlagH); if (z.r1[X] & 0x0f == 0) { z.r1[F] |= FlagH; } if (z.r1[X] == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 4); } }.impl; } fn inc_hl__(z: *Z80) void { const r = z.read8(z.r2[HL]) +% 1; z.r1[F] &= ~(FlagS | FlagZ | FlagH); z.write8(z.r2[HL], r); if (r & 0x0f == 0) { z.r1[F] |= FlagH; } if (r == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 12); } // rX -= 1, no flags set fn decw(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { z.r2[X] -%= 1; z.cycle(); assert(z.ticks == 8); } }.impl; } // rX = rX - 1 fn dec__(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { z.r1[X] -%= 1; z.r1[F] &= ~(FlagZ | FlagH); z.r1[F] |= FlagS; if (z.r1[X] & 0xf == 0xf) { z.r1[F] |= FlagH; } if (z.r1[X] == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 4); } }.impl; } fn dec_hl__(z: *Z80) void { const r = z.read8(z.r2[HL]) -% 1; z.r1[F] &= ~(FlagZ | FlagH); z.r1[F] |= FlagS; z.write8(z.r2[HL], r); if (r & 0xf == 0xf) { z.r1[F] |= FlagH; } if (r == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 12); } // A = A + r \w carry fn adc__(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { adcv(z, z.r1[X]); assert(z.ticks == 4); } }.impl; } fn adc_a_d8(z: *Z80) void { const r = z.read8(z.r2[PC]); z.r2[PC] +%= 1; adcv(z, r); assert(z.ticks == 8); } fn adchl___(z: *Z80) void { adcv(z, z.read8(z.r2[HL])); assert(z.ticks == 8); } fn adcv(z: *Z80, r: u8) void { const a = z.r1[A]; const c = @boolToInt((z.r1[F] & FlagC) != 0); z.r1[A] = a +% r +% c; if (a +% r +% c == 0) { z.r1[F] |= FlagZ; } if ((a & 0xf) + (r & 0xf) + c > 0xf) { z.r1[F] |= FlagH; } if (usize(a) + usize(r) + c > 0xff) { z.r1[F] |= FlagC; } } // A = A - r \w carry fn sbc__(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { sbcv(z, z.r1[X]); assert(z.ticks == 4); } }.impl; } fn sbc_a_d8(z: *Z80) void { const r = z.read8(z.r2[PC]); z.r2[PC] +%= 1; sbcv(z, r); assert(z.ticks == 8); } fn sbchl___(z: *Z80) void { sbcv(z, z.read8(z.r2[HL])); assert(z.ticks == 8); } fn sbcv(z: *Z80, r: u8) void { const a = z.r1[A]; const c = @boolToInt((z.r1[F] & FlagC) != 0); z.r1[A] = a -% r -% c; z.r1[F] = FlagS; if (a -% r -% c == 0) { z.r1[F] |= FlagZ; } if ((a & 0xf) < (r & 0xf) + c) { z.r1[F] |= FlagH; } if (usize(a) -% usize(r) - c > 0xff) { z.r1[F] |= FlagC; } } // A = A + r fn add__(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { addv(z, z.r1[X]); assert(z.ticks == 4); } }.impl; } fn add_a_d8(z: *Z80) void { const r = z.read8(z.r2[PC]); z.r2[PC] +%= 1; addv(z, r); assert(z.ticks == 8); } fn addhl___(z: *Z80) void { addv(z, z.read8(z.r2[HL])); assert(z.ticks == 8); } fn addv(z: *Z80, r: u8) void { const a = z.r1[A]; z.r1[A] +%= r; if (a +% r == 0) { z.r1[F] |= FlagZ; } if ((a & 0xf) + (r & 0xf) > 0xf) { z.r1[F] |= FlagH; } if (usize(a) + usize(r) > 0xff) { z.r1[F] |= FlagC; } } // A = A - r fn sub__(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { subv(z, z.r1[X]); assert(z.ticks == 4); } }.impl; } fn sub_a_d8(z: *Z80) void { const r = z.read8(z.r2[PC]); z.r2[PC] +%= 1; subv(z, r); assert(z.ticks == 8); } fn subhl___(z: *Z80) void { subv(z, z.read8(z.r2[HL])); assert(z.ticks == 8); } fn subv(z: *Z80, r: u8) void { const a = z.r1[A]; z.r1[A] -%= r; z.r1[F] |= FlagS; if (a == r) { z.r1[F] |= FlagZ; } if ((a & 0xf) < (r & 0xf)) { z.r1[F] |= FlagH; } if (a < r) { z.r1[F] |= FlagC; } } // A = A ^ r fn xor__(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { xorv(z, z.r1[X]); assert(z.ticks == 4); } }.impl; } fn xor_a_d8(z: *Z80) void { const r = z.read8(z.r2[PC]); z.r2[PC] +%= 1; xorv(z, r); assert(z.ticks == 8); } fn xorhl___(z: *Z80) void { xorv(z, z.read8(z.r2[HL])); assert(z.ticks == 8); } fn xorv(z: *Z80, r: u8) void { z.r1[F] = if (z.r1[A] ^ r == 0) FlagZ else 0; z.r1[A] ^= r; } // A = A & r fn and__(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { andv(z, z.r1[X]); assert(z.ticks == 4); } }.impl; } fn and_a_d8(z: *Z80) void { const r = z.read8(z.r2[PC]); z.r2[PC] +%= 1; andv(z, r); assert(z.ticks == 8); } fn andhl___(z: *Z80) void { andv(z, z.read8(z.r2[HL])); assert(z.ticks == 8); } fn andv(z: *Z80, r: u8) void { z.r1[F] = FlagH | if ((z.r1[A] & r) == 0) FlagZ else 0; z.r1[A] &= r; } // A = A | r fn or___(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { orv(z, z.r1[X]); assert(z.ticks == 4); } }.impl; } fn or_a_d8_(z: *Z80) void { const r = z.read8(z.r2[PC]); z.r2[PC] +%= 1; orv(z, r); assert(z.ticks == 8); } fn orhl____(z: *Z80) void { orv(z, z.read8(z.r2[HL])); assert(z.ticks == 8); } fn orv(z: *Z80, r: u8) void { z.r1[F] = if ((z.r1[A] | r) == 0) FlagZ else 0; z.r1[A] |= r; } fn cp___(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { cpv(z, z.r1[X]); assert(z.ticks == 4); } }.impl; } fn cp_a_d8_(z: *Z80) void { const r = z.read8(z.r2[PC]); z.r2[PC] +%= 1; cpv(z, r); assert(z.ticks == 8); } fn cphl____(z: *Z80) void { cpv(z, z.read8(z.r2[HL])); assert(z.ticks == 8); } fn cpv(z: *Z80, r: u8) void { const a = z.r1[A]; z.r1[F] = FlagS; if (a == r) { z.r1[F] |= FlagZ; } if ((a & 0xf) < (r & 0xf)) { z.r1[F] |= FlagH; } if (a < r) { z.r1[F] |= FlagC; } } // These are similar to the generic rlc_ but do not modify the zero flag and are lower latency. fn rlca____(z: *Z80) void { const r = z.r1[A]; const c = @boolToInt(r & 0x80 != 0); z.r1[A] = (r << 1) | c; z.r1[F] = 0; if (c != 0) { z.r1[F] |= FlagC; } assert(z.ticks == 4); } fn rla_____(z: *Z80) void { const r = z.r1[A]; const c = @boolToInt(r & 0x80 != 0); const h = z.r1[F] & FlagC != 0; z.r1[A] = (r << 1) | c; z.r1[F] = 0; if (h) { z.r1[F] |= FlagC; } assert(z.ticks == 4); } fn rrca____(z: *Z80) void { const r = z.r1[A]; const c = r & 1; z.r1[A] = (r >> 1) | (c << 7); z.r1[F] = 0; if (c != 0) { z.r1[F] |= FlagC; } } fn rra_____(z: *Z80) void { const r = z.r1[A]; const c = r & 1; const h = z.r1[F] & FlagC != 0; z.r1[A] = (r >> 1) | (c << 7); z.r1[F] = 0; if (h) { z.r1[F] |= FlagC; } assert(z.ticks == 4); } // TODO: Check this as it seems the wrong way around. const cb_instruction_table = [256]Instruction{ // X0, X1, X2, X3, X4, X5, X6, X7, // X8, X9, Xa, Xb, Xc, Xd, Xe, Xf, rlc__(B), rlc__(C), rlc__(D), rlc__(E), rlc__(H), rlc__(L), rlc_hl__, rlc__(A), // 0X rrc__(B), rrc__(C), rrc__(D), rrc__(E), rrc__(H), rrc__(L), rrc_hl__, rrc__(A), rl___(B), rl___(C), rl___(D), rl___(E), rl___(H), rl___(L), rl_hl___, rl___(A), // 1X rr___(B), rr___(C), rr___(D), rr___(E), rr___(H), rr___(L), rr_hl___, rr___(A), sla__(B), sla__(C), sla__(D), sla__(E), sla__(H), sla__(L), sla_hl__, sla__(A), // 2X sra__(B), sra__(C), sra__(D), sra__(E), sra__(H), sra__(L), sra_hl__, sra__(A), swap_(B), swap_(C), swap_(D), swap_(E), swap_(H), swap_(L), swap_hl_, swap_(A), // 3X srl__(B), srl__(C), srl__(D), srl__(E), srl__(H), srl__(L), srl_hl__, srl__(A), bt(0, B), bt(0, C), bt(0, D), bt(0, E), bt(0, H), bt(0, L), bt_hl(0), bt(0, A), // 4X bt(1, B), bt(1, C), bt(1, D), bt(1, E), bt(1, H), bt(1, L), bt_hl(1), bt(1, A), bt(2, B), bt(2, C), bt(2, D), bt(2, E), bt(2, H), bt(2, L), bt_hl(2), bt(2, A), // 5X bt(3, B), bt(3, C), bt(3, D), bt(3, E), bt(3, H), bt(3, L), bt_hl(3), bt(3, A), bt(4, B), bt(4, C), bt(4, D), bt(4, E), bt(4, H), bt(4, L), bt_hl(4), bt(4, A), // 6X bt(5, B), bt(5, C), bt(5, D), bt(5, E), bt(5, H), bt(5, L), bt_hl(5), bt(5, A), bt(6, B), bt(6, C), bt(6, D), bt(6, E), bt(6, H), bt(6, L), bt_hl(6), bt(6, A), // 7X bt(7, B), bt(7, C), bt(7, D), bt(7, E), bt(7, H), bt(7, L), bt_hl(7), bt(7, A), rs(0, B), rs(0, C), rs(0, D), rs(0, E), rs(0, H), rs(0, L), rs_hl(0), rs(0, A), // 8X rs(1, B), rs(1, C), rs(1, D), rs(1, E), rs(1, H), rs(1, L), rs_hl(1), rs(1, A), rs(2, B), rs(2, C), rs(2, D), rs(2, E), rs(2, H), rs(2, L), rs_hl(2), rs(2, A), // 9X rs(3, B), rs(3, C), rs(3, D), rs(3, E), rs(3, H), rs(3, L), rs_hl(3), rs(3, A), rs(4, B), rs(4, C), rs(4, D), rs(4, E), rs(4, H), rs(4, L), rs_hl(4), rs(4, A), // aX rs(5, B), rs(5, C), rs(5, D), rs(5, E), rs(5, H), rs(5, L), rs_hl(5), rs(5, A), rs(6, B), rs(6, C), rs(6, D), rs(6, E), rs(6, H), rs(6, L), rs_hl(6), rs(6, A), // bX rs(7, B), rs(7, C), rs(7, D), rs(7, E), rs(7, H), rs(7, L), rs_hl(7), rs(7, A), st(0, B), st(0, C), st(0, D), st(0, E), st(0, H), st(0, L), st_hl(0), st(0, A), // cX st(1, B), st(1, C), st(1, D), st(1, E), st(1, H), st(1, L), st_hl(1), st(1, A), st(2, B), st(2, C), st(2, D), st(2, E), st(2, H), st(2, L), st_hl(2), st(2, A), // dX st(3, B), st(3, C), st(3, D), st(3, E), st(3, H), st(3, L), st_hl(3), st(3, A), st(4, B), st(4, C), st(4, D), st(4, E), st(4, H), st(4, L), st_hl(4), st(4, A), // eX st(5, B), st(5, C), st(5, D), st(5, E), st(5, H), st(5, L), st_hl(5), st(5, A), st(6, B), st(6, C), st(6, D), st(6, E), st(6, H), st(6, L), st_hl(6), st(6, A), // fX st(7, B), st(7, C), st(7, D), st(7, E), st(7, H), st(7, L), st_hl(7), st(7, A), }; const cb_instruction_names_table = [256][11]u8{ "RLC B ", "RLC C ", "RLC D ", "RLC E ", "RLC H ", "RLC L ", "RLC (HL) ", "RLC A ", "RRC B ", "RRC C ", "RRC D ", "RRC E ", "RRC H ", "RRC L ", "RRC (HL) ", "RRC A ", "RL B ", "RL C ", "RL D ", "RL E ", "RL H ", "RL L ", "RL (HL) ", "RL A ", "RR B ", "RR C ", "RR D ", "RR E ", "RR H ", "RR L ", "RR (HL) ", "RR A ", "SLA B ", "SLA C ", "SLA D ", "SLA E ", "SLA H ", "SLA L ", "SLA (HL) ", "SLA A ", "SRA B ", "SRA C ", "SRA D ", "SRA E ", "SRA H ", "SRA L ", "SRA (HL) ", "SRA A ", "SWAP B ", "SWAP C ", "SWAP D ", "SWAP E ", "SWAP H ", "SWAP L ", "SWAP (HL) ", "SWAP A ", "SRL B ", "SRL C ", "SRL D ", "SRL E ", "SRL H ", "SRL L ", "SRL (HL) ", "SRL A ", "BIT 0,B ", "BIT 0,C ", "BIT 0,D ", "BIT 0,E ", "BIT 0,H ", "BIT 0,L ", "BIT 0,(HL) ", "BIT 0,A ", "BIT 1,B ", "BIT 1,C ", "BIT 1,D ", "BIT 1,E ", "BIT 1,H ", "BIT 1,L ", "BIT 1,(HL) ", "BIT 1,A ", "BIT 2,B ", "BIT 2,C ", "BIT 2,D ", "BIT 2,E ", "BIT 2,H ", "BIT 2,L ", "BIT 2,(HL) ", "BIT 2,A ", "BIT 3,B ", "BIT 3,C ", "BIT 3,D ", "BIT 3,E ", "BIT 3,H ", "BIT 3,L ", "BIT 3,(HL) ", "BIT 3,A ", "BIT 4,B ", "BIT 4,C ", "BIT 4,D ", "BIT 4,E ", "BIT 4,H ", "BIT 4,L ", "BIT 4,(HL) ", "BIT 4,A ", "BIT 5,B ", "BIT 5,C ", "BIT 5,D ", "BIT 5,E ", "BIT 5,H ", "BIT 5,L ", "BIT 5,(HL) ", "BIT 5,A ", "BIT 6,B ", "BIT 4,C ", "BIT 4,D ", "BIT 4,E ", "BIT 4,H ", "BIT 4,L ", "BIT 4,(HL) ", "BIT 4,A ", "BIT 7,B ", "BIT 7,C ", "BIT 7,D ", "BIT 7,E ", "BIT 7,H ", "BIT 7,L ", "BIT 7,(HL) ", "BIT 7,A ", "RES 0,B ", "RES 0,C ", "RES 0,D ", "RES 0,E ", "RES 0,H ", "RES 0,L ", "RES 0,(HL) ", "RES 0,A ", "RES 1,B ", "RES 1,C ", "RES 1,D ", "RES 1,E ", "RES 1,H ", "RES 1,L ", "RES 1,(HL) ", "RES 1,A ", "RES 2,B ", "RES 2,C ", "RES 2,D ", "RES 2,E ", "RES 2,H ", "RES 2,L ", "RES 2,(HL) ", "RES 2,A ", "RES 3,B ", "RES 3,C ", "RES 3,D ", "RES 3,E ", "RES 3,H ", "RES 3,L ", "RES 3,(HL) ", "RES 3,A ", "RES 4,B ", "RES 4,C ", "RES 4,D ", "RES 4,E ", "RES 4,H ", "RES 4,L ", "RES 4,(HL) ", "RES 4,A ", "RES 5,B ", "RES 5,C ", "RES 5,D ", "RES 5,E ", "RES 5,H ", "RES 5,L ", "RES 5,(HL) ", "RES 5,A ", "RES 6,B ", "RES 4,C ", "RES 4,D ", "RES 4,E ", "RES 4,H ", "RES 4,L ", "RES 4,(HL) ", "RES 4,A ", "RES 7,B ", "RES 7,C ", "RES 7,D ", "RES 7,E ", "RES 7,H ", "RES 7,L ", "RES 7,(HL) ", "RES 7,A ", "SET 0,B ", "SET 0,C ", "SET 0,D ", "SET 0,E ", "SET 0,H ", "SET 0,L ", "SET 0,(HL) ", "SET 0,A ", "SET 1,B ", "SET 1,C ", "SET 1,D ", "SET 1,E ", "SET 1,H ", "SET 1,L ", "SET 1,(HL) ", "SET 1,A ", "SET 2,B ", "SET 2,C ", "SET 2,D ", "SET 2,E ", "SET 2,H ", "SET 2,L ", "SET 2,(HL) ", "SET 2,A ", "SET 3,B ", "SET 3,C ", "SET 3,D ", "SET 3,E ", "SET 3,H ", "SET 3,L ", "SET 3,(HL) ", "SET 3,A ", "SET 4,B ", "SET 4,C ", "SET 4,D ", "SET 4,E ", "SET 4,H ", "SET 4,L ", "SET 4,(HL) ", "SET 4,A ", "SET 5,B ", "SET 5,C ", "SET 5,D ", "SET 5,E ", "SET 5,H ", "SET 5,L ", "SET 5,(HL) ", "SET 5,A ", "SET 6,B ", "SET 4,C ", "SET 4,D ", "SET 4,E ", "SET 4,H ", "SET 4,L ", "SET 4,(HL) ", "SET 4,A ", "SET 7,B ", "SET 7,C ", "SET 7,D ", "SET 7,E ", "SET 7,H ", "SET 7,L ", "SET 7,(HL) ", "SET 7,A ", }; fn cb______(z: *Z80) void { const cb_op = z.read8(z.r2[PC]); z.r2[PC] += 1; cb_instruction_table[cb_op](z); } // TODO: Merge common paths with a generic write/read fn rlc__(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { const r = z.r1[X]; const c = @boolToInt(r & 0x80 != 0); z.r1[F] = 0; z.r1[X] = (r << 1) | c; if (c != 0) { z.r1[F] |= FlagC; } if (r << 1 == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 8); } }.impl; } fn rlc_hl__(z: *Z80) void { const r = z.read8(z.r2[HL]); const c = @boolToInt(r & 0x80 != 0); z.r1[F] = 0; z.write8(z.r2[HL], (r << 1) | c); if (c != 0) { z.r1[F] |= FlagC; } if (r << 1 == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 16); } fn rrc__(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { const r = z.r1[X]; const c = @boolToInt(r & 0x01 != 0); z.r1[F] = 0; z.r1[X] = (r >> 1) | (u8(c) << 7); if (c != 0) { z.r1[F] |= FlagC; } if (r == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 8); } }.impl; } fn rrc_hl__(z: *Z80) void { const r = z.read8(z.r2[HL]); const c = @boolToInt(r & 0x01 != 0); z.r1[F] = 0; z.write8(z.r2[HL], (r >> 1) | (u8(c) << 7)); if (c != 0) { z.r1[F] |= FlagC; } if (r == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 16); } fn rl___(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { const r = z.r1[X]; const c = @boolToInt(z.r1[F] & FlagC != 0); const h = r & 0x80 != 0; z.r1[F] = 0; z.r1[X] = (r << 1) | c; if (h) { z.r1[F] |= FlagC; } if (r == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 8); } }.impl; } fn rl_hl___(z: *Z80) void { const r = z.read8(z.r2[HL]); const c = @boolToInt(z.r1[F] & FlagC != 0); const h = r & 0x80 != 0; z.r1[F] = 0; z.write8(z.r2[HL], (r << 1) | c); if (h) { z.r1[F] |= FlagC; } if (r == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 16); } fn rr___(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { const r = z.r1[X]; const c = @boolToInt(z.r1[F] & FlagC != 0); const l = 0x01 != 0; z.r1[F] = 0; z.r1[X] = (r >> 1) | (u8(c) << 7); if (l) { z.r1[F] |= FlagC; } if (r == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 8); } }.impl; } fn rr_hl___(z: *Z80) void { const r = z.read8(z.r2[HL]); const c = @boolToInt(z.r1[F] & FlagC != 0); const l = 0x01 != 0; z.r1[F] = 0; z.write8(z.r2[HL], (r >> 1) | (u8(c) << 7)); if (l) { z.r1[F] |= FlagC; } if (r == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 16); } fn sla__(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { const r = z.r1[X]; const c = r & 0x80 != 0; z.r1[F] = 0; z.r1[X] = r << 1; if (c) { z.r1[F] |= FlagC; } if (r & 0x7f == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 8); } }.impl; } fn sla_hl__(z: *Z80) void { const r = z.read8(z.r2[HL]); const c = r & 0x80 != 0; z.r1[F] = 0; z.write8(z.r2[HL], r << 1); if (c) { z.r1[F] |= FlagC; } if (r & 0x7f == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 16); } fn sra__(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { const r = z.r1[X]; const h = r & 0x80; z.r1[F] = 0; z.r1[X] = (r >> 1) | h; if (r & 1 != 0) { z.r1[F] |= FlagC; } if (z.r1[X] == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 8); } }.impl; } fn sra_hl__(z: *Z80) void { const r = z.read8(z.r2[HL]); const h = r & 0x80; z.r1[F] = 0; z.write8(z.r2[HL], (r >> 1) | h); if (r & 1 != 0) { z.r1[F] |= FlagC; } if (r == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 16); } fn srl__(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { const r = z.r1[X]; const h = r & 0x80; z.r1[F] = 0; z.r1[X] = r >> 1; if (r & 1 != 0) { z.r1[F] |= FlagC; } if (r >> 1 == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 8); } }.impl; } fn srl_hl__(z: *Z80) void { const r = z.read8(z.r2[HL]); const h = r & 0x80; z.r1[F] = 0; z.write8(z.r2[HL], r >> 1); if (r & 1 != 0) { z.r1[F] |= FlagC; } if (r >> 1 == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 16); } fn swap_(comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { const r = z.r1[X]; const h = r & 0x80; z.r1[F] = 0; z.r1[X] = (r >> 4) | (r << 4); if (r == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 8); } }.impl; } fn swap_hl_(z: *Z80) void { const r = z.read8(z.r2[HL]); const h = r & 0x80; z.r1[F] = 0; z.write8(z.r2[HL], (r >> 4) | (r << 4)); if (r == 0) { z.r1[F] |= FlagZ; } assert(z.ticks == 16); } fn bt_hl(comptime i: u3) Instruction { return struct { fn impl(z: *Z80) void { btv(i, z, z.read8(z.r2[HL])); assert(z.ticks == 16); } }.impl; } fn bt(comptime i: u3, comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { btv(i, z, z.r1[X]); assert(z.ticks == 8); } }.impl; } fn btv(comptime i: u3, z: *Z80, r: u8) void { z.r1[F] = FlagC | FlagH; if ((r & (u8(1) << i)) == 0) { z.r1[F] |= FlagZ; } } fn rs_hl(comptime i: u3) Instruction { return struct { fn impl(z: *Z80) void { // TODO: Check cycle counts here var r = z.read8(z.r2[HL]); r &= ~(u8(1) << i); z.write8(z.r2[HL], r); assert(z.ticks == 16); } }.impl; } fn rs(comptime i: u3, comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { z.r1[X] &= ~(u8(1) << i); assert(z.ticks == 8); } }.impl; } fn st_hl(comptime i: u3) Instruction { return struct { fn impl(z: *Z80) void { var r = z.read8(z.r2[HL]); r |= u8(1) << i; z.write8(z.r2[HL], r); assert(z.ticks == 16); } }.impl; } fn st(comptime i: u3, comptime X: comptime_int) Instruction { return struct { fn impl(z: *Z80) void { z.r1[X] |= u8(1) << i; assert(z.ticks == 8); } }.impl; }
src/cpu.zig
const std = @import("std"); const c = @import("c.zig"); const helpers = @import("helpers.zig"); const varint = @import("varint.zig"); const constants = @import("constants.zig"); fn getType(env: c.napi_env, value: c.napi_value) u8 { if (helpers.isTypeof(env, value, c.napi_valuetype.napi_string)) return constants.STRING; if (helpers.instanceOfDate(env, value) catch false) return constants.STRING; var isBuffer: bool = undefined; if (c.napi_is_buffer(env, value, &isBuffer) == .napi_ok) { if (isBuffer) return constants.BUFFER; } if (helpers.callBoolMethod(env, "Number", "isInteger", value) catch false) { var num: i32 = undefined; if (c.napi_get_value_int32(env, value, &num) == .napi_ok) { if (std.math.absInt(num) catch 0 < 4294967296) return constants.INT; } } if (helpers.isTypeof(env, value, c.napi_valuetype.napi_number) and helpers.callBoolMethod(env, "Number", "isFinite", value) catch false) { return constants.DOUBLE; } var isArray: bool = undefined; if (c.napi_is_array(env, value, &isArray) == .napi_ok) { if (isArray) return constants.ARRAY; } if ((helpers.isTruthy(env, value) catch false) and helpers.isTypeof(env, value, c.napi_valuetype.napi_object)) return constants.OBJECT; if (helpers.isTypeof(env, value, c.napi_valuetype.napi_boolean)) return constants.BOOLNULL; if (helpers.isNull(env, value) catch false) return constants.BOOLNULL; if (helpers.isUndefined(env, value) catch false) return constants.BOOLNULL; return constants.RESERVED; } const Encoders = struct { pub fn String(env: c.napi_env, string: c.napi_value, dest: []u8, start: u32) !u32 { var bytes: usize = 0; if (c.napi_get_value_string_utf8(env, string, @ptrCast([*c]u8, dest[start..]), dest.len, &bytes) != .napi_ok) { return helpers.throw(env, "Failed to encode string"); } return @intCast(u32, bytes); } pub fn Buffer(env: c.napi_env, buffer: c.napi_value, dest: []u8, start: u32) !u32 { var bytes: usize = 0; var slice = helpers.slice_from_value(env, buffer, "buffer") catch return 0; const end = start + slice.len; std.mem.copy(u8, dest[start..end], slice[0..slice.len]); return @intCast(u32, slice.len); } pub fn Integer(env: c.napi_env, int: c.napi_value, dest: []u8, start: u32) !u32 { var i: i32 = undefined; if (c.napi_get_value_int32(env, int, &i) != .napi_ok) { return helpers.throw(env, "Failed to encode integer"); } var slice = std.mem.asBytes(&i); if (slice.len > dest.len) { return helpers.throw(env, "Failed to encode integer as bytes"); } const end = start + slice.len; std.mem.copy(u8, dest[start..end], slice[0..slice.len]); return 4; } pub fn Double(env: c.napi_env, double: c.napi_value, dest: []u8, start: u32) !u32 { var x: f64 = undefined; if (c.napi_get_value_double(env, double, &x) != .napi_ok) { return helpers.throw(env, "Failed to encode double"); } var slice = std.mem.asBytes(&x); if (slice.len > dest.len) { return helpers.throw(env, "Failed to encode double as bytes"); } const end = start + slice.len; std.mem.copy(u8, dest[start..end], slice[0..slice.len]); return 8; } pub fn Array(env: c.napi_env, array: c.napi_value, dest: []u8, start: u32) !u32 { var length: u32 = undefined; if (c.napi_get_array_length(env, array, &length) != .napi_ok) { return helpers.throw(env, "Failed to get array length"); } var i: u32 = 0; var position: u32 = start; while (i < length) : (i += 1) { var elem: c.napi_value = undefined; if (c.napi_get_element(env, array, i, &elem) != .napi_ok) { return helpers.throw(env, "Failed to get array element"); } position += encode(env, elem, dest, position) catch return 0; } return position - start; } pub fn Object(env: c.napi_env, object: c.napi_value, dest: []u8, start: u32) !u32 { var keys: c.napi_value = undefined; if (c.napi_get_property_names(env, object, &keys) != .napi_ok) { return helpers.throw(env, "Failed to get object keys"); } var length: u32 = undefined; if (c.napi_get_array_length(env, keys, &length) != .napi_ok) { return helpers.throw(env, "Failed to get object keys length"); } var i: u32 = 0; var position: u32 = start; while (i < length) : (i += 1) { var key: c.napi_value = undefined; if (c.napi_get_element(env, keys, i, &key) != .napi_ok) { return helpers.throw(env, "Failed to get object key"); } position += encode(env, key, dest, position) catch return 0; var value: c.napi_value = undefined; if (c.napi_get_property(env, object, key, &value) != .napi_ok) { return helpers.throw(env, "Failed to get object property"); } position += encode(env, value, dest, position) catch return 0; } return position - start; } pub fn Boolnull(env: c.napi_env, boolnull: c.napi_value, dest: []u8, start: u32) !u32 { if (helpers.isNull(env, boolnull) catch false) { return 0; } if (helpers.isUndefined(env, boolnull) catch false) { dest[start] = 2; return 1; } var result: bool = undefined; if (c.napi_get_value_bool(env, boolnull, &result) != .napi_ok) { return helpers.throw(env, "Failed to get boolean value"); } dest[start] = if (result) 1 else 0; return 1; } pub fn Any(env: c.napi_env, _type: u8, value: c.napi_value, buffer: []u8, start: u32) u32 { const len = switch (_type) { constants.INT => Encoders.Integer(env, value, buffer, start) catch 0, constants.BUFFER => Encoders.Buffer(env, value, buffer, start) catch 0, constants.STRING => Encoders.String(env, value, buffer, start) catch 0, constants.DOUBLE => Encoders.Double(env, value, buffer, start) catch 0, constants.ARRAY => Encoders.Array(env, value, buffer, start) catch 0, constants.OBJECT => Encoders.Object(env, value, buffer, start) catch 0, constants.BOOLNULL => Encoders.Boolnull(env, value, buffer, start) catch 0, else => 0, }; return len; } }; const EncodingLengthers = struct { pub fn String(env: c.napi_env, string: c.napi_value) !u32 { return helpers.bufferByteLength(env, string); } pub fn Buffer(env: c.napi_env, buffer: c.napi_value) !u32 { var length: c.napi_value = undefined; if (c.napi_get_named_property(env, buffer, "length", &length) != .napi_ok) { return helpers.throw(env, "Failed to get buffer.length"); } var result: u32 = undefined; if (c.napi_get_value_uint32(env, length, &result) != .napi_ok) { return helpers.throw(env, "Failed to get the u32 value of buffer.length"); } return result; } pub const Integer = 4; pub const Double = 8; pub fn Array(env: c.napi_env, array: c.napi_value) !u32 { var bytes: u32 = 0; var length: u32 = undefined; if (c.napi_get_array_length(env, array, &length) != .napi_ok) { return helpers.throw(env, "Failed to get array length"); } var i: u32 = 0; while (i < length) : (i += 1) { var elem: c.napi_value = undefined; if (c.napi_get_element(env, array, i, &elem) != .napi_ok) { return helpers.throw(env, "Failed to get array element"); } bytes += encodingLength(env, elem) catch 0; } return bytes; } pub fn Object(env: c.napi_env, object: c.napi_value) !u32 { var bytes: u32 = 0; var keys: c.napi_value = undefined; if (c.napi_get_property_names(env, object, &keys) != .napi_ok) { return helpers.throw(env, "Failed to get object keys"); } var length: u32 = undefined; if (c.napi_get_array_length(env, keys, &length) != .napi_ok) { return helpers.throw(env, "Failed to get object keys length"); } var i: u32 = 0; while (i < length) : (i += 1) { var key: c.napi_value = undefined; if (c.napi_get_element(env, keys, i, &key) != .napi_ok) { return helpers.throw(env, "Failed to get object key"); } bytes += encodingLength(env, key) catch 0; var value: c.napi_value = undefined; if (c.napi_get_property(env, object, key, &value) != .napi_ok) { return helpers.throw(env, "Failed to get object property"); } bytes += encodingLength(env, value) catch 0; } return bytes; } pub fn Boolnull(env: c.napi_env, value: c.napi_value) !u32 { if (helpers.isNull(env, value) catch false) return 0; return 1; } pub fn Any(env: c.napi_env, _type: u8, value: c.napi_value) u32 { const len = switch (_type) { constants.STRING => EncodingLengthers.String(env, value) catch 0, constants.BUFFER => EncodingLengthers.Buffer(env, value) catch 0, constants.INT => EncodingLengthers.Integer, constants.DOUBLE => EncodingLengthers.Double, constants.ARRAY => EncodingLengthers.Array(env, value) catch 0, constants.OBJECT => EncodingLengthers.Object(env, value) catch 0, constants.BOOLNULL => EncodingLengthers.Boolnull(env, value) catch 0, else => 0, }; return len; } }; pub fn encodingLength(env: c.napi_env, value: c.napi_value) !u32 { var _type = getType(env, value); const len = EncodingLengthers.Any(env, _type, value); return len + varint.encodingLength(len << constants.TAG_SIZE); } pub fn encode(env: c.napi_env, inputJS: c.napi_value, dest: []u8, start: u32) !u32 { var _type = getType(env, inputJS); if (_type >= constants.RESERVED) { helpers.throw(env, "unknown type") catch return 0; } var len = EncodingLengthers.Any(env, _type, inputJS); const bytes = varint.encode((len << constants.TAG_SIZE) | _type, dest, start); const encodedLen = Encoders.Any(env, _type, inputJS, dest, start + bytes); return encodedLen + bytes; }
src/encode.zig
const std = @import("std"); const bitjuggle = @import("bitjuggle"); const PrivilegeLevel = @import("types.zig").PrivilegeLevel; const IntegerRegister = @import("types.zig").IntegerRegister; const ExceptionCode = @import("types.zig").ExceptionCode; const ContextStatus = @import("types.zig").ContextStatus; const VectorMode = @import("types.zig").VectorMode; const AddressTranslationMode = @import("types.zig").AddressTranslationMode; pub const InstructionType = enum { // 32I /// load upper immediate LUI, /// add upper immediate to pc AUIPC, /// jump and link JAL, /// jumpa and link register JALR, /// branch equal BEQ, /// branch not equal BNE, /// branch less than - signed BLT, /// branch greater equal - signed BGE, /// branch less than - unsigned BLTU, /// branch greater equal - unsigned BGEU, /// load 8 bits - sign extended LB, /// load 16 bits - sign extended LH, /// load 32 bits - sign extended LW, /// load 8 bits - zero extended LBU, /// load 16 bits - zero extended LHU, /// store 8 bits SB, /// store 16 bits SH, /// store 32 bits SW, /// add immediate ADDI, /// set less than immediate - signed SLTI, /// set less than immediate - unsigned SLTIU, /// xor immediate XORI, /// or immediate ORI, /// and immediate ANDI, /// logical left shift SLLI, /// logical right shift SRLI, /// arithmetic right shift SRAI, /// add ADD, /// sub SUB, /// shift logical left SLL, /// set less than - signed SLT, /// set less than - unsigned SLTU, /// exclusive or XOR, /// shift right logical SRL, /// shift right arithmetic SRA, /// or OR, /// and AND, /// memory fence FENCE, /// environment call ECALL, /// environment break EBREAK, // 64I /// load 32 bits - zero extended LWU, /// load 64 bits LD, /// store 64 bits SD, /// add immediate - 32 bit ADDIW, /// logical left shift - 32 bit SLLIW, /// logical right shift - 32 bit SRLIW, /// arithmetic right shift - 32 bit SRAIW, /// add - 32 bit ADDW, /// sub - 32 bit SUBW, /// shift logical left - 32 bit SLLW, /// shift right logical - 32 bit SRLW, /// shift right arithmetic - 32 bit SRAW, // Zicsr /// atomic read/write csr CSRRW, /// atomic read and set bits in csr CSRRS, /// atomic read and clear bits in csr CSRRC, /// atomic read/write csr - immediate CSRRWI, // 32M /// multiply MUL, /// multiply - high bits MULH, /// multiply - high bits - signed/unsigned MULHSU, /// multiply - high bits - unsigned MULHU, /// divide DIV, /// divide - unsigned DIVU, /// remainder REM, /// remainder - unsigned REMU, // 64M /// multiply - 32 bit MULW, /// divide - 32 bit DIVW, /// divide - unsigned - 32 bit DIVUW, /// remainder - 32 bit REMW, /// remainder - unsigned - 32 bit REMUW, /// Privilege MRET, }; pub const Instruction = extern union { opcode: bitjuggle.Bitfield(u32, 0, 7), funct3: bitjuggle.Bitfield(u32, 12, 3), funct7: bitjuggle.Bitfield(u32, 25, 7), funct7_shift: bitjuggle.Bitfield(u32, 26, 6), _rd: bitjuggle.Bitfield(u32, 7, 5), _rs1: bitjuggle.Bitfield(u32, 15, 5), _rs2: bitjuggle.Bitfield(u32, 20, 5), csr: bitjuggle.Bitfield(u32, 20, 12), j_imm: JImm, b_imm: BImm, i_imm: IImm, u_imm: UImm, s_imm: SImm, i_specialization: ISpecialization, backing: u32, pub fn decode(instruction: Instruction, comptime unimplemented_is_fatal: bool) !InstructionType { const opcode = instruction.opcode.read(); const funct3 = instruction.funct3.read(); const funct7 = instruction.funct7.read(); return switch (opcode) { // STORE 0b0100011 => switch (funct3) { 0b000 => InstructionType.SB, 0b001 => InstructionType.SH, 0b010 => InstructionType.SW, 0b011 => InstructionType.SD, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented STORE {b:0>7}/{b:0>3}", .{ opcode, funct3 }); } return error.UnimplementedOpcode; }, }, // LOAD 0b0000011 => switch (funct3) { 0b000 => InstructionType.LB, 0b001 => InstructionType.LH, 0b010 => InstructionType.LW, 0b100 => InstructionType.LBU, 0b101 => InstructionType.LHU, 0b110 => InstructionType.LWU, 0b011 => InstructionType.LD, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented LOAD {b:0>7}/{b:0>3}", .{ opcode, funct3 }); } return error.UnimplementedOpcode; }, }, 0b0110111 => InstructionType.LUI, 0b0010111 => InstructionType.AUIPC, 0b1101111 => InstructionType.JAL, 0b1100111 => InstructionType.JALR, // BRANCH 0b1100011 => switch (funct3) { 0b000 => InstructionType.BEQ, 0b001 => InstructionType.BNE, 0b100 => InstructionType.BLT, 0b101 => InstructionType.BGE, 0b110 => InstructionType.BLTU, 0b111 => InstructionType.BGEU, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented BRANCH {b:0>7}/{b:0>3}", .{ opcode, funct3 }); } return error.UnimplementedOpcode; }, }, // OP-IMM 0b0010011 => switch (funct3) { 0b000 => InstructionType.ADDI, 0b010 => InstructionType.SLTI, 0b011 => InstructionType.SLTIU, 0b001 => if (instruction.funct7_shift.read() == 0) InstructionType.SLLI else { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP-IMM {b:0>7}/{b:0>3}/{b:0>6}", .{ opcode, funct3, instruction.funct7_shift.read() }); } return error.UnimplementedOpcode; }, 0b100 => InstructionType.XORI, 0b110 => InstructionType.ORI, 0b111 => InstructionType.ANDI, 0b101 => switch (instruction.funct7_shift.read()) { 0b000000 => InstructionType.SRLI, 0b010000 => InstructionType.SRAI, else => |funct7_shift| { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP-IMM {b:0>7}/{b:0>3}/{b:0>6}", .{ opcode, funct3, funct7_shift }); } return error.UnimplementedOpcode; }, }, }, // OP 0b0110011 => switch (funct3) { 0b000 => switch (funct7) { 0b0000000 => InstructionType.ADD, 0b0100000 => InstructionType.SUB, 0b0000001 => InstructionType.MUL, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, 0b110 => switch (funct7) { 0b0000000 => InstructionType.OR, 0b0000001 => InstructionType.REM, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, 0b111 => switch (funct7) { 0b0000000 => InstructionType.AND, 0b0000001 => InstructionType.REMU, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, 0b001 => switch (funct7) { 0b0000000 => InstructionType.SLL, 0b0000001 => InstructionType.MULH, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, 0b010 => switch (funct7) { 0b0000000 => InstructionType.SLT, 0b0000001 => InstructionType.MULHSU, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, 0b011 => switch (funct7) { 0b0000000 => InstructionType.SLTU, 0b0000001 => InstructionType.MULHU, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, 0b100 => switch (funct7) { 0b0000000 => InstructionType.XOR, 0b0000001 => InstructionType.DIV, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, 0b101 => switch (funct7) { 0b0000000 => InstructionType.SRL, 0b0100000 => InstructionType.SRA, 0b0000001 => InstructionType.DIVU, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, }, 0b001111 => InstructionType.FENCE, // SYSTEM 0b1110011 => switch (funct3) { 0b000 => switch (funct7) { 0b0000000 => InstructionType.ECALL, 0b0000001 => InstructionType.EBREAK, 0b0011000 => InstructionType.MRET, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented SYSTEM {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, 0b001 => InstructionType.CSRRW, 0b010 => InstructionType.CSRRS, 0b011 => InstructionType.CSRRC, 0b101 => InstructionType.CSRRWI, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented SYSTEM {b:0>7}/{b:0>3}", .{ opcode, funct3 }); } return error.UnimplementedOpcode; }, }, // OP-IMM-32 0b0011011 => switch (funct3) { 0b000 => InstructionType.ADDIW, 0b001 => switch (funct7) { 0b0000000 => InstructionType.SLLIW, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP-IMM-32 {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, 0b101 => switch (funct7) { 0b0000000 => InstructionType.SRLIW, 0b0100000 => InstructionType.SRAIW, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP-IMM-32 {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP-IMM-32 {b:0>7}/{b:0>3}", .{ opcode, funct3 }); } return error.UnimplementedOpcode; }, }, // OP-32 0b0111011 => switch (funct3) { 0b000 => switch (funct7) { 0b0000000 => InstructionType.ADDW, 0b0000001 => InstructionType.MULW, 0b0100000 => InstructionType.SUBW, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP-32 {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, 0b001 => switch (funct7) { 0b0000000 => InstructionType.SLLW, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP-32 {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, 0b100 => switch (funct7) { 0b0000001 => InstructionType.DIVW, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP-32 {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, 0b110 => switch (funct7) { 0b0000001 => InstructionType.REMW, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP-32 {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, 0b111 => switch (funct7) { 0b0000001 => InstructionType.REMUW, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP-32 {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, 0b101 => switch (funct7) { 0b0000000 => InstructionType.SRLW, 0b0000001 => InstructionType.DIVUW, 0b0100000 => InstructionType.SRAW, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP-32 {b:0>7}/{b:0>3}/{b:0>7}", .{ opcode, funct3, funct7 }); } return error.UnimplementedOpcode; }, }, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented OP-32 {b:0>7}/{b:0>3}", .{ opcode, funct3 }); } return error.UnimplementedOpcode; }, }, else => { if (unimplemented_is_fatal) { std.log.emerg("unimplemented opcode {b:0>7}", .{opcode}); } return error.UnimplementedOpcode; }, }; } pub fn rd(self: Instruction) IntegerRegister { return IntegerRegister.getIntegerRegister(self._rd.read()); } pub fn rs1(self: Instruction) IntegerRegister { return IntegerRegister.getIntegerRegister(self._rs1.read()); } pub fn rs2(self: Instruction) IntegerRegister { return IntegerRegister.getIntegerRegister(self._rs2.read()); } pub const ISpecialization = extern union { shmt4_0: bitjuggle.Bitfield(u32, 20, 5), shmt5: bitjuggle.Bitfield(u32, 25, 1), shift_type: bitjuggle.Bitfield(u32, 26, 6), backing: u32, pub fn smallShift(self: ISpecialization) u5 { return @truncate(u5, self.shmt4_0.read()); } pub fn fullShift(self: ISpecialization) u6 { return @truncate(u6, @as(u64, self.shmt5.read()) << 5 | self.shmt4_0.read()); } }; pub const SImm = extern union { imm4_0: bitjuggle.Bitfield(u32, 7, 5), imm11_5: bitjuggle.Bitfield(u32, 25, 7), backing: u32, pub fn read(self: SImm) i64 { const shift_amount = 20 + 32; return @bitCast( i64, (@as(u64, self.imm11_5.read()) << 5 | @as(u64, self.imm4_0.read())) << shift_amount, ) >> shift_amount; } }; pub const UImm = extern union { imm31_12: bitjuggle.Bitfield(u32, 12, 20), backing: u32, pub fn read(self: UImm) i64 { return @bitCast( i64, (@as(u64, self.imm31_12.read()) << 12) << 32, ) >> 32; } }; pub const IImm = extern union { imm11_0: bitjuggle.Bitfield(u32, 20, 12), backing: u32, pub fn read(self: IImm) i64 { const shift_amount = 20 + 32; return @bitCast(i64, @as(u64, self.imm11_0.read()) << shift_amount) >> shift_amount; } }; pub const JImm = extern union { imm19_12: bitjuggle.Bitfield(u32, 12, 8), imm11: bitjuggle.Bitfield(u32, 20, 1), imm10_1: bitjuggle.Bitfield(u32, 21, 10), imm20: bitjuggle.Bitfield(u32, 31, 1), backing: u32, pub fn read(self: JImm) i64 { const shift_amount = 11 + 32; return @bitCast( i64, @as(u64, self.imm20.read()) << 20 + shift_amount | @as(u64, self.imm19_12.read()) << 12 + shift_amount | @as(u64, self.imm11.read()) << 11 + shift_amount | @as(u64, self.imm10_1.read()) << 1 + shift_amount, ) >> shift_amount; } }; pub const BImm = extern union { imm11: bitjuggle.Bitfield(u32, 7, 1), imm4_1: bitjuggle.Bitfield(u32, 8, 4), imm10_5: bitjuggle.Bitfield(u32, 25, 6), imm12: bitjuggle.Bitfield(u32, 31, 1), backing: u32, pub fn read(self: BImm) i64 { const shift_amount = 19 + 32; return @bitCast( i64, @as(u64, self.imm12.read()) << 12 + shift_amount | @as(u64, self.imm11.read()) << 11 + shift_amount | @as(u64, self.imm10_5.read()) << 5 + shift_amount | @as(u64, self.imm4_1.read()) << 1 + shift_amount, ) >> shift_amount; } }; comptime { std.testing.refAllDecls(@This()); } }; comptime { std.testing.refAllDecls(@This()); }
lib/instruction.zig
const std = @import("std"); const Pkg = std.build.Pkg; const string = []const u8; pub const cache = ".zigmod/deps"; pub fn addAllTo(exe: *std.build.LibExeObjStep) void { @setEvalBranchQuota(1_000_000); for (packages) |pkg| { exe.addPackage(pkg.pkg.?); } inline for (std.meta.declarations(package_data)) |decl| { const pkg = @as(Package, @field(package_data, decl.name)); var llc = false; inline for (pkg.system_libs) |item| { exe.linkSystemLibrary(item); llc = true; } inline for (pkg.c_include_dirs) |item| { exe.addIncludeDir(@field(dirs, decl.name) ++ "/" ++ item); llc = true; } inline for (pkg.c_source_files) |item| { exe.addCSourceFile(@field(dirs, decl.name) ++ "/" ++ item, pkg.c_source_flags); llc = true; } if (llc) { exe.linkLibC(); } } } pub const Package = struct { directory: string, pkg: ?Pkg = null, c_include_dirs: []const string = &.{}, c_source_files: []const string = &.{}, c_source_flags: []const string = &.{}, system_libs: []const string = &.{}, }; const dirs = struct { pub const _root = ""; pub const _93jjp4rc0htn = cache ++ "/../.."; pub const _9jt7n3xad653 = cache ++ "/git/github.com/Hejsil/mecha"; }; pub const package_data = struct { pub const _93jjp4rc0htn = Package{ .directory = dirs._93jjp4rc0htn, .pkg = Pkg{ .name = "lunez", .path = .{ .path = dirs._93jjp4rc0htn ++ "/src/main.zig" }, .dependencies = null }, }; pub const _9jt7n3xad653 = Package{ .directory = dirs._9jt7n3xad653, .pkg = Pkg{ .name = "mecha", .path = .{ .path = dirs._9jt7n3xad653 ++ "/mecha.zig" }, .dependencies = null }, }; pub const _root = Package{ .directory = dirs._root, }; }; pub const packages = &[_]Package{ package_data._93jjp4rc0htn, package_data._9jt7n3xad653, }; pub const pkgs = struct { pub const lunez = package_data._93jjp4rc0htn; pub const mecha = package_data._9jt7n3xad653; }; pub const imports = struct { pub const lunez = @import(".zigmod/deps/../../src/main.zig"); pub const mecha = @import(".zigmod/deps/git/github.com/Hejsil/mecha/mecha.zig"); };
deps.zig
const std = @import("std"); const ast = std.zig.ast; const util = @import("utils.zig"); var tree: ast.Tree = undefined; const Md = struct { fields: std.ArrayList(AnalysedDecl), types: std.ArrayList(AnalysedDecl), funcs: std.ArrayList(AnalysedDecl), values: std.ArrayList(AnalysedDecl), pub fn init(ally: *std.mem.Allocator) !@This() { return @This(){ .fields = std.ArrayList(AnalysedDecl).init(ally), .types = std.ArrayList(AnalysedDecl).init(ally), .funcs = std.ArrayList(AnalysedDecl).init(ally), .values = std.ArrayList(AnalysedDecl).init(ally), }; } pub fn deinit(self: *const @This(), ally: *std.mem.Allocator) void { inline for (comptime std.meta.fieldNames(@This())) |n| { for (@field(self, n).items) |*anal| { anal.deinit(ally); } @field(self, n).deinit(); } } pub fn jsonStringify(self: @This(), options: anytype, writer: anytype) !void { try writer.writeByte('{'); try writer.writeAll("\"fields\":"); try std.json.stringify(self.fields.items, .{}, writer); try writer.writeByte(','); try writer.writeAll("\"types\":"); try std.json.stringify(self.types.items, .{}, writer); try writer.writeByte(','); try writer.writeAll("\"funcs\":"); try std.json.stringify(self.funcs.items, .{}, writer); try writer.writeByte(','); try writer.writeAll("\"values\":"); try std.json.stringify(self.values.items, .{}, writer); try writer.writeByte('}'); } }; const AnalysedDecl = struct { /// The doc comment of the decl /// Owned by this decl dc: ?[]const u8, /// Should be owned by this decl pl: []const u8, sub_cont_ty: ?[]const u8 = null, md: ?Md, // TODO: make a range src: usize, fn deinit(self: *const @This(), ally: *std.mem.Allocator) void { if (self.md) |*m| m.deinit(ally); ally.free(self.pl); if (self.dc) |d| ally.free(d); if (self.sub_cont_ty) |s| ally.free(s); } pub fn jsonStringify(self: AnalysedDecl, options: anytype, writer: anytype) !void { try writer.writeAll("{"); if (self.dc) |d| { try writer.writeAll("\"doc_comment\":"); try std.json.stringify(d, options, writer); try writer.writeAll(","); } try writer.writeAll("\"pl\":"); try std.json.stringify(self.pl, options, writer); try writer.writeAll(","); if (self.sub_cont_ty) |s| { try writer.writeAll("\"sub_container_type\":"); try std.json.stringify(s, options, writer); try writer.writeAll(","); } try writer.writeAll("\"src\":"); try std.json.stringify(self.src, options, writer); try writer.writeAll(","); try writer.writeAll("\"more_decls\":"); try std.json.stringify(self.md, options, writer); try writer.writeAll("}"); } pub fn htmlStringify(self: AnalysedDecl, writer: anytype) std.fs.File.WriteError!void { try writer.writeAll("<div class=\"anal-decl\">"); // doc comment if (self.dc) |d| { try writer.writeAll("<b>"); try util.writeEscaped(writer, d); try writer.writeByte('\n'); try writer.writeAll("</b>"); } // payload if (opts.docs_url) |url| { // TODO src loc try writer.print("<a href=\"{s}{s}#L{d}\">src</a>", .{ opts.docs_url, cur_file, self.src + 1 }); } try util.highlightZigCode(self.pl, writer, true); if (self.md != null) { if (self.md.?.fields.items.len > 0) { try writer.writeAll("<details><summary>fields:</summary>"); try writer.writeAll("<div class=\"md-fields more-decls\">"); for (self.md.?.fields.items) |decl| { try decl.htmlStringify(writer); } try writer.writeAll("</div>"); try writer.writeAll("</details>"); } if (self.md.?.types.items.len > 0) { try writer.writeAll("<details><summary>types:</summary>"); try writer.writeAll("<div class=\"md-types more-decls\">"); for (self.md.?.types.items) |decl| { try decl.htmlStringify(writer); } try writer.writeAll("</div>"); try writer.writeAll("</details>"); } if (self.md.?.funcs.items.len > 0) { try writer.writeAll("<details><summary>funcs</summary>"); try writer.writeAll("<div class=\"md-funcs more-decls\">"); for (self.md.?.funcs.items) |decl| { try decl.htmlStringify(writer); } try writer.writeAll("</div>"); try writer.writeAll("</details>"); } if (self.md.?.values.items.len > 0) { try writer.writeAll("<details><summary>values:</summary>"); try writer.writeAll("<div class=\"md-vals more-decls\">"); for (self.md.?.values.items) |decl| { try decl.htmlStringify(writer); } try writer.writeAll("</div>"); try writer.writeAll("</details>"); } } try writer.writeAll("</div>"); } }; fn fatal(s: []const u8) noreturn { std.log.emerg("{s}\n", .{s}); std.process.exit(1); } fn fatalArgs(comptime s: []const u8, args: anytype) noreturn { std.log.emerg(s, args); std.process.exit(1); } const Args = struct { dirname: []const u8, docs_url: ?[]const u8 = null, type: enum { json, html } = .html, output_dir: []const u8 = "docs", }; var opts: Args = undefined; var cur_file: []const u8 = undefined; fn removeTrailingSlash(n: [:0]u8) []u8 { if (std.mem.endsWith(u8, n, "/")) return n[0 .. n.len - 1]; return n; } pub fn main() (error{ OutOfMemory, Overflow, InvalidCmdLine, TimerUnsupported } || std.os.UnexpectedError || std.os.WriteError)!void { var general_pa = std.heap.GeneralPurposeAllocator(.{ .stack_trace_frames = 8 }){}; defer _ = general_pa.deinit(); const ally = &general_pa.allocator; const args = try std.process.argsAlloc(ally); defer ally.free(args); if (args.len < 2) fatal("the first argument needs to be the directory to run zigdoc on"); opts = .{ .dirname = removeTrailingSlash(args[1]) }; if (args.len >= 3) { var i: usize = 2; while (i < args.len) : (i += 1) { const arg = args[i]; if (std.mem.eql(u8, arg, "-json")) opts.type = .json else if (std.mem.eql(u8, arg, "-html")) opts.type = .html else if (std.mem.eql(u8, arg, "-o")) { if (i == args.len) fatal("need an argument after -o"); opts.output_dir = args[i + 1]; i += 1; } else if (std.mem.eql(u8, arg, "-url")) { if (i == args.len) fatal("need an argument after -url"); var durl: [:0]u8 = args[i + 1]; opts.docs_url = removeTrailingSlash(durl); i += 1; } else if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) { fatal( \\zigdoc help: \\Example: `docgen ~/dev/zig/lib/std/ -url https://github.com/ziglang/zig/blob/master/lib/std` \\Outputs do `docs` folder by default. \\docgen FOLDER_LOCATION [ -json -o [output folder] -url [source url] -h ] \\-json for json output \\-o for output folder \\-url for source url \\-h for this help menu ); } } } var walker = std.fs.walkPath(ally, opts.dirname) catch |e| fatalArgs("could not read dir: {s}: {}", .{ opts.dirname, e }); defer walker.deinit(); var file_to_anal_map = std.StringHashMap(Md).init(ally); defer { var iter = file_to_anal_map.iterator(); while (iter.next()) |entry| { entry.value_ptr.deinit(ally); ally.free(entry.key_ptr.*); } file_to_anal_map.deinit(); } var progress: std.Progress = .{}; var main_progress_node = try progress.start("", 0); main_progress_node.activate(); defer main_progress_node.end(); var analyse_node = main_progress_node.start("Analysis", 0); analyse_node.activate(); var i: usize = 0; while (walker.next() catch |e| fatalArgs("could not read next directory walker item: {}", .{e})) |entry| { if (std.mem.endsWith(u8, entry.path, ".zig")) { const strings = compareStrings(entry.path, opts.dirname); const str = try ally.dupe(u8, strings); if (!(file_to_anal_map.contains(strings))) { i += 1; var node = analyse_node.start(strings, i + 1); node.activate(); // screw thread safety! node.unprotected_completed_items = i; defer node.end(); const list = try getAnalFromFile(ally, entry.path); const pogr = try file_to_anal_map.put(str, list); } } } analyse_node.end(); var output_dir = std.fs.cwd().makeOpenPath(opts.output_dir, .{}) catch |e| switch (e) { error.PathAlreadyExists => std.fs.cwd().openDir(opts.output_dir, .{}) catch |er| fatalArgs("could not open docs folder: {}", .{er}), else => |er| fatalArgs("could not make a \"docs\" output dir: {}", .{er}), }; defer output_dir.close(); var iter = file_to_anal_map.iterator(); if (opts.type == .html) { while (iter.next()) |entry| { cur_file = entry.key_ptr.*; const dname = std.fs.path.dirname(entry.key_ptr.*).?[1..]; // remove the first / var output_path = if (!std.mem.eql(u8, dname, "")) (output_dir.makeOpenPath(dname, .{}) catch |e| fatalArgs("could not make dir {s}: {}", .{ dname, e })) else (output_dir.openDir(".", .{}) catch |e| fatalArgs("could not open dir '.': {}", .{e})); defer output_path.close(); const name_to_open = std.fs.path.basename(entry.key_ptr.*); const catted = try std.mem.concat(ally, u8, &.{ name_to_open, ".html" }); defer ally.free(catted); const output_file = output_path.createFile(catted, .{}) catch |e| fatalArgs("could not create file {s}: {}", .{ catted, e }); defer output_file.close(); const w = output_file.writer(); const anal_list = entry.value_ptr; try w.print(our_css, .{ .our_background = background_color }); try w.writeAll(code_css); try w.writeAll("<html>"); try w.print("<a href=\"{s}/{s}\"><h1>{s}</h1></a>", .{ opts.docs_url, cur_file, cur_file }); inline for (comptime std.meta.fieldNames(Md)) |n| { if (@field(anal_list, n).items.len != 0) try w.print("<h2 style=\"color: orange;\">{s}:</h2>", .{n}); try w.writeAll("<div class=\"more-decls\">"); for (@field(anal_list, n).items) |decl| { try decl.htmlStringify(w); } try w.writeAll("</div>"); } try w.writeAll("</html>"); } } else { while (iter.next()) |entry| { const dname = std.fs.path.dirname(entry.key_ptr.*).?[1..]; // remove the first / var output_path = if (!std.mem.eql(u8, dname, "")) (output_dir.makeOpenPath(dname, .{}) catch |e| fatalArgs("could not make dir {s}: {}", .{ dname, e })) else (output_dir.openDir(".", .{}) catch |e| fatalArgs("could not open dir '.': {}", .{e})); defer output_path.close(); const name_to_open = std.fs.path.basename(entry.key_ptr.*); const catted = try std.mem.concat(ally, u8, &.{ name_to_open, ".json" }); defer ally.free(catted); const output_file = output_path.createFile(catted, .{}) catch |e| fatalArgs("could not create file {s}: {}", .{ catted, e }); defer output_file.close(); const w = output_file.writer(); const anal_list = entry.value_ptr; try w.writeAll("["); try std.json.stringify(anal_list, .{}, w); try w.writeAll("]"); } } } fn getAnalFromFile( ally: *std.mem.Allocator, fname: []const u8, ) error{OutOfMemory}!Md { const zig_code = std.fs.cwd().readFileAlloc(ally, fname, 2 * 1024 * 1024 * 1024) catch fatal("could not read file provided"); defer ally.free(zig_code); tree = std.zig.parse(ally, zig_code) catch |e| { std.log.emerg("could not parse zig file {s}: {}", .{ fname, e }); fatal("parsing failed"); }; defer tree.deinit(ally); const decls = tree.rootDecls(); const anal_list = try recAnalListOfDecls(ally, decls); return anal_list; } fn recAnalListOfDecls( ally: *std.mem.Allocator, list_d: []const ast.Node.Index, ) error{OutOfMemory}!Md { const node_tags = tree.nodes.items(.tag); const node_datas = tree.nodes.items(.data); const main_tokens = tree.nodes.items(.main_token); const token_starts = tree.tokens.items(.start); var list = try Md.init(ally); for (list_d) |member| if (util.isNodePublic(tree, member)) { const tag = node_tags[member]; // we know it has to be a vardecl now const decl_addr = member; var doc: ?[]const u8 = null; if (try util.getDocComments(ally, tree, decl_addr)) |dc| { doc = dc; } if (tag == .container_field or tag == .container_field_align or tag == .container_field_init) { const ftoken = tree.firstToken(member); const ltoken = tree.lastToken(member); const start = token_starts[ftoken]; const end = token_starts[ltoken + 1]; try list.fields.append(.{ .pl = try ally.dupe(u8, tree.source[start..end]), .dc = doc, .md = null, .src = std.zig.findLineColumn(tree.source, start).line, }); continue; } else if (tag == .fn_decl) { var d = try doFunction(ally, decl_addr); d.dc = doc; try list.funcs.append(d); continue; } else if (tag == .global_var_decl or tag == .local_var_decl or tag == .simple_var_decl or tag == .aligned_var_decl) { // handle if it is a vardecl const vardecl = util.varDecl(tree, decl_addr).?; const name_loc = vardecl.ast.mut_token + 1; const name = tree.tokenSlice(name_loc); const init = node_datas[decl_addr].rhs; const rhst = node_tags[init]; // we find if the var is a container, we dont wanna display the full thing if it is // then we recurse over it var buf: [2]ast.Node.Index = undefined; var cd = getContainer(node_datas[decl_addr].rhs, &buf); if (cd) |container_decl| { const offset = if (container_decl.ast.enum_token != null) if (rhst == .tagged_union_enum_tag or rhst == .tagged_union_enum_tag_trailing) @as(u32, 7) else @as(u32, 4) else @as(u32, 1); const more = try recAnalListOfDecls(ally, container_decl.ast.members); try list.types.append(.{ .pl = try ally.dupe(u8, tree.source[token_starts[tree.firstToken(member)]..token_starts[ main_tokens[init] + offset ]]), .dc = doc, .md = more, .src = std.zig.findLineColumn(tree.source, token_starts[tree.firstToken(decl_addr)]).line, }); continue; } else { const sig = util.getVariableSignature(tree, vardecl); var ad: AnalysedDecl = .{ .pl = try ally.dupe(u8, sig), .dc = doc, .md = null, .src = std.zig.findLineColumn(tree.source, token_starts[tree.firstToken(decl_addr)]).line, }; try list.values.append(ad); continue; } } else if (tag == .fn_proto or tag == .fn_proto_multi or tag == .fn_proto_one or tag == .fn_proto_simple) { var params: [1]ast.Node.Index = undefined; const fn_proto = util.fnProto( tree, member, &params, ).?; var sig: []const u8 = undefined; { var start = util.tokenLocation(tree, fn_proto.extern_export_inline_token.?); // return type can be 0 when user wrote incorrect fn signature // to ensure we don't break, just end the signature at end of fn token if (fn_proto.ast.return_type == 0) sig = tree.source[start.start..start.end]; const end = util.tokenLocation(tree, tree.lastToken(fn_proto.ast.return_type)).end; sig = tree.source[start.start..end]; } sig = try ally.dupe(u8, sig); var ad: AnalysedDecl = .{ .pl = sig, .dc = doc, .md = null, .src = std.zig.findLineColumn(tree.source, token_starts[tree.firstToken(decl_addr)]).line, }; try list.types.append(ad); continue; } else { continue; } unreachable; }; return list; } fn doFunction(ally: *std.mem.Allocator, decl_addr: ast.Node.Index) !AnalysedDecl { const node_tags = tree.nodes.items(.tag); const node_datas = tree.nodes.items(.data); const main_tokens = tree.nodes.items(.main_token); const token_starts = tree.tokens.items(.start); const full_source = tree.source[token_starts[tree.firstToken(decl_addr)] .. token_starts[tree.lastToken(decl_addr)] + 1]; // TODO configure max if (nlGtMax(full_source, 5)) { // handle if it is a function and the number of lines is greater than max const proto = node_datas[decl_addr].lhs; const block = node_datas[decl_addr].rhs; var params: [1]ast.Node.Index = undefined; const fn_proto = util.fnProto( tree, proto, &params, ).?; const sig = util.getFunctionSignature(tree, fn_proto); var sub_cont_ty: ?[]const u8 = null; const md = if (util.isTypeFunction(tree, fn_proto)) blk: { const ret = util.findReturnStatement(tree, fn_proto, block) orelse break :blk null; if (node_datas[ret].lhs == 0) break :blk null; var buf: [2]ast.Node.Index = undefined; const container = getContainer(node_datas[ret].lhs, &buf) orelse break :blk null; const offset = if (container.ast.enum_token != null) if (node_tags[node_datas[ret].lhs] == .tagged_union_enum_tag or node_tags[node_datas[ret].lhs] == .tagged_union_enum_tag_trailing) @as(u32, 7) else @as(u32, 4) else @as(u32, 1); sub_cont_ty = tree.source[token_starts[tree.firstToken(node_datas[ret].lhs)]..token_starts[ main_tokens[node_datas[ret].lhs] + offset ]]; break :blk try recAnalListOfDecls(ally, container.ast.members); } else null; return AnalysedDecl{ .pl = try removeNewLinesFromRest(ally, sig), // to be filled in later .dc = null, .md = md, .sub_cont_ty = if (sub_cont_ty) |sct| try ally.dupe(u8, sct) else null, .src = std.zig.findLineColumn(tree.source, token_starts[tree.firstToken(decl_addr)]).line, }; } else { return AnalysedDecl{ .pl = try removeNewLinesFromRest(ally, full_source), // filled in later .dc = null, .md = null, .src = std.zig.findLineColumn(tree.source, token_starts[tree.firstToken(decl_addr)]).line, }; } } fn getContainer(decl_addr: ast.Node.Index, buf: *[2]ast.Node.Index) ?ast.full.ContainerDecl { const node_tags = tree.nodes.items(.tag); const node_datas = tree.nodes.items(.data); const main_tokens = tree.nodes.items(.main_token); const token_starts = tree.tokens.items(.start); const rhst = node_tags[decl_addr]; // we find if the var is a container, we dont wanna display the full thing if it is // then we recurse over it return if (rhst == .container_decl or rhst == .container_decl_trailing) tree.containerDecl(decl_addr) else if (rhst == .container_decl_arg or rhst == .container_decl_arg_trailing) tree.containerDeclArg(decl_addr) else if (rhst == .container_decl_two or rhst == .container_decl_two_trailing) blk: { break :blk tree.containerDeclTwo(buf, decl_addr); } else if (rhst == .tagged_union or rhst == .tagged_union_trailing) tree.taggedUnion(decl_addr) else if (rhst == .tagged_union_two or rhst == .tagged_union_two_trailing) blk: { break :blk tree.taggedUnionTwo(buf, decl_addr); } else if (rhst == .tagged_union_enum_tag or rhst == .tagged_union_enum_tag_trailing) tree.taggedUnionEnumTag(decl_addr) else null; } fn nlGtMax(str: []const u8, max: usize) bool { var n: usize = 0; for (str) |c| { if (c == '\n') n += 1; if (n > max) return true; } return false; } /// returns an owned slice /// O(2n) /// ``` /// pub fn x() { /// a(); /// } /// ``` /// -> /// ``` /// pub fn x() { /// a(); /// } /// ``` fn removeNewLinesFromRest(ally: *std.mem.Allocator, s: []const u8) ![]const u8 { var numspaces: u32 = 0; var pure = false; var on_first_line = true; for (s) |c, i| { if (on_first_line) { if (c == '\n') on_first_line = false else continue; } if (c == ' ') { if (pure) numspaces += 1; } else if (c == '\n') { if (!(i == s.len - 1)) numspaces = 0; pure = true; } else pure = false; } on_first_line = true; pure = true; const num_on_last = numspaces; var z = std.ArrayList(u8).init(ally); for (s) |c| { if (on_first_line) { if (c == '\n') { pure = false; numspaces = 0; on_first_line = false; } try z.append(c); continue; } if (c == '\n') { numspaces = 0; try z.append('\n'); } else numspaces += 1; if (!(numspaces <= num_on_last)) try z.append(c); } return z.toOwnedSlice(); } /// returns the difference of two strings reversed /// asserts b is in a fn compareStrings(a: []const u8, b: []const u8) []const u8 { const diff = a.len - b.len; return a[b.len..]; } const background_color = "#F7A41D77"; const our_css = \\<style type="text/css" > \\.more-decls {{ \\ padding-left: 50px; \\}} \\.anal-decl {{ \\ background-color: {[our_background]s}; \\}} \\code {{ \\ background-color: {[our_background]s}; \\}} \\</style> ; const code_css = \\<style type="text/css" > \\pre > code { \\ display: block; \\ overflow: auto; \\ padding: 0.5em; \\ color: black; \\} \\ \\details { \\ margin-bottom: 0.5em; \\ -webkit-touch-callout: none; /* iOS Safari */ \\ -webkit-user-select: none; /* Safari */ \\ -khtml-user-select: none; /* Konqueror HTML */ \\ -moz-user-select: none; /* Old versions of Firefox */ \\ -ms-user-select: none; /* Internet Explorer/Edge */ \\ user-select: none; /* Non-prefixed version, currently \\ supported by Chrome, Edge, Opera and Firefox */ \\} \\ \\.tok { \\ color: #333; \\ font-style: normal; \\} \\ \\.code { \\ font-family: monospace; \\ font-size: 0.8em; \\} \\ \\.tok-kw { \\ color: #333; \\ font-weight: bold; \\} \\ \\.tok-str { \\ color: #d14; \\} \\ \\.tok-builtin { \\ color: #0086b3; \\} \\ \\code.zig { \\ color: #777; \\ font-style: italic; \\} \\ \\.tok-fn { \\ color: #900; \\ font-weight: bold; \\} \\ \\.tok-null { \\ color: #008080; \\} \\ \\.tok-number { \\ color: #008080; \\} \\ \\.tok-type { \\ color: #458; \\ font-weight: bold; \\} \\</style> ;
src/main.zig
const std = @import("std"); const stdx = @import("stdx"); const Vec2 = stdx.math.Vec2; const ui = @import("ui.zig"); const Layout = ui.Layout; const RenderContext = ui.RenderContext; const FrameId = ui.FrameId; /// Id can be an enum literal that is given a unique id at comptime. pub const WidgetUserId = usize; pub const WidgetTypeId = usize; pub const WidgetKey = union(enum) { Idx: usize, EnumLiteral: usize, }; /// If the user does not have the access to a widget's type, NodeRef still allows capturing the creating Node. pub const NodeRef = struct { node: *Node = undefined, binded: bool = false, pub fn init(node: *Node) NodeRef { return .{ .node = node, .binded = true, }; } }; /// Contains the widget and it's corresponding node in the layout tree. /// Although the widget can be obtained from the node, this is more type safe and can provide convenience functions. pub fn WidgetRef(comptime Widget: type) type { return struct { const Self = @This(); /// Use widget's *anyopaque pointer in node to avoid "depends on itself" when WidgetRef(Widget) is declared in Widget. node: *Node = undefined, binded: bool = false, pub fn init(node: *Node) Self { return .{ .node = node, .binded = true, }; } pub inline fn getWidget(self: Self) *Widget { return stdx.mem.ptrCastAlign(*Widget, self.node.widget); } pub inline fn getAbsLayout(self: *Self) Layout { return .{ .x = self.node.abs_pos.x, .y = self.node.abs_pos.y, .width = self.node.layout.width, .height = self.node.layout.height, }; } pub inline fn getHeight(self: Self) f32 { return self.node.layout.height; } pub inline fn getWidth(self: Self) f32 { return self.node.layout.width; } }; } const NullId = stdx.ds.CompactNull(u32); /// A Node contains the metadata for a widget instance and is initially created from a declared Frame. pub const Node = struct { const Self = @This(); /// The vtable is also used to id the widget instance. vtable: *const WidgetVTable, key: WidgetKey, // TODO: Document why a parent reference is useful. parent: ?*Node, /// Pointer to the widget instance. widget: *anyopaque, /// Is only defined if has_widget_id = true. id: WidgetUserId, // TODO: This was added to Node for convenience. Since binding is a one time operation, it shouldn't have to carry over from a Frame. /// Binds the widget to a WidgetRef upon initialization. bind: ?*anyopaque, /// The final layout is set by it's parent during the layout phase. /// x, y are relative to the parent's position. layout: Layout, /// Absolute position of the node is computed when traversing the render tree. abs_pos: Vec2, // TODO: Use a shared buffer. /// The child nodes. children: std.ArrayList(*Node), /// Unmanaged slice of child event ordering. Only defined if has_child_event_ordering = true. child_event_ordering: []const *Node, // TODO: It might be better to keep things simple and only allow one callback per event type per node. If the widget wants more they can multiplex in their implementation. /// Singly linked lists of events attached to this node. Can be NullId. mouse_down_list: u32, mouse_up_list: u32, mouse_scroll_list: u32, key_up_list: u32, key_down_list: u32, // TODO: Should use a shared hashmap from Module. key_to_child: std.AutoHashMap(WidgetKey, *Node), has_child_event_ordering: bool, has_widget_id: bool, pub fn init(self: *Self, alloc: std.mem.Allocator, vtable: *const WidgetVTable, parent: ?*Node, key: WidgetKey, widget: *anyopaque) void { self.* = .{ .vtable = vtable, .key = key, .parent = parent, .widget = widget, .bind = null, .children = std.ArrayList(*Node).init(alloc), .child_event_ordering = undefined, .layout = undefined, .abs_pos = undefined, .key_to_child = std.AutoHashMap(WidgetKey, *Node).init(alloc), .mouse_down_list = NullId, .mouse_up_list = NullId, .mouse_scroll_list = NullId, .key_up_list = NullId, .key_down_list = NullId, .has_child_event_ordering = false, .id = undefined, .has_widget_id = false, }; } /// Caller still owns ordering afterwards. pub fn setChildEventOrdering(self: *Self, ordering: []const *Node) void { self.child_event_ordering = ordering; self.has_child_event_ordering = true; } pub fn getWidget(self: Self, comptime Widget: type) *Widget { return stdx.mem.ptrCastAlign(*Widget, self.widget); } pub fn deinit(self: *Self) void { self.children.deinit(); self.key_to_child.deinit(); } /// Returns the number of immediate children. pub fn numChildren(self: *Self) usize { return self.children.items.len; } /// Returns the total number of children recursively. pub fn numChildrenR(self: *Self) usize { var total = self.children.items.len; for (self.children.items) |child| { total += child.numChildrenR(); } return total; } pub fn getChild(self: *Self, idx: usize) *Node { return self.children.items[idx]; } /// Compute the absolute position of the node by adding up it's ancestor positions. /// This is only accurate if the layout has been computed for this node and upwards. pub fn computeCurrentAbsPos(self: Self) Vec2 { if (self.parent) |parent| { return parent.computeCurrentAbsPos().add(Vec2.init(self.layout.x, self.layout.y)); } else { return Vec2.init(self.layout.x, self.layout.y); } } pub fn getAbsLayout(self: Self) Layout { return .{ .x = self.abs_pos.x, .y = self.abs_pos.y, .width = self.layout.width, .height = self.layout.height, }; } }; /// VTable for a Widget. pub const WidgetVTable = struct { /// Creates a new Widget on the heap and returns the pointer. create: fn (alloc: std.mem.Allocator, node: *Node, init_ctx: *anyopaque, props_ptr: ?[*]const u8) *anyopaque, /// Runs post init on an existing Widget. postInit: fn (widget_ptr: *anyopaque, init_ctx: *anyopaque) void, /// Updates the props on an existing Widget. updateProps: fn (widget_ptr: *anyopaque, props_ptr: [*]const u8) void, /// Runs post update. postUpdate: fn (node: *Node) void, /// Generates the frame for an existing Widget. build: fn (widget_ptr: *anyopaque, build_ctx: *anyopaque) FrameId, /// Renders an existing Widget. render: fn (node: *Node, render_ctx: *RenderContext, parent_abs_x: f32, parent_abs_y: f32) void, /// Computes the layout size for an existing Widget and sets the relative positioning for it's child nodes. layout: fn (widget_ptr: *anyopaque, layout_ctx: *anyopaque) LayoutSize, /// Destroys an existing Widget. destroy: fn (node: *Node, alloc: std.mem.Allocator) void, name: []const u8, has_post_update: bool, }; pub const LayoutSize = struct { const Self = @This(); width: f32, height: f32, pub fn init(width: f32, height: f32) @This() { return .{ .width = width, .height = height, }; } pub fn cropTo(self: *Self, max_size: LayoutSize) void { if (self.width > max_size.width) { self.width = max_size.width; } if (self.height > max_size.height) { self.height = max_size.height; } } pub fn cropToWidth(self: *Self, width: f32) void { if (self.width > width) { self.width = width; } } pub fn cropToHeight(self: *Self, height: f32) void { if (self.height > height) { self.height = height; } } pub fn toIncSize(self: Self, inc_width: f32, inc_height: f32) LayoutSize { return .{ .width = self.width + inc_width, .height = self.height + inc_height, }; } };
ui/src/widget.zig
const std = @import("std"); const ir = @import("ir.zig"); const trace = @import("tracy.zig").trace; /// Perform Liveness Analysis over the `Body`. Each `Inst` will have its `deaths` field populated. pub fn analyze( /// Used for temporary storage during the analysis. gpa: *std.mem.Allocator, /// Used to tack on extra allocations in the same lifetime as the existing instructions. arena: *std.mem.Allocator, body: ir.Body, ) error{OutOfMemory}!void { const tracy = trace(@src()); defer tracy.end(); var table = std.AutoHashMap(*ir.Inst, void).init(gpa); defer table.deinit(); try table.ensureCapacity(@intCast(u32, body.instructions.len)); try analyzeWithTable(arena, &table, null, body); } fn analyzeWithTable( arena: *std.mem.Allocator, table: *std.AutoHashMap(*ir.Inst, void), new_set: ?*std.AutoHashMap(*ir.Inst, void), body: ir.Body, ) error{OutOfMemory}!void { var i: usize = body.instructions.len; if (new_set) |ns| { // We are only interested in doing this for instructions which are born // before a conditional branch, so after obtaining the new set for // each branch we prune the instructions which were born within. while (i != 0) { i -= 1; const base = body.instructions[i]; _ = ns.remove(base); try analyzeInst(arena, table, new_set, base); } } else { while (i != 0) { i -= 1; const base = body.instructions[i]; try analyzeInst(arena, table, new_set, base); } } } fn analyzeInst( arena: *std.mem.Allocator, table: *std.AutoHashMap(*ir.Inst, void), new_set: ?*std.AutoHashMap(*ir.Inst, void), base: *ir.Inst, ) error{OutOfMemory}!void { if (table.contains(base)) { base.deaths = 0; } else { // No tombstone for this instruction means it is never referenced, // and its birth marks its own death. Very metal 🤘 base.deaths = 1 << ir.Inst.unreferenced_bit_index; } switch (base.tag) { .constant => return, .block => { const inst = base.castTag(.block).?; try analyzeWithTable(arena, table, new_set, inst.body); // We let this continue so that it can possibly mark the block as // unreferenced below. }, .loop => { const inst = base.castTag(.loop).?; try analyzeWithTable(arena, table, new_set, inst.body); return; // Loop has no operands and it is always unreferenced. }, .condbr => { const inst = base.castTag(.condbr).?; // Each death that occurs inside one branch, but not the other, needs // to be added as a death immediately upon entering the other branch. var then_table = std.AutoHashMap(*ir.Inst, void).init(table.allocator); defer then_table.deinit(); try analyzeWithTable(arena, table, &then_table, inst.then_body); // Reset the table back to its state from before the branch. { var it = then_table.iterator(); while (it.next()) |entry| { table.removeAssertDiscard(entry.key); } } var else_table = std.AutoHashMap(*ir.Inst, void).init(table.allocator); defer else_table.deinit(); try analyzeWithTable(arena, table, &else_table, inst.else_body); var then_entry_deaths = std.ArrayList(*ir.Inst).init(table.allocator); defer then_entry_deaths.deinit(); var else_entry_deaths = std.ArrayList(*ir.Inst).init(table.allocator); defer else_entry_deaths.deinit(); { var it = else_table.iterator(); while (it.next()) |entry| { const else_death = entry.key; if (!then_table.contains(else_death)) { try then_entry_deaths.append(else_death); } } } // This loop is the same, except it's for the then branch, and it additionally // has to put its items back into the table to undo the reset. { var it = then_table.iterator(); while (it.next()) |entry| { const then_death = entry.key; if (!else_table.contains(then_death)) { try else_entry_deaths.append(then_death); } _ = try table.put(then_death, {}); } } // Now we have to correctly populate new_set. if (new_set) |ns| { try ns.ensureCapacity(@intCast(u32, ns.count() + then_table.count() + else_table.count())); var it = then_table.iterator(); while (it.next()) |entry| { _ = ns.putAssumeCapacity(entry.key, {}); } it = else_table.iterator(); while (it.next()) |entry| { _ = ns.putAssumeCapacity(entry.key, {}); } } inst.then_death_count = std.math.cast(@TypeOf(inst.then_death_count), then_entry_deaths.items.len) catch return error.OutOfMemory; inst.else_death_count = std.math.cast(@TypeOf(inst.else_death_count), else_entry_deaths.items.len) catch return error.OutOfMemory; const allocated_slice = try arena.alloc(*ir.Inst, then_entry_deaths.items.len + else_entry_deaths.items.len); inst.deaths = allocated_slice.ptr; std.mem.copy(*ir.Inst, inst.thenDeaths(), then_entry_deaths.items); std.mem.copy(*ir.Inst, inst.elseDeaths(), else_entry_deaths.items); // Continue on with the instruction analysis. The following code will find the condition // instruction, and the deaths flag for the CondBr instruction will indicate whether the // condition's lifetime ends immediately before entering any branch. }, .switchbr => { const inst = base.castTag(.switchbr).?; const Table = std.AutoHashMap(*ir.Inst, void); const case_tables = try table.allocator.alloc(Table, inst.cases.len + 1); // +1 for else defer table.allocator.free(case_tables); std.mem.set(Table, case_tables, Table.init(table.allocator)); defer for (case_tables) |*ct| ct.deinit(); for (inst.cases) |case, i| { try analyzeWithTable(arena, table, &case_tables[i], case.body); // Reset the table back to its state from before the case. var it = case_tables[i].iterator(); while (it.next()) |entry| { table.removeAssertDiscard(entry.key); } } { // else try analyzeWithTable(arena, table, &case_tables[case_tables.len - 1], inst.else_body); // Reset the table back to its state from before the case. var it = case_tables[case_tables.len - 1].iterator(); while (it.next()) |entry| { table.removeAssertDiscard(entry.key); } } const List = std.ArrayList(*ir.Inst); const case_deaths = try table.allocator.alloc(List, case_tables.len); // +1 for else defer table.allocator.free(case_deaths); std.mem.set(List, case_deaths, List.init(table.allocator)); defer for (case_deaths) |*cd| cd.deinit(); var total_deaths: u32 = 0; for (case_tables) |*ct, i| { total_deaths += ct.count(); var it = ct.iterator(); while (it.next()) |entry| { const case_death = entry.key; for (case_tables) |*ct_inner, j| { if (i == j) continue; if (!ct_inner.contains(case_death)) { // instruction is not referenced in this case try case_deaths[j].append(case_death); } } // undo resetting the table _ = try table.put(case_death, {}); } } // Now we have to correctly populate new_set. if (new_set) |ns| { try ns.ensureCapacity(@intCast(u32, ns.count() + total_deaths)); for (case_tables) |*ct| { var it = ct.iterator(); while (it.next()) |entry| { _ = ns.putAssumeCapacity(entry.key, {}); } } } total_deaths = 0; for (case_deaths[0 .. case_deaths.len - 1]) |*ct, i| { inst.cases[i].index = total_deaths; const len = std.math.cast(@TypeOf(inst.else_deaths), ct.items.len) catch return error.OutOfMemory; inst.cases[i].deaths = len; total_deaths += len; } { // else const else_deaths = std.math.cast(@TypeOf(inst.else_deaths), case_deaths[case_deaths.len - 1].items.len) catch return error.OutOfMemory; inst.else_index = total_deaths; inst.else_deaths = else_deaths; total_deaths += else_deaths; } const allocated_slice = try arena.alloc(*ir.Inst, total_deaths); inst.deaths = allocated_slice.ptr; for (case_deaths[0 .. case_deaths.len - 1]) |*cd, i| { std.mem.copy(*ir.Inst, inst.caseDeaths(i), cd.items); } std.mem.copy(*ir.Inst, inst.elseDeaths(), case_deaths[case_deaths.len - 1].items); }, else => {}, } const needed_bits = base.operandCount(); if (needed_bits <= ir.Inst.deaths_bits) { var bit_i: ir.Inst.DeathsBitIndex = 0; while (base.getOperand(bit_i)) |operand| : (bit_i += 1) { const prev = try table.fetchPut(operand, {}); if (prev == null) { // Death. base.deaths |= @as(ir.Inst.DeathsInt, 1) << bit_i; if (new_set) |ns| try ns.putNoClobber(operand, {}); } } } else { @panic("Handle liveness analysis for instructions with many parameters"); } std.log.scoped(.liveness).debug("analyze {}: 0b{b}\n", .{ base.tag, base.deaths }); }
src/liveness.zig
const std = @import("std"); const mem = std.mem; const Allocator = std.mem.Allocator; const fs = std.fs; const log = std.log.scoped(.link); const assert = std.debug.assert; const Compilation = @import("Compilation.zig"); const Module = @import("Module.zig"); const trace = @import("tracy.zig").trace; const Package = @import("Package.zig"); const Type = @import("type.zig").Type; const Cache = @import("Cache.zig"); const build_options = @import("build_options"); const LibCInstallation = @import("libc_installation.zig").LibCInstallation; pub const producer_string = if (std.builtin.is_test) "zig test" else "zig " ++ build_options.version; pub const Emit = struct { /// Where the output will go. directory: Compilation.Directory, /// Path to the output file, relative to `directory`. sub_path: []const u8, }; pub const Options = struct { /// This is `null` when -fno-emit-bin is used. When `openPath` or `flush` is called, /// it will have already been null-checked. emit: ?Emit, target: std.Target, output_mode: std.builtin.OutputMode, link_mode: std.builtin.LinkMode, object_format: std.builtin.ObjectFormat, optimize_mode: std.builtin.Mode, machine_code_model: std.builtin.CodeModel, root_name: []const u8, /// Not every Compilation compiles .zig code! For example you could do `zig build-exe foo.o`. module: ?*Module, dynamic_linker: ?[]const u8, /// Used for calculating how much space to reserve for symbols in case the binary file /// does not already have a symbol table. symbol_count_hint: u64 = 32, /// Used for calculating how much space to reserve for executable program code in case /// the binary file does not already have such a section. program_code_size_hint: u64 = 256 * 1024, entry_addr: ?u64 = null, stack_size_override: ?u64, image_base_override: ?u64, /// Set to `true` to omit debug info. strip: bool, /// If this is true then this link code is responsible for outputting an object /// file and then using LLD to link it together with the link options and other objects. /// Otherwise (depending on `use_llvm`) this link code directly outputs and updates the final binary. use_lld: bool, /// If this is true then this link code is responsible for making an LLVM IR Module, /// outputting it to an object file, and then linking that together with link options and /// other objects. /// Otherwise (depending on `use_lld`) this link code directly outputs and updates the final binary. use_llvm: bool, link_libc: bool, link_libcpp: bool, function_sections: bool, eh_frame_hdr: bool, emit_relocs: bool, rdynamic: bool, z_nodelete: bool, z_defs: bool, bind_global_refs_locally: bool, is_native_os: bool, pic: bool, valgrind: bool, stack_check: bool, single_threaded: bool, verbose_link: bool, dll_export_fns: bool, error_return_tracing: bool, is_compiler_rt_or_libc: bool, parent_compilation_link_libc: bool, each_lib_rpath: bool, disable_lld_caching: bool, is_test: bool, gc_sections: ?bool = null, allow_shlib_undefined: ?bool, subsystem: ?std.Target.SubSystem, linker_script: ?[]const u8, version_script: ?[]const u8, override_soname: ?[]const u8, llvm_cpu_features: ?[*:0]const u8, /// Extra args passed directly to LLD. Ignored when not linking with LLD. extra_lld_args: []const []const u8, objects: []const []const u8, framework_dirs: []const []const u8, frameworks: []const []const u8, system_libs: std.StringArrayHashMapUnmanaged(void), lib_dirs: []const []const u8, rpath_list: []const []const u8, version: ?std.builtin.Version, libc_installation: ?*const LibCInstallation, pub fn effectiveOutputMode(options: Options) std.builtin.OutputMode { return if (options.use_lld) .Obj else options.output_mode; } }; pub const File = struct { tag: Tag, options: Options, file: ?fs.File, allocator: *Allocator, /// When linking with LLD, this linker code will output an object file only at /// this location, and then this path can be placed on the LLD linker line. intermediary_basename: ?[]const u8 = null, /// Prevents other processes from clobbering files in the output directory /// of this linking operation. lock: ?Cache.Lock = null, pub const LinkBlock = union { elf: Elf.TextBlock, coff: Coff.TextBlock, macho: MachO.TextBlock, c: void, wasm: void, }; pub const LinkFn = union { elf: Elf.SrcFn, coff: Coff.SrcFn, macho: MachO.SrcFn, c: void, wasm: ?Wasm.FnData, }; /// For DWARF .debug_info. pub const DbgInfoTypeRelocsTable = std.HashMapUnmanaged(Type, DbgInfoTypeReloc, Type.hash, Type.eql, std.hash_map.DefaultMaxLoadPercentage); /// For DWARF .debug_info. pub const DbgInfoTypeReloc = struct { /// Offset from `TextBlock.dbg_info_off` (the buffer that is local to a Decl). /// This is where the .debug_info tag for the type is. off: u32, /// Offset from `TextBlock.dbg_info_off` (the buffer that is local to a Decl). /// List of DW.AT_type / DW.FORM_ref4 that points to the type. relocs: std.ArrayListUnmanaged(u32), }; /// Attempts incremental linking, if the file already exists. If /// incremental linking fails, falls back to truncating the file and /// rewriting it. A malicious file is detected as incremental link failure /// and does not cause Illegal Behavior. This operation is not atomic. pub fn openPath(allocator: *Allocator, options: Options) !*File { const use_stage1 = build_options.is_stage1 and options.use_llvm; if (use_stage1 or options.emit == null) { return switch (options.object_format) { .coff, .pe => &(try Coff.createEmpty(allocator, options)).base, .elf => &(try Elf.createEmpty(allocator, options)).base, .macho => &(try MachO.createEmpty(allocator, options)).base, .wasm => &(try Wasm.createEmpty(allocator, options)).base, .c => unreachable, // Reported error earlier. .hex => return error.HexObjectFormatUnimplemented, .raw => return error.RawObjectFormatUnimplemented, }; } const emit = options.emit.?; const use_lld = build_options.have_llvm and options.use_lld; // comptime known false when !have_llvm const sub_path = if (use_lld) blk: { if (options.module == null) { // No point in opening a file, we would not write anything to it. Initialize with empty. return switch (options.object_format) { .coff, .pe => &(try Coff.createEmpty(allocator, options)).base, .elf => &(try Elf.createEmpty(allocator, options)).base, .macho => &(try MachO.createEmpty(allocator, options)).base, .wasm => &(try Wasm.createEmpty(allocator, options)).base, .c => unreachable, // Reported error earlier. .hex => return error.HexObjectFormatUnimplemented, .raw => return error.RawObjectFormatUnimplemented, }; } // Open a temporary object file, not the final output file because we want to link with LLD. break :blk try std.fmt.allocPrint(allocator, "{s}{s}", .{ emit.sub_path, options.target.oFileExt() }); } else emit.sub_path; errdefer if (use_lld) allocator.free(sub_path); const file: *File = switch (options.object_format) { .coff, .pe => &(try Coff.openPath(allocator, sub_path, options)).base, .elf => &(try Elf.openPath(allocator, sub_path, options)).base, .macho => &(try MachO.openPath(allocator, sub_path, options)).base, .wasm => &(try Wasm.openPath(allocator, sub_path, options)).base, .c => &(try C.openPath(allocator, sub_path, options)).base, .hex => return error.HexObjectFormatUnimplemented, .raw => return error.RawObjectFormatUnimplemented, }; if (use_lld) { file.intermediary_basename = sub_path; } return file; } pub fn cast(base: *File, comptime T: type) ?*T { if (base.tag != T.base_tag) return null; return @fieldParentPtr(T, "base", base); } pub fn makeWritable(base: *File) !void { switch (base.tag) { .coff, .elf, .macho => { if (base.file != null) return; const emit = base.options.emit orelse return; base.file = try emit.directory.handle.createFile(emit.sub_path, .{ .truncate = false, .read = true, .mode = determineMode(base.options), }); }, .c, .wasm => {}, } } pub fn makeExecutable(base: *File) !void { switch (base.tag) { .coff, .elf, .macho => if (base.file) |f| { if (base.intermediary_basename != null) { // The file we have open is not the final file that we want to // make executable, so we don't have to close it. return; } f.close(); base.file = null; }, .c, .wasm => {}, } } /// May be called before or after updateDeclExports but must be called /// after allocateDeclIndexes for any given Decl. pub fn updateDecl(base: *File, module: *Module, decl: *Module.Decl) !void { switch (base.tag) { .coff => return @fieldParentPtr(Coff, "base", base).updateDecl(module, decl), .elf => return @fieldParentPtr(Elf, "base", base).updateDecl(module, decl), .macho => return @fieldParentPtr(MachO, "base", base).updateDecl(module, decl), .c => return @fieldParentPtr(C, "base", base).updateDecl(module, decl), .wasm => return @fieldParentPtr(Wasm, "base", base).updateDecl(module, decl), } } pub fn updateDeclLineNumber(base: *File, module: *Module, decl: *Module.Decl) !void { switch (base.tag) { .coff => return @fieldParentPtr(Coff, "base", base).updateDeclLineNumber(module, decl), .elf => return @fieldParentPtr(Elf, "base", base).updateDeclLineNumber(module, decl), .macho => return @fieldParentPtr(MachO, "base", base).updateDeclLineNumber(module, decl), .c, .wasm => {}, } } /// Must be called before any call to updateDecl or updateDeclExports for /// any given Decl. pub fn allocateDeclIndexes(base: *File, decl: *Module.Decl) !void { switch (base.tag) { .coff => return @fieldParentPtr(Coff, "base", base).allocateDeclIndexes(decl), .elf => return @fieldParentPtr(Elf, "base", base).allocateDeclIndexes(decl), .macho => return @fieldParentPtr(MachO, "base", base).allocateDeclIndexes(decl), .c, .wasm => {}, } } pub fn releaseLock(self: *File) void { if (self.lock) |*lock| { lock.release(); self.lock = null; } } pub fn toOwnedLock(self: *File) Cache.Lock { const lock = self.lock.?; self.lock = null; return lock; } pub fn destroy(base: *File) void { base.releaseLock(); if (base.file) |f| f.close(); if (base.intermediary_basename) |sub_path| base.allocator.free(sub_path); switch (base.tag) { .coff => { const parent = @fieldParentPtr(Coff, "base", base); parent.deinit(); base.allocator.destroy(parent); }, .elf => { const parent = @fieldParentPtr(Elf, "base", base); parent.deinit(); base.allocator.destroy(parent); }, .macho => { const parent = @fieldParentPtr(MachO, "base", base); parent.deinit(); base.allocator.destroy(parent); }, .c => { const parent = @fieldParentPtr(C, "base", base); parent.deinit(); base.allocator.destroy(parent); }, .wasm => { const parent = @fieldParentPtr(Wasm, "base", base); parent.deinit(); base.allocator.destroy(parent); }, } } /// Commit pending changes and write headers. Takes into account final output mode /// and `use_lld`, not only `effectiveOutputMode`. pub fn flush(base: *File, comp: *Compilation) !void { const emit = base.options.emit orelse return; // -fno-emit-bin if (comp.clang_preprocessor_mode == .yes) { // TODO: avoid extra link step when it's just 1 object file (the `zig cc -c` case) // Until then, we do `lld -r -o output.o input.o` even though the output is the same // as the input. For the preprocessing case (`zig cc -E -o foo`) we copy the file // to the final location. See also the corresponding TODO in Coff linking. const full_out_path = try emit.directory.join(comp.gpa, &[_][]const u8{emit.sub_path}); defer comp.gpa.free(full_out_path); assert(comp.c_object_table.count() == 1); const the_entry = comp.c_object_table.items()[0]; const cached_pp_file_path = the_entry.key.status.success.object_path; try fs.cwd().copyFile(cached_pp_file_path, fs.cwd(), full_out_path, .{}); return; } const use_lld = build_options.have_llvm and base.options.use_lld; if (use_lld and base.options.output_mode == .Lib and base.options.link_mode == .Static and !base.options.target.isWasm()) { return base.linkAsArchive(comp); } switch (base.tag) { .coff => return @fieldParentPtr(Coff, "base", base).flush(comp), .elf => return @fieldParentPtr(Elf, "base", base).flush(comp), .macho => return @fieldParentPtr(MachO, "base", base).flush(comp), .c => return @fieldParentPtr(C, "base", base).flush(comp), .wasm => return @fieldParentPtr(Wasm, "base", base).flush(comp), } } /// Commit pending changes and write headers. Works based on `effectiveOutputMode` /// rather than final output mode. pub fn flushModule(base: *File, comp: *Compilation) !void { switch (base.tag) { .coff => return @fieldParentPtr(Coff, "base", base).flushModule(comp), .elf => return @fieldParentPtr(Elf, "base", base).flushModule(comp), .macho => return @fieldParentPtr(MachO, "base", base).flushModule(comp), .c => return @fieldParentPtr(C, "base", base).flushModule(comp), .wasm => return @fieldParentPtr(Wasm, "base", base).flushModule(comp), } } pub fn freeDecl(base: *File, decl: *Module.Decl) void { switch (base.tag) { .coff => @fieldParentPtr(Coff, "base", base).freeDecl(decl), .elf => @fieldParentPtr(Elf, "base", base).freeDecl(decl), .macho => @fieldParentPtr(MachO, "base", base).freeDecl(decl), .c => unreachable, .wasm => @fieldParentPtr(Wasm, "base", base).freeDecl(decl), } } pub fn errorFlags(base: *File) ErrorFlags { switch (base.tag) { .coff => return @fieldParentPtr(Coff, "base", base).error_flags, .elf => return @fieldParentPtr(Elf, "base", base).error_flags, .macho => return @fieldParentPtr(MachO, "base", base).error_flags, .c => return .{ .no_entry_point_found = false }, .wasm => return ErrorFlags{}, } } /// May be called before or after updateDecl, but must be called after /// allocateDeclIndexes for any given Decl. pub fn updateDeclExports( base: *File, module: *Module, decl: *const Module.Decl, exports: []const *Module.Export, ) !void { switch (base.tag) { .coff => return @fieldParentPtr(Coff, "base", base).updateDeclExports(module, decl, exports), .elf => return @fieldParentPtr(Elf, "base", base).updateDeclExports(module, decl, exports), .macho => return @fieldParentPtr(MachO, "base", base).updateDeclExports(module, decl, exports), .c => return {}, .wasm => return @fieldParentPtr(Wasm, "base", base).updateDeclExports(module, decl, exports), } } pub fn getDeclVAddr(base: *File, decl: *const Module.Decl) u64 { switch (base.tag) { .coff => return @fieldParentPtr(Coff, "base", base).getDeclVAddr(decl), .elf => return @fieldParentPtr(Elf, "base", base).getDeclVAddr(decl), .macho => return @fieldParentPtr(MachO, "base", base).getDeclVAddr(decl), .c => unreachable, .wasm => unreachable, } } fn linkAsArchive(base: *File, comp: *Compilation) !void { const tracy = trace(@src()); defer tracy.end(); var arena_allocator = std.heap.ArenaAllocator.init(base.allocator); defer arena_allocator.deinit(); const arena = &arena_allocator.allocator; const directory = base.options.emit.?.directory; // Just an alias to make it shorter to type. // If there is no Zig code to compile, then we should skip flushing the output file because it // will not be part of the linker line anyway. const module_obj_path: ?[]const u8 = if (base.options.module) |module| blk: { const use_stage1 = build_options.is_stage1 and base.options.use_llvm; if (use_stage1) { const obj_basename = try std.zig.binNameAlloc(arena, .{ .root_name = base.options.root_name, .target = base.options.target, .output_mode = .Obj, }); const full_obj_path = try directory.join(arena, &[_][]const u8{obj_basename}); break :blk full_obj_path; } try base.flushModule(comp); const obj_basename = base.intermediary_basename.?; const full_obj_path = try directory.join(arena, &[_][]const u8{obj_basename}); break :blk full_obj_path; } else null; // This function follows the same pattern as link.Elf.linkWithLLD so if you want some // insight as to what's going on here you can read that function body which is more // well-commented. const id_symlink_basename = "llvm-ar.id"; base.releaseLock(); var ch = comp.cache_parent.obtain(); defer ch.deinit(); try ch.addListOfFiles(base.options.objects); for (comp.c_object_table.items()) |entry| { _ = try ch.addFile(entry.key.status.success.object_path, null); } try ch.addOptionalFile(module_obj_path); // We don't actually care whether it's a cache hit or miss; we just need the digest and the lock. _ = try ch.hit(); const digest = ch.final(); var prev_digest_buf: [digest.len]u8 = undefined; const prev_digest: []u8 = directory.handle.readLink(id_symlink_basename, &prev_digest_buf) catch |err| b: { log.debug("archive new_digest={} readlink error: {}", .{ digest, @errorName(err) }); break :b prev_digest_buf[0..0]; }; if (mem.eql(u8, prev_digest, &digest)) { log.debug("archive digest={} match - skipping invocation", .{digest}); base.lock = ch.toOwnedLock(); return; } // We are about to change the output file to be different, so we invalidate the build hash now. directory.handle.deleteFile(id_symlink_basename) catch |err| switch (err) { error.FileNotFound => {}, else => |e| return e, }; var object_files = std.ArrayList([*:0]const u8).init(base.allocator); defer object_files.deinit(); try object_files.ensureCapacity(base.options.objects.len + comp.c_object_table.items().len + 1); for (base.options.objects) |obj_path| { object_files.appendAssumeCapacity(try arena.dupeZ(u8, obj_path)); } for (comp.c_object_table.items()) |entry| { object_files.appendAssumeCapacity(try arena.dupeZ(u8, entry.key.status.success.object_path)); } if (module_obj_path) |p| { object_files.appendAssumeCapacity(try arena.dupeZ(u8, p)); } const full_out_path = try directory.join(arena, &[_][]const u8{base.options.emit.?.sub_path}); const full_out_path_z = try arena.dupeZ(u8, full_out_path); if (base.options.verbose_link) { std.debug.print("ar rcs {}", .{full_out_path_z}); for (object_files.items) |arg| { std.debug.print(" {}", .{arg}); } std.debug.print("\n", .{}); } const llvm = @import("llvm.zig"); const os_type = @import("target.zig").osToLLVM(base.options.target.os.tag); const bad = llvm.WriteArchive(full_out_path_z, object_files.items.ptr, object_files.items.len, os_type); if (bad) return error.UnableToWriteArchive; directory.handle.symLink(&digest, id_symlink_basename, .{}) catch |err| { std.log.warn("failed to save archive hash digest symlink: {}", .{@errorName(err)}); }; ch.writeManifest() catch |err| { std.log.warn("failed to write cache manifest when archiving: {}", .{@errorName(err)}); }; base.lock = ch.toOwnedLock(); } pub const Tag = enum { coff, elf, macho, c, wasm, }; pub const ErrorFlags = struct { no_entry_point_found: bool = false, }; pub const C = @import("link/C.zig"); pub const Coff = @import("link/Coff.zig"); pub const Elf = @import("link/Elf.zig"); pub const MachO = @import("link/MachO.zig"); pub const Wasm = @import("link/Wasm.zig"); }; pub fn determineMode(options: Options) fs.File.Mode { // On common systems with a 0o022 umask, 0o777 will still result in a file created // with 0o755 permissions, but it works appropriately if the system is configured // more leniently. As another data point, C's fopen seems to open files with the // 666 mode. const executable_mode = if (std.Target.current.os.tag == .windows) 0 else 0o777; switch (options.effectiveOutputMode()) { .Lib => return switch (options.link_mode) { .Dynamic => executable_mode, .Static => fs.File.default_mode, }, .Exe => return executable_mode, .Obj => return fs.File.default_mode, } }
src/link.zig
const std = @import("std"); const builtin = @import("builtin"); const native_endian = builtin.target.cpu.arch.endian(); const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const expectEqualSlices = std.testing.expectEqualSlices; const maxInt = std.math.maxInt; top_level_field: i32, test "top level fields" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; var instance = @This(){ .top_level_field = 1234, }; instance.top_level_field += 1; try expect(@as(i32, 1235) == instance.top_level_field); } const StructWithFields = struct { a: u8, b: u32, c: u64, d: u32, fn first(self: *const StructWithFields) u8 { return self.a; } fn second(self: *const StructWithFields) u32 { return self.b; } fn third(self: *const StructWithFields) u64 { return self.c; } fn fourth(self: *const StructWithFields) u32 { return self.d; } }; test "non-packed struct has fields padded out to the required alignment" { if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const foo = StructWithFields{ .a = 5, .b = 1, .c = 10, .d = 2 }; try expect(foo.first() == 5); try expect(foo.second() == 1); try expect(foo.third() == 10); try expect(foo.fourth() == 2); } const SmallStruct = struct { a: u8, b: u8, fn first(self: *SmallStruct) u8 { return self.a; } fn second(self: *SmallStruct) u8 { return self.b; } }; test "lower unnamed constants" { var foo = SmallStruct{ .a = 1, .b = 255 }; try expect(foo.first() == 1); try expect(foo.second() == 255); } const StructWithNoFields = struct { fn add(a: i32, b: i32) i32 { return a + b; } }; const StructFoo = struct { a: i32, b: bool, c: f32, }; test "structs" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; var foo: StructFoo = undefined; @memset(@ptrCast([*]u8, &foo), 0, @sizeOf(StructFoo)); foo.a += 1; foo.b = foo.a == 1; try testFoo(foo); testMutation(&foo); try expect(foo.c == 100); } fn testFoo(foo: StructFoo) !void { try expect(foo.b); } fn testMutation(foo: *StructFoo) void { foo.c = 100; } test "struct byval assign" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; var foo1: StructFoo = undefined; var foo2: StructFoo = undefined; foo1.a = 1234; foo2.a = 0; try expect(foo2.a == 0); foo2 = foo1; try expect(foo2.a == 1234); } test "call struct static method" { const result = StructWithNoFields.add(3, 4); try expect(result == 7); } const should_be_11 = StructWithNoFields.add(5, 6); test "invoke static method in global scope" { try expect(should_be_11 == 11); } const empty_global_instance = StructWithNoFields{}; test "return empty struct instance" { _ = returnEmptyStructInstance(); } fn returnEmptyStructInstance() StructWithNoFields { return empty_global_instance; } test "fn call of struct field" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const Foo = struct { ptr: fn () i32, }; const S = struct { fn aFunc() i32 { return 13; } fn callStructField(foo: Foo) i32 { return foo.ptr(); } }; try expect(S.callStructField(Foo{ .ptr = S.aFunc }) == 13); } test "struct initializer" { const val = Val{ .x = 42 }; try expect(val.x == 42); } const MemberFnTestFoo = struct { x: i32, fn member(foo: MemberFnTestFoo) i32 { return foo.x; } }; test "call member function directly" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; const instance = MemberFnTestFoo{ .x = 1234 }; const result = MemberFnTestFoo.member(instance); try expect(result == 1234); } test "store member function in variable" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; const instance = MemberFnTestFoo{ .x = 1234 }; const memberFn = MemberFnTestFoo.member; const result = memberFn(instance); try expect(result == 1234); } test "member functions" { const r = MemberFnRand{ .seed = 1234 }; try expect(r.getSeed() == 1234); } const MemberFnRand = struct { seed: u32, pub fn getSeed(r: *const MemberFnRand) u32 { return r.seed; } }; test "return struct byval from function" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const bar = makeBar2(1234, 5678); try expect(bar.y == 5678); } const Bar = struct { x: i32, y: i32, }; fn makeBar2(x: i32, y: i32) Bar { return Bar{ .x = x, .y = y, }; } test "call method with mutable reference to struct with no fields" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const S = struct { fn doC(s: *const @This()) bool { _ = s; return true; } fn do(s: *@This()) bool { _ = s; return true; } }; var s = S{}; try expect(S.doC(&s)); try expect(s.doC()); try expect(S.do(&s)); try expect(s.do()); } test "usingnamespace within struct scope" { const S = struct { usingnamespace struct { pub fn inner() i32 { return 42; } }; }; try expect(@as(i32, 42) == S.inner()); } test "struct field init with catch" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const S = struct { fn doTheTest() !void { var x: anyerror!isize = 1; var req = Foo{ .field = x catch undefined, }; try expect(req.field == 1); } pub const Foo = extern struct { field: isize, }; }; try S.doTheTest(); comptime try S.doTheTest(); } const blah: packed struct { a: u3, b: u3, c: u2, } = undefined; test "bit field alignment" { try expect(@TypeOf(&blah.b) == *align(1:3:1) const u3); } const Node = struct { val: Val, next: *Node, }; const Val = struct { x: i32, }; test "struct point to self" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO var root: Node = undefined; root.val.x = 1; var node: Node = undefined; node.next = &root; node.val.x = 2; root.next = &node; try expect(node.next.next.next.val.x == 1); } test "void struct fields" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO const foo = VoidStructFieldsFoo{ .a = void{}, .b = 1, .c = void{}, }; try expect(foo.b == 1); try expect(@sizeOf(VoidStructFieldsFoo) == 4); } const VoidStructFieldsFoo = struct { a: void, b: i32, c: void, }; test "return empty struct from fn" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO _ = testReturnEmptyStructFromFn(); } const EmptyStruct2 = struct {}; fn testReturnEmptyStructFromFn() EmptyStruct2 { return EmptyStruct2{}; } test "pass slice of empty struct to fn" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO try expect(testPassSliceOfEmptyStructToFn(&[_]EmptyStruct2{EmptyStruct2{}}) == 1); } fn testPassSliceOfEmptyStructToFn(slice: []const EmptyStruct2) usize { return slice.len; } test "self-referencing struct via array member" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO const T = struct { children: [1]*@This(), }; var x: T = undefined; x = T{ .children = .{&x} }; try expect(x.children[0] == &x); } test "empty struct method call" { if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64 and builtin.os.tag == .macos) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64 and builtin.os.tag == .macos) return error.SkipZigTest; // TODO const es = EmptyStruct{}; try expect(es.method() == 1234); } const EmptyStruct = struct { fn method(es: *const EmptyStruct) i32 { _ = es; return 1234; } }; test "align 1 field before self referential align 8 field as slice return type" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO const result = alloc(Expr); try expect(result.len == 0); } const Expr = union(enum) { Literal: u8, Question: *Expr, }; fn alloc(comptime T: type) []T { return &[_]T{}; } const APackedStruct = packed struct { x: u8, y: u8, }; test "packed struct" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO var foo = APackedStruct{ .x = 1, .y = 2, }; foo.y += 1; const four = foo.x + foo.y; try expect(four == 4); } const Foo24Bits = packed struct { field: u24, }; const Foo96Bits = packed struct { a: u24, b: u24, c: u24, d: u24, }; test "packed struct 24bits" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO comptime { try expect(@sizeOf(Foo24Bits) == 4); if (@sizeOf(usize) == 4) { try expect(@sizeOf(Foo96Bits) == 12); } else { try expect(@sizeOf(Foo96Bits) == 16); } } var value = Foo96Bits{ .a = 0, .b = 0, .c = 0, .d = 0, }; value.a += 1; try expect(value.a == 1); try expect(value.b == 0); try expect(value.c == 0); try expect(value.d == 0); value.b += 1; try expect(value.a == 1); try expect(value.b == 1); try expect(value.c == 0); try expect(value.d == 0); value.c += 1; try expect(value.a == 1); try expect(value.b == 1); try expect(value.c == 1); try expect(value.d == 0); value.d += 1; try expect(value.a == 1); try expect(value.b == 1); try expect(value.c == 1); try expect(value.d == 1); } test "runtime struct initialization of bitfield" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO const s1 = Nibbles{ .x = x1, .y = x1, }; const s2 = Nibbles{ .x = @intCast(u4, x2), .y = @intCast(u4, x2), }; try expect(s1.x == x1); try expect(s1.y == x1); try expect(s2.x == @intCast(u4, x2)); try expect(s2.y == @intCast(u4, x2)); } var x1 = @as(u4, 1); var x2 = @as(u8, 2); const Nibbles = packed struct { x: u4, y: u4, }; const Bitfields = packed struct { f1: u16, f2: u16, f3: u8, f4: u8, f5: u4, f6: u4, f7: u8, }; test "native bit field understands endianness" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO var all: u64 = if (native_endian != .Little) 0x1111222233445677 else 0x7765443322221111; var bytes: [8]u8 = undefined; @memcpy(&bytes, @ptrCast([*]u8, &all), 8); var bitfields = @ptrCast(*Bitfields, &bytes).*; try expect(bitfields.f1 == 0x1111); try expect(bitfields.f2 == 0x2222); try expect(bitfields.f3 == 0x33); try expect(bitfields.f4 == 0x44); try expect(bitfields.f5 == 0x5); try expect(bitfields.f6 == 0x6); try expect(bitfields.f7 == 0x77); } test "implicit cast packed struct field to const ptr" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO const LevelUpMove = packed struct { move_id: u9, level: u7, fn toInt(value: u7) u7 { return value; } }; var lup: LevelUpMove = undefined; lup.level = 12; const res = LevelUpMove.toInt(lup.level); try expect(res == 12); } test "zero-bit field in packed struct" { if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO const S = packed struct { x: u10, y: void, }; var x: S = undefined; _ = x; } test "packed struct with non-ABI-aligned field" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO const S = packed struct { x: u9, y: u183, }; var s: S = undefined; s.x = 1; s.y = 42; try expect(s.x == 1); try expect(s.y == 42); } const BitField1 = packed struct { a: u3, b: u3, c: u2, }; const bit_field_1 = BitField1{ .a = 1, .b = 2, .c = 3, }; test "bit field access" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO var data = bit_field_1; try expect(getA(&data) == 1); try expect(getB(&data) == 2); try expect(getC(&data) == 3); comptime try expect(@sizeOf(BitField1) == 1); data.b += 1; try expect(data.b == 3); data.a += 1; try expect(data.a == 2); try expect(data.b == 3); } fn getA(data: *const BitField1) u3 { return data.a; } fn getB(data: *const BitField1) u3 { return data.b; } fn getC(data: *const BitField1) u2 { return data.c; } test "default struct initialization fields" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO const S = struct { a: i32 = 1234, b: i32, }; const x = S{ .b = 5, }; var five: i32 = 5; const y = S{ .b = five, }; if (x.a + x.b != 1239) { @compileError("it should be comptime known"); } try expect(y.a == x.a); try expect(y.b == x.b); try expect(1239 == x.a + x.b); } test "packed array 24bits" { if (builtin.zig_backend == .stage1) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; comptime { try expect(@sizeOf([9]Foo32Bits) == 9 * 4); try expect(@sizeOf(FooArray24Bits) == @sizeOf(u96)); } var bytes = [_]u8{0} ** (@sizeOf(FooArray24Bits) + 1); bytes[bytes.len - 1] = 0xbb; const ptr = &std.mem.bytesAsSlice(FooArray24Bits, bytes[0 .. bytes.len - 1])[0]; try expect(ptr.a == 0); try expect(ptr.b0.field == 0); try expect(ptr.b1.field == 0); try expect(ptr.c == 0); ptr.a = maxInt(u16); try expect(ptr.a == maxInt(u16)); try expect(ptr.b0.field == 0); try expect(ptr.b1.field == 0); try expect(ptr.c == 0); ptr.b0.field = maxInt(u24); try expect(ptr.a == maxInt(u16)); try expect(ptr.b0.field == maxInt(u24)); try expect(ptr.b1.field == 0); try expect(ptr.c == 0); ptr.b1.field = maxInt(u24); try expect(ptr.a == maxInt(u16)); try expect(ptr.b0.field == maxInt(u24)); try expect(ptr.b1.field == maxInt(u24)); try expect(ptr.c == 0); ptr.c = maxInt(u16); try expect(ptr.a == maxInt(u16)); try expect(ptr.b0.field == maxInt(u24)); try expect(ptr.b1.field == maxInt(u24)); try expect(ptr.c == maxInt(u16)); try expect(bytes[bytes.len - 1] == 0xbb); } const Foo32Bits = packed struct { field: u24, pad: u8, }; const FooArray24Bits = packed struct { a: u16, b0: Foo32Bits, b1: Foo32Bits, c: u16, }; test "aligned array of packed struct" { if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO comptime { try expect(@sizeOf(FooStructAligned) == 2); try expect(@sizeOf(FooArrayOfAligned) == 2 * 2); } var bytes = [_]u8{0xbb} ** @sizeOf(FooArrayOfAligned); const ptr = &std.mem.bytesAsSlice(FooArrayOfAligned, bytes[0..])[0]; try expect(ptr.a[0].a == 0xbb); try expect(ptr.a[0].b == 0xbb); try expect(ptr.a[1].a == 0xbb); try expect(ptr.a[1].b == 0xbb); } const FooStructAligned = packed struct { a: u8, b: u8, }; const FooArrayOfAligned = packed struct { a: [2]FooStructAligned, }; test "pointer to packed struct member in a stack variable" { if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO const S = packed struct { a: u2, b: u2, }; var s = S{ .a = 2, .b = 0 }; var b_ptr = &s.b; try expect(s.b == 0); b_ptr.* = 2; try expect(s.b == 2); } test "packed struct with u0 field access" { if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO const S = packed struct { f0: u0, }; var s = S{ .f0 = 0 }; comptime try expect(s.f0 == 0); } test "access to global struct fields" { if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO g_foo.bar.value = 42; try expect(g_foo.bar.value == 42); } const S0 = struct { bar: S1, pub const S1 = struct { value: u8, }; fn init() @This() { return S0{ .bar = S1{ .value = 123 } }; } }; var g_foo: S0 = S0.init(); test "packed struct with fp fields" { if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO const S = packed struct { data0: f32, data1: f32, data2: f32, pub fn frob(self: *@This()) void { self.data0 += self.data1 + self.data2; self.data1 += self.data0 + self.data2; self.data2 += self.data0 + self.data1; } }; var s: S = undefined; s.data0 = 1.0; s.data1 = 2.0; s.data2 = 3.0; s.frob(); try expect(@as(f32, 6.0) == s.data0); try expect(@as(f32, 11.0) == s.data1); try expect(@as(f32, 20.0) == s.data2); } test "fn with C calling convention returns struct by value" { if (builtin.zig_backend != .stage1) return error.SkipZigTest; // TODO const S = struct { fn entry() !void { var x = makeBar(10); try expectEqual(@as(i32, 10), x.handle); } const ExternBar = extern struct { handle: i32, }; fn makeBar(t: i32) callconv(.C) ExternBar { return ExternBar{ .handle = t, }; } }; try S.entry(); comptime try S.entry(); } test "non-packed struct with u128 entry in union" { if (builtin.zig_backend != .stage1) return error.SkipZigTest; // TODO const U = union(enum) { Num: u128, Void, }; const S = struct { f1: U, f2: U, }; var sx: S = undefined; var s = &sx; try std.testing.expect(@ptrToInt(&s.f2) - @ptrToInt(&s.f1) == @offsetOf(S, "f2")); var v2 = U{ .Num = 123 }; s.f2 = v2; try std.testing.expect(s.f2.Num == 123); } test "packed struct field passed to generic function" { if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO const S = struct { const P = packed struct { b: u5, g: u5, r: u5, a: u1, }; fn genericReadPackedField(ptr: anytype) u5 { return ptr.*; } }; var p: S.P = undefined; p.b = 29; var loaded = S.genericReadPackedField(&p.b); try expect(loaded == 29); } test "anonymous struct literal syntax" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO const S = struct { const Point = struct { x: i32, y: i32, }; fn doTheTest() !void { var p: Point = .{ .x = 1, .y = 2, }; try expect(p.x == 1); try expect(p.y == 2); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "fully anonymous struct" { if (builtin.zig_backend != .stage1) return error.SkipZigTest; // TODO const S = struct { fn doTheTest() !void { try dump(.{ .int = @as(u32, 1234), .float = @as(f64, 12.34), .b = true, .s = "hi", }); } fn dump(args: anytype) !void { try expect(args.int == 1234); try expect(args.float == 12.34); try expect(args.b); try expect(args.s[0] == 'h'); try expect(args.s[1] == 'i'); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "fully anonymous list literal" { if (builtin.zig_backend != .stage1) return error.SkipZigTest; // TODO const S = struct { fn doTheTest() !void { try dump(.{ @as(u32, 1234), @as(f64, 12.34), true, "hi" }); } fn dump(args: anytype) !void { try expect(args.@"0" == 1234); try expect(args.@"1" == 12.34); try expect(args.@"2"); try expect(args.@"3"[0] == 'h'); try expect(args.@"3"[1] == 'i'); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "anonymous struct literal assigned to variable" { if (builtin.zig_backend != .stage1) return error.SkipZigTest; // TODO var vec = .{ @as(i32, 22), @as(i32, 55), @as(i32, 99) }; try expect(vec.@"0" == 22); try expect(vec.@"1" == 55); try expect(vec.@"2" == 99); } test "comptime struct field" { if (builtin.zig_backend != .stage1) return error.SkipZigTest; // TODO const T = struct { a: i32, comptime b: i32 = 1234, }; var foo: T = undefined; comptime try expect(foo.b == 1234); } test "anon struct literal field value initialized with fn call" { if (builtin.zig_backend != .stage1) return error.SkipZigTest; // TODO const S = struct { fn doTheTest() !void { var x = .{foo()}; try expectEqualSlices(u8, x[0], "hi"); } fn foo() []const u8 { return "hi"; } }; try S.doTheTest(); comptime try S.doTheTest(); } test "struct with union field" { if (builtin.zig_backend != .stage1) return error.SkipZigTest; // TODO const Value = struct { ref: u32 = 2, kind: union(enum) { None: usize, Bool: bool, }, }; var True = Value{ .kind = .{ .Bool = true }, }; try expect(@as(u32, 2) == True.ref); try expect(True.kind.Bool); } test "type coercion of anon struct literal to struct" { if (builtin.zig_backend != .stage1) return error.SkipZigTest; // TODO const S = struct { const S2 = struct { A: u32, B: []const u8, C: void, D: Foo = .{}, }; const Foo = struct { field: i32 = 1234, }; fn doTheTest() !void { var y: u32 = 42; const t0 = .{ .A = 123, .B = "foo", .C = {} }; const t1 = .{ .A = y, .B = "foo", .C = {} }; const y0: S2 = t0; var y1: S2 = t1; try expect(y0.A == 123); try expect(std.mem.eql(u8, y0.B, "foo")); try expect(y0.C == {}); try expect(y0.D.field == 1234); try expect(y1.A == y); try expect(std.mem.eql(u8, y1.B, "foo")); try expect(y1.C == {}); try expect(y1.D.field == 1234); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "type coercion of pointer to anon struct literal to pointer to struct" { if (builtin.zig_backend != .stage1) return error.SkipZigTest; // TODO const S = struct { const S2 = struct { A: u32, B: []const u8, C: void, D: Foo = .{}, }; const Foo = struct { field: i32 = 1234, }; fn doTheTest() !void { var y: u32 = 42; const t0 = &.{ .A = 123, .B = "foo", .C = {} }; const t1 = &.{ .A = y, .B = "foo", .C = {} }; const y0: *const S2 = t0; var y1: *const S2 = t1; try expect(y0.A == 123); try expect(std.mem.eql(u8, y0.B, "foo")); try expect(y0.C == {}); try expect(y0.D.field == 1234); try expect(y1.A == y); try expect(std.mem.eql(u8, y1.B, "foo")); try expect(y1.C == {}); try expect(y1.D.field == 1234); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "packed struct with undefined initializers" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO const S = struct { const P = packed struct { a: u3, _a: u3 = undefined, b: u3, _b: u3 = undefined, c: u3, _c: u3 = undefined, }; fn doTheTest() !void { var p: P = undefined; p = P{ .a = 2, .b = 4, .c = 6 }; // Make sure the compiler doesn't touch the unprefixed fields. // Use expect since i386-linux doesn't like expectEqual try expect(p.a == 2); try expect(p.b == 4); try expect(p.c == 6); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "for loop over pointers to struct, getting field from struct pointer" { // When enabling this test, be careful. I have observed it to pass when compiling // stage2 alone, but when using stage1 with -fno-stage1 -fLLVM it fails. // Maybe eyeball the LLVM that it generates and run in valgrind, both the compiler // and the generated test at runtime. if (builtin.zig_backend != .stage1) return error.SkipZigTest; // TODO const S = struct { const Foo = struct { name: []const u8, }; var ok = true; fn eql(a: []const u8) bool { _ = a; return true; } const ArrayList = struct { fn toSlice(self: *ArrayList) []*Foo { _ = self; return @as([*]*Foo, undefined)[0..0]; } }; fn doTheTest() !void { var objects: ArrayList = undefined; for (objects.toSlice()) |obj| { if (eql(obj.name)) { ok = false; } } try expect(ok); } }; try S.doTheTest(); } test "anon init through error unions and optionals" { if (builtin.zig_backend == .stage1) return error.SkipZigTest; if (builtin.zig_backend != .stage2_llvm) return error.SkipZigTest; // TODO const S = struct { a: u32, fn foo() anyerror!?anyerror!@This() { return .{ .a = 1 }; } fn bar() ?anyerror![2]u8 { return .{ 1, 2 }; } fn doTheTest() !void { var a = try (try foo()).?; var b = try bar().?; try expect(a.a + b[1] == 3); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "anon init through optional" { if (builtin.zig_backend == .stage1) return error.SkipZigTest; if (builtin.zig_backend != .stage2_llvm) return error.SkipZigTest; // TODO const S = struct { a: u32, fn doTheTest() !void { var s: ?@This() = null; s = .{ .a = 1 }; try expect(s.?.a == 1); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "anon init through error union" { if (builtin.zig_backend == .stage1) return error.SkipZigTest; if (builtin.zig_backend != .stage2_llvm) return error.SkipZigTest; // TODO const S = struct { a: u32, fn doTheTest() !void { var s: anyerror!@This() = error.Foo; s = .{ .a = 1 }; try expect((try s).a == 1); } }; try S.doTheTest(); comptime try S.doTheTest(); }
test/behavior/struct.zig
const std = @import("std"); const mem = std.mem; const assert = std.debug.assert; const print = std.debug.print; const util = @import("utils.zig"); const input = @embedFile("../in/day01.txt"); /// Strategy: /// Store expenses in a hash set and query the set for existence of a complement /// fulfilling the sum. /// Example: /// Set: {1,2,3} /// Target_Sum: 3 /// Complement(x) = Target_Sum - x /// since Set.contains(Complement(1)), we know that (1 + Complement(1)) = Target_Sum /// Complexity: Time O(n), Space O(n) fn part1(allocator: *mem.Allocator, target: u16) !void { const expenses: []u16 = try util.splitToInts(u16, allocator, input, "\n"); var expense_index = util.HashSet(u16).init(allocator); for (expenses) |expense| { try expense_index.put(expense, {}); } const pair = findPairSum(expenses, &expense_index, target).?; const n1 = pair.n1; const n2 = pair.n2; print("part1:\t{} * {} = {}", .{n1, n2, @as(u32, n1) * n2}); } const Pair = struct {n1: u16, n2: u16}; fn findPairSum(expenses: []u16, expense_index: *util.HashSet(u16), target: u16) ?Pair { const tmp: ?u16 = blk: { for (expenses) |expense| { if (expense > target) continue; // guard for overflow if (expense_index.contains(target - expense)) { break :blk expense; } } break :blk null; }; if (tmp) |value| { return Pair{.n1 = value, .n2 = target - value}; } else { return null; } } fn part2(allocator: *mem.Allocator, target: u16) !void { const expenses: []u16 = try util.splitToInts(u16, allocator, input, "\n"); var expense_index = util.HashSet(u16).init(allocator); for (expenses) |expense| { try expense_index.put(expense, {}); } for (expenses) |n3| { if (n3 > target) continue; // guard for overflow const pair = findPairSum(expenses, &expense_index, target - n3) orelse continue; const n1 = pair.n1; const n2 = pair.n2; print("part2:\t{} * {} * {} = {}", .{n1, n2, n3, @as(u32, n1) * n2 * n3}); break; } } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; try part1(allocator, 2020); print("\n", .{}); try part2(allocator, 2020); }
src/day01.zig
const std = @import("std"); const builtin = @import("builtin"); const blake2 = crypto.hash.blake2; const crypto = std.crypto; const math = std.math; const mem = std.mem; const phc_format = pwhash.phc_format; const pwhash = crypto.pwhash; const Thread = std.Thread; const Blake2b512 = blake2.Blake2b512; const Blocks = std.ArrayListAligned([block_length]u64, 16); const H0 = [Blake2b512.digest_length + 8]u8; const EncodingError = crypto.errors.EncodingError; const KdfError = pwhash.KdfError; const HasherError = pwhash.HasherError; const Error = pwhash.Error; const version = 0x13; const block_length = 128; const sync_points = 4; const max_int = 0xffff_ffff; const default_salt_len = 32; const default_hash_len = 32; const max_salt_len = 64; const max_hash_len = 64; /// Argon2 type pub const Mode = enum { /// Argon2d is faster and uses data-depending memory access, which makes it highly resistant /// against GPU cracking attacks and suitable for applications with no threats from side-channel /// timing attacks (eg. cryptocurrencies). argon2d, /// Argon2i instead uses data-independent memory access, which is preferred for password /// hashing and password-based key derivation, but it is slower as it makes more passes over /// the memory to protect from tradeoff attacks. argon2i, /// Argon2id is a hybrid of Argon2i and Argon2d, using a combination of data-depending and /// data-independent memory accesses, which gives some of Argon2i's resistance to side-channel /// cache timing attacks and much of Argon2d's resistance to GPU cracking attacks. argon2id, }; /// Argon2 parameters pub const Params = struct { const Self = @This(); /// A [t]ime cost, which defines the amount of computation realized and therefore the execution /// time, given in number of iterations. t: u32, /// A [m]emory cost, which defines the memory usage, given in kibibytes. m: u32, /// A [p]arallelism degree, which defines the number of parallel threads. p: u24, /// The [secret] parameter, which is used for keyed hashing. This allows a secret key to be input /// at hashing time (from some external location) and be folded into the value of the hash. This /// means that even if your salts and hashes are compromised, an attacker cannot brute-force to /// find the password without the key. secret: ?[]const u8 = null, /// The [ad] parameter, which is used to fold any additional data into the hash value. Functionally, /// this behaves almost exactly like the secret or salt parameters; the ad parameter is folding /// into the value of the hash. However, this parameter is used for different data. The salt /// should be a random string stored alongside your password. The secret should be a random key /// only usable at hashing time. The ad is for any other data. ad: ?[]const u8 = null, /// Baseline parameters for interactive logins using argon2i type pub const interactive_2i = Self.fromLimits(4, 33554432); /// Baseline parameters for normal usage using argon2i type pub const moderate_2i = Self.fromLimits(6, 134217728); /// Baseline parameters for offline usage using argon2i type pub const sensitive_2i = Self.fromLimits(8, 536870912); /// Baseline parameters for interactive logins using argon2id type pub const interactive_2id = Self.fromLimits(2, 67108864); /// Baseline parameters for normal usage using argon2id type pub const moderate_2id = Self.fromLimits(3, 268435456); /// Baseline parameters for offline usage using argon2id type pub const sensitive_2id = Self.fromLimits(4, 1073741824); /// Create parameters from ops and mem limits, where mem_limit given in bytes pub fn fromLimits(ops_limit: u32, mem_limit: usize) Self { const m = mem_limit / 1024; std.debug.assert(m <= max_int); return .{ .t = ops_limit, .m = @intCast(u32, m), .p = 1 }; } }; fn initHash( password: []const u8, salt: []const u8, params: Params, dk_len: usize, mode: Mode, ) H0 { var h0: H0 = undefined; var parameters: [24]u8 = undefined; var tmp: [4]u8 = undefined; var b2 = Blake2b512.init(.{}); mem.writeIntLittle(u32, parameters[0..4], params.p); mem.writeIntLittle(u32, parameters[4..8], @intCast(u32, dk_len)); mem.writeIntLittle(u32, parameters[8..12], params.m); mem.writeIntLittle(u32, parameters[12..16], params.t); mem.writeIntLittle(u32, parameters[16..20], version); mem.writeIntLittle(u32, parameters[20..24], @enumToInt(mode)); b2.update(&parameters); mem.writeIntLittle(u32, &tmp, @intCast(u32, password.len)); b2.update(&tmp); b2.update(password); mem.writeIntLittle(u32, &tmp, @intCast(u32, salt.len)); b2.update(&tmp); b2.update(salt); const secret = params.secret orelse ""; std.debug.assert(secret.len <= max_int); mem.writeIntLittle(u32, &tmp, @intCast(u32, secret.len)); b2.update(&tmp); b2.update(secret); const ad = params.ad orelse ""; std.debug.assert(ad.len <= max_int); mem.writeIntLittle(u32, &tmp, @intCast(u32, ad.len)); b2.update(&tmp); b2.update(ad); b2.final(h0[0..Blake2b512.digest_length]); return h0; } fn blake2bLong(out: []u8, in: []const u8) void { var b2 = Blake2b512.init(.{ .expected_out_bits = math.min(512, out.len * 8) }); var buffer: [Blake2b512.digest_length]u8 = undefined; mem.writeIntLittle(u32, buffer[0..4], @intCast(u32, out.len)); b2.update(buffer[0..4]); b2.update(in); b2.final(&buffer); if (out.len <= Blake2b512.digest_length) { mem.copy(u8, out, buffer[0..out.len]); return; } b2 = Blake2b512.init(.{}); mem.copy(u8, out, buffer[0..32]); var out_slice = out[32..]; while (out_slice.len > Blake2b512.digest_length) : ({ out_slice = out_slice[32..]; b2 = Blake2b512.init(.{}); }) { b2.update(&buffer); b2.final(&buffer); mem.copy(u8, out_slice, buffer[0..32]); } var r = Blake2b512.digest_length; if (out.len % Blake2b512.digest_length > 0) { r = ((out.len + 31) / 32) - 2; b2 = Blake2b512.init(.{ .expected_out_bits = r * 8 }); } b2.update(&buffer); b2.final(&buffer); mem.copy(u8, out_slice, buffer[0..r]); } fn initBlocks( blocks: *Blocks, h0: *H0, memory: u32, threads: u24, ) void { var block0: [1024]u8 = undefined; var lane: u24 = 0; while (lane < threads) : (lane += 1) { const j = lane * (memory / threads); mem.writeIntLittle(u32, h0[Blake2b512.digest_length + 4 ..][0..4], lane); mem.writeIntLittle(u32, h0[Blake2b512.digest_length..][0..4], 0); blake2bLong(&block0, h0); for (blocks.items[j + 0]) |*v, i| { v.* = mem.readIntLittle(u64, block0[i * 8 ..][0..8]); } mem.writeIntLittle(u32, h0[Blake2b512.digest_length..][0..4], 1); blake2bLong(&block0, h0); for (blocks.items[j + 1]) |*v, i| { v.* = mem.readIntLittle(u64, block0[i * 8 ..][0..8]); } } } fn processBlocks( allocator: mem.Allocator, blocks: *Blocks, time: u32, memory: u32, threads: u24, mode: Mode, ) KdfError!void { const lanes = memory / threads; const segments = lanes / sync_points; if (builtin.single_threaded or threads == 1) { processBlocksSt(blocks, time, memory, threads, mode, lanes, segments); } else { try processBlocksMt(allocator, blocks, time, memory, threads, mode, lanes, segments); } } fn processBlocksSt( blocks: *Blocks, time: u32, memory: u32, threads: u24, mode: Mode, lanes: u32, segments: u32, ) void { var n: u32 = 0; while (n < time) : (n += 1) { var slice: u32 = 0; while (slice < sync_points) : (slice += 1) { var lane: u24 = 0; while (lane < threads) : (lane += 1) { processSegment(blocks, time, memory, threads, mode, lanes, segments, n, slice, lane); } } } } fn processBlocksMt( allocator: mem.Allocator, blocks: *Blocks, time: u32, memory: u32, threads: u24, mode: Mode, lanes: u32, segments: u32, ) KdfError!void { var threads_list = try std.ArrayList(Thread).initCapacity(allocator, threads); defer threads_list.deinit(); var n: u32 = 0; while (n < time) : (n += 1) { var slice: u32 = 0; while (slice < sync_points) : (slice += 1) { var lane: u24 = 0; while (lane < threads) : (lane += 1) { const thread = try Thread.spawn(.{}, processSegment, .{ blocks, time, memory, threads, mode, lanes, segments, n, slice, lane, }); threads_list.appendAssumeCapacity(thread); } lane = 0; while (lane < threads) : (lane += 1) { threads_list.items[lane].join(); } threads_list.clearRetainingCapacity(); } } } fn processSegment( blocks: *Blocks, passes: u32, memory: u32, threads: u24, mode: Mode, lanes: u32, segments: u32, n: u32, slice: u32, lane: u24, ) void { var addresses align(16) = [_]u64{0} ** block_length; var in align(16) = [_]u64{0} ** block_length; const zero align(16) = [_]u64{0} ** block_length; if (mode == .argon2i or (mode == .argon2id and n == 0 and slice < sync_points / 2)) { in[0] = n; in[1] = lane; in[2] = slice; in[3] = memory; in[4] = passes; in[5] = @enumToInt(mode); } var index: u32 = 0; if (n == 0 and slice == 0) { index = 2; if (mode == .argon2i or mode == .argon2id) { in[6] += 1; processBlock(&addresses, &in, &zero); processBlock(&addresses, &addresses, &zero); } } var offset = lane * lanes + slice * segments + index; var random: u64 = 0; while (index < segments) : ({ index += 1; offset += 1; }) { var prev = offset -% 1; if (index == 0 and slice == 0) { prev +%= lanes; } if (mode == .argon2i or (mode == .argon2id and n == 0 and slice < sync_points / 2)) { if (index % block_length == 0) { in[6] += 1; processBlock(&addresses, &in, &zero); processBlock(&addresses, &addresses, &zero); } random = addresses[index % block_length]; } else { random = blocks.items[prev][0]; } const new_offset = indexAlpha(random, lanes, segments, threads, n, slice, lane, index); processBlockXor(&blocks.items[offset], &blocks.items[prev], &blocks.items[new_offset]); } } fn processBlock( out: *align(16) [block_length]u64, in1: *align(16) const [block_length]u64, in2: *align(16) const [block_length]u64, ) void { processBlockGeneric(out, in1, in2, false); } fn processBlockXor( out: *[block_length]u64, in1: *const [block_length]u64, in2: *const [block_length]u64, ) void { processBlockGeneric(out, in1, in2, true); } fn processBlockGeneric( out: *[block_length]u64, in1: *const [block_length]u64, in2: *const [block_length]u64, comptime xor: bool, ) void { var t: [block_length]u64 = undefined; for (t) |*v, i| { v.* = in1[i] ^ in2[i]; } var i: usize = 0; while (i < block_length) : (i += 16) { blamkaGeneric(t[i..][0..16]); } i = 0; var buffer: [16]u64 = undefined; while (i < block_length / 8) : (i += 2) { var j: usize = 0; while (j < block_length / 8) : (j += 2) { buffer[j] = t[j * 8 + i]; buffer[j + 1] = t[j * 8 + i + 1]; } blamkaGeneric(&buffer); j = 0; while (j < block_length / 8) : (j += 2) { t[j * 8 + i] = buffer[j]; t[j * 8 + i + 1] = buffer[j + 1]; } } if (xor) { for (t) |v, j| { out[j] ^= in1[j] ^ in2[j] ^ v; } } else { for (t) |v, j| { out[j] = in1[j] ^ in2[j] ^ v; } } } const QuarterRound = struct { a: usize, b: usize, c: usize, d: usize }; fn Rp(a: usize, b: usize, c: usize, d: usize) QuarterRound { return .{ .a = a, .b = b, .c = c, .d = d }; } fn fBlaMka(x: u64, y: u64) u64 { const xy = @as(u64, @truncate(u32, x)) * @as(u64, @truncate(u32, y)); return x +% y +% 2 *% xy; } fn blamkaGeneric(x: *[16]u64) void { const rounds = comptime [_]QuarterRound{ Rp(0, 4, 8, 12), Rp(1, 5, 9, 13), Rp(2, 6, 10, 14), Rp(3, 7, 11, 15), Rp(0, 5, 10, 15), Rp(1, 6, 11, 12), Rp(2, 7, 8, 13), Rp(3, 4, 9, 14), }; inline for (rounds) |r| { x[r.a] = fBlaMka(x[r.a], x[r.b]); x[r.d] = math.rotr(u64, x[r.d] ^ x[r.a], 32); x[r.c] = fBlaMka(x[r.c], x[r.d]); x[r.b] = math.rotr(u64, x[r.b] ^ x[r.c], 24); x[r.a] = fBlaMka(x[r.a], x[r.b]); x[r.d] = math.rotr(u64, x[r.d] ^ x[r.a], 16); x[r.c] = fBlaMka(x[r.c], x[r.d]); x[r.b] = math.rotr(u64, x[r.b] ^ x[r.c], 63); } } fn finalize( blocks: *Blocks, memory: u32, threads: u24, out: []u8, ) void { const lanes = memory / threads; var lane: u24 = 0; while (lane < threads - 1) : (lane += 1) { for (blocks.items[(lane * lanes) + lanes - 1]) |v, i| { blocks.items[memory - 1][i] ^= v; } } var block: [1024]u8 = undefined; for (blocks.items[memory - 1]) |v, i| { mem.writeIntLittle(u64, block[i * 8 ..][0..8], v); } blake2bLong(out, &block); } fn indexAlpha( rand: u64, lanes: u32, segments: u32, threads: u24, n: u32, slice: u32, lane: u24, index: u32, ) u32 { var ref_lane = @intCast(u32, rand >> 32) % threads; if (n == 0 and slice == 0) { ref_lane = lane; } var m = 3 * segments; var s = ((slice + 1) % sync_points) * segments; if (lane == ref_lane) { m += index; } if (n == 0) { m = slice * segments; s = 0; if (slice == 0 or lane == ref_lane) { m += index; } } if (index == 0 or lane == ref_lane) { m -= 1; } var p = @as(u64, @truncate(u32, rand)); p = (p * p) >> 32; p = (p * m) >> 32; return ref_lane * lanes + @intCast(u32, ((s + m - (p + 1)) % lanes)); } /// Derives a key from the password, salt, and argon2 parameters. /// /// Derived key has to be at least 4 bytes length. /// /// Salt has to be at least 8 bytes length. pub fn kdf( allocator: mem.Allocator, derived_key: []u8, password: []const u8, salt: []const u8, params: Params, mode: Mode, ) KdfError!void { if (derived_key.len < 4) return KdfError.WeakParameters; if (derived_key.len > max_int) return KdfError.OutputTooLong; if (password.len > max_int) return KdfError.WeakParameters; if (salt.len < 8 or salt.len > max_int) return KdfError.WeakParameters; if (params.t < 1 or params.p < 1) return KdfError.WeakParameters; var h0 = initHash(password, salt, params, derived_key.len, mode); const memory = math.max( params.m / (sync_points * params.p) * (sync_points * params.p), 2 * sync_points * params.p, ); var blocks = try Blocks.initCapacity(allocator, memory); defer blocks.deinit(); blocks.appendNTimesAssumeCapacity([_]u64{0} ** block_length, memory); initBlocks(&blocks, &h0, memory, params.p); try processBlocks(allocator, &blocks, params.t, memory, params.p, mode); finalize(&blocks, memory, params.p, derived_key); } const PhcFormatHasher = struct { const BinValue = phc_format.BinValue; const HashResult = struct { alg_id: []const u8, alg_version: ?u32, m: u32, t: u32, p: u24, salt: BinValue(max_salt_len), hash: BinValue(max_hash_len), }; pub fn create( allocator: mem.Allocator, password: []const u8, params: Params, mode: Mode, buf: []u8, ) HasherError![]const u8 { if (params.secret != null or params.ad != null) return HasherError.InvalidEncoding; var salt: [default_salt_len]u8 = undefined; crypto.random.bytes(&salt); var hash: [default_hash_len]u8 = undefined; try kdf(allocator, &hash, password, &salt, params, mode); return phc_format.serialize(HashResult{ .alg_id = @tagName(mode), .alg_version = version, .m = params.m, .t = params.t, .p = params.p, .salt = try BinValue(max_salt_len).fromSlice(&salt), .hash = try BinValue(max_hash_len).fromSlice(&hash), }, buf); } pub fn verify( allocator: mem.Allocator, str: []const u8, password: []const u8, ) HasherError!void { const hash_result = try phc_format.deserialize(HashResult, str); const mode = std.meta.stringToEnum(Mode, hash_result.alg_id) orelse return HasherError.PasswordVerificationFailed; if (hash_result.alg_version) |v| { if (v != version) return HasherError.InvalidEncoding; } const params = Params{ .t = hash_result.t, .m = hash_result.m, .p = hash_result.p }; const expected_hash = hash_result.hash.constSlice(); var hash_buf: [max_hash_len]u8 = undefined; if (expected_hash.len > hash_buf.len) return HasherError.InvalidEncoding; var hash = hash_buf[0..expected_hash.len]; try kdf(allocator, hash, password, hash_result.salt.constSlice(), params, mode); if (!mem.eql(u8, hash, expected_hash)) return HasherError.PasswordVerificationFailed; } }; /// Options for hashing a password. /// /// Allocator is required for argon2. /// /// Only phc encoding is supported. pub const HashOptions = struct { allocator: ?mem.Allocator, params: Params, mode: Mode = .argon2id, encoding: pwhash.Encoding = .phc, }; /// Compute a hash of a password using the argon2 key derivation function. /// The function returns a string that includes all the parameters required for verification. pub fn strHash( password: []const u8, options: HashOptions, out: []u8, ) Error![]const u8 { const allocator = options.allocator orelse return Error.AllocatorRequired; switch (options.encoding) { .phc => return PhcFormatHasher.create( allocator, password, options.params, options.mode, out, ), .crypt => return Error.InvalidEncoding, } } /// Options for hash verification. /// /// Allocator is required for argon2. pub const VerifyOptions = struct { allocator: ?mem.Allocator, }; /// Verify that a previously computed hash is valid for a given password. pub fn strVerify( str: []const u8, password: []const u8, options: VerifyOptions, ) Error!void { const allocator = options.allocator orelse return Error.AllocatorRequired; return PhcFormatHasher.verify(allocator, str, password); } test "argon2d" { const password = [_]u8{0x01} ** 32; const salt = [_]u8{0x02} ** 16; const secret = [_]u8{0x03} ** 8; const ad = [_]u8{0x04} ** 12; var dk: [32]u8 = undefined; try kdf( std.testing.allocator, &dk, &password, &salt, .{ .t = 3, .m = 32, .p = 4, .secret = &secret, .ad = &ad }, .argon2d, ); const want = [_]u8{ 0x51, 0x2b, 0x39, 0x1b, 0x6f, 0x11, 0x62, 0x97, 0x53, 0x71, 0xd3, 0x09, 0x19, 0x73, 0x42, 0x94, 0xf8, 0x68, 0xe3, 0xbe, 0x39, 0x84, 0xf3, 0xc1, 0xa1, 0x3a, 0x4d, 0xb9, 0xfa, 0xbe, 0x4a, 0xcb, }; try std.testing.expectEqualSlices(u8, &dk, &want); } test "argon2i" { const password = [_]u8{0x01} ** 32; const salt = [_]u8{0x02} ** 16; const secret = [_]u8{0x03} ** 8; const ad = [_]u8{0x04} ** 12; var dk: [32]u8 = undefined; try kdf( std.testing.allocator, &dk, &password, &salt, .{ .t = 3, .m = 32, .p = 4, .secret = &secret, .ad = &ad }, .argon2i, ); const want = [_]u8{ 0xc8, 0x14, 0xd9, 0xd1, 0xdc, 0x7f, 0x37, 0xaa, 0x13, 0xf0, 0xd7, 0x7f, 0x24, 0x94, 0xbd, 0xa1, 0xc8, 0xde, 0x6b, 0x01, 0x6d, 0xd3, 0x88, 0xd2, 0x99, 0x52, 0xa4, 0xc4, 0x67, 0x2b, 0x6c, 0xe8, }; try std.testing.expectEqualSlices(u8, &dk, &want); } test "argon2id" { const password = [_]u8{0x01} ** 32; const salt = [_]u8{0x02} ** 16; const secret = [_]u8{0x03} ** 8; const ad = [_]u8{0x04} ** 12; var dk: [32]u8 = undefined; try kdf( std.testing.allocator, &dk, &password, &salt, .{ .t = 3, .m = 32, .p = 4, .secret = &secret, .ad = &ad }, .argon2id, ); const want = [_]u8{ 0x0d, 0x64, 0x0d, 0xf5, 0x8d, 0x78, 0x76, 0x6c, 0x08, 0xc0, 0x37, 0xa3, 0x4a, 0x8b, 0x53, 0xc9, 0xd0, 0x1e, 0xf0, 0x45, 0x2d, 0x75, 0xb6, 0x5e, 0xb5, 0x25, 0x20, 0xe9, 0x6b, 0x01, 0xe6, 0x59, }; try std.testing.expectEqualSlices(u8, &dk, &want); } test "kdf" { const password = "password"; const salt = "<PASSWORD>"; const TestVector = struct { mode: Mode, time: u32, memory: u32, threads: u8, hash: []const u8, }; const test_vectors = [_]TestVector{ .{ .mode = .argon2i, .time = 1, .memory = 64, .threads = 1, .hash = "b9c401d1844a67d50eae3967dc28870b22e508092e861a37", }, .{ .mode = .argon2d, .time = 1, .memory = 64, .threads = 1, .hash = "8727405fd07c32c78d64f547f24150d3f2e703a89f981a19", }, .{ .mode = .argon2id, .time = 1, .memory = 64, .threads = 1, .hash = "655ad15eac652dc59f7170a7332bf49b8469be1fdb9c28bb", }, .{ .mode = .argon2i, .time = 2, .memory = 64, .threads = 1, .hash = "8cf3d8f76a6617afe35fac48eb0b7433a9a670ca4a07ed64", }, .{ .mode = .argon2d, .time = 2, .memory = 64, .threads = 1, .hash = "3be9ec79a69b75d3752acb59a1fbb8b295a46529c48fbb75", }, .{ .mode = .argon2id, .time = 2, .memory = 64, .threads = 1, .hash = "068d62b26455936aa6ebe60060b0a65870dbfa3ddf8d41f7", }, .{ .mode = .argon2i, .time = 2, .memory = 64, .threads = 2, .hash = "2089f3e78a799720f80af806553128f29b132cafe40d059f", }, .{ .mode = .argon2d, .time = 2, .memory = 64, .threads = 2, .hash = "68e2462c98b8bc6bb60ec68db418ae2c9ed24fc6748a40e9", }, .{ .mode = .argon2id, .time = 2, .memory = 64, .threads = 2, .hash = "350ac37222f436ccb5c0972f1ebd3bf6b958bf2071841362", }, .{ .mode = .argon2i, .time = 3, .memory = 256, .threads = 2, .hash = "f5bbf5d4c3836af13193053155b73ec7476a6a2eb93fd5e6", }, .{ .mode = .argon2d, .time = 3, .memory = 256, .threads = 2, .hash = "f4f0669218eaf3641f39cc97efb915721102f4b128211ef2", }, .{ .mode = .argon2id, .time = 3, .memory = 256, .threads = 2, .hash = "4668d30ac4187e6878eedeacf0fd83c5a0a30db2cc16ef0b", }, .{ .mode = .argon2i, .time = 4, .memory = 4096, .threads = 4, .hash = "a11f7b7f3f93f02ad4bddb59ab62d121e278369288a0d0e7", }, .{ .mode = .argon2d, .time = 4, .memory = 4096, .threads = 4, .hash = "935598181aa8dc2b720914aa6435ac8d3e3a4210c5b0fb2d", }, .{ .mode = .argon2id, .time = 4, .memory = 4096, .threads = 4, .hash = "145db9733a9f4ee43edf33c509be96b934d505a4efb33c5a", }, .{ .mode = .argon2i, .time = 4, .memory = 1024, .threads = 8, .hash = "0cdd3956aa35e6b475a7b0c63488822f774f15b43f6e6e17", }, .{ .mode = .argon2d, .time = 4, .memory = 1024, .threads = 8, .hash = "83604fc2ad0589b9d055578f4d3cc55bc616df3578a896e9", }, .{ .mode = .argon2id, .time = 4, .memory = 1024, .threads = 8, .hash = "8dafa8e004f8ea96bf7c0f93eecf67a6047476143d15577f", }, .{ .mode = .argon2i, .time = 2, .memory = 64, .threads = 3, .hash = "5cab452fe6b8479c8661def8cd703b611a3905a6d5477fe6", }, .{ .mode = .argon2d, .time = 2, .memory = 64, .threads = 3, .hash = "22474a423bda2ccd36ec9afd5119e5c8949798cadf659f51", }, .{ .mode = .argon2id, .time = 2, .memory = 64, .threads = 3, .hash = "4a15b31aec7c2590b87d1f520be7d96f56658172deaa3079", }, .{ .mode = .argon2i, .time = 3, .memory = 1024, .threads = 6, .hash = "d236b29c2b2a09babee842b0dec6aa1e83ccbdea8023dced", }, .{ .mode = .argon2d, .time = 3, .memory = 1024, .threads = 6, .hash = "a3351b0319a53229152023d9206902f4ef59661cdca89481", }, .{ .mode = .argon2id, .time = 3, .memory = 1024, .threads = 6, .hash = "1640b932f4b60e272f5d2207b9a9c626ffa1bd88d2349016", }, }; inline for (test_vectors) |v| { var want: [24]u8 = undefined; _ = try std.fmt.hexToBytes(&want, v.hash); var dk: [24]u8 = undefined; try kdf( std.testing.allocator, &dk, password, salt, .{ .t = v.time, .m = v.memory, .p = v.threads }, v.mode, ); try std.testing.expectEqualSlices(u8, &dk, &want); } } test "phc format hasher" { if (@import("builtin").zig_backend != .stage1) return error.SkipZigTest; // TODO const allocator = std.testing.allocator; const password = "<PASSWORD>"; var buf: [128]u8 = undefined; const hash = try PhcFormatHasher.create( allocator, password, .{ .t = 3, .m = 32, .p = 4 }, .argon2id, &buf, ); try PhcFormatHasher.verify(allocator, hash, password); } test "password hash and password verify" { if (@import("builtin").zig_backend != .stage1) return error.SkipZigTest; // TODO const allocator = std.testing.allocator; const password = "<PASSWORD>"; var buf: [128]u8 = undefined; const hash = try strHash( password, .{ .allocator = allocator, .params = .{ .t = 3, .m = 32, .p = 4 } }, &buf, ); try strVerify(hash, password, .{ .allocator = allocator }); } test "kdf derived key length" { const allocator = std.testing.allocator; const password = "<PASSWORD>"; const salt = "<PASSWORD>"; const params = Params{ .t = 3, .m = 32, .p = 4 }; const mode = Mode.argon2id; var dk1: [11]u8 = undefined; try kdf(allocator, &dk1, password, salt, params, mode); var dk2: [77]u8 = undefined; try kdf(allocator, &dk2, password, salt, params, mode); var dk3: [111]u8 = undefined; try kdf(allocator, &dk3, password, salt, params, mode); }
lib/std/crypto/argon2.zig
const std = @import("../std.zig"); const io = std.io; const mem = std.mem; const testing = std.testing; /// Creates a stream which supports 'un-reading' data, so that it can be read again. /// This makes look-ahead style parsing much easier. /// TODO merge this with `std.io.BufferedReader`: https://github.com/ziglang/zig/issues/4501 pub fn PeekStream( comptime buffer_type: std.fifo.LinearFifoBufferType, comptime ReaderType: type, ) type { return struct { unbuffered_in_stream: ReaderType, fifo: FifoType, pub const Error = ReaderType.Error; pub const Reader = io.Reader(*Self, Error, read); /// Deprecated: use `Reader` pub const InStream = Reader; const Self = @This(); const FifoType = std.fifo.LinearFifo(u8, buffer_type); pub usingnamespace switch (buffer_type) { .Static => struct { pub fn init(base: ReaderType) Self { return .{ .unbuffered_in_stream = base, .fifo = FifoType.init(), }; } }, .Slice => struct { pub fn init(base: ReaderType, buf: []u8) Self { return .{ .unbuffered_in_stream = base, .fifo = FifoType.init(buf), }; } }, .Dynamic => struct { pub fn init(base: ReaderType, allocator: *mem.Allocator) Self { return .{ .unbuffered_in_stream = base, .fifo = FifoType.init(allocator), }; } }, }; pub fn putBackByte(self: *Self, byte: u8) !void { try self.putBack(&[_]u8{byte}); } pub fn putBack(self: *Self, bytes: []const u8) !void { try self.fifo.unget(bytes); } pub fn read(self: *Self, dest: []u8) Error!usize { // copy over anything putBack()'d var dest_index = self.fifo.read(dest); if (dest_index == dest.len) return dest_index; // ask the backing stream for more dest_index += try self.unbuffered_in_stream.read(dest[dest_index..]); return dest_index; } pub fn reader(self: *Self) Reader { return .{ .context = self }; } /// Deprecated: use `reader` pub fn inStream(self: *Self) InStream { return .{ .context = self }; } }; } pub fn peekStream( comptime lookahead: comptime_int, underlying_stream: var, ) PeekStream(.{ .Static = lookahead }, @TypeOf(underlying_stream)) { return PeekStream(.{ .Static = lookahead }, @TypeOf(underlying_stream)).init(underlying_stream); } test "PeekStream" { const bytes = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8 }; var fbs = io.fixedBufferStream(&bytes); var ps = peekStream(2, fbs.reader()); var dest: [4]u8 = undefined; try ps.putBackByte(9); try ps.putBackByte(10); var read = try ps.reader().read(dest[0..4]); testing.expect(read == 4); testing.expect(dest[0] == 10); testing.expect(dest[1] == 9); testing.expect(mem.eql(u8, dest[2..4], bytes[0..2])); read = try ps.reader().read(dest[0..4]); testing.expect(read == 4); testing.expect(mem.eql(u8, dest[0..4], bytes[2..6])); read = try ps.reader().read(dest[0..4]); testing.expect(read == 2); testing.expect(mem.eql(u8, dest[0..2], bytes[6..8])); try ps.putBackByte(11); try ps.putBackByte(12); read = try ps.reader().read(dest[0..4]); testing.expect(read == 2); testing.expect(dest[0] == 12); testing.expect(dest[1] == 11); }
lib/std/io/peek_stream.zig
const std = @import("std"); const sabaton = @import("root").sabaton; const LoadType = enum { MakePageTables, LoadDataPages, }; const addr = u64; const off = u64; const half = u16; const word = u32; const xword = u64; pub const elf64hdr = packed struct { ident: [16]u8, elf_type: half, machine: half, version: word, entry: addr, phoff: off, shoff: off, flags: word, ehsize: half, phentsize: half, phnum: half, shentsize: half, shnum: half, shstrndx: half, }; pub const elf64shdr = packed struct { name: word, stype: word, flags: xword, vaddr: addr, offset: off, size: xword, link: word, info: word, addralign: xword, entsize: xword, }; pub const elf64phdr = packed struct { phtype: word, flags: word, offset: off, vaddr: addr, paddr: addr, filesz: xword, memsz: xword, alignment: xword, }; pub const Elf = struct { data: sabaton.platform.ElfType, shstrtab: ?[]u8 = undefined, pub fn init(self: *@This()) void { if(!std.mem.eql(u8, self.data[0..4], "\x7FELF")) { @panic("Invalid kernel ELF magic!"); } const shshstrtab = self.shdr(self.header().shstrndx); self.shstrtab = (self.data + shshstrtab.offset)[0..shshstrtab.size]; } pub fn section_name(self: *@This(), offset: usize) [*:0]u8 { return @ptrCast([*:0]u8, &self.shstrtab.?[offset]); } pub fn header(self: *@This()) *elf64hdr { return @ptrCast(*elf64hdr, self.data); } pub fn shdr(self: *@This(), num: usize) *elf64shdr { const h = self.header(); return @ptrCast(*elf64shdr, self.data + h.shoff + h.shentsize * num); } pub fn phdr(self: *@This(), num: usize) *elf64phdr { const h = self.header(); return @ptrCast(*elf64phdr, self.data + h.phoff + h.phentsize * num); } pub fn load_section(self: *@This(), name: []const u8, buf: []u8) !void { var snum: usize = 0; const h = self.header(); while(snum < h.shnum): (snum += 1) { const s = self.shdr(snum); const sname = self.section_name(s.name); if(std.mem.eql(u8, sname[0..name.len], name) and sname[name.len] == 0) { var load_size = s.size; if(load_size > buf.len) load_size = buf.len; @memcpy(buf.ptr, self.data + s.offset, load_size); return; // TODO: Relocations } } return error.HeaderNotFound; } pub fn load(self: *@This(), mempool_c: []align(4096) u8) void { const page_size = sabaton.platform.get_page_size(); var mempool = mempool_c; var phnum: usize = 0; const h = self.header(); while(phnum < h.phnum): (phnum += 1) { const ph = self.phdr(phnum); if(ph.phtype != 1) continue; if(sabaton.debug) { sabaton.log("Loading 0x{X} bytes at ELF offset 0x{X}\n", .{ph.filesz, ph.offset}); sabaton.log("Memory size is 0x{X} and is backed by physical memory at 0x{X}\n", .{ph.memsz, @ptrToInt(mempool.ptr)}); } @memcpy(mempool.ptr, self.data + ph.offset, ph.filesz); @memset(mempool.ptr + ph.filesz, 0, ph.memsz - ph.filesz); const perms = @intToEnum(sabaton.paging.Perms, @intCast(u3, ph.flags & 0x7)); sabaton.paging.map(ph.vaddr, @ptrToInt(mempool.ptr), ph.memsz, perms, .memory, null); // TODO: Relocations var used_bytes = ph.memsz; used_bytes += page_size - 1; used_bytes &= ~(page_size - 1); mempool.ptr = @alignCast(4096, mempool.ptr + used_bytes); mempool.len -= used_bytes; } if(sabaton.debug and mempool.len != 0) { sabaton.puts("Kernel overallocated??\n"); } } pub fn paged_bytes(self: *@This()) usize { const page_size = sabaton.platform.get_page_size(); var result: usize = 0; var phnum: usize = 0; const h = self.header(); while(phnum < h.phnum): (phnum += 1) { const ph = self.phdr(phnum); if(ph.phtype != 1) continue; result += ph.memsz; result += page_size - 1; result &= ~(page_size - 1); } return result; } pub fn entry(self: *@This()) usize { const h = self.header(); return h.entry; } };
src/lib/elf.zig
const std = @import("std"); const math = std.math; const mem = std.mem; const fmt = std.fmt; const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const ArrayList = std.ArrayList; const debug = std.debug; const range_set = @import("range_set.zig"); const ByteClassTemplates = range_set.ByteClassTemplates; /// A single class range (e.g. [a-z]). pub const ByteRange = range_set.Range(u8); /// Multiple class ranges (e.g. [a-z0-9]) pub const ByteClass = range_set.RangeSet(u8); /// Repeat sequence (e.g. +, *, ?, {m,n}) pub const Repeater = struct { // The sub-expression to repeat subexpr: *Expr, // Lower number of times to match min: usize, // Upper number of times to match (null -> infinite) max: ?usize, // Whether this matches greedily greedy: bool, }; /// A specific look-around assertion pub const Assertion = enum { // Always true assertion None, // ^ anchor, beginning of text (or line depending on mode) BeginLine, // $ anchor, beginning of text (or line dependening on mode) EndLine, // \A anchor, beginning of text BeginText, // \z anchor, end of text EndText, // \w anchor, word boundary ascii WordBoundaryAscii, // \W anchor, non-word boundary ascii NotWordBoundaryAscii, }; /// A single node of an expression tree. pub const Expr = union(enum) { // Empty match (\w assertion) EmptyMatch: Assertion, // A single character byte to match Literal: u8, // . character AnyCharNotNL, // Capture group Capture: *Expr, // *, +, ? Repeat: Repeater, // Character class [a-z0-9] ByteClass: ByteClass, // Concatenation Concat: ArrayList(*Expr), // | Alternate: ArrayList(*Expr), // Pseudo stack operator to define start of a capture PseudoLeftParen, pub fn isByteClass(re: *const Expr) bool { switch (re.*) { Expr.Literal, Expr.ByteClass, Expr.AnyCharNotNL, // TODO: Don't keep capture here, but allow on repeat operators. Expr.Capture, => return true, else => return false, } } }; // Private in fmt. fn charToDigit(c: u8, radix: u8) !u8 { const value = switch (c) { '0'...'9' => c - '0', 'A'...'Z' => c - 'A' + 10, 'a'...'z' => c - 'a' + 10, else => return error.InvalidChar, }; if (value >= radix) return error.InvalidChar; return value; } const StringIterator = struct { const Self = @This(); slice: []const u8, index: usize, pub fn init(s: []const u8) Self { return StringIterator{ .slice = s, .index = 0, }; } // Advance the stream and return the next token. pub fn next(it: *Self) ?u8 { if (it.index < it.slice.len) { const n = it.index; it.index += 1; return it.slice[n]; } else { return null; } } // Advance the stream. pub fn bump(it: *Self) void { if (it.index < it.slice.len) { it.index += 1; } } // Reset the stream back one character pub fn bumpBack(it: *Self) void { if (it.index > 0) { it.index -= 1; } } // Look at the nth character in the stream without advancing. fn peekAhead(it: *const Self, comptime n: usize) ?u8 { if (it.index + n < it.slice.len) { return it.slice[it.index + n]; } else { return null; } } // Return true if the next character in the stream is `ch`. pub fn peekNextIs(it: *const Self, ch: u8) bool { if (it.peekAhead(1)) |ok_ch| { return ok_ch == ch; } else { return false; } } // Look at the next character in the stream without advancing. pub fn peek(it: *const Self) ?u8 { return it.peekAhead(0); } // Return true if the next character in the stream is `ch`. pub fn peekIs(it: *const Self, ch: u8) bool { if (it.peek()) |ok_ch| { return ok_ch == ch; } else { return false; } } // Read an integer from the stream. Any non-digit characters stops the parsing chain. // // Error if no digits were read. // // TODO: Non character word-boundary instead? pub fn readInt(it: *Self, comptime T: type, comptime radix: u8) !T { return it.readIntN(T, radix, math.maxInt(usize)); } // Read an integer from the stream, limiting the read to N characters at most. pub fn readIntN(it: *Self, comptime T: type, comptime radix: u8, comptime N: usize) !T { const start = it.index; var i: usize = 0; while (it.peek()) |ch| : (i += 1) { if (i >= N) { break; } if (charToDigit(ch, radix)) |is_valid| { it.bump(); } else |_| { break; } } if (start != it.index) { return try fmt.parseUnsigned(T, it.slice[start..it.index], radix); } else { return error.NoIntegerRead; } } pub fn skipSpaces(it: *Self) void { while (it.peek()) |ok| { if (ok != ' ') return; it.bump(); } } }; pub const ParseError = error{ MissingRepeatOperand, MissingRepeatArgument, InvalidRepeatArgument, EmptyAlternate, UnbalancedParentheses, UnopenedParentheses, UnclosedParentheses, EmptyCaptureGroup, UnmatchedByteClass, StackUnderflow, InvalidRepeatRange, UnclosedRepeat, UnclosedBrackets, ExcessiveRepeatCount, OpenEscapeCode, UnclosedHexCharacterCode, InvalidHexDigit, InvalidOctalDigit, UnrecognizedEscapeCode, }; pub const ParserOptions = struct { // Upper limit on values allowed in a bounded expression (e.g. {500,1000}). // This must be bounded as these are unrolled by the engine into individual branches and // otherwise are a vector for memory exhaustion attacks. max_repeat_length: usize, pub fn default() ParserOptions { return ParserOptions{ .max_repeat_length = 1000 }; } }; /// Parser manages the parsing state and converts a regular expression string into an expression tree. /// /// The resulting expression is tied to the Parser which generated it. pub const Parser = struct { // Parse expression stack stack: ArrayList(*Expr), // ArenaAllocator for generating all expression nodes arena: ArenaAllocator, // Allocator for temporary lists/items allocator: *Allocator, // Configurable parser options options: ParserOptions, // Internal execution state. it: StringIterator, pub fn init(a: *Allocator) Parser { return initWithOptions(a, ParserOptions.default()); } pub fn initWithOptions(a: *Allocator, options: ParserOptions) Parser { return Parser{ .stack = ArrayList(*Expr).init(a), .arena = ArenaAllocator.init(a), .allocator = a, .options = options, .it = undefined, }; } pub fn deinit(p: *Parser) void { p.stack.deinit(); p.arena.deinit(); } pub fn reset(p: *Parser) void { p.stack.shrink(0); // Note: A shrink or reset on the ArenaAllocator would be nice. p.arena.deinit(); p.arena = ArenaAllocator.init(p.allocator); } fn popStack(p: *Parser) !*Expr { if (p.stack.items.len == 0) { return error.StackUnderflow; } return p.stack.pop(); } fn popByteClass(p: *Parser) !*Expr { const re1 = try p.popStack(); if (re1.isByteClass()) { return re1; } else { return error.MissingRepeatOperand; } } fn isPunctuation(c: u8) bool { return switch (c) { '\\', '.', '+', '*', '?', '(', ')', '|', '[', ']', '{', '}', '^', '$', '-' => true, else => false, }; } pub fn parse(p: *Parser, re: []const u8) !*Expr { p.it = StringIterator.init(re); // Shorter alias var it = &p.it; while (it.next()) |ch| { // TODO: Consolidate some of the same common patterns. switch (ch) { '*' => { try p.parseRepeat(0, null); }, '+' => { try p.parseRepeat(1, null); }, '?' => { try p.parseRepeat(0, 1); }, '{' => { it.skipSpaces(); const min = it.readInt(usize, 10) catch return error.InvalidRepeatArgument; var max: ?usize = min; it.skipSpaces(); if (it.peekIs(',')) { it.bump(); it.skipSpaces(); // {m,} case with infinite upper bound if (it.peekIs('}')) { max = null; } // {m,n} case with explicit bounds else { max = it.readInt(usize, 10) catch return error.InvalidRepeatArgument; if (max.? < min) { return error.InvalidRepeatRange; } } } it.skipSpaces(); if (!it.peekIs('}')) { return error.UnclosedRepeat; } it.bump(); // We limit repeat counts to overoad arbitrary memory blowup during compilation const limit = p.options.max_repeat_length; if (min > limit or max != null and max.? > limit) { return error.ExcessiveRepeatCount; } try p.parseRepeat(min, max); }, '.' => { var r = try p.arena.allocator.create(Expr); r.* = Expr{ .AnyCharNotNL = undefined }; try p.stack.append(r); }, '[' => { try p.parseCharClass(); }, // Don't handle alternation just yet, parentheses group together arguments into // a sub-expression only. '(' => { var r = try p.arena.allocator.create(Expr); r.* = Expr{ .PseudoLeftParen = undefined }; try p.stack.append(r); }, ')' => { // Pop the stack until. // // - Empty, error unopened parenthesis. // - ( pseudo operator, push a group expression of the concat // - '|' pop and add the concat to the alternation list. Pop one more item // after which must be a opening parenthesis. // // '|' ensures there will be only one alternation on the stack here. var concat = ArrayList(*Expr).init(p.allocator); while (true) { // would underflow, push a new alternation if (p.stack.items.len == 0) { return error.UnopenedParentheses; } const e = p.stack.pop(); switch (e.*) { // Existing alternation Expr.Alternate => { mem.reverse(*Expr, concat.items); var ra = try p.arena.allocator.create(Expr); if (concat.items.len == 1) { ra.* = concat.items[0].*; } else { ra.* = Expr{ .Concat = concat }; } // append to the alternation stack try e.Alternate.append(ra); if (p.stack.items.len == 0) { return error.UnopenedParentheses; } // pop the left parentheses that must now exist debug.assert(p.stack.pop().* == Expr.PseudoLeftParen); var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Capture = e }; try p.stack.append(r); break; }, // Existing parentheses, push new alternation Expr.PseudoLeftParen => { mem.reverse(*Expr, concat.items); var ra = try p.arena.allocator.create(Expr); ra.* = Expr{ .Concat = concat }; if (concat.items.len == 0) { return error.EmptyCaptureGroup; } else if (concat.items.len == 1) { ra.* = concat.items[0].*; } else { ra.* = Expr{ .Concat = concat }; } var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Capture = ra }; try p.stack.append(r); break; }, // New expression, push onto concat stack else => { try concat.append(e); }, } } }, '|' => { // Pop the stack until. // // - Empty, then push the sub-expression as a concat. // - ( pseudo operator, leave '(' and push concat. // - '|' is found, pop the existing and add a new alternation to the array. var concat = ArrayList(*Expr).init(p.allocator); if (p.stack.items.len == 0 or !p.stack.items[p.stack.items.len - 1].isByteClass()) { return error.EmptyAlternate; } while (true) { // would underflow, push a new alternation if (p.stack.items.len == 0) { // We need to create a single expr node for the alternation. var ra = try p.arena.allocator.create(Expr); mem.reverse(*Expr, concat.items); if (concat.items.len == 1) { ra.* = concat.items[0].*; } else { ra.* = Expr{ .Concat = concat }; } var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Alternate = ArrayList(*Expr).init(p.allocator) }; try r.Alternate.append(ra); try p.stack.append(r); break; } const e = p.stack.pop(); switch (e.*) { // Existing alternation, combine Expr.Alternate => { mem.reverse(*Expr, concat.items); var ra = try p.arena.allocator.create(Expr); if (concat.items.len == 1) { ra.* = concat.items[0].*; } else { ra.* = Expr{ .Concat = concat }; } // use the expression itself try e.Alternate.append(ra); try p.stack.append(e); break; }, // Existing parentheses, push new alternation Expr.PseudoLeftParen => { // re-push parentheses marker try p.stack.append(e); mem.reverse(*Expr, concat.items); var ra = try p.arena.allocator.create(Expr); if (concat.items.len == 1) { ra.* = concat.items[0].*; } else { ra.* = Expr{ .Concat = concat }; } var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Alternate = ArrayList(*Expr).init(p.allocator) }; try r.Alternate.append(ra); try p.stack.append(r); break; }, // New expression, push onto concat stack else => { try concat.append(e); }, } } }, '\\' => { const r = try p.parseEscape(); try p.stack.append(r); }, '^' => { var r = try p.arena.allocator.create(Expr); r.* = Expr{ .EmptyMatch = Assertion.BeginLine }; try p.stack.append(r); }, '$' => { var r = try p.arena.allocator.create(Expr); r.* = Expr{ .EmptyMatch = Assertion.EndLine }; try p.stack.append(r); }, else => { try p.parseLiteral(ch); }, } } // special case empty item if (p.stack.items.len == 0) { var r = try p.arena.allocator.create(Expr); r.* = Expr{ .EmptyMatch = Assertion.None }; return r; } // special case single item to avoid top-level concat for simple. if (p.stack.items.len == 1) { return p.stack.pop(); } // finish a concatenation result // // This pops items off the stack and concatenates them until: // // - The stack is empty (the items are concat and pushed and the single result is returned). // - An alternation is seen, this is popped and the current concat state is pushed as an // alternation item. // // After any of these cases, the stack must be empty. // // There can be no parentheses left on the stack during this popping. var concat = ArrayList(*Expr).init(p.allocator); while (true) { if (p.stack.items.len == 0) { // concat the items in reverse order and return mem.reverse(*Expr, concat.items); var r = try p.arena.allocator.create(Expr); if (concat.items.len == 1) { r.* = concat.items[0].*; } else { r.* = Expr{ .Concat = concat }; } return r; } // pop an item, check if it is an alternate and not a pseudo left paren const e = p.stack.pop(); switch (e.*) { Expr.PseudoLeftParen => { return error.UnclosedParentheses; }, // Alternation at top-level, push concat and return Expr.Alternate => { mem.reverse(*Expr, concat.items); var ra = try p.arena.allocator.create(Expr); if (concat.items.len == 1) { ra.* = concat.items[0].*; } else { ra.* = Expr{ .Concat = concat }; } // use the expression itself try e.Alternate.append(ra); // if stack is not empty, this is an error if (p.stack.items.len != 0) { switch (p.stack.pop().*) { Expr.PseudoLeftParen => return error.UnclosedParentheses, else => unreachable, } } return e; }, // New expression, push onto concat stack else => { try concat.append(e); }, } } } fn parseLiteral(p: *Parser, ch: u8) !void { var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Literal = ch }; try p.stack.append(r); } fn parseRepeat(p: *Parser, min: usize, max: ?usize) !void { var greedy = true; if (p.it.peekIs('?')) { p.it.bump(); greedy = false; } const sub_expr = p.popByteClass() catch return error.MissingRepeatOperand; const repeat = Repeater{ .subexpr = sub_expr, .min = min, .max = max, .greedy = greedy, }; var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Repeat = repeat }; try p.stack.append(r); } // NOTE: We don't handle needed character classes. fn parseCharClass(p: *Parser) !void { var it = &p.it; var class = ByteClass.init(p.allocator); var negate = false; if (it.peekIs('^')) { it.bump(); negate = true; } // First '[' in a multi-class is always treated as a literal. This disallows // the empty byte-set '[]'. if (it.peekIs(']')) { it.bump(); const range = ByteRange{ .min = ']', .max = ']' }; try class.addRange(range); } while (!it.peekIs(']')) : (it.bump()) { if (it.peek() == null) { return error.UnclosedBrackets; } const chp = it.peek().?; // If this is a byte-class escape, we cannot expect an '-' range after it. // Accept the following - as a literal (may be bad behaviour). // // If it is not, then we can and it is fine. var range: ByteRange = undefined; if (chp == '\\') { it.bump(); // parseEscape returns a literal or byteclass so reformat var r = try p.parseEscape(); // NOTE: this is bumped on loop it.index -= 1; switch (r.*) { Expr.Literal => |value| { range = ByteRange{ .min = value, .max = value }; }, Expr.ByteClass => |vv| { // '-' doesn't make sense following this, merge class here // and continue next. try class.mergeClass(vv); continue; }, else => unreachable, } } else { range = ByteRange{ .min = chp, .max = chp }; } // is this a range? if (it.peekNextIs('-')) { it.bump(); it.bump(); if (it.peek() == null) { return error.UnclosedBrackets; } else if (it.peekIs(']')) { // treat the '-' as a literal instead it.index -= 1; } else { range.max = it.peek().?; } } try class.addRange(range); } it.bump(); if (negate) { try class.negate(); } var r = try p.arena.allocator.create(Expr); r.* = Expr{ .ByteClass = class }; try p.stack.append(r); } fn parseEscape(p: *Parser) !*Expr { const ch = p.it.next() orelse return error.OpenEscapeCode; if (isPunctuation(ch)) { var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Literal = ch }; return r; } switch (ch) { // escape chars 'a' => { var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Literal = '\x07' }; return r; }, 'f' => { var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Literal = '\x0c' }; return r; }, 'n' => { var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Literal = '\n' }; return r; }, 'r' => { var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Literal = '\r' }; return r; }, 't' => { var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Literal = '\t' }; return r; }, 'v' => { var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Literal = '\x0b' }; return r; }, // perl codes 's' => { var s = try ByteClassTemplates.Whitespace(p.allocator); var r = try p.arena.allocator.create(Expr); r.* = Expr{ .ByteClass = s }; return r; }, 'S' => { var s = try ByteClassTemplates.NonWhitespace(p.allocator); var r = try p.arena.allocator.create(Expr); r.* = Expr{ .ByteClass = s }; return r; }, 'w' => { var s = try ByteClassTemplates.AlphaNumeric(p.allocator); var r = try p.arena.allocator.create(Expr); r.* = Expr{ .ByteClass = s }; return r; }, 'W' => { var s = try ByteClassTemplates.NonAlphaNumeric(p.allocator); var r = try p.arena.allocator.create(Expr); r.* = Expr{ .ByteClass = s }; return r; }, 'd' => { var s = try ByteClassTemplates.Digits(p.allocator); var r = try p.arena.allocator.create(Expr); r.* = Expr{ .ByteClass = s }; return r; }, 'D' => { var s = try ByteClassTemplates.NonDigits(p.allocator); var r = try p.arena.allocator.create(Expr); r.* = Expr{ .ByteClass = s }; return r; }, '0'...'9' => { p.it.bumpBack(); // octal integer up to 3 digits, always succeeds since we have at least one digit // TODO: u32 codepoint and not u8 const value = p.it.readIntN(u8, 8, 3) catch return error.InvalidOctalDigit; var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Literal = value }; return r; }, 'x' => { p.it.skipSpaces(); // '\x{2423} if (p.it.peekIs('{')) { p.it.bump(); // TODO: u32 codepoint and not u8 const value = p.it.readInt(u8, 16) catch return error.InvalidHexDigit; // TODO: Check range as well and if valid unicode codepoint if (!p.it.peekIs('}')) { return error.UnclosedHexCharacterCode; } p.it.bump(); var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Literal = value }; return r; } // '\x23 else { const value = p.it.readIntN(u8, 16, 2) catch return error.InvalidHexDigit; var r = try p.arena.allocator.create(Expr); r.* = Expr{ .Literal = value }; return r; } }, else => { return error.UnrecognizedEscapeCode; }, } } };
src/parse.zig
const std = @import("std"); /// Super simple "perfect hash" algorithm /// Only really useful for switching on strings // TODO: can we auto detect and promote the underlying type? pub fn Swhash(comptime max_bytes: comptime_int) type { const T = std.meta.Int(.unsigned, max_bytes * 8); return struct { pub fn match(string: []const u8) T { return hash(string) orelse std.math.maxInt(T); } pub fn case(comptime string: []const u8) T { return hash(string) orelse @compileError("Cannot hash '" ++ string ++ "'"); } fn hash(string: []const u8) ?T { if (string.len > max_bytes) return null; var tmp = [_]u8{0} ** max_bytes; std.mem.copy(u8, &tmp, string); return std.mem.readIntNative(T, &tmp); } }; } pub fn boolMatcher(comptime size: comptime_int) @TypeOf(BoolMatcher(size).m) { return BoolMatcher(size).m; } pub fn BoolMatcher(comptime size: comptime_int) type { const T = std.meta.Int(.unsigned, size); return struct { pub fn m(array: [size]bool) T { var result: T = 0; comptime var i = 0; inline while (i < size) : (i += 1) { result |= @as(T, @boolToInt(array[i])) << i; } return result; } }; } fn ReturnOf(comptime func: anytype) type { return @typeInfo(@TypeOf(func)).Fn.return_type.?; } pub fn Mailbox(comptime T: type, size: usize) type { return struct { const Self = @This(); const Queue = std.fifo.LinearFifo(T, .{ .Static = size }); queue: Queue = Queue.init(), qutex: std.Thread.Mutex = .{}, cond: std.Thread.Condition = .{}, mutex: std.Thread.Mutex = .{}, pub fn get(self: *Self) T { self.mutex.lock(); defer self.mutex.unlock(); const ready_value = blk: { self.qutex.lock(); defer self.qutex.unlock(); break :blk self.queue.readItem(); }; return ready_value orelse { self.cond.wait(&self.mutex); self.qutex.lock(); defer self.qutex.unlock(); return self.queue.readItem().?; }; } pub fn getWithTimeout(self: *Self, timeout_ns: u64) ?T { self.mutex.lock(); defer self.mutex.unlock(); const ready_value = blk: { self.qutex.lock(); defer self.qutex.unlock(); break :blk self.queue.readItem(); }; return ready_value orelse { const future_ns = std.time.nanoTimestamp() + timeout_ns; var future: std.os.timespec = undefined; future.tv_sec = @intCast(@TypeOf(future.tv_sec), @divFloor(future_ns, std.time.ns_per_s)); future.tv_nsec = @intCast(@TypeOf(future.tv_nsec), @mod(future_ns, std.time.ns_per_s)); const rc = std.os.system.pthread_cond_timedwait(&self.cond.impl.cond, &self.mutex.impl.pthread_mutex, &future); std.debug.assert(rc == 0 or rc == std.os.system.ETIMEDOUT); return self.queue.readItem(); }; } pub fn putOverwrite(self: *Self, value: T) ?T { self.qutex.lock(); defer self.qutex.unlock(); const existing = if (self.queue.ensureUnusedCapacity(1)) null else |err| switch (err) { error.OutOfMemory => self.queue.readItem(), }; self.queue.writeItemAssumeCapacity(value); self.cond.impl.signal(); return existing; } }; } pub fn mapSigaction(comptime T: type) void { inline for (std.meta.declarations(T)) |decl| { std.os.sigaction( @field(std.os.SIG, decl.name), &std.os.Sigaction{ .handler = .{ .handler = @field(T, decl.name) }, .mask = std.os.empty_sigset, .flags = std.os.SA.NODEFER, }, null, ); } } pub const PoolString = struct { next: ?*PoolString, array: std.BoundedArray(u8, 0x1000), var root: ?*PoolString = null; var scratch: [16]PoolString = undefined; pub fn create() !*PoolString { const node = root orelse return error.OutOfMemory; node.array.len = 0; root = node.next; return node; } pub fn destroy(self: *PoolString) void { self.next = root; root = self; } pub fn prefill() void { for (scratch) |*string| { destroy(string); } } };
src/util.zig
const main = @import("main.zig"); const vectors = @import("vectors.zig"); const uart = @import("uart.zig"); pub export fn _start() callconv(.Naked) noreturn { // At startup the stack pointer is at the end of RAM // so, no need to set it manually! // Reference this such that the file is analyzed and the vectors // are added. _ = vectors; copy_data_to_ram(); clear_bss(); main.main(); while (true) {} } fn copy_data_to_ram() void { asm volatile ( \\ ; load Z register with the address of the data in flash \\ ldi r30, lo8(__data_load_start) \\ ldi r31, hi8(__data_load_start) \\ ; load X register with address of the data in ram \\ ldi r26, lo8(__data_start) \\ ldi r27, hi8(__data_start) \\ ; load address of end of the data in ram \\ ldi r24, lo8(__data_end) \\ ldi r25, hi8(__data_end) \\ rjmp .L2 \\ \\.L1: \\ lpm r18, Z+ ; copy from Z into r18 and increment Z \\ st X+, r18 ; store r18 at location X and increment X \\ \\.L2: \\ cp r26, r24 \\ cpc r27, r25 ; check and branch if we are at the end of data \\ brne .L1 ); // Probably a good idea to add clobbers here, but compiler doesn't seem to care } fn clear_bss() void { asm volatile ( \\ ; load X register with the beginning of bss section \\ ldi r26, lo8(__bss_start) \\ ldi r27, hi8(__bss_start) \\ ; load end of the bss in registers \\ ldi r24, lo8(__bss_end) \\ ldi r25, hi8(__bss_end) \\ ldi r18, 0x00 \\ rjmp .L4 \\ \\.L3: \\ st X+, r18 \\ \\.L4: \\ cp r26, r24 \\ cpc r27, r25 ; check and branch if we are at the end of bss \\ brne .L3 ); // Probably a good idea to add clobbers here, but compiler doesn't seem to care } pub fn panic(msg: []const u8, error_return_trace: ?*@import("std").builtin.StackTrace) noreturn { // Currently assumes that the uart is initialized in main(). uart.write("PANIC: "); uart.write(msg); // TODO: print stack trace (addresses), which can than be turned into actual source line // numbers on the connected machine. while (true) {} }
src/start.zig
const std = @import("std"); pub fn Pkg(srcdir: []const u8) type { return struct { pub fn addRaylib(b: *std.build.Builder, target: std.zig.CrossTarget) *std.build.LibExeObjStep { // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const raylib_flags = &[_][]const u8{ "-std=gnu99", "-DPLATFORM_DESKTOP", "-DGL_SILENCE_DEPRECATION=199309L", "-fno-sanitize=undefined", // https://github.com/raysan5/raylib/issues/1891 }; const raylib = b.addStaticLibrary("raylib", srcdir ++ "/raylib.h"); raylib.setTarget(target); raylib.setBuildMode(mode); raylib.linkLibC(); raylib.addIncludeDir(srcdir ++ "/external/glfw/include"); raylib.addCSourceFiles(&.{ srcdir ++ "/raudio.c", srcdir ++ "/rcore.c", srcdir ++ "/rmodels.c", srcdir ++ "/rshapes.c", srcdir ++ "/rtext.c", srcdir ++ "/rtextures.c", srcdir ++ "/utils.c", }, raylib_flags); switch (raylib.target.toTarget().os.tag) { .windows => { raylib.addCSourceFiles(&.{srcdir ++ "/rglfw.c"}, raylib_flags); raylib.linkSystemLibrary("winmm"); raylib.linkSystemLibrary("gdi32"); raylib.linkSystemLibrary("opengl32"); raylib.addIncludeDir("external/glfw/deps/mingw"); }, .linux => { raylib.addCSourceFiles(&.{srcdir ++ "/rglfw.c"}, raylib_flags); raylib.linkSystemLibrary("GL"); raylib.linkSystemLibrary("rt"); raylib.linkSystemLibrary("dl"); raylib.linkSystemLibrary("m"); raylib.linkSystemLibrary("X11"); }, .freebsd, .openbsd, .netbsd, .dragonfly => { raylib.addCSourceFiles(&.{srcdir ++ "/rglfw.c"}, raylib_flags); raylib.linkSystemLibrary("GL"); raylib.linkSystemLibrary("rt"); raylib.linkSystemLibrary("dl"); raylib.linkSystemLibrary("m"); raylib.linkSystemLibrary("X11"); raylib.linkSystemLibrary("Xrandr"); raylib.linkSystemLibrary("Xinerama"); raylib.linkSystemLibrary("Xi"); raylib.linkSystemLibrary("Xxf86vm"); raylib.linkSystemLibrary("Xcursor"); }, .macos => { // On macos rglfw.c include Objective-C files. const raylib_flags_extra_macos = &[_][]const u8{ "-ObjC", }; raylib.addCSourceFiles( &.{srcdir ++ "/rglfw.c"}, raylib_flags ++ raylib_flags_extra_macos, ); raylib.linkFramework("Foundation"); }, else => { @panic("Unsupported OS"); }, } raylib.setOutputDir("./"); raylib.install(); return raylib; } }; } const lib = Pkg("."); pub fn build(b: *std.build.Builder) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); _ = lib.addRaylib(b, target); }
src/build.zig
pub const GPM_USE_PDC = @as(u32, 0); pub const GPM_USE_ANYDC = @as(u32, 1); pub const GPM_DONOTUSE_W2KDC = @as(u32, 2); pub const GPM_DONOT_VALIDATEDC = @as(u32, 1); pub const GPM_MIGRATIONTABLE_ONLY = @as(u32, 1); pub const GPM_PROCESS_SECURITY = @as(u32, 2); pub const RSOP_NO_COMPUTER = @as(u32, 65536); pub const RSOP_NO_USER = @as(u32, 131072); pub const RSOP_PLANNING_ASSUME_SLOW_LINK = @as(u32, 1); pub const RSOP_PLANNING_ASSUME_LOOPBACK_MERGE = @as(u32, 2); pub const RSOP_PLANNING_ASSUME_LOOPBACK_REPLACE = @as(u32, 4); pub const RSOP_PLANNING_ASSUME_USER_WQLFILTER_TRUE = @as(u32, 8); pub const RSOP_PLANNING_ASSUME_COMP_WQLFILTER_TRUE = @as(u32, 16); pub const PI_NOUI = @as(u32, 1); pub const PI_APPLYPOLICY = @as(u32, 2); pub const PT_TEMPORARY = @as(u32, 1); pub const PT_ROAMING = @as(u32, 2); pub const PT_MANDATORY = @as(u32, 4); pub const PT_ROAMING_PREEXISTING = @as(u32, 8); pub const RP_FORCE = @as(u32, 1); pub const RP_SYNC = @as(u32, 2); pub const GPC_BLOCK_POLICY = @as(u32, 1); pub const GPO_FLAG_DISABLE = @as(u32, 1); pub const GPO_FLAG_FORCE = @as(u32, 2); pub const GPO_LIST_FLAG_MACHINE = @as(u32, 1); pub const GPO_LIST_FLAG_SITEONLY = @as(u32, 2); pub const GPO_LIST_FLAG_NO_WMIFILTERS = @as(u32, 4); pub const GPO_LIST_FLAG_NO_SECURITYFILTERS = @as(u32, 8); pub const GPO_INFO_FLAG_MACHINE = @as(u32, 1); pub const GPO_INFO_FLAG_BACKGROUND = @as(u32, 16); pub const GPO_INFO_FLAG_SLOWLINK = @as(u32, 32); pub const GPO_INFO_FLAG_VERBOSE = @as(u32, 64); pub const GPO_INFO_FLAG_NOCHANGES = @as(u32, 128); pub const GPO_INFO_FLAG_LINKTRANSITION = @as(u32, 256); pub const GPO_INFO_FLAG_LOGRSOP_TRANSITION = @as(u32, 512); pub const GPO_INFO_FLAG_FORCED_REFRESH = @as(u32, 1024); pub const GPO_INFO_FLAG_SAFEMODE_BOOT = @as(u32, 2048); pub const GPO_INFO_FLAG_ASYNC_FOREGROUND = @as(u32, 4096); pub const FLAG_NO_GPO_FILTER = @as(u32, 2147483648); pub const FLAG_NO_CSE_INVOKE = @as(u32, 1073741824); pub const FLAG_ASSUME_SLOW_LINK = @as(u32, 536870912); pub const FLAG_LOOPBACK_MERGE = @as(u32, 268435456); pub const FLAG_LOOPBACK_REPLACE = @as(u32, 134217728); pub const FLAG_ASSUME_USER_WQLFILTER_TRUE = @as(u32, 67108864); pub const FLAG_ASSUME_COMP_WQLFILTER_TRUE = @as(u32, 33554432); pub const FLAG_PLANNING_MODE = @as(u32, 16777216); pub const FLAG_NO_USER = @as(u32, 1); pub const FLAG_NO_COMPUTER = @as(u32, 2); pub const FLAG_FORCE_CREATENAMESPACE = @as(u32, 4); pub const RSOP_USER_ACCESS_DENIED = @as(u32, 1); pub const RSOP_COMPUTER_ACCESS_DENIED = @as(u32, 2); pub const RSOP_TEMPNAMESPACE_EXISTS = @as(u32, 4); pub const LOCALSTATE_ASSIGNED = @as(u32, 1); pub const LOCALSTATE_PUBLISHED = @as(u32, 2); pub const LOCALSTATE_UNINSTALL_UNMANAGED = @as(u32, 4); pub const LOCALSTATE_POLICYREMOVE_ORPHAN = @as(u32, 8); pub const LOCALSTATE_POLICYREMOVE_UNINSTALL = @as(u32, 16); pub const LOCALSTATE_ORPHANED = @as(u32, 32); pub const LOCALSTATE_UNINSTALLED = @as(u32, 64); pub const MANAGED_APPS_USERAPPLICATIONS = @as(u32, 1); pub const MANAGED_APPS_FROMCATEGORY = @as(u32, 2); pub const MANAGED_APPS_INFOLEVEL_DEFAULT = @as(u32, 65536); pub const MANAGED_APPTYPE_WINDOWSINSTALLER = @as(u32, 1); pub const MANAGED_APPTYPE_SETUPEXE = @as(u32, 2); pub const MANAGED_APPTYPE_UNSUPPORTED = @as(u32, 3); pub const CLSID_GPESnapIn = Guid.initString("8fc0b734-a0e1-11d1-a7d3-0000f87571e3"); pub const NODEID_Machine = Guid.initString("8fc0b737-a0e1-11d1-a7d3-0000f87571e3"); pub const NODEID_MachineSWSettings = Guid.initString("8fc0b73a-a0e1-11d1-a7d3-0000f87571e3"); pub const NODEID_User = Guid.initString("8fc0b738-a0e1-11d1-a7d3-0000f87571e3"); pub const NODEID_UserSWSettings = Guid.initString("8fc0b73c-a0e1-11d1-a7d3-0000f87571e3"); pub const CLSID_GroupPolicyObject = Guid.initString("ea502722-a23d-11d1-a7d3-0000f87571e3"); pub const CLSID_RSOPSnapIn = Guid.initString("6dc3804b-7212-458d-adb0-9a07e2ae1fa2"); pub const NODEID_RSOPMachine = Guid.initString("bd4c1a2e-0b7a-4a62-a6b0-c0577539c97e"); pub const NODEID_RSOPMachineSWSettings = Guid.initString("6a76273e-eb8e-45db-94c5-25663a5f2c1a"); pub const NODEID_RSOPUser = Guid.initString("ab87364f-0cec-4cd8-9bf8-898f34628fb8"); pub const NODEID_RSOPUserSWSettings = Guid.initString("e52c5ce3-fd27-4402-84de-d9a5f2858910"); pub const GPO_SECTION_ROOT = @as(u32, 0); pub const GPO_SECTION_USER = @as(u32, 1); pub const GPO_SECTION_MACHINE = @as(u32, 2); pub const GPO_OPEN_LOAD_REGISTRY = @as(u32, 1); pub const GPO_OPEN_READ_ONLY = @as(u32, 2); pub const GPO_OPTION_DISABLE_USER = @as(u32, 1); pub const GPO_OPTION_DISABLE_MACHINE = @as(u32, 2); pub const RSOP_INFO_FLAG_DIAGNOSTIC_MODE = @as(u32, 1); pub const GPO_BROWSE_DISABLENEW = @as(u32, 1); pub const GPO_BROWSE_NOCOMPUTERS = @as(u32, 2); pub const GPO_BROWSE_NODSGPOS = @as(u32, 4); pub const GPO_BROWSE_OPENBUTTON = @as(u32, 8); pub const GPO_BROWSE_INITTOALL = @as(u32, 16); pub const GPO_BROWSE_NOUSERGPOS = @as(u32, 32); pub const GPO_BROWSE_SENDAPPLYONEDIT = @as(u32, 64); //-------------------------------------------------------------------------------- // Section: Types (109) //-------------------------------------------------------------------------------- // TODO: this type has a FreeFunc 'LeaveCriticalPolicySection', what can Zig do with this information? pub const CriticalPolicySectionHandle = isize; const CLSID_GPM_Value = @import("../zig.zig").Guid.initString("f5694708-88fe-4b35-babf-e56162d5fbc8"); pub const CLSID_GPM = &CLSID_GPM_Value; const CLSID_GPMDomain_Value = @import("../zig.zig").Guid.initString("710901be-1050-4cb1-838a-c5cff259e183"); pub const CLSID_GPMDomain = &CLSID_GPMDomain_Value; const CLSID_GPMSitesContainer_Value = @import("../zig.zig").Guid.initString("229f5c42-852c-4b30-945f-c522be9bd386"); pub const CLSID_GPMSitesContainer = &CLSID_GPMSitesContainer_Value; const CLSID_GPMBackupDir_Value = @import("../zig.zig").Guid.initString("fce4a59d-0f21-4afa-b859-e6d0c62cd10c"); pub const CLSID_GPMBackupDir = &CLSID_GPMBackupDir_Value; const CLSID_GPMSOM_Value = @import("../zig.zig").Guid.initString("32d93fac-450e-44cf-829c-8b22ff6bdae1"); pub const CLSID_GPMSOM = &CLSID_GPMSOM_Value; const CLSID_GPMSearchCriteria_Value = @import("../zig.zig").Guid.initString("17aaca26-5ce0-44fa-8cc0-5259e6483566"); pub const CLSID_GPMSearchCriteria = &CLSID_GPMSearchCriteria_Value; const CLSID_GPMPermission_Value = @import("../zig.zig").Guid.initString("5871a40a-e9c0-46ec-913e-944ef9225a94"); pub const CLSID_GPMPermission = &CLSID_GPMPermission_Value; const CLSID_GPMSecurityInfo_Value = @import("../zig.zig").Guid.initString("547a5e8f-9162-4516-a4df-9ddb9686d846"); pub const CLSID_GPMSecurityInfo = &CLSID_GPMSecurityInfo_Value; const CLSID_GPMBackup_Value = @import("../zig.zig").Guid.initString("ed1a54b8-5efa-482a-93c0-8ad86f0d68c3"); pub const CLSID_GPMBackup = &CLSID_GPMBackup_Value; const CLSID_GPMBackupCollection_Value = @import("../zig.zig").Guid.initString("eb8f035b-70db-4a9f-9676-37c25994e9dc"); pub const CLSID_GPMBackupCollection = &CLSID_GPMBackupCollection_Value; const CLSID_GPMSOMCollection_Value = @import("../zig.zig").Guid.initString("24c1f147-3720-4f5b-a9c3-06b4e4f931d2"); pub const CLSID_GPMSOMCollection = &CLSID_GPMSOMCollection_Value; const CLSID_GPMWMIFilter_Value = @import("../zig.zig").Guid.initString("626745d8-0dea-4062-bf60-cfc5b1ca1286"); pub const CLSID_GPMWMIFilter = &CLSID_GPMWMIFilter_Value; const CLSID_GPMWMIFilterCollection_Value = @import("../zig.zig").Guid.initString("74dc6d28-e820-47d6-a0b8-f08d93d7fa33"); pub const CLSID_GPMWMIFilterCollection = &CLSID_GPMWMIFilterCollection_Value; const CLSID_GPMRSOP_Value = @import("../zig.zig").Guid.initString("489b0caf-9ec2-4eb7-91f5-b6f71d43da8c"); pub const CLSID_GPMRSOP = &CLSID_GPMRSOP_Value; const CLSID_GPMGPO_Value = @import("../zig.zig").Guid.initString("d2ce2994-59b5-4064-b581-4d68486a16c4"); pub const CLSID_GPMGPO = &CLSID_GPMGPO_Value; const CLSID_GPMGPOCollection_Value = @import("../zig.zig").Guid.initString("7a057325-832d-4de3-a41f-c780436a4e09"); pub const CLSID_GPMGPOCollection = &CLSID_GPMGPOCollection_Value; const CLSID_GPMGPOLink_Value = @import("../zig.zig").Guid.initString("c1df9880-5303-42c6-8a3c-0488e1bf7364"); pub const CLSID_GPMGPOLink = &CLSID_GPMGPOLink_Value; const CLSID_GPMGPOLinksCollection_Value = @import("../zig.zig").Guid.initString("f6ed581a-49a5-47e2-b771-fd8dc02b6259"); pub const CLSID_GPMGPOLinksCollection = &CLSID_GPMGPOLinksCollection_Value; const CLSID_GPMAsyncCancel_Value = @import("../zig.zig").Guid.initString("372796a9-76ec-479d-ad6c-556318ed5f9d"); pub const CLSID_GPMAsyncCancel = &CLSID_GPMAsyncCancel_Value; const CLSID_GPMStatusMsgCollection_Value = @import("../zig.zig").Guid.initString("2824e4be-4bcc-4cac-9e60-0e3ed7f12496"); pub const CLSID_GPMStatusMsgCollection = &CLSID_GPMStatusMsgCollection_Value; const CLSID_GPMStatusMessage_Value = @import("../zig.zig").Guid.initString("4b77cc94-d255-409b-bc62-370881715a19"); pub const CLSID_GPMStatusMessage = &CLSID_GPMStatusMessage_Value; const CLSID_GPMTrustee_Value = @import("../zig.zig").Guid.initString("c54a700d-19b6-4211-bcb0-e8e2475e471e"); pub const CLSID_GPMTrustee = &CLSID_GPMTrustee_Value; const CLSID_GPMClientSideExtension_Value = @import("../zig.zig").Guid.initString("c1a2e70e-659c-4b1a-940b-f88b0af9c8a4"); pub const CLSID_GPMClientSideExtension = &CLSID_GPMClientSideExtension_Value; const CLSID_GPMCSECollection_Value = @import("../zig.zig").Guid.initString("cf92b828-2d44-4b61-b10a-b327afd42da8"); pub const CLSID_GPMCSECollection = &CLSID_GPMCSECollection_Value; const CLSID_GPMConstants_Value = @import("../zig.zig").Guid.initString("3855e880-cd9e-4d0c-9eaf-1579283a1888"); pub const CLSID_GPMConstants = &CLSID_GPMConstants_Value; const CLSID_GPMResult_Value = @import("../zig.zig").Guid.initString("92101ac0-9287-4206-a3b2-4bdb73d225f6"); pub const CLSID_GPMResult = &CLSID_GPMResult_Value; const CLSID_GPMMapEntryCollection_Value = @import("../zig.zig").Guid.initString("0cf75d5b-a3a1-4c55-b4fe-9e149c41f66d"); pub const CLSID_GPMMapEntryCollection = &CLSID_GPMMapEntryCollection_Value; const CLSID_GPMMapEntry_Value = @import("../zig.zig").Guid.initString("8c975253-5431-4471-b35d-0626c928258a"); pub const CLSID_GPMMapEntry = &CLSID_GPMMapEntry_Value; const CLSID_GPMMigrationTable_Value = @import("../zig.zig").Guid.initString("55af4043-2a06-4f72-abef-631b44079c76"); pub const CLSID_GPMMigrationTable = &CLSID_GPMMigrationTable_Value; const CLSID_GPMBackupDirEx_Value = @import("../zig.zig").Guid.initString("e8c0988a-cf03-4c5b-8be2-2aa9ad32aada"); pub const CLSID_GPMBackupDirEx = &CLSID_GPMBackupDirEx_Value; const CLSID_GPMStarterGPOBackupCollection_Value = @import("../zig.zig").Guid.initString("e75ea59d-1aeb-4cb5-a78a-281daa582406"); pub const CLSID_GPMStarterGPOBackupCollection = &CLSID_GPMStarterGPOBackupCollection_Value; const CLSID_GPMStarterGPOBackup_Value = @import("../zig.zig").Guid.initString("389e400a-d8ef-455b-a861-5f9ca34a6a02"); pub const CLSID_GPMStarterGPOBackup = &CLSID_GPMStarterGPOBackup_Value; const CLSID_GPMTemplate_Value = @import("../zig.zig").Guid.initString("ecf1d454-71da-4e2f-a8c0-8185465911d9"); pub const CLSID_GPMTemplate = &CLSID_GPMTemplate_Value; const CLSID_GPMStarterGPOCollection_Value = @import("../zig.zig").Guid.initString("82f8aa8b-49ba-43b2-956e-3397f9b94c3a"); pub const CLSID_GPMStarterGPOCollection = &CLSID_GPMStarterGPOCollection_Value; pub const GPMRSOPMode = enum(i32) { Unknown = 0, Planning = 1, Logging = 2, }; pub const rsopUnknown = GPMRSOPMode.Unknown; pub const rsopPlanning = GPMRSOPMode.Planning; pub const rsopLogging = GPMRSOPMode.Logging; pub const GPMPermissionType = enum(i32) { GPOApply = 65536, GPORead = 65792, GPOEdit = 65793, GPOEditSecurityAndDelete = 65794, GPOCustom = 65795, WMIFilterEdit = 131072, WMIFilterFullControl = 131073, WMIFilterCustom = 131074, SOMLink = 1835008, SOMLogging = 1573120, SOMPlanning = 1573376, SOMWMICreate = 1049344, SOMWMIFullControl = 1049345, SOMGPOCreate = 1049600, StarterGPORead = 197888, StarterGPOEdit = 197889, StarterGPOFullControl = 197890, StarterGPOCustom = 197891, SOMStarterGPOCreate = 1049856, }; pub const permGPOApply = GPMPermissionType.GPOApply; pub const permGPORead = GPMPermissionType.GPORead; pub const permGPOEdit = GPMPermissionType.GPOEdit; pub const permGPOEditSecurityAndDelete = GPMPermissionType.GPOEditSecurityAndDelete; pub const permGPOCustom = GPMPermissionType.GPOCustom; pub const permWMIFilterEdit = GPMPermissionType.WMIFilterEdit; pub const permWMIFilterFullControl = GPMPermissionType.WMIFilterFullControl; pub const permWMIFilterCustom = GPMPermissionType.WMIFilterCustom; pub const permSOMLink = GPMPermissionType.SOMLink; pub const permSOMLogging = GPMPermissionType.SOMLogging; pub const permSOMPlanning = GPMPermissionType.SOMPlanning; pub const permSOMWMICreate = GPMPermissionType.SOMWMICreate; pub const permSOMWMIFullControl = GPMPermissionType.SOMWMIFullControl; pub const permSOMGPOCreate = GPMPermissionType.SOMGPOCreate; pub const permStarterGPORead = GPMPermissionType.StarterGPORead; pub const permStarterGPOEdit = GPMPermissionType.StarterGPOEdit; pub const permStarterGPOFullControl = GPMPermissionType.StarterGPOFullControl; pub const permStarterGPOCustom = GPMPermissionType.StarterGPOCustom; pub const permSOMStarterGPOCreate = GPMPermissionType.SOMStarterGPOCreate; pub const GPMSearchProperty = enum(i32) { gpoPermissions = 0, gpoEffectivePermissions = 1, gpoDisplayName = 2, gpoWMIFilter = 3, gpoID = 4, gpoComputerExtensions = 5, gpoUserExtensions = 6, somLinks = 7, gpoDomain = 8, backupMostRecent = 9, starterGPOPermissions = 10, starterGPOEffectivePermissions = 11, starterGPODisplayName = 12, starterGPOID = 13, starterGPODomain = 14, }; pub const gpoPermissions = GPMSearchProperty.gpoPermissions; pub const gpoEffectivePermissions = GPMSearchProperty.gpoEffectivePermissions; pub const gpoDisplayName = GPMSearchProperty.gpoDisplayName; pub const gpoWMIFilter = GPMSearchProperty.gpoWMIFilter; pub const gpoID = GPMSearchProperty.gpoID; pub const gpoComputerExtensions = GPMSearchProperty.gpoComputerExtensions; pub const gpoUserExtensions = GPMSearchProperty.gpoUserExtensions; pub const somLinks = GPMSearchProperty.somLinks; pub const gpoDomain = GPMSearchProperty.gpoDomain; pub const backupMostRecent = GPMSearchProperty.backupMostRecent; pub const starterGPOPermissions = GPMSearchProperty.starterGPOPermissions; pub const starterGPOEffectivePermissions = GPMSearchProperty.starterGPOEffectivePermissions; pub const starterGPODisplayName = GPMSearchProperty.starterGPODisplayName; pub const starterGPOID = GPMSearchProperty.starterGPOID; pub const starterGPODomain = GPMSearchProperty.starterGPODomain; pub const GPMSearchOperation = enum(i32) { Equals = 0, Contains = 1, NotContains = 2, NotEquals = 3, }; pub const opEquals = GPMSearchOperation.Equals; pub const opContains = GPMSearchOperation.Contains; pub const opNotContains = GPMSearchOperation.NotContains; pub const opNotEquals = GPMSearchOperation.NotEquals; pub const GPMReportType = enum(i32) { XML = 0, HTML = 1, InfraXML = 2, InfraRefreshXML = 3, ClientHealthXML = 4, ClientHealthRefreshXML = 5, }; pub const repXML = GPMReportType.XML; pub const repHTML = GPMReportType.HTML; pub const repInfraXML = GPMReportType.InfraXML; pub const repInfraRefreshXML = GPMReportType.InfraRefreshXML; pub const repClientHealthXML = GPMReportType.ClientHealthXML; pub const repClientHealthRefreshXML = GPMReportType.ClientHealthRefreshXML; pub const GPMEntryType = enum(i32) { User = 0, Computer = 1, LocalGroup = 2, GlobalGroup = 3, UniversalGroup = 4, UNCPath = 5, Unknown = 6, }; pub const typeUser = GPMEntryType.User; pub const typeComputer = GPMEntryType.Computer; pub const typeLocalGroup = GPMEntryType.LocalGroup; pub const typeGlobalGroup = GPMEntryType.GlobalGroup; pub const typeUniversalGroup = GPMEntryType.UniversalGroup; pub const typeUNCPath = GPMEntryType.UNCPath; pub const typeUnknown = GPMEntryType.Unknown; pub const GPMDestinationOption = enum(i32) { SameAsSource = 0, None = 1, ByRelativeName = 2, Set = 3, }; pub const opDestinationSameAsSource = GPMDestinationOption.SameAsSource; pub const opDestinationNone = GPMDestinationOption.None; pub const opDestinationByRelativeName = GPMDestinationOption.ByRelativeName; pub const opDestinationSet = GPMDestinationOption.Set; pub const GPMReportingOptions = enum(i32) { Legacy = 0, Comments = 1, }; pub const opReportLegacy = GPMReportingOptions.Legacy; pub const opReportComments = GPMReportingOptions.Comments; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPM_Value = @import("../zig.zig").Guid.initString("f5fae809-3bd6-4da9-a65e-17665b41d763"); pub const IID_IGPM = &IID_IGPM_Value; pub const IGPM = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, GetDomain: fn( self: *const IGPM, bstrDomain: ?BSTR, bstrDomainController: ?BSTR, lDCFlags: i32, pIGPMDomain: ?*?*IGPMDomain, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBackupDir: fn( self: *const IGPM, bstrBackupDir: ?BSTR, pIGPMBackupDir: ?*?*IGPMBackupDir, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSitesContainer: fn( self: *const IGPM, bstrForest: ?BSTR, bstrDomain: ?BSTR, bstrDomainController: ?BSTR, lDCFlags: i32, ppIGPMSitesContainer: ?*?*IGPMSitesContainer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRSOP: fn( self: *const IGPM, gpmRSoPMode: GPMRSOPMode, bstrNamespace: ?BSTR, lFlags: i32, ppIGPMRSOP: ?*?*IGPMRSOP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePermission: fn( self: *const IGPM, bstrTrustee: ?BSTR, perm: GPMPermissionType, bInheritable: i16, ppPerm: ?*?*IGPMPermission, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateSearchCriteria: fn( self: *const IGPM, ppIGPMSearchCriteria: ?*?*IGPMSearchCriteria, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateTrustee: fn( self: *const IGPM, bstrTrustee: ?BSTR, ppIGPMTrustee: ?*?*IGPMTrustee, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClientSideExtensions: fn( self: *const IGPM, ppIGPMCSECollection: ?*?*IGPMCSECollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetConstants: fn( self: *const IGPM, ppIGPMConstants: ?*?*IGPMConstants, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMigrationTable: fn( self: *const IGPM, bstrMigrationTablePath: ?BSTR, ppMigrationTable: ?*?*IGPMMigrationTable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateMigrationTable: fn( self: *const IGPM, ppMigrationTable: ?*?*IGPMMigrationTable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitializeReporting: fn( self: *const IGPM, bstrAdmPath: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPM_GetDomain(self: *const T, bstrDomain: ?BSTR, bstrDomainController: ?BSTR, lDCFlags: i32, pIGPMDomain: ?*?*IGPMDomain) callconv(.Inline) HRESULT { return @ptrCast(*const IGPM.VTable, self.vtable).GetDomain(@ptrCast(*const IGPM, self), bstrDomain, bstrDomainController, lDCFlags, pIGPMDomain); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPM_GetBackupDir(self: *const T, bstrBackupDir: ?BSTR, pIGPMBackupDir: ?*?*IGPMBackupDir) callconv(.Inline) HRESULT { return @ptrCast(*const IGPM.VTable, self.vtable).GetBackupDir(@ptrCast(*const IGPM, self), bstrBackupDir, pIGPMBackupDir); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPM_GetSitesContainer(self: *const T, bstrForest: ?BSTR, bstrDomain: ?BSTR, bstrDomainController: ?BSTR, lDCFlags: i32, ppIGPMSitesContainer: ?*?*IGPMSitesContainer) callconv(.Inline) HRESULT { return @ptrCast(*const IGPM.VTable, self.vtable).GetSitesContainer(@ptrCast(*const IGPM, self), bstrForest, bstrDomain, bstrDomainController, lDCFlags, ppIGPMSitesContainer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPM_GetRSOP(self: *const T, gpmRSoPMode: GPMRSOPMode, bstrNamespace: ?BSTR, lFlags: i32, ppIGPMRSOP: ?*?*IGPMRSOP) callconv(.Inline) HRESULT { return @ptrCast(*const IGPM.VTable, self.vtable).GetRSOP(@ptrCast(*const IGPM, self), gpmRSoPMode, bstrNamespace, lFlags, ppIGPMRSOP); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPM_CreatePermission(self: *const T, bstrTrustee: ?BSTR, perm: GPMPermissionType, bInheritable: i16, ppPerm: ?*?*IGPMPermission) callconv(.Inline) HRESULT { return @ptrCast(*const IGPM.VTable, self.vtable).CreatePermission(@ptrCast(*const IGPM, self), bstrTrustee, perm, bInheritable, ppPerm); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPM_CreateSearchCriteria(self: *const T, ppIGPMSearchCriteria: ?*?*IGPMSearchCriteria) callconv(.Inline) HRESULT { return @ptrCast(*const IGPM.VTable, self.vtable).CreateSearchCriteria(@ptrCast(*const IGPM, self), ppIGPMSearchCriteria); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPM_CreateTrustee(self: *const T, bstrTrustee: ?BSTR, ppIGPMTrustee: ?*?*IGPMTrustee) callconv(.Inline) HRESULT { return @ptrCast(*const IGPM.VTable, self.vtable).CreateTrustee(@ptrCast(*const IGPM, self), bstrTrustee, ppIGPMTrustee); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPM_GetClientSideExtensions(self: *const T, ppIGPMCSECollection: ?*?*IGPMCSECollection) callconv(.Inline) HRESULT { return @ptrCast(*const IGPM.VTable, self.vtable).GetClientSideExtensions(@ptrCast(*const IGPM, self), ppIGPMCSECollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPM_GetConstants(self: *const T, ppIGPMConstants: ?*?*IGPMConstants) callconv(.Inline) HRESULT { return @ptrCast(*const IGPM.VTable, self.vtable).GetConstants(@ptrCast(*const IGPM, self), ppIGPMConstants); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPM_GetMigrationTable(self: *const T, bstrMigrationTablePath: ?BSTR, ppMigrationTable: ?*?*IGPMMigrationTable) callconv(.Inline) HRESULT { return @ptrCast(*const IGPM.VTable, self.vtable).GetMigrationTable(@ptrCast(*const IGPM, self), bstrMigrationTablePath, ppMigrationTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPM_CreateMigrationTable(self: *const T, ppMigrationTable: ?*?*IGPMMigrationTable) callconv(.Inline) HRESULT { return @ptrCast(*const IGPM.VTable, self.vtable).CreateMigrationTable(@ptrCast(*const IGPM, self), ppMigrationTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPM_InitializeReporting(self: *const T, bstrAdmPath: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPM.VTable, self.vtable).InitializeReporting(@ptrCast(*const IGPM, self), bstrAdmPath); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMDomain_Value = @import("../zig.zig").Guid.initString("6b21cc14-5a00-4f44-a738-feec8a94c7e3"); pub const IID_IGPMDomain = &IID_IGPMDomain_Value; pub const IGPMDomain = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DomainController: fn( self: *const IGPMDomain, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Domain: fn( self: *const IGPMDomain, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateGPO: fn( self: *const IGPMDomain, ppNewGPO: ?*?*IGPMGPO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGPO: fn( self: *const IGPMDomain, bstrGuid: ?BSTR, ppGPO: ?*?*IGPMGPO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SearchGPOs: fn( self: *const IGPMDomain, pIGPMSearchCriteria: ?*IGPMSearchCriteria, ppIGPMGPOCollection: ?*?*IGPMGPOCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RestoreGPO: fn( self: *const IGPMDomain, pIGPMBackup: ?*IGPMBackup, lDCFlags: i32, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSOM: fn( self: *const IGPMDomain, bstrPath: ?BSTR, ppSOM: ?*?*IGPMSOM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SearchSOMs: fn( self: *const IGPMDomain, pIGPMSearchCriteria: ?*IGPMSearchCriteria, ppIGPMSOMCollection: ?*?*IGPMSOMCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWMIFilter: fn( self: *const IGPMDomain, bstrPath: ?BSTR, ppWMIFilter: ?*?*IGPMWMIFilter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SearchWMIFilters: fn( self: *const IGPMDomain, pIGPMSearchCriteria: ?*IGPMSearchCriteria, ppIGPMWMIFilterCollection: ?*?*IGPMWMIFilterCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain_get_DomainController(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain.VTable, self.vtable).get_DomainController(@ptrCast(*const IGPMDomain, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain_get_Domain(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain.VTable, self.vtable).get_Domain(@ptrCast(*const IGPMDomain, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain_CreateGPO(self: *const T, ppNewGPO: ?*?*IGPMGPO) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain.VTable, self.vtable).CreateGPO(@ptrCast(*const IGPMDomain, self), ppNewGPO); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain_GetGPO(self: *const T, bstrGuid: ?BSTR, ppGPO: ?*?*IGPMGPO) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain.VTable, self.vtable).GetGPO(@ptrCast(*const IGPMDomain, self), bstrGuid, ppGPO); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain_SearchGPOs(self: *const T, pIGPMSearchCriteria: ?*IGPMSearchCriteria, ppIGPMGPOCollection: ?*?*IGPMGPOCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain.VTable, self.vtable).SearchGPOs(@ptrCast(*const IGPMDomain, self), pIGPMSearchCriteria, ppIGPMGPOCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain_RestoreGPO(self: *const T, pIGPMBackup: ?*IGPMBackup, lDCFlags: i32, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain.VTable, self.vtable).RestoreGPO(@ptrCast(*const IGPMDomain, self), pIGPMBackup, lDCFlags, pvarGPMProgress, pvarGPMCancel, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain_GetSOM(self: *const T, bstrPath: ?BSTR, ppSOM: ?*?*IGPMSOM) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain.VTable, self.vtable).GetSOM(@ptrCast(*const IGPMDomain, self), bstrPath, ppSOM); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain_SearchSOMs(self: *const T, pIGPMSearchCriteria: ?*IGPMSearchCriteria, ppIGPMSOMCollection: ?*?*IGPMSOMCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain.VTable, self.vtable).SearchSOMs(@ptrCast(*const IGPMDomain, self), pIGPMSearchCriteria, ppIGPMSOMCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain_GetWMIFilter(self: *const T, bstrPath: ?BSTR, ppWMIFilter: ?*?*IGPMWMIFilter) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain.VTable, self.vtable).GetWMIFilter(@ptrCast(*const IGPMDomain, self), bstrPath, ppWMIFilter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain_SearchWMIFilters(self: *const T, pIGPMSearchCriteria: ?*IGPMSearchCriteria, ppIGPMWMIFilterCollection: ?*?*IGPMWMIFilterCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain.VTable, self.vtable).SearchWMIFilters(@ptrCast(*const IGPMDomain, self), pIGPMSearchCriteria, ppIGPMWMIFilterCollection); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMBackupDir_Value = @import("../zig.zig").Guid.initString("b1568bed-0a93-4acc-810f-afe7081019b9"); pub const IID_IGPMBackupDir = &IID_IGPMBackupDir_Value; pub const IGPMBackupDir = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BackupDirectory: fn( self: *const IGPMBackupDir, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBackup: fn( self: *const IGPMBackupDir, bstrID: ?BSTR, ppBackup: ?*?*IGPMBackup, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SearchBackups: fn( self: *const IGPMBackupDir, pIGPMSearchCriteria: ?*IGPMSearchCriteria, ppIGPMBackupCollection: ?*?*IGPMBackupCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackupDir_get_BackupDirectory(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackupDir.VTable, self.vtable).get_BackupDirectory(@ptrCast(*const IGPMBackupDir, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackupDir_GetBackup(self: *const T, bstrID: ?BSTR, ppBackup: ?*?*IGPMBackup) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackupDir.VTable, self.vtable).GetBackup(@ptrCast(*const IGPMBackupDir, self), bstrID, ppBackup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackupDir_SearchBackups(self: *const T, pIGPMSearchCriteria: ?*IGPMSearchCriteria, ppIGPMBackupCollection: ?*?*IGPMBackupCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackupDir.VTable, self.vtable).SearchBackups(@ptrCast(*const IGPMBackupDir, self), pIGPMSearchCriteria, ppIGPMBackupCollection); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMSitesContainer_Value = @import("../zig.zig").Guid.initString("4725a899-2782-4d27-a6bb-d499246ffd72"); pub const IID_IGPMSitesContainer = &IID_IGPMSitesContainer_Value; pub const IGPMSitesContainer = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DomainController: fn( self: *const IGPMSitesContainer, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Domain: fn( self: *const IGPMSitesContainer, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Forest: fn( self: *const IGPMSitesContainer, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSite: fn( self: *const IGPMSitesContainer, bstrSiteName: ?BSTR, ppSOM: ?*?*IGPMSOM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SearchSites: fn( self: *const IGPMSitesContainer, pIGPMSearchCriteria: ?*IGPMSearchCriteria, ppIGPMSOMCollection: ?*?*IGPMSOMCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSitesContainer_get_DomainController(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSitesContainer.VTable, self.vtable).get_DomainController(@ptrCast(*const IGPMSitesContainer, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSitesContainer_get_Domain(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSitesContainer.VTable, self.vtable).get_Domain(@ptrCast(*const IGPMSitesContainer, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSitesContainer_get_Forest(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSitesContainer.VTable, self.vtable).get_Forest(@ptrCast(*const IGPMSitesContainer, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSitesContainer_GetSite(self: *const T, bstrSiteName: ?BSTR, ppSOM: ?*?*IGPMSOM) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSitesContainer.VTable, self.vtable).GetSite(@ptrCast(*const IGPMSitesContainer, self), bstrSiteName, ppSOM); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSitesContainer_SearchSites(self: *const T, pIGPMSearchCriteria: ?*IGPMSearchCriteria, ppIGPMSOMCollection: ?*?*IGPMSOMCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSitesContainer.VTable, self.vtable).SearchSites(@ptrCast(*const IGPMSitesContainer, self), pIGPMSearchCriteria, ppIGPMSOMCollection); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMSearchCriteria_Value = @import("../zig.zig").Guid.initString("d6f11c42-829b-48d4-83f5-3615b67dfc22"); pub const IID_IGPMSearchCriteria = &IID_IGPMSearchCriteria_Value; pub const IGPMSearchCriteria = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Add: fn( self: *const IGPMSearchCriteria, searchProperty: GPMSearchProperty, searchOperation: GPMSearchOperation, varValue: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSearchCriteria_Add(self: *const T, searchProperty: GPMSearchProperty, searchOperation: GPMSearchOperation, varValue: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSearchCriteria.VTable, self.vtable).Add(@ptrCast(*const IGPMSearchCriteria, self), searchProperty, searchOperation, varValue); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMTrustee_Value = @import("../zig.zig").Guid.initString("3b466da8-c1a4-4b2a-999a-befcdd56cefb"); pub const IID_IGPMTrustee = &IID_IGPMTrustee_Value; pub const IGPMTrustee = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TrusteeSid: fn( self: *const IGPMTrustee, bstrVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TrusteeName: fn( self: *const IGPMTrustee, bstrVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TrusteeDomain: fn( self: *const IGPMTrustee, bstrVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TrusteeDSPath: fn( self: *const IGPMTrustee, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TrusteeType: fn( self: *const IGPMTrustee, lVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMTrustee_get_TrusteeSid(self: *const T, bstrVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMTrustee.VTable, self.vtable).get_TrusteeSid(@ptrCast(*const IGPMTrustee, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMTrustee_get_TrusteeName(self: *const T, bstrVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMTrustee.VTable, self.vtable).get_TrusteeName(@ptrCast(*const IGPMTrustee, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMTrustee_get_TrusteeDomain(self: *const T, bstrVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMTrustee.VTable, self.vtable).get_TrusteeDomain(@ptrCast(*const IGPMTrustee, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMTrustee_get_TrusteeDSPath(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMTrustee.VTable, self.vtable).get_TrusteeDSPath(@ptrCast(*const IGPMTrustee, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMTrustee_get_TrusteeType(self: *const T, lVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMTrustee.VTable, self.vtable).get_TrusteeType(@ptrCast(*const IGPMTrustee, self), lVal); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMPermission_Value = @import("../zig.zig").Guid.initString("35ebca40-e1a1-4a02-8905-d79416fb464a"); pub const IID_IGPMPermission = &IID_IGPMPermission_Value; pub const IGPMPermission = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Inherited: fn( self: *const IGPMPermission, pVal: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Inheritable: fn( self: *const IGPMPermission, pVal: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Denied: fn( self: *const IGPMPermission, pVal: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Permission: fn( self: *const IGPMPermission, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Trustee: fn( self: *const IGPMPermission, ppIGPMTrustee: ?*?*IGPMTrustee, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMPermission_get_Inherited(self: *const T, pVal: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMPermission.VTable, self.vtable).get_Inherited(@ptrCast(*const IGPMPermission, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMPermission_get_Inheritable(self: *const T, pVal: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMPermission.VTable, self.vtable).get_Inheritable(@ptrCast(*const IGPMPermission, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMPermission_get_Denied(self: *const T, pVal: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMPermission.VTable, self.vtable).get_Denied(@ptrCast(*const IGPMPermission, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMPermission_get_Permission(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMPermission.VTable, self.vtable).get_Permission(@ptrCast(*const IGPMPermission, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMPermission_get_Trustee(self: *const T, ppIGPMTrustee: ?*?*IGPMTrustee) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMPermission.VTable, self.vtable).get_Trustee(@ptrCast(*const IGPMPermission, self), ppIGPMTrustee); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMSecurityInfo_Value = @import("../zig.zig").Guid.initString("b6c31ed4-1c93-4d3e-ae84-eb6d61161b60"); pub const IID_IGPMSecurityInfo = &IID_IGPMSecurityInfo_Value; pub const IGPMSecurityInfo = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IGPMSecurityInfo, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IGPMSecurityInfo, lIndex: i32, pVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IGPMSecurityInfo, ppEnum: ?*?*IEnumVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const IGPMSecurityInfo, pPerm: ?*IGPMPermission, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const IGPMSecurityInfo, pPerm: ?*IGPMPermission, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveTrustee: fn( self: *const IGPMSecurityInfo, bstrTrustee: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSecurityInfo_get_Count(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSecurityInfo.VTable, self.vtable).get_Count(@ptrCast(*const IGPMSecurityInfo, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSecurityInfo_get_Item(self: *const T, lIndex: i32, pVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSecurityInfo.VTable, self.vtable).get_Item(@ptrCast(*const IGPMSecurityInfo, self), lIndex, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSecurityInfo_get__NewEnum(self: *const T, ppEnum: ?*?*IEnumVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSecurityInfo.VTable, self.vtable).get__NewEnum(@ptrCast(*const IGPMSecurityInfo, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSecurityInfo_Add(self: *const T, pPerm: ?*IGPMPermission) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSecurityInfo.VTable, self.vtable).Add(@ptrCast(*const IGPMSecurityInfo, self), pPerm); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSecurityInfo_Remove(self: *const T, pPerm: ?*IGPMPermission) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSecurityInfo.VTable, self.vtable).Remove(@ptrCast(*const IGPMSecurityInfo, self), pPerm); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSecurityInfo_RemoveTrustee(self: *const T, bstrTrustee: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSecurityInfo.VTable, self.vtable).RemoveTrustee(@ptrCast(*const IGPMSecurityInfo, self), bstrTrustee); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMBackup_Value = @import("../zig.zig").Guid.initString("d8a16a35-3b0d-416b-8d02-4df6f95a7119"); pub const IID_IGPMBackup = &IID_IGPMBackup_Value; pub const IGPMBackup = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ID: fn( self: *const IGPMBackup, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GPOID: fn( self: *const IGPMBackup, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GPODomain: fn( self: *const IGPMBackup, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GPODisplayName: fn( self: *const IGPMBackup, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Timestamp: fn( self: *const IGPMBackup, pVal: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Comment: fn( self: *const IGPMBackup, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BackupDir: fn( self: *const IGPMBackup, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Delete: fn( self: *const IGPMBackup, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GenerateReport: fn( self: *const IGPMBackup, gpmReportType: GPMReportType, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GenerateReportToFile: fn( self: *const IGPMBackup, gpmReportType: GPMReportType, bstrTargetFilePath: ?BSTR, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackup_get_ID(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackup.VTable, self.vtable).get_ID(@ptrCast(*const IGPMBackup, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackup_get_GPOID(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackup.VTable, self.vtable).get_GPOID(@ptrCast(*const IGPMBackup, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackup_get_GPODomain(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackup.VTable, self.vtable).get_GPODomain(@ptrCast(*const IGPMBackup, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackup_get_GPODisplayName(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackup.VTable, self.vtable).get_GPODisplayName(@ptrCast(*const IGPMBackup, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackup_get_Timestamp(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackup.VTable, self.vtable).get_Timestamp(@ptrCast(*const IGPMBackup, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackup_get_Comment(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackup.VTable, self.vtable).get_Comment(@ptrCast(*const IGPMBackup, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackup_get_BackupDir(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackup.VTable, self.vtable).get_BackupDir(@ptrCast(*const IGPMBackup, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackup_Delete(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackup.VTable, self.vtable).Delete(@ptrCast(*const IGPMBackup, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackup_GenerateReport(self: *const T, gpmReportType: GPMReportType, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackup.VTable, self.vtable).GenerateReport(@ptrCast(*const IGPMBackup, self), gpmReportType, pvarGPMProgress, pvarGPMCancel, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackup_GenerateReportToFile(self: *const T, gpmReportType: GPMReportType, bstrTargetFilePath: ?BSTR, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackup.VTable, self.vtable).GenerateReportToFile(@ptrCast(*const IGPMBackup, self), gpmReportType, bstrTargetFilePath, ppIGPMResult); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMBackupCollection_Value = @import("../zig.zig").Guid.initString("c786fc0f-26d8-4bab-a745-39ca7e800cac"); pub const IID_IGPMBackupCollection = &IID_IGPMBackupCollection_Value; pub const IGPMBackupCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IGPMBackupCollection, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IGPMBackupCollection, lIndex: i32, pVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IGPMBackupCollection, ppIGPMBackup: ?*?*IEnumVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackupCollection_get_Count(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackupCollection.VTable, self.vtable).get_Count(@ptrCast(*const IGPMBackupCollection, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackupCollection_get_Item(self: *const T, lIndex: i32, pVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackupCollection.VTable, self.vtable).get_Item(@ptrCast(*const IGPMBackupCollection, self), lIndex, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackupCollection_get__NewEnum(self: *const T, ppIGPMBackup: ?*?*IEnumVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackupCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IGPMBackupCollection, self), ppIGPMBackup); } };} pub usingnamespace MethodMixin(@This()); }; pub const GPMSOMType = enum(i32) { Site = 0, Domain = 1, OU = 2, }; pub const somSite = GPMSOMType.Site; pub const somDomain = GPMSOMType.Domain; pub const somOU = GPMSOMType.OU; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMSOM_Value = @import("../zig.zig").Guid.initString("c0a7f09e-05a1-4f0c-8158-9e5c33684f6b"); pub const IID_IGPMSOM = &IID_IGPMSOM_Value; pub const IGPMSOM = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GPOInheritanceBlocked: fn( self: *const IGPMSOM, pVal: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_GPOInheritanceBlocked: fn( self: *const IGPMSOM, newVal: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IGPMSOM, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Path: fn( self: *const IGPMSOM, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateGPOLink: fn( self: *const IGPMSOM, lLinkPos: i32, pGPO: ?*IGPMGPO, ppNewGPOLink: ?*?*IGPMGPOLink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Type: fn( self: *const IGPMSOM, pVal: ?*GPMSOMType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGPOLinks: fn( self: *const IGPMSOM, ppGPOLinks: ?*?*IGPMGPOLinksCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInheritedGPOLinks: fn( self: *const IGPMSOM, ppGPOLinks: ?*?*IGPMGPOLinksCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSecurityInfo: fn( self: *const IGPMSOM, ppSecurityInfo: ?*?*IGPMSecurityInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSecurityInfo: fn( self: *const IGPMSOM, pSecurityInfo: ?*IGPMSecurityInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSOM_get_GPOInheritanceBlocked(self: *const T, pVal: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSOM.VTable, self.vtable).get_GPOInheritanceBlocked(@ptrCast(*const IGPMSOM, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSOM_put_GPOInheritanceBlocked(self: *const T, newVal: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSOM.VTable, self.vtable).put_GPOInheritanceBlocked(@ptrCast(*const IGPMSOM, self), newVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSOM_get_Name(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSOM.VTable, self.vtable).get_Name(@ptrCast(*const IGPMSOM, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSOM_get_Path(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSOM.VTable, self.vtable).get_Path(@ptrCast(*const IGPMSOM, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSOM_CreateGPOLink(self: *const T, lLinkPos: i32, pGPO: ?*IGPMGPO, ppNewGPOLink: ?*?*IGPMGPOLink) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSOM.VTable, self.vtable).CreateGPOLink(@ptrCast(*const IGPMSOM, self), lLinkPos, pGPO, ppNewGPOLink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSOM_get_Type(self: *const T, pVal: ?*GPMSOMType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSOM.VTable, self.vtable).get_Type(@ptrCast(*const IGPMSOM, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSOM_GetGPOLinks(self: *const T, ppGPOLinks: ?*?*IGPMGPOLinksCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSOM.VTable, self.vtable).GetGPOLinks(@ptrCast(*const IGPMSOM, self), ppGPOLinks); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSOM_GetInheritedGPOLinks(self: *const T, ppGPOLinks: ?*?*IGPMGPOLinksCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSOM.VTable, self.vtable).GetInheritedGPOLinks(@ptrCast(*const IGPMSOM, self), ppGPOLinks); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSOM_GetSecurityInfo(self: *const T, ppSecurityInfo: ?*?*IGPMSecurityInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSOM.VTable, self.vtable).GetSecurityInfo(@ptrCast(*const IGPMSOM, self), ppSecurityInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSOM_SetSecurityInfo(self: *const T, pSecurityInfo: ?*IGPMSecurityInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSOM.VTable, self.vtable).SetSecurityInfo(@ptrCast(*const IGPMSOM, self), pSecurityInfo); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMSOMCollection_Value = @import("../zig.zig").Guid.initString("adc1688e-00e4-4495-abba-bed200df0cab"); pub const IID_IGPMSOMCollection = &IID_IGPMSOMCollection_Value; pub const IGPMSOMCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IGPMSOMCollection, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IGPMSOMCollection, lIndex: i32, pVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IGPMSOMCollection, ppIGPMSOM: ?*?*IEnumVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSOMCollection_get_Count(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSOMCollection.VTable, self.vtable).get_Count(@ptrCast(*const IGPMSOMCollection, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSOMCollection_get_Item(self: *const T, lIndex: i32, pVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSOMCollection.VTable, self.vtable).get_Item(@ptrCast(*const IGPMSOMCollection, self), lIndex, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMSOMCollection_get__NewEnum(self: *const T, ppIGPMSOM: ?*?*IEnumVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMSOMCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IGPMSOMCollection, self), ppIGPMSOM); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMWMIFilter_Value = @import("../zig.zig").Guid.initString("ef2ff9b4-3c27-459a-b979-038305cec75d"); pub const IID_IGPMWMIFilter = &IID_IGPMWMIFilter_Value; pub const IGPMWMIFilter = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Path: fn( self: *const IGPMWMIFilter, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Name: fn( self: *const IGPMWMIFilter, newVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IGPMWMIFilter, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IGPMWMIFilter, newVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IGPMWMIFilter, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetQueryList: fn( self: *const IGPMWMIFilter, pQryList: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSecurityInfo: fn( self: *const IGPMWMIFilter, ppSecurityInfo: ?*?*IGPMSecurityInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSecurityInfo: fn( self: *const IGPMWMIFilter, pSecurityInfo: ?*IGPMSecurityInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMWMIFilter_get_Path(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMWMIFilter.VTable, self.vtable).get_Path(@ptrCast(*const IGPMWMIFilter, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMWMIFilter_put_Name(self: *const T, newVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMWMIFilter.VTable, self.vtable).put_Name(@ptrCast(*const IGPMWMIFilter, self), newVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMWMIFilter_get_Name(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMWMIFilter.VTable, self.vtable).get_Name(@ptrCast(*const IGPMWMIFilter, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMWMIFilter_put_Description(self: *const T, newVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMWMIFilter.VTable, self.vtable).put_Description(@ptrCast(*const IGPMWMIFilter, self), newVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMWMIFilter_get_Description(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMWMIFilter.VTable, self.vtable).get_Description(@ptrCast(*const IGPMWMIFilter, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMWMIFilter_GetQueryList(self: *const T, pQryList: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMWMIFilter.VTable, self.vtable).GetQueryList(@ptrCast(*const IGPMWMIFilter, self), pQryList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMWMIFilter_GetSecurityInfo(self: *const T, ppSecurityInfo: ?*?*IGPMSecurityInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMWMIFilter.VTable, self.vtable).GetSecurityInfo(@ptrCast(*const IGPMWMIFilter, self), ppSecurityInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMWMIFilter_SetSecurityInfo(self: *const T, pSecurityInfo: ?*IGPMSecurityInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMWMIFilter.VTable, self.vtable).SetSecurityInfo(@ptrCast(*const IGPMWMIFilter, self), pSecurityInfo); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMWMIFilterCollection_Value = @import("../zig.zig").Guid.initString("5782d582-1a36-4661-8a94-c3c32551945b"); pub const IID_IGPMWMIFilterCollection = &IID_IGPMWMIFilterCollection_Value; pub const IGPMWMIFilterCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IGPMWMIFilterCollection, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IGPMWMIFilterCollection, lIndex: i32, pVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IGPMWMIFilterCollection, pVal: ?*?*IEnumVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMWMIFilterCollection_get_Count(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMWMIFilterCollection.VTable, self.vtable).get_Count(@ptrCast(*const IGPMWMIFilterCollection, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMWMIFilterCollection_get_Item(self: *const T, lIndex: i32, pVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMWMIFilterCollection.VTable, self.vtable).get_Item(@ptrCast(*const IGPMWMIFilterCollection, self), lIndex, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMWMIFilterCollection_get__NewEnum(self: *const T, pVal: ?*?*IEnumVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMWMIFilterCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IGPMWMIFilterCollection, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMRSOP_Value = @import("../zig.zig").Guid.initString("49ed785a-3237-4ff2-b1f0-fdf5a8d5a1ee"); pub const IID_IGPMRSOP = &IID_IGPMRSOP_Value; pub const IGPMRSOP = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Mode: fn( self: *const IGPMRSOP, pVal: ?*GPMRSOPMode, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Namespace: fn( self: *const IGPMRSOP, bstrVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LoggingComputer: fn( self: *const IGPMRSOP, bstrVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LoggingComputer: fn( self: *const IGPMRSOP, bstrVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LoggingUser: fn( self: *const IGPMRSOP, bstrVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LoggingUser: fn( self: *const IGPMRSOP, bstrVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LoggingFlags: fn( self: *const IGPMRSOP, lVal: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LoggingFlags: fn( self: *const IGPMRSOP, lVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PlanningFlags: fn( self: *const IGPMRSOP, lVal: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PlanningFlags: fn( self: *const IGPMRSOP, lVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PlanningDomainController: fn( self: *const IGPMRSOP, bstrVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PlanningDomainController: fn( self: *const IGPMRSOP, bstrVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PlanningSiteName: fn( self: *const IGPMRSOP, bstrVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PlanningSiteName: fn( self: *const IGPMRSOP, bstrVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PlanningUser: fn( self: *const IGPMRSOP, bstrVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PlanningUser: fn( self: *const IGPMRSOP, bstrVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PlanningUserSOM: fn( self: *const IGPMRSOP, bstrVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PlanningUserSOM: fn( self: *const IGPMRSOP, bstrVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PlanningUserWMIFilters: fn( self: *const IGPMRSOP, varVal: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PlanningUserWMIFilters: fn( self: *const IGPMRSOP, varVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PlanningUserSecurityGroups: fn( self: *const IGPMRSOP, varVal: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PlanningUserSecurityGroups: fn( self: *const IGPMRSOP, varVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PlanningComputer: fn( self: *const IGPMRSOP, bstrVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PlanningComputer: fn( self: *const IGPMRSOP, bstrVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PlanningComputerSOM: fn( self: *const IGPMRSOP, bstrVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PlanningComputerSOM: fn( self: *const IGPMRSOP, bstrVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PlanningComputerWMIFilters: fn( self: *const IGPMRSOP, varVal: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PlanningComputerWMIFilters: fn( self: *const IGPMRSOP, varVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PlanningComputerSecurityGroups: fn( self: *const IGPMRSOP, varVal: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PlanningComputerSecurityGroups: fn( self: *const IGPMRSOP, varVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LoggingEnumerateUsers: fn( self: *const IGPMRSOP, varVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateQueryResults: fn( self: *const IGPMRSOP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseQueryResults: fn( self: *const IGPMRSOP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GenerateReport: fn( self: *const IGPMRSOP, gpmReportType: GPMReportType, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GenerateReportToFile: fn( self: *const IGPMRSOP, gpmReportType: GPMReportType, bstrTargetFilePath: ?BSTR, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_Mode(self: *const T, pVal: ?*GPMRSOPMode) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_Mode(@ptrCast(*const IGPMRSOP, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_Namespace(self: *const T, bstrVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_Namespace(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_put_LoggingComputer(self: *const T, bstrVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).put_LoggingComputer(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_LoggingComputer(self: *const T, bstrVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_LoggingComputer(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_put_LoggingUser(self: *const T, bstrVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).put_LoggingUser(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_LoggingUser(self: *const T, bstrVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_LoggingUser(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_put_LoggingFlags(self: *const T, lVal: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).put_LoggingFlags(@ptrCast(*const IGPMRSOP, self), lVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_LoggingFlags(self: *const T, lVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_LoggingFlags(@ptrCast(*const IGPMRSOP, self), lVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_put_PlanningFlags(self: *const T, lVal: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).put_PlanningFlags(@ptrCast(*const IGPMRSOP, self), lVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_PlanningFlags(self: *const T, lVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_PlanningFlags(@ptrCast(*const IGPMRSOP, self), lVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_put_PlanningDomainController(self: *const T, bstrVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).put_PlanningDomainController(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_PlanningDomainController(self: *const T, bstrVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_PlanningDomainController(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_put_PlanningSiteName(self: *const T, bstrVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).put_PlanningSiteName(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_PlanningSiteName(self: *const T, bstrVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_PlanningSiteName(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_put_PlanningUser(self: *const T, bstrVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).put_PlanningUser(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_PlanningUser(self: *const T, bstrVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_PlanningUser(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_put_PlanningUserSOM(self: *const T, bstrVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).put_PlanningUserSOM(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_PlanningUserSOM(self: *const T, bstrVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_PlanningUserSOM(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_put_PlanningUserWMIFilters(self: *const T, varVal: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).put_PlanningUserWMIFilters(@ptrCast(*const IGPMRSOP, self), varVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_PlanningUserWMIFilters(self: *const T, varVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_PlanningUserWMIFilters(@ptrCast(*const IGPMRSOP, self), varVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_put_PlanningUserSecurityGroups(self: *const T, varVal: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).put_PlanningUserSecurityGroups(@ptrCast(*const IGPMRSOP, self), varVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_PlanningUserSecurityGroups(self: *const T, varVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_PlanningUserSecurityGroups(@ptrCast(*const IGPMRSOP, self), varVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_put_PlanningComputer(self: *const T, bstrVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).put_PlanningComputer(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_PlanningComputer(self: *const T, bstrVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_PlanningComputer(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_put_PlanningComputerSOM(self: *const T, bstrVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).put_PlanningComputerSOM(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_PlanningComputerSOM(self: *const T, bstrVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_PlanningComputerSOM(@ptrCast(*const IGPMRSOP, self), bstrVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_put_PlanningComputerWMIFilters(self: *const T, varVal: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).put_PlanningComputerWMIFilters(@ptrCast(*const IGPMRSOP, self), varVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_PlanningComputerWMIFilters(self: *const T, varVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_PlanningComputerWMIFilters(@ptrCast(*const IGPMRSOP, self), varVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_put_PlanningComputerSecurityGroups(self: *const T, varVal: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).put_PlanningComputerSecurityGroups(@ptrCast(*const IGPMRSOP, self), varVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_get_PlanningComputerSecurityGroups(self: *const T, varVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).get_PlanningComputerSecurityGroups(@ptrCast(*const IGPMRSOP, self), varVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_LoggingEnumerateUsers(self: *const T, varVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).LoggingEnumerateUsers(@ptrCast(*const IGPMRSOP, self), varVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_CreateQueryResults(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).CreateQueryResults(@ptrCast(*const IGPMRSOP, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_ReleaseQueryResults(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).ReleaseQueryResults(@ptrCast(*const IGPMRSOP, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_GenerateReport(self: *const T, gpmReportType: GPMReportType, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).GenerateReport(@ptrCast(*const IGPMRSOP, self), gpmReportType, pvarGPMProgress, pvarGPMCancel, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMRSOP_GenerateReportToFile(self: *const T, gpmReportType: GPMReportType, bstrTargetFilePath: ?BSTR, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMRSOP.VTable, self.vtable).GenerateReportToFile(@ptrCast(*const IGPMRSOP, self), gpmReportType, bstrTargetFilePath, ppIGPMResult); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMGPO_Value = @import("../zig.zig").Guid.initString("58cc4352-1ca3-48e5-9864-1da4d6e0d60f"); pub const IID_IGPMGPO = &IID_IGPMGPO_Value; pub const IGPMGPO = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisplayName: fn( self: *const IGPMGPO, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DisplayName: fn( self: *const IGPMGPO, newVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Path: fn( self: *const IGPMGPO, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ID: fn( self: *const IGPMGPO, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DomainName: fn( self: *const IGPMGPO, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CreationTime: fn( self: *const IGPMGPO, pDate: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ModificationTime: fn( self: *const IGPMGPO, pDate: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserDSVersionNumber: fn( self: *const IGPMGPO, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ComputerDSVersionNumber: fn( self: *const IGPMGPO, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserSysvolVersionNumber: fn( self: *const IGPMGPO, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ComputerSysvolVersionNumber: fn( self: *const IGPMGPO, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWMIFilter: fn( self: *const IGPMGPO, ppIGPMWMIFilter: ?*?*IGPMWMIFilter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetWMIFilter: fn( self: *const IGPMGPO, pIGPMWMIFilter: ?*IGPMWMIFilter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetUserEnabled: fn( self: *const IGPMGPO, vbEnabled: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetComputerEnabled: fn( self: *const IGPMGPO, vbEnabled: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsUserEnabled: fn( self: *const IGPMGPO, pvbEnabled: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsComputerEnabled: fn( self: *const IGPMGPO, pvbEnabled: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSecurityInfo: fn( self: *const IGPMGPO, ppSecurityInfo: ?*?*IGPMSecurityInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSecurityInfo: fn( self: *const IGPMGPO, pSecurityInfo: ?*IGPMSecurityInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Delete: fn( self: *const IGPMGPO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Backup: fn( self: *const IGPMGPO, bstrBackupDir: ?BSTR, bstrComment: ?BSTR, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Import: fn( self: *const IGPMGPO, lFlags: i32, pIGPMBackup: ?*IGPMBackup, pvarMigrationTable: ?*VARIANT, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GenerateReport: fn( self: *const IGPMGPO, gpmReportType: GPMReportType, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GenerateReportToFile: fn( self: *const IGPMGPO, gpmReportType: GPMReportType, bstrTargetFilePath: ?BSTR, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyTo: fn( self: *const IGPMGPO, lFlags: i32, pIGPMDomain: ?*IGPMDomain, pvarNewDisplayName: ?*VARIANT, pvarMigrationTable: ?*VARIANT, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSecurityDescriptor: fn( self: *const IGPMGPO, lFlags: i32, pSD: ?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSecurityDescriptor: fn( self: *const IGPMGPO, lFlags: i32, ppSD: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsACLConsistent: fn( self: *const IGPMGPO, pvbConsistent: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MakeACLConsistent: fn( self: *const IGPMGPO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_get_DisplayName(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).get_DisplayName(@ptrCast(*const IGPMGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_put_DisplayName(self: *const T, newVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).put_DisplayName(@ptrCast(*const IGPMGPO, self), newVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_get_Path(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).get_Path(@ptrCast(*const IGPMGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_get_ID(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).get_ID(@ptrCast(*const IGPMGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_get_DomainName(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).get_DomainName(@ptrCast(*const IGPMGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_get_CreationTime(self: *const T, pDate: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).get_CreationTime(@ptrCast(*const IGPMGPO, self), pDate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_get_ModificationTime(self: *const T, pDate: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).get_ModificationTime(@ptrCast(*const IGPMGPO, self), pDate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_get_UserDSVersionNumber(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).get_UserDSVersionNumber(@ptrCast(*const IGPMGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_get_ComputerDSVersionNumber(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).get_ComputerDSVersionNumber(@ptrCast(*const IGPMGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_get_UserSysvolVersionNumber(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).get_UserSysvolVersionNumber(@ptrCast(*const IGPMGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_get_ComputerSysvolVersionNumber(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).get_ComputerSysvolVersionNumber(@ptrCast(*const IGPMGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_GetWMIFilter(self: *const T, ppIGPMWMIFilter: ?*?*IGPMWMIFilter) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).GetWMIFilter(@ptrCast(*const IGPMGPO, self), ppIGPMWMIFilter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_SetWMIFilter(self: *const T, pIGPMWMIFilter: ?*IGPMWMIFilter) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).SetWMIFilter(@ptrCast(*const IGPMGPO, self), pIGPMWMIFilter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_SetUserEnabled(self: *const T, vbEnabled: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).SetUserEnabled(@ptrCast(*const IGPMGPO, self), vbEnabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_SetComputerEnabled(self: *const T, vbEnabled: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).SetComputerEnabled(@ptrCast(*const IGPMGPO, self), vbEnabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_IsUserEnabled(self: *const T, pvbEnabled: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).IsUserEnabled(@ptrCast(*const IGPMGPO, self), pvbEnabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_IsComputerEnabled(self: *const T, pvbEnabled: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).IsComputerEnabled(@ptrCast(*const IGPMGPO, self), pvbEnabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_GetSecurityInfo(self: *const T, ppSecurityInfo: ?*?*IGPMSecurityInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).GetSecurityInfo(@ptrCast(*const IGPMGPO, self), ppSecurityInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_SetSecurityInfo(self: *const T, pSecurityInfo: ?*IGPMSecurityInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).SetSecurityInfo(@ptrCast(*const IGPMGPO, self), pSecurityInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_Delete(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).Delete(@ptrCast(*const IGPMGPO, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_Backup(self: *const T, bstrBackupDir: ?BSTR, bstrComment: ?BSTR, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).Backup(@ptrCast(*const IGPMGPO, self), bstrBackupDir, bstrComment, pvarGPMProgress, pvarGPMCancel, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_Import(self: *const T, lFlags: i32, pIGPMBackup: ?*IGPMBackup, pvarMigrationTable: ?*VARIANT, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).Import(@ptrCast(*const IGPMGPO, self), lFlags, pIGPMBackup, pvarMigrationTable, pvarGPMProgress, pvarGPMCancel, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_GenerateReport(self: *const T, gpmReportType: GPMReportType, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).GenerateReport(@ptrCast(*const IGPMGPO, self), gpmReportType, pvarGPMProgress, pvarGPMCancel, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_GenerateReportToFile(self: *const T, gpmReportType: GPMReportType, bstrTargetFilePath: ?BSTR, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).GenerateReportToFile(@ptrCast(*const IGPMGPO, self), gpmReportType, bstrTargetFilePath, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_CopyTo(self: *const T, lFlags: i32, pIGPMDomain: ?*IGPMDomain, pvarNewDisplayName: ?*VARIANT, pvarMigrationTable: ?*VARIANT, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).CopyTo(@ptrCast(*const IGPMGPO, self), lFlags, pIGPMDomain, pvarNewDisplayName, pvarMigrationTable, pvarGPMProgress, pvarGPMCancel, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_SetSecurityDescriptor(self: *const T, lFlags: i32, pSD: ?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).SetSecurityDescriptor(@ptrCast(*const IGPMGPO, self), lFlags, pSD); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_GetSecurityDescriptor(self: *const T, lFlags: i32, ppSD: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).GetSecurityDescriptor(@ptrCast(*const IGPMGPO, self), lFlags, ppSD); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_IsACLConsistent(self: *const T, pvbConsistent: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).IsACLConsistent(@ptrCast(*const IGPMGPO, self), pvbConsistent); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO_MakeACLConsistent(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO.VTable, self.vtable).MakeACLConsistent(@ptrCast(*const IGPMGPO, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMGPOCollection_Value = @import("../zig.zig").Guid.initString("f0f0d5cf-70ca-4c39-9e29-b642f8726c01"); pub const IID_IGPMGPOCollection = &IID_IGPMGPOCollection_Value; pub const IGPMGPOCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IGPMGPOCollection, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IGPMGPOCollection, lIndex: i32, pVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IGPMGPOCollection, ppIGPMGPOs: ?*?*IEnumVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPOCollection_get_Count(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPOCollection.VTable, self.vtable).get_Count(@ptrCast(*const IGPMGPOCollection, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPOCollection_get_Item(self: *const T, lIndex: i32, pVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPOCollection.VTable, self.vtable).get_Item(@ptrCast(*const IGPMGPOCollection, self), lIndex, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPOCollection_get__NewEnum(self: *const T, ppIGPMGPOs: ?*?*IEnumVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPOCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IGPMGPOCollection, self), ppIGPMGPOs); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMGPOLink_Value = @import("../zig.zig").Guid.initString("434b99bd-5de7-478a-809c-c251721df70c"); pub const IID_IGPMGPOLink = &IID_IGPMGPOLink_Value; pub const IGPMGPOLink = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GPOID: fn( self: *const IGPMGPOLink, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GPODomain: fn( self: *const IGPMGPOLink, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Enabled: fn( self: *const IGPMGPOLink, pVal: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Enabled: fn( self: *const IGPMGPOLink, newVal: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Enforced: fn( self: *const IGPMGPOLink, pVal: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Enforced: fn( self: *const IGPMGPOLink, newVal: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SOMLinkOrder: fn( self: *const IGPMGPOLink, lVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SOM: fn( self: *const IGPMGPOLink, ppIGPMSOM: ?*?*IGPMSOM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Delete: fn( self: *const IGPMGPOLink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPOLink_get_GPOID(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPOLink.VTable, self.vtable).get_GPOID(@ptrCast(*const IGPMGPOLink, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPOLink_get_GPODomain(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPOLink.VTable, self.vtable).get_GPODomain(@ptrCast(*const IGPMGPOLink, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPOLink_get_Enabled(self: *const T, pVal: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPOLink.VTable, self.vtable).get_Enabled(@ptrCast(*const IGPMGPOLink, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPOLink_put_Enabled(self: *const T, newVal: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPOLink.VTable, self.vtable).put_Enabled(@ptrCast(*const IGPMGPOLink, self), newVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPOLink_get_Enforced(self: *const T, pVal: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPOLink.VTable, self.vtable).get_Enforced(@ptrCast(*const IGPMGPOLink, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPOLink_put_Enforced(self: *const T, newVal: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPOLink.VTable, self.vtable).put_Enforced(@ptrCast(*const IGPMGPOLink, self), newVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPOLink_get_SOMLinkOrder(self: *const T, lVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPOLink.VTable, self.vtable).get_SOMLinkOrder(@ptrCast(*const IGPMGPOLink, self), lVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPOLink_get_SOM(self: *const T, ppIGPMSOM: ?*?*IGPMSOM) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPOLink.VTable, self.vtable).get_SOM(@ptrCast(*const IGPMGPOLink, self), ppIGPMSOM); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPOLink_Delete(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPOLink.VTable, self.vtable).Delete(@ptrCast(*const IGPMGPOLink, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMGPOLinksCollection_Value = @import("../zig.zig").Guid.initString("189d7b68-16bd-4d0d-a2ec-2e6aa2288c7f"); pub const IID_IGPMGPOLinksCollection = &IID_IGPMGPOLinksCollection_Value; pub const IGPMGPOLinksCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IGPMGPOLinksCollection, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IGPMGPOLinksCollection, lIndex: i32, pVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IGPMGPOLinksCollection, ppIGPMLinks: ?*?*IEnumVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPOLinksCollection_get_Count(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPOLinksCollection.VTable, self.vtable).get_Count(@ptrCast(*const IGPMGPOLinksCollection, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPOLinksCollection_get_Item(self: *const T, lIndex: i32, pVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPOLinksCollection.VTable, self.vtable).get_Item(@ptrCast(*const IGPMGPOLinksCollection, self), lIndex, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPOLinksCollection_get__NewEnum(self: *const T, ppIGPMLinks: ?*?*IEnumVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPOLinksCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IGPMGPOLinksCollection, self), ppIGPMLinks); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMCSECollection_Value = @import("../zig.zig").Guid.initString("2e52a97d-0a4a-4a6f-85db-201622455da0"); pub const IID_IGPMCSECollection = &IID_IGPMCSECollection_Value; pub const IGPMCSECollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IGPMCSECollection, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IGPMCSECollection, lIndex: i32, pVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IGPMCSECollection, ppIGPMCSEs: ?*?*IEnumVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMCSECollection_get_Count(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMCSECollection.VTable, self.vtable).get_Count(@ptrCast(*const IGPMCSECollection, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMCSECollection_get_Item(self: *const T, lIndex: i32, pVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMCSECollection.VTable, self.vtable).get_Item(@ptrCast(*const IGPMCSECollection, self), lIndex, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMCSECollection_get__NewEnum(self: *const T, ppIGPMCSEs: ?*?*IEnumVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMCSECollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IGPMCSECollection, self), ppIGPMCSEs); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMClientSideExtension_Value = @import("../zig.zig").Guid.initString("69da7488-b8db-415e-9266-901be4d49928"); pub const IID_IGPMClientSideExtension = &IID_IGPMClientSideExtension_Value; pub const IGPMClientSideExtension = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ID: fn( self: *const IGPMClientSideExtension, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisplayName: fn( self: *const IGPMClientSideExtension, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsUserEnabled: fn( self: *const IGPMClientSideExtension, pvbEnabled: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsComputerEnabled: fn( self: *const IGPMClientSideExtension, pvbEnabled: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMClientSideExtension_get_ID(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMClientSideExtension.VTable, self.vtable).get_ID(@ptrCast(*const IGPMClientSideExtension, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMClientSideExtension_get_DisplayName(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMClientSideExtension.VTable, self.vtable).get_DisplayName(@ptrCast(*const IGPMClientSideExtension, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMClientSideExtension_IsUserEnabled(self: *const T, pvbEnabled: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMClientSideExtension.VTable, self.vtable).IsUserEnabled(@ptrCast(*const IGPMClientSideExtension, self), pvbEnabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMClientSideExtension_IsComputerEnabled(self: *const T, pvbEnabled: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMClientSideExtension.VTable, self.vtable).IsComputerEnabled(@ptrCast(*const IGPMClientSideExtension, self), pvbEnabled); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMAsyncCancel_Value = @import("../zig.zig").Guid.initString("ddc67754-be67-4541-8166-f48166868c9c"); pub const IID_IGPMAsyncCancel = &IID_IGPMAsyncCancel_Value; pub const IGPMAsyncCancel = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Cancel: fn( self: *const IGPMAsyncCancel, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMAsyncCancel_Cancel(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMAsyncCancel.VTable, self.vtable).Cancel(@ptrCast(*const IGPMAsyncCancel, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMAsyncProgress_Value = @import("../zig.zig").Guid.initString("6aac29f8-5948-4324-bf70-423818942dbc"); pub const IID_IGPMAsyncProgress = &IID_IGPMAsyncProgress_Value; pub const IGPMAsyncProgress = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Status: fn( self: *const IGPMAsyncProgress, lProgressNumerator: i32, lProgressDenominator: i32, hrStatus: HRESULT, pResult: ?*VARIANT, ppIGPMStatusMsgCollection: ?*IGPMStatusMsgCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMAsyncProgress_Status(self: *const T, lProgressNumerator: i32, lProgressDenominator: i32, hrStatus: HRESULT, pResult: ?*VARIANT, ppIGPMStatusMsgCollection: ?*IGPMStatusMsgCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMAsyncProgress.VTable, self.vtable).Status(@ptrCast(*const IGPMAsyncProgress, self), lProgressNumerator, lProgressDenominator, hrStatus, pResult, ppIGPMStatusMsgCollection); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMStatusMsgCollection_Value = @import("../zig.zig").Guid.initString("9b6e1af0-1a92-40f3-a59d-f36ac1f728b7"); pub const IID_IGPMStatusMsgCollection = &IID_IGPMStatusMsgCollection_Value; pub const IGPMStatusMsgCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IGPMStatusMsgCollection, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IGPMStatusMsgCollection, lIndex: i32, pVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IGPMStatusMsgCollection, pVal: ?*?*IEnumVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStatusMsgCollection_get_Count(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStatusMsgCollection.VTable, self.vtable).get_Count(@ptrCast(*const IGPMStatusMsgCollection, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStatusMsgCollection_get_Item(self: *const T, lIndex: i32, pVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStatusMsgCollection.VTable, self.vtable).get_Item(@ptrCast(*const IGPMStatusMsgCollection, self), lIndex, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStatusMsgCollection_get__NewEnum(self: *const T, pVal: ?*?*IEnumVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStatusMsgCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IGPMStatusMsgCollection, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMStatusMessage_Value = @import("../zig.zig").Guid.initString("8496c22f-f3de-4a1f-8f58-603caaa93d7b"); pub const IID_IGPMStatusMessage = &IID_IGPMStatusMessage_Value; pub const IGPMStatusMessage = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ObjectPath: fn( self: *const IGPMStatusMessage, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ErrorCode: fn( self: *const IGPMStatusMessage, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ExtensionName: fn( self: *const IGPMStatusMessage, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SettingsName: fn( self: *const IGPMStatusMessage, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OperationCode: fn( self: *const IGPMStatusMessage, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Message: fn( self: *const IGPMStatusMessage, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStatusMessage_get_ObjectPath(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStatusMessage.VTable, self.vtable).get_ObjectPath(@ptrCast(*const IGPMStatusMessage, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStatusMessage_ErrorCode(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStatusMessage.VTable, self.vtable).ErrorCode(@ptrCast(*const IGPMStatusMessage, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStatusMessage_get_ExtensionName(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStatusMessage.VTable, self.vtable).get_ExtensionName(@ptrCast(*const IGPMStatusMessage, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStatusMessage_get_SettingsName(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStatusMessage.VTable, self.vtable).get_SettingsName(@ptrCast(*const IGPMStatusMessage, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStatusMessage_OperationCode(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStatusMessage.VTable, self.vtable).OperationCode(@ptrCast(*const IGPMStatusMessage, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStatusMessage_get_Message(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStatusMessage.VTable, self.vtable).get_Message(@ptrCast(*const IGPMStatusMessage, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMConstants_Value = @import("../zig.zig").Guid.initString("50ef73e6-d35c-4c8d-be63-7ea5d2aac5c4"); pub const IID_IGPMConstants = &IID_IGPMConstants_Value; pub const IGPMConstants = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermGPOApply: fn( self: *const IGPMConstants, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermGPORead: fn( self: *const IGPMConstants, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermGPOEdit: fn( self: *const IGPMConstants, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermGPOEditSecurityAndDelete: fn( self: *const IGPMConstants, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermGPOCustom: fn( self: *const IGPMConstants, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermWMIFilterEdit: fn( self: *const IGPMConstants, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermWMIFilterFullControl: fn( self: *const IGPMConstants, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermWMIFilterCustom: fn( self: *const IGPMConstants, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermSOMLink: fn( self: *const IGPMConstants, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermSOMLogging: fn( self: *const IGPMConstants, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermSOMPlanning: fn( self: *const IGPMConstants, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermSOMGPOCreate: fn( self: *const IGPMConstants, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermSOMWMICreate: fn( self: *const IGPMConstants, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermSOMWMIFullControl: fn( self: *const IGPMConstants, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchPropertyGPOPermissions: fn( self: *const IGPMConstants, pVal: ?*GPMSearchProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchPropertyGPOEffectivePermissions: fn( self: *const IGPMConstants, pVal: ?*GPMSearchProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchPropertyGPODisplayName: fn( self: *const IGPMConstants, pVal: ?*GPMSearchProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchPropertyGPOWMIFilter: fn( self: *const IGPMConstants, pVal: ?*GPMSearchProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchPropertyGPOID: fn( self: *const IGPMConstants, pVal: ?*GPMSearchProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchPropertyGPOComputerExtensions: fn( self: *const IGPMConstants, pVal: ?*GPMSearchProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchPropertyGPOUserExtensions: fn( self: *const IGPMConstants, pVal: ?*GPMSearchProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchPropertySOMLinks: fn( self: *const IGPMConstants, pVal: ?*GPMSearchProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchPropertyGPODomain: fn( self: *const IGPMConstants, pVal: ?*GPMSearchProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchPropertyBackupMostRecent: fn( self: *const IGPMConstants, pVal: ?*GPMSearchProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchOpEquals: fn( self: *const IGPMConstants, pVal: ?*GPMSearchOperation, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchOpContains: fn( self: *const IGPMConstants, pVal: ?*GPMSearchOperation, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchOpNotContains: fn( self: *const IGPMConstants, pVal: ?*GPMSearchOperation, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchOpNotEquals: fn( self: *const IGPMConstants, pVal: ?*GPMSearchOperation, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UsePDC: fn( self: *const IGPMConstants, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UseAnyDC: fn( self: *const IGPMConstants, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DoNotUseW2KDC: fn( self: *const IGPMConstants, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SOMSite: fn( self: *const IGPMConstants, pVal: ?*GPMSOMType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SOMDomain: fn( self: *const IGPMConstants, pVal: ?*GPMSOMType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SOMOU: fn( self: *const IGPMConstants, pVal: ?*GPMSOMType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SecurityFlags: fn( self: *const IGPMConstants, vbOwner: i16, vbGroup: i16, vbDACL: i16, vbSACL: i16, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DoNotValidateDC: fn( self: *const IGPMConstants, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReportHTML: fn( self: *const IGPMConstants, pVal: ?*GPMReportType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReportXML: fn( self: *const IGPMConstants, pVal: ?*GPMReportType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RSOPModeUnknown: fn( self: *const IGPMConstants, pVal: ?*GPMRSOPMode, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RSOPModePlanning: fn( self: *const IGPMConstants, pVal: ?*GPMRSOPMode, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RSOPModeLogging: fn( self: *const IGPMConstants, pVal: ?*GPMRSOPMode, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EntryTypeUser: fn( self: *const IGPMConstants, pVal: ?*GPMEntryType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EntryTypeComputer: fn( self: *const IGPMConstants, pVal: ?*GPMEntryType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EntryTypeLocalGroup: fn( self: *const IGPMConstants, pVal: ?*GPMEntryType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EntryTypeGlobalGroup: fn( self: *const IGPMConstants, pVal: ?*GPMEntryType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EntryTypeUniversalGroup: fn( self: *const IGPMConstants, pVal: ?*GPMEntryType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EntryTypeUNCPath: fn( self: *const IGPMConstants, pVal: ?*GPMEntryType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EntryTypeUnknown: fn( self: *const IGPMConstants, pVal: ?*GPMEntryType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DestinationOptionSameAsSource: fn( self: *const IGPMConstants, pVal: ?*GPMDestinationOption, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DestinationOptionNone: fn( self: *const IGPMConstants, pVal: ?*GPMDestinationOption, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DestinationOptionByRelativeName: fn( self: *const IGPMConstants, pVal: ?*GPMDestinationOption, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DestinationOptionSet: fn( self: *const IGPMConstants, pVal: ?*GPMDestinationOption, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MigrationTableOnly: fn( self: *const IGPMConstants, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ProcessSecurity: fn( self: *const IGPMConstants, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RsopLoggingNoComputer: fn( self: *const IGPMConstants, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RsopLoggingNoUser: fn( self: *const IGPMConstants, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RsopPlanningAssumeSlowLink: fn( self: *const IGPMConstants, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RsopPlanningLoopbackOption: fn( self: *const IGPMConstants, vbMerge: i16, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RsopPlanningAssumeUserWQLFilterTrue: fn( self: *const IGPMConstants, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RsopPlanningAssumeCompWQLFilterTrue: fn( self: *const IGPMConstants, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_PermGPOApply(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_PermGPOApply(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_PermGPORead(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_PermGPORead(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_PermGPOEdit(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_PermGPOEdit(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_PermGPOEditSecurityAndDelete(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_PermGPOEditSecurityAndDelete(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_PermGPOCustom(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_PermGPOCustom(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_PermWMIFilterEdit(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_PermWMIFilterEdit(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_PermWMIFilterFullControl(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_PermWMIFilterFullControl(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_PermWMIFilterCustom(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_PermWMIFilterCustom(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_PermSOMLink(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_PermSOMLink(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_PermSOMLogging(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_PermSOMLogging(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_PermSOMPlanning(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_PermSOMPlanning(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_PermSOMGPOCreate(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_PermSOMGPOCreate(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_PermSOMWMICreate(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_PermSOMWMICreate(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_PermSOMWMIFullControl(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_PermSOMWMIFullControl(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SearchPropertyGPOPermissions(self: *const T, pVal: ?*GPMSearchProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SearchPropertyGPOPermissions(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SearchPropertyGPOEffectivePermissions(self: *const T, pVal: ?*GPMSearchProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SearchPropertyGPOEffectivePermissions(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SearchPropertyGPODisplayName(self: *const T, pVal: ?*GPMSearchProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SearchPropertyGPODisplayName(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SearchPropertyGPOWMIFilter(self: *const T, pVal: ?*GPMSearchProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SearchPropertyGPOWMIFilter(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SearchPropertyGPOID(self: *const T, pVal: ?*GPMSearchProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SearchPropertyGPOID(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SearchPropertyGPOComputerExtensions(self: *const T, pVal: ?*GPMSearchProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SearchPropertyGPOComputerExtensions(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SearchPropertyGPOUserExtensions(self: *const T, pVal: ?*GPMSearchProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SearchPropertyGPOUserExtensions(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SearchPropertySOMLinks(self: *const T, pVal: ?*GPMSearchProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SearchPropertySOMLinks(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SearchPropertyGPODomain(self: *const T, pVal: ?*GPMSearchProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SearchPropertyGPODomain(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SearchPropertyBackupMostRecent(self: *const T, pVal: ?*GPMSearchProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SearchPropertyBackupMostRecent(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SearchOpEquals(self: *const T, pVal: ?*GPMSearchOperation) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SearchOpEquals(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SearchOpContains(self: *const T, pVal: ?*GPMSearchOperation) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SearchOpContains(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SearchOpNotContains(self: *const T, pVal: ?*GPMSearchOperation) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SearchOpNotContains(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SearchOpNotEquals(self: *const T, pVal: ?*GPMSearchOperation) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SearchOpNotEquals(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_UsePDC(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_UsePDC(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_UseAnyDC(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_UseAnyDC(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_DoNotUseW2KDC(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_DoNotUseW2KDC(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SOMSite(self: *const T, pVal: ?*GPMSOMType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SOMSite(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SOMDomain(self: *const T, pVal: ?*GPMSOMType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SOMDomain(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SOMOU(self: *const T, pVal: ?*GPMSOMType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SOMOU(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_SecurityFlags(self: *const T, vbOwner: i16, vbGroup: i16, vbDACL: i16, vbSACL: i16, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_SecurityFlags(@ptrCast(*const IGPMConstants, self), vbOwner, vbGroup, vbDACL, vbSACL, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_DoNotValidateDC(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_DoNotValidateDC(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_ReportHTML(self: *const T, pVal: ?*GPMReportType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_ReportHTML(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_ReportXML(self: *const T, pVal: ?*GPMReportType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_ReportXML(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_RSOPModeUnknown(self: *const T, pVal: ?*GPMRSOPMode) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_RSOPModeUnknown(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_RSOPModePlanning(self: *const T, pVal: ?*GPMRSOPMode) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_RSOPModePlanning(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_RSOPModeLogging(self: *const T, pVal: ?*GPMRSOPMode) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_RSOPModeLogging(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_EntryTypeUser(self: *const T, pVal: ?*GPMEntryType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_EntryTypeUser(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_EntryTypeComputer(self: *const T, pVal: ?*GPMEntryType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_EntryTypeComputer(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_EntryTypeLocalGroup(self: *const T, pVal: ?*GPMEntryType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_EntryTypeLocalGroup(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_EntryTypeGlobalGroup(self: *const T, pVal: ?*GPMEntryType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_EntryTypeGlobalGroup(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_EntryTypeUniversalGroup(self: *const T, pVal: ?*GPMEntryType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_EntryTypeUniversalGroup(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_EntryTypeUNCPath(self: *const T, pVal: ?*GPMEntryType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_EntryTypeUNCPath(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_EntryTypeUnknown(self: *const T, pVal: ?*GPMEntryType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_EntryTypeUnknown(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_DestinationOptionSameAsSource(self: *const T, pVal: ?*GPMDestinationOption) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_DestinationOptionSameAsSource(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_DestinationOptionNone(self: *const T, pVal: ?*GPMDestinationOption) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_DestinationOptionNone(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_DestinationOptionByRelativeName(self: *const T, pVal: ?*GPMDestinationOption) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_DestinationOptionByRelativeName(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_DestinationOptionSet(self: *const T, pVal: ?*GPMDestinationOption) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_DestinationOptionSet(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_MigrationTableOnly(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_MigrationTableOnly(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_ProcessSecurity(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_ProcessSecurity(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_RsopLoggingNoComputer(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_RsopLoggingNoComputer(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_RsopLoggingNoUser(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_RsopLoggingNoUser(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_RsopPlanningAssumeSlowLink(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_RsopPlanningAssumeSlowLink(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_RsopPlanningLoopbackOption(self: *const T, vbMerge: i16, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_RsopPlanningLoopbackOption(@ptrCast(*const IGPMConstants, self), vbMerge, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_RsopPlanningAssumeUserWQLFilterTrue(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_RsopPlanningAssumeUserWQLFilterTrue(@ptrCast(*const IGPMConstants, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants_get_RsopPlanningAssumeCompWQLFilterTrue(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants.VTable, self.vtable).get_RsopPlanningAssumeCompWQLFilterTrue(@ptrCast(*const IGPMConstants, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMResult_Value = @import("../zig.zig").Guid.initString("86dff7e9-f76f-42ab-9570-cebc6be8a52d"); pub const IID_IGPMResult = &IID_IGPMResult_Value; pub const IGPMResult = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Status: fn( self: *const IGPMResult, ppIGPMStatusMsgCollection: ?*?*IGPMStatusMsgCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Result: fn( self: *const IGPMResult, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OverallStatus: fn( self: *const IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMResult_get_Status(self: *const T, ppIGPMStatusMsgCollection: ?*?*IGPMStatusMsgCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMResult.VTable, self.vtable).get_Status(@ptrCast(*const IGPMResult, self), ppIGPMStatusMsgCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMResult_get_Result(self: *const T, pvarResult: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMResult.VTable, self.vtable).get_Result(@ptrCast(*const IGPMResult, self), pvarResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMResult_OverallStatus(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMResult.VTable, self.vtable).OverallStatus(@ptrCast(*const IGPMResult, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMMapEntryCollection_Value = @import("../zig.zig").Guid.initString("bb0bf49b-e53f-443f-b807-8be22bfb6d42"); pub const IID_IGPMMapEntryCollection = &IID_IGPMMapEntryCollection_Value; pub const IGPMMapEntryCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IGPMMapEntryCollection, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IGPMMapEntryCollection, lIndex: i32, pVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IGPMMapEntryCollection, pVal: ?*?*IEnumVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMMapEntryCollection_get_Count(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMMapEntryCollection.VTable, self.vtable).get_Count(@ptrCast(*const IGPMMapEntryCollection, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMMapEntryCollection_get_Item(self: *const T, lIndex: i32, pVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMMapEntryCollection.VTable, self.vtable).get_Item(@ptrCast(*const IGPMMapEntryCollection, self), lIndex, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMMapEntryCollection_get__NewEnum(self: *const T, pVal: ?*?*IEnumVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMMapEntryCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IGPMMapEntryCollection, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMMapEntry_Value = @import("../zig.zig").Guid.initString("8e79ad06-2381-4444-be4c-ff693e6e6f2b"); pub const IID_IGPMMapEntry = &IID_IGPMMapEntry_Value; pub const IGPMMapEntry = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Source: fn( self: *const IGPMMapEntry, pbstrSource: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Destination: fn( self: *const IGPMMapEntry, pbstrDestination: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DestinationOption: fn( self: *const IGPMMapEntry, pgpmDestOption: ?*GPMDestinationOption, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EntryType: fn( self: *const IGPMMapEntry, pgpmEntryType: ?*GPMEntryType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMMapEntry_get_Source(self: *const T, pbstrSource: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMMapEntry.VTable, self.vtable).get_Source(@ptrCast(*const IGPMMapEntry, self), pbstrSource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMMapEntry_get_Destination(self: *const T, pbstrDestination: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMMapEntry.VTable, self.vtable).get_Destination(@ptrCast(*const IGPMMapEntry, self), pbstrDestination); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMMapEntry_get_DestinationOption(self: *const T, pgpmDestOption: ?*GPMDestinationOption) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMMapEntry.VTable, self.vtable).get_DestinationOption(@ptrCast(*const IGPMMapEntry, self), pgpmDestOption); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMMapEntry_get_EntryType(self: *const T, pgpmEntryType: ?*GPMEntryType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMMapEntry.VTable, self.vtable).get_EntryType(@ptrCast(*const IGPMMapEntry, self), pgpmEntryType); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMMigrationTable_Value = @import("../zig.zig").Guid.initString("48f823b1-efaf-470b-b6ed-40d14ee1a4ec"); pub const IID_IGPMMigrationTable = &IID_IGPMMigrationTable_Value; pub const IGPMMigrationTable = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Save: fn( self: *const IGPMMigrationTable, bstrMigrationTablePath: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const IGPMMigrationTable, lFlags: i32, @"var": VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddEntry: fn( self: *const IGPMMigrationTable, bstrSource: ?BSTR, gpmEntryType: GPMEntryType, pvarDestination: ?*VARIANT, ppEntry: ?*?*IGPMMapEntry, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEntry: fn( self: *const IGPMMigrationTable, bstrSource: ?BSTR, ppEntry: ?*?*IGPMMapEntry, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteEntry: fn( self: *const IGPMMigrationTable, bstrSource: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateDestination: fn( self: *const IGPMMigrationTable, bstrSource: ?BSTR, pvarDestination: ?*VARIANT, ppEntry: ?*?*IGPMMapEntry, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Validate: fn( self: *const IGPMMigrationTable, ppResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEntries: fn( self: *const IGPMMigrationTable, ppEntries: ?*?*IGPMMapEntryCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMMigrationTable_Save(self: *const T, bstrMigrationTablePath: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMMigrationTable.VTable, self.vtable).Save(@ptrCast(*const IGPMMigrationTable, self), bstrMigrationTablePath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMMigrationTable_Add(self: *const T, lFlags: i32, @"var": VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMMigrationTable.VTable, self.vtable).Add(@ptrCast(*const IGPMMigrationTable, self), lFlags, @"var"); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMMigrationTable_AddEntry(self: *const T, bstrSource: ?BSTR, gpmEntryType: GPMEntryType, pvarDestination: ?*VARIANT, ppEntry: ?*?*IGPMMapEntry) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMMigrationTable.VTable, self.vtable).AddEntry(@ptrCast(*const IGPMMigrationTable, self), bstrSource, gpmEntryType, pvarDestination, ppEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMMigrationTable_GetEntry(self: *const T, bstrSource: ?BSTR, ppEntry: ?*?*IGPMMapEntry) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMMigrationTable.VTable, self.vtable).GetEntry(@ptrCast(*const IGPMMigrationTable, self), bstrSource, ppEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMMigrationTable_DeleteEntry(self: *const T, bstrSource: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMMigrationTable.VTable, self.vtable).DeleteEntry(@ptrCast(*const IGPMMigrationTable, self), bstrSource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMMigrationTable_UpdateDestination(self: *const T, bstrSource: ?BSTR, pvarDestination: ?*VARIANT, ppEntry: ?*?*IGPMMapEntry) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMMigrationTable.VTable, self.vtable).UpdateDestination(@ptrCast(*const IGPMMigrationTable, self), bstrSource, pvarDestination, ppEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMMigrationTable_Validate(self: *const T, ppResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMMigrationTable.VTable, self.vtable).Validate(@ptrCast(*const IGPMMigrationTable, self), ppResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMMigrationTable_GetEntries(self: *const T, ppEntries: ?*?*IGPMMapEntryCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMMigrationTable.VTable, self.vtable).GetEntries(@ptrCast(*const IGPMMigrationTable, self), ppEntries); } };} pub usingnamespace MethodMixin(@This()); }; pub const GPMBackupType = enum(i32) { GPO = 0, StarterGPO = 1, }; pub const typeGPO = GPMBackupType.GPO; pub const typeStarterGPO = GPMBackupType.StarterGPO; pub const GPMStarterGPOType = enum(i32) { System = 0, Custom = 1, }; pub const typeSystem = GPMStarterGPOType.System; pub const typeCustom = GPMStarterGPOType.Custom; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMBackupDirEx_Value = @import("../zig.zig").Guid.initString("f8dc55ed-3ba0-4864-aad4-d365189ee1d5"); pub const IID_IGPMBackupDirEx = &IID_IGPMBackupDirEx_Value; pub const IGPMBackupDirEx = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BackupDir: fn( self: *const IGPMBackupDirEx, pbstrBackupDir: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BackupType: fn( self: *const IGPMBackupDirEx, pgpmBackupType: ?*GPMBackupType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBackup: fn( self: *const IGPMBackupDirEx, bstrID: ?BSTR, pvarBackup: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SearchBackups: fn( self: *const IGPMBackupDirEx, pIGPMSearchCriteria: ?*IGPMSearchCriteria, pvarBackupCollection: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackupDirEx_get_BackupDir(self: *const T, pbstrBackupDir: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackupDirEx.VTable, self.vtable).get_BackupDir(@ptrCast(*const IGPMBackupDirEx, self), pbstrBackupDir); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackupDirEx_get_BackupType(self: *const T, pgpmBackupType: ?*GPMBackupType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackupDirEx.VTable, self.vtable).get_BackupType(@ptrCast(*const IGPMBackupDirEx, self), pgpmBackupType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackupDirEx_GetBackup(self: *const T, bstrID: ?BSTR, pvarBackup: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackupDirEx.VTable, self.vtable).GetBackup(@ptrCast(*const IGPMBackupDirEx, self), bstrID, pvarBackup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMBackupDirEx_SearchBackups(self: *const T, pIGPMSearchCriteria: ?*IGPMSearchCriteria, pvarBackupCollection: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMBackupDirEx.VTable, self.vtable).SearchBackups(@ptrCast(*const IGPMBackupDirEx, self), pIGPMSearchCriteria, pvarBackupCollection); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMStarterGPOBackupCollection_Value = @import("../zig.zig").Guid.initString("c998031d-add0-4bb5-8dea-298505d8423b"); pub const IID_IGPMStarterGPOBackupCollection = &IID_IGPMStarterGPOBackupCollection_Value; pub const IGPMStarterGPOBackupCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IGPMStarterGPOBackupCollection, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IGPMStarterGPOBackupCollection, lIndex: i32, pVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IGPMStarterGPOBackupCollection, ppIGPMTmplBackup: ?*?*IEnumVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOBackupCollection_get_Count(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOBackupCollection.VTable, self.vtable).get_Count(@ptrCast(*const IGPMStarterGPOBackupCollection, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOBackupCollection_get_Item(self: *const T, lIndex: i32, pVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOBackupCollection.VTable, self.vtable).get_Item(@ptrCast(*const IGPMStarterGPOBackupCollection, self), lIndex, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOBackupCollection_get__NewEnum(self: *const T, ppIGPMTmplBackup: ?*?*IEnumVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOBackupCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IGPMStarterGPOBackupCollection, self), ppIGPMTmplBackup); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMStarterGPOBackup_Value = @import("../zig.zig").Guid.initString("51d98eda-a87e-43dd-b80a-0b66ef1938d6"); pub const IID_IGPMStarterGPOBackup = &IID_IGPMStarterGPOBackup_Value; pub const IGPMStarterGPOBackup = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BackupDir: fn( self: *const IGPMStarterGPOBackup, pbstrBackupDir: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Comment: fn( self: *const IGPMStarterGPOBackup, pbstrComment: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisplayName: fn( self: *const IGPMStarterGPOBackup, pbstrDisplayName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Domain: fn( self: *const IGPMStarterGPOBackup, pbstrTemplateDomain: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StarterGPOID: fn( self: *const IGPMStarterGPOBackup, pbstrTemplateID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ID: fn( self: *const IGPMStarterGPOBackup, pbstrID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Timestamp: fn( self: *const IGPMStarterGPOBackup, pTimestamp: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Type: fn( self: *const IGPMStarterGPOBackup, pType: ?*GPMStarterGPOType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Delete: fn( self: *const IGPMStarterGPOBackup, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GenerateReport: fn( self: *const IGPMStarterGPOBackup, gpmReportType: GPMReportType, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GenerateReportToFile: fn( self: *const IGPMStarterGPOBackup, gpmReportType: GPMReportType, bstrTargetFilePath: ?BSTR, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOBackup_get_BackupDir(self: *const T, pbstrBackupDir: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOBackup.VTable, self.vtable).get_BackupDir(@ptrCast(*const IGPMStarterGPOBackup, self), pbstrBackupDir); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOBackup_get_Comment(self: *const T, pbstrComment: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOBackup.VTable, self.vtable).get_Comment(@ptrCast(*const IGPMStarterGPOBackup, self), pbstrComment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOBackup_get_DisplayName(self: *const T, pbstrDisplayName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOBackup.VTable, self.vtable).get_DisplayName(@ptrCast(*const IGPMStarterGPOBackup, self), pbstrDisplayName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOBackup_get_Domain(self: *const T, pbstrTemplateDomain: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOBackup.VTable, self.vtable).get_Domain(@ptrCast(*const IGPMStarterGPOBackup, self), pbstrTemplateDomain); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOBackup_get_StarterGPOID(self: *const T, pbstrTemplateID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOBackup.VTable, self.vtable).get_StarterGPOID(@ptrCast(*const IGPMStarterGPOBackup, self), pbstrTemplateID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOBackup_get_ID(self: *const T, pbstrID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOBackup.VTable, self.vtable).get_ID(@ptrCast(*const IGPMStarterGPOBackup, self), pbstrID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOBackup_get_Timestamp(self: *const T, pTimestamp: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOBackup.VTable, self.vtable).get_Timestamp(@ptrCast(*const IGPMStarterGPOBackup, self), pTimestamp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOBackup_get_Type(self: *const T, pType: ?*GPMStarterGPOType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOBackup.VTable, self.vtable).get_Type(@ptrCast(*const IGPMStarterGPOBackup, self), pType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOBackup_Delete(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOBackup.VTable, self.vtable).Delete(@ptrCast(*const IGPMStarterGPOBackup, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOBackup_GenerateReport(self: *const T, gpmReportType: GPMReportType, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOBackup.VTable, self.vtable).GenerateReport(@ptrCast(*const IGPMStarterGPOBackup, self), gpmReportType, pvarGPMProgress, pvarGPMCancel, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOBackup_GenerateReportToFile(self: *const T, gpmReportType: GPMReportType, bstrTargetFilePath: ?BSTR, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOBackup.VTable, self.vtable).GenerateReportToFile(@ptrCast(*const IGPMStarterGPOBackup, self), gpmReportType, bstrTargetFilePath, ppIGPMResult); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPM2_Value = @import("../zig.zig").Guid.initString("00238f8a-3d86-41ac-8f5e-06a6638a634a"); pub const IID_IGPM2 = &IID_IGPM2_Value; pub const IGPM2 = extern struct { pub const VTable = extern struct { base: IGPM.VTable, GetBackupDirEx: fn( self: *const IGPM2, bstrBackupDir: ?BSTR, backupDirType: GPMBackupType, ppIGPMBackupDirEx: ?*?*IGPMBackupDirEx, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitializeReportingEx: fn( self: *const IGPM2, bstrAdmPath: ?BSTR, reportingOptions: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IGPM.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPM2_GetBackupDirEx(self: *const T, bstrBackupDir: ?BSTR, backupDirType: GPMBackupType, ppIGPMBackupDirEx: ?*?*IGPMBackupDirEx) callconv(.Inline) HRESULT { return @ptrCast(*const IGPM2.VTable, self.vtable).GetBackupDirEx(@ptrCast(*const IGPM2, self), bstrBackupDir, backupDirType, ppIGPMBackupDirEx); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPM2_InitializeReportingEx(self: *const T, bstrAdmPath: ?BSTR, reportingOptions: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPM2.VTable, self.vtable).InitializeReportingEx(@ptrCast(*const IGPM2, self), bstrAdmPath, reportingOptions); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMStarterGPO_Value = @import("../zig.zig").Guid.initString("dfc3f61b-8880-4490-9337-d29c7ba8c2f0"); pub const IID_IGPMStarterGPO = &IID_IGPMStarterGPO_Value; pub const IGPMStarterGPO = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisplayName: fn( self: *const IGPMStarterGPO, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DisplayName: fn( self: *const IGPMStarterGPO, newVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IGPMStarterGPO, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IGPMStarterGPO, newVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Author: fn( self: *const IGPMStarterGPO, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Product: fn( self: *const IGPMStarterGPO, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CreationTime: fn( self: *const IGPMStarterGPO, pVal: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ID: fn( self: *const IGPMStarterGPO, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ModifiedTime: fn( self: *const IGPMStarterGPO, pVal: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Type: fn( self: *const IGPMStarterGPO, pVal: ?*GPMStarterGPOType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ComputerVersion: fn( self: *const IGPMStarterGPO, pVal: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserVersion: fn( self: *const IGPMStarterGPO, pVal: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StarterGPOVersion: fn( self: *const IGPMStarterGPO, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Delete: fn( self: *const IGPMStarterGPO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Save: fn( self: *const IGPMStarterGPO, bstrSaveFile: ?BSTR, bOverwrite: i16, bSaveAsSystem: i16, bstrLanguage: ?*VARIANT, bstrAuthor: ?*VARIANT, bstrProduct: ?*VARIANT, bstrUniqueID: ?*VARIANT, bstrVersion: ?*VARIANT, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Backup: fn( self: *const IGPMStarterGPO, bstrBackupDir: ?BSTR, bstrComment: ?BSTR, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyTo: fn( self: *const IGPMStarterGPO, pvarNewDisplayName: ?*VARIANT, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GenerateReport: fn( self: *const IGPMStarterGPO, gpmReportType: GPMReportType, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GenerateReportToFile: fn( self: *const IGPMStarterGPO, gpmReportType: GPMReportType, bstrTargetFilePath: ?BSTR, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSecurityInfo: fn( self: *const IGPMStarterGPO, ppSecurityInfo: ?*?*IGPMSecurityInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSecurityInfo: fn( self: *const IGPMStarterGPO, pSecurityInfo: ?*IGPMSecurityInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_get_DisplayName(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).get_DisplayName(@ptrCast(*const IGPMStarterGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_put_DisplayName(self: *const T, newVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).put_DisplayName(@ptrCast(*const IGPMStarterGPO, self), newVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_get_Description(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).get_Description(@ptrCast(*const IGPMStarterGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_put_Description(self: *const T, newVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).put_Description(@ptrCast(*const IGPMStarterGPO, self), newVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_get_Author(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).get_Author(@ptrCast(*const IGPMStarterGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_get_Product(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).get_Product(@ptrCast(*const IGPMStarterGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_get_CreationTime(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).get_CreationTime(@ptrCast(*const IGPMStarterGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_get_ID(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).get_ID(@ptrCast(*const IGPMStarterGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_get_ModifiedTime(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).get_ModifiedTime(@ptrCast(*const IGPMStarterGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_get_Type(self: *const T, pVal: ?*GPMStarterGPOType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).get_Type(@ptrCast(*const IGPMStarterGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_get_ComputerVersion(self: *const T, pVal: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).get_ComputerVersion(@ptrCast(*const IGPMStarterGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_get_UserVersion(self: *const T, pVal: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).get_UserVersion(@ptrCast(*const IGPMStarterGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_get_StarterGPOVersion(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).get_StarterGPOVersion(@ptrCast(*const IGPMStarterGPO, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_Delete(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).Delete(@ptrCast(*const IGPMStarterGPO, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_Save(self: *const T, bstrSaveFile: ?BSTR, bOverwrite: i16, bSaveAsSystem: i16, bstrLanguage: ?*VARIANT, bstrAuthor: ?*VARIANT, bstrProduct: ?*VARIANT, bstrUniqueID: ?*VARIANT, bstrVersion: ?*VARIANT, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).Save(@ptrCast(*const IGPMStarterGPO, self), bstrSaveFile, bOverwrite, bSaveAsSystem, bstrLanguage, bstrAuthor, bstrProduct, bstrUniqueID, bstrVersion, pvarGPMProgress, pvarGPMCancel, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_Backup(self: *const T, bstrBackupDir: ?BSTR, bstrComment: ?BSTR, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).Backup(@ptrCast(*const IGPMStarterGPO, self), bstrBackupDir, bstrComment, pvarGPMProgress, pvarGPMCancel, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_CopyTo(self: *const T, pvarNewDisplayName: ?*VARIANT, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).CopyTo(@ptrCast(*const IGPMStarterGPO, self), pvarNewDisplayName, pvarGPMProgress, pvarGPMCancel, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_GenerateReport(self: *const T, gpmReportType: GPMReportType, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).GenerateReport(@ptrCast(*const IGPMStarterGPO, self), gpmReportType, pvarGPMProgress, pvarGPMCancel, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_GenerateReportToFile(self: *const T, gpmReportType: GPMReportType, bstrTargetFilePath: ?BSTR, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).GenerateReportToFile(@ptrCast(*const IGPMStarterGPO, self), gpmReportType, bstrTargetFilePath, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_GetSecurityInfo(self: *const T, ppSecurityInfo: ?*?*IGPMSecurityInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).GetSecurityInfo(@ptrCast(*const IGPMStarterGPO, self), ppSecurityInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPO_SetSecurityInfo(self: *const T, pSecurityInfo: ?*IGPMSecurityInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPO.VTable, self.vtable).SetSecurityInfo(@ptrCast(*const IGPMStarterGPO, self), pSecurityInfo); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMStarterGPOCollection_Value = @import("../zig.zig").Guid.initString("2e522729-2219-44ad-933a-64dfd650c423"); pub const IID_IGPMStarterGPOCollection = &IID_IGPMStarterGPOCollection_Value; pub const IGPMStarterGPOCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IGPMStarterGPOCollection, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IGPMStarterGPOCollection, lIndex: i32, pVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IGPMStarterGPOCollection, ppIGPMTemplates: ?*?*IEnumVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOCollection_get_Count(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOCollection.VTable, self.vtable).get_Count(@ptrCast(*const IGPMStarterGPOCollection, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOCollection_get_Item(self: *const T, lIndex: i32, pVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOCollection.VTable, self.vtable).get_Item(@ptrCast(*const IGPMStarterGPOCollection, self), lIndex, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMStarterGPOCollection_get__NewEnum(self: *const T, ppIGPMTemplates: ?*?*IEnumVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMStarterGPOCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IGPMStarterGPOCollection, self), ppIGPMTemplates); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMDomain2_Value = @import("../zig.zig").Guid.initString("7ca6bb8b-f1eb-490a-938d-3c4e51c768e6"); pub const IID_IGPMDomain2 = &IID_IGPMDomain2_Value; pub const IGPMDomain2 = extern struct { pub const VTable = extern struct { base: IGPMDomain.VTable, CreateStarterGPO: fn( self: *const IGPMDomain2, ppnewTemplate: ?*?*IGPMStarterGPO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateGPOFromStarterGPO: fn( self: *const IGPMDomain2, pGPOTemplate: ?*IGPMStarterGPO, ppnewGPO: ?*?*IGPMGPO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStarterGPO: fn( self: *const IGPMDomain2, bstrGuid: ?BSTR, ppTemplate: ?*?*IGPMStarterGPO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SearchStarterGPOs: fn( self: *const IGPMDomain2, pIGPMSearchCriteria: ?*IGPMSearchCriteria, ppIGPMTemplateCollection: ?*?*IGPMStarterGPOCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LoadStarterGPO: fn( self: *const IGPMDomain2, bstrLoadFile: ?BSTR, bOverwrite: i16, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RestoreStarterGPO: fn( self: *const IGPMDomain2, pIGPMTmplBackup: ?*IGPMStarterGPOBackup, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IGPMDomain.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain2_CreateStarterGPO(self: *const T, ppnewTemplate: ?*?*IGPMStarterGPO) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain2.VTable, self.vtable).CreateStarterGPO(@ptrCast(*const IGPMDomain2, self), ppnewTemplate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain2_CreateGPOFromStarterGPO(self: *const T, pGPOTemplate: ?*IGPMStarterGPO, ppnewGPO: ?*?*IGPMGPO) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain2.VTable, self.vtable).CreateGPOFromStarterGPO(@ptrCast(*const IGPMDomain2, self), pGPOTemplate, ppnewGPO); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain2_GetStarterGPO(self: *const T, bstrGuid: ?BSTR, ppTemplate: ?*?*IGPMStarterGPO) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain2.VTable, self.vtable).GetStarterGPO(@ptrCast(*const IGPMDomain2, self), bstrGuid, ppTemplate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain2_SearchStarterGPOs(self: *const T, pIGPMSearchCriteria: ?*IGPMSearchCriteria, ppIGPMTemplateCollection: ?*?*IGPMStarterGPOCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain2.VTable, self.vtable).SearchStarterGPOs(@ptrCast(*const IGPMDomain2, self), pIGPMSearchCriteria, ppIGPMTemplateCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain2_LoadStarterGPO(self: *const T, bstrLoadFile: ?BSTR, bOverwrite: i16, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain2.VTable, self.vtable).LoadStarterGPO(@ptrCast(*const IGPMDomain2, self), bstrLoadFile, bOverwrite, pvarGPMProgress, pvarGPMCancel, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain2_RestoreStarterGPO(self: *const T, pIGPMTmplBackup: ?*IGPMStarterGPOBackup, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain2.VTable, self.vtable).RestoreStarterGPO(@ptrCast(*const IGPMDomain2, self), pIGPMTmplBackup, pvarGPMProgress, pvarGPMCancel, ppIGPMResult); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMConstants2_Value = @import("../zig.zig").Guid.initString("05ae21b0-ac09-4032-a26f-9e7da786dc19"); pub const IID_IGPMConstants2 = &IID_IGPMConstants2_Value; pub const IGPMConstants2 = extern struct { pub const VTable = extern struct { base: IGPMConstants.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BackupTypeGPO: fn( self: *const IGPMConstants2, pVal: ?*GPMBackupType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BackupTypeStarterGPO: fn( self: *const IGPMConstants2, pVal: ?*GPMBackupType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StarterGPOTypeSystem: fn( self: *const IGPMConstants2, pVal: ?*GPMStarterGPOType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StarterGPOTypeCustom: fn( self: *const IGPMConstants2, pVal: ?*GPMStarterGPOType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchPropertyStarterGPOPermissions: fn( self: *const IGPMConstants2, pVal: ?*GPMSearchProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchPropertyStarterGPOEffectivePermissions: fn( self: *const IGPMConstants2, pVal: ?*GPMSearchProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchPropertyStarterGPODisplayName: fn( self: *const IGPMConstants2, pVal: ?*GPMSearchProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchPropertyStarterGPOID: fn( self: *const IGPMConstants2, pVal: ?*GPMSearchProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SearchPropertyStarterGPODomain: fn( self: *const IGPMConstants2, pVal: ?*GPMSearchProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermStarterGPORead: fn( self: *const IGPMConstants2, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermStarterGPOEdit: fn( self: *const IGPMConstants2, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermStarterGPOFullControl: fn( self: *const IGPMConstants2, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PermStarterGPOCustom: fn( self: *const IGPMConstants2, pVal: ?*GPMPermissionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReportLegacy: fn( self: *const IGPMConstants2, pVal: ?*GPMReportingOptions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReportComments: fn( self: *const IGPMConstants2, pVal: ?*GPMReportingOptions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IGPMConstants.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants2_get_BackupTypeGPO(self: *const T, pVal: ?*GPMBackupType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants2.VTable, self.vtable).get_BackupTypeGPO(@ptrCast(*const IGPMConstants2, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants2_get_BackupTypeStarterGPO(self: *const T, pVal: ?*GPMBackupType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants2.VTable, self.vtable).get_BackupTypeStarterGPO(@ptrCast(*const IGPMConstants2, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants2_get_StarterGPOTypeSystem(self: *const T, pVal: ?*GPMStarterGPOType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants2.VTable, self.vtable).get_StarterGPOTypeSystem(@ptrCast(*const IGPMConstants2, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants2_get_StarterGPOTypeCustom(self: *const T, pVal: ?*GPMStarterGPOType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants2.VTable, self.vtable).get_StarterGPOTypeCustom(@ptrCast(*const IGPMConstants2, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants2_get_SearchPropertyStarterGPOPermissions(self: *const T, pVal: ?*GPMSearchProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants2.VTable, self.vtable).get_SearchPropertyStarterGPOPermissions(@ptrCast(*const IGPMConstants2, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants2_get_SearchPropertyStarterGPOEffectivePermissions(self: *const T, pVal: ?*GPMSearchProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants2.VTable, self.vtable).get_SearchPropertyStarterGPOEffectivePermissions(@ptrCast(*const IGPMConstants2, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants2_get_SearchPropertyStarterGPODisplayName(self: *const T, pVal: ?*GPMSearchProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants2.VTable, self.vtable).get_SearchPropertyStarterGPODisplayName(@ptrCast(*const IGPMConstants2, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants2_get_SearchPropertyStarterGPOID(self: *const T, pVal: ?*GPMSearchProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants2.VTable, self.vtable).get_SearchPropertyStarterGPOID(@ptrCast(*const IGPMConstants2, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants2_get_SearchPropertyStarterGPODomain(self: *const T, pVal: ?*GPMSearchProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants2.VTable, self.vtable).get_SearchPropertyStarterGPODomain(@ptrCast(*const IGPMConstants2, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants2_get_PermStarterGPORead(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants2.VTable, self.vtable).get_PermStarterGPORead(@ptrCast(*const IGPMConstants2, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants2_get_PermStarterGPOEdit(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants2.VTable, self.vtable).get_PermStarterGPOEdit(@ptrCast(*const IGPMConstants2, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants2_get_PermStarterGPOFullControl(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants2.VTable, self.vtable).get_PermStarterGPOFullControl(@ptrCast(*const IGPMConstants2, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants2_get_PermStarterGPOCustom(self: *const T, pVal: ?*GPMPermissionType) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants2.VTable, self.vtable).get_PermStarterGPOCustom(@ptrCast(*const IGPMConstants2, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants2_get_ReportLegacy(self: *const T, pVal: ?*GPMReportingOptions) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants2.VTable, self.vtable).get_ReportLegacy(@ptrCast(*const IGPMConstants2, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMConstants2_get_ReportComments(self: *const T, pVal: ?*GPMReportingOptions) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMConstants2.VTable, self.vtable).get_ReportComments(@ptrCast(*const IGPMConstants2, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPMGPO2_Value = @import("../zig.zig").Guid.initString("8a66a210-b78b-4d99-88e2-c306a817c925"); pub const IID_IGPMGPO2 = &IID_IGPMGPO2_Value; pub const IGPMGPO2 = extern struct { pub const VTable = extern struct { base: IGPMGPO.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IGPMGPO2, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IGPMGPO2, newVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IGPMGPO.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO2_get_Description(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO2.VTable, self.vtable).get_Description(@ptrCast(*const IGPMGPO2, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO2_put_Description(self: *const T, newVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO2.VTable, self.vtable).put_Description(@ptrCast(*const IGPMGPO2, self), newVal); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IGPMDomain3_Value = @import("../zig.zig").Guid.initString("0077fdfe-88c7-4acf-a11d-d10a7c310a03"); pub const IID_IGPMDomain3 = &IID_IGPMDomain3_Value; pub const IGPMDomain3 = extern struct { pub const VTable = extern struct { base: IGPMDomain2.VTable, GenerateReport: fn( self: *const IGPMDomain3, gpmReportType: GPMReportType, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_InfrastructureDC: fn( self: *const IGPMDomain3, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_InfrastructureDC: fn( self: *const IGPMDomain3, newVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_InfrastructureFlags: fn( self: *const IGPMDomain3, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IGPMDomain2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain3_GenerateReport(self: *const T, gpmReportType: GPMReportType, pvarGPMProgress: ?*VARIANT, pvarGPMCancel: ?*VARIANT, ppIGPMResult: ?*?*IGPMResult) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain3.VTable, self.vtable).GenerateReport(@ptrCast(*const IGPMDomain3, self), gpmReportType, pvarGPMProgress, pvarGPMCancel, ppIGPMResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain3_get_InfrastructureDC(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain3.VTable, self.vtable).get_InfrastructureDC(@ptrCast(*const IGPMDomain3, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain3_put_InfrastructureDC(self: *const T, newVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain3.VTable, self.vtable).put_InfrastructureDC(@ptrCast(*const IGPMDomain3, self), newVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMDomain3_put_InfrastructureFlags(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMDomain3.VTable, self.vtable).put_InfrastructureFlags(@ptrCast(*const IGPMDomain3, self), dwFlags); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IGPMGPO3_Value = @import("../zig.zig").Guid.initString("7cf123a1-f94a-4112-bfae-6aa1db9cb248"); pub const IID_IGPMGPO3 = &IID_IGPMGPO3_Value; pub const IGPMGPO3 = extern struct { pub const VTable = extern struct { base: IGPMGPO2.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_InfrastructureDC: fn( self: *const IGPMGPO3, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_InfrastructureDC: fn( self: *const IGPMGPO3, newVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_InfrastructureFlags: fn( self: *const IGPMGPO3, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IGPMGPO2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO3_get_InfrastructureDC(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO3.VTable, self.vtable).get_InfrastructureDC(@ptrCast(*const IGPMGPO3, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO3_put_InfrastructureDC(self: *const T, newVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO3.VTable, self.vtable).put_InfrastructureDC(@ptrCast(*const IGPMGPO3, self), newVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPMGPO3_put_InfrastructureFlags(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPMGPO3.VTable, self.vtable).put_InfrastructureFlags(@ptrCast(*const IGPMGPO3, self), dwFlags); } };} pub usingnamespace MethodMixin(@This()); }; pub const GPO_LINK = enum(i32) { Unknown = 0, Machine = 1, Site = 2, Domain = 3, OrganizationalUnit = 4, }; pub const GPLinkUnknown = GPO_LINK.Unknown; pub const GPLinkMachine = GPO_LINK.Machine; pub const GPLinkSite = GPO_LINK.Site; pub const GPLinkDomain = GPO_LINK.Domain; pub const GPLinkOrganizationalUnit = GPO_LINK.OrganizationalUnit; pub const GROUP_POLICY_OBJECTA = extern struct { dwOptions: u32, dwVersion: u32, lpDSPath: ?PSTR, lpFileSysPath: ?PSTR, lpDisplayName: ?PSTR, szGPOName: [50]CHAR, GPOLink: GPO_LINK, lParam: LPARAM, pNext: ?*GROUP_POLICY_OBJECTA, pPrev: ?*GROUP_POLICY_OBJECTA, lpExtensions: ?PSTR, lParam2: LPARAM, lpLink: ?PSTR, }; pub const GROUP_POLICY_OBJECTW = extern struct { dwOptions: u32, dwVersion: u32, lpDSPath: ?PWSTR, lpFileSysPath: ?PWSTR, lpDisplayName: ?PWSTR, szGPOName: [50]u16, GPOLink: GPO_LINK, lParam: LPARAM, pNext: ?*GROUP_POLICY_OBJECTW, pPrev: ?*GROUP_POLICY_OBJECTW, lpExtensions: ?PWSTR, lParam2: LPARAM, lpLink: ?PWSTR, }; pub const PFNSTATUSMESSAGECALLBACK = fn( bVerbose: BOOL, lpMessage: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFNPROCESSGROUPPOLICY = fn( dwFlags: u32, hToken: ?HANDLE, hKeyRoot: ?HKEY, pDeletedGPOList: ?*GROUP_POLICY_OBJECTA, pChangedGPOList: ?*GROUP_POLICY_OBJECTA, pHandle: usize, pbAbort: ?*BOOL, pStatusCallback: ?PFNSTATUSMESSAGECALLBACK, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFNPROCESSGROUPPOLICYEX = fn( dwFlags: u32, hToken: ?HANDLE, hKeyRoot: ?HKEY, pDeletedGPOList: ?*GROUP_POLICY_OBJECTA, pChangedGPOList: ?*GROUP_POLICY_OBJECTA, pHandle: usize, pbAbort: ?*BOOL, pStatusCallback: ?PFNSTATUSMESSAGECALLBACK, pWbemServices: ?*IWbemServices, pRsopStatus: ?*HRESULT, ) callconv(@import("std").os.windows.WINAPI) u32; pub const RSOP_TARGET = extern struct { pwszAccountName: ?PWSTR, pwszNewSOM: ?PWSTR, psaSecurityGroups: ?*SAFEARRAY, pRsopToken: ?*anyopaque, pGPOList: ?*GROUP_POLICY_OBJECTA, pWbemServices: ?*IWbemServices, }; pub const PFNGENERATEGROUPPOLICY = fn( dwFlags: u32, pbAbort: ?*BOOL, pwszSite: ?PWSTR, pComputerTarget: ?*RSOP_TARGET, pUserTarget: ?*RSOP_TARGET, ) callconv(@import("std").os.windows.WINAPI) u32; pub const SETTINGSTATUS = enum(i32) { Unspecified = 0, Applied = 1, Ignored = 2, Failed = 3, SubsettingFailed = 4, }; pub const RSOPUnspecified = SETTINGSTATUS.Unspecified; pub const RSOPApplied = SETTINGSTATUS.Applied; pub const RSOPIgnored = SETTINGSTATUS.Ignored; pub const RSOPFailed = SETTINGSTATUS.Failed; pub const RSOPSubsettingFailed = SETTINGSTATUS.SubsettingFailed; pub const POLICYSETTINGSTATUSINFO = extern struct { szKey: ?PWSTR, szEventSource: ?PWSTR, szEventLogName: ?PWSTR, dwEventID: u32, dwErrorCode: u32, status: SETTINGSTATUS, timeLogged: SYSTEMTIME, }; pub const INSTALLSPECTYPE = enum(i32) { APPNAME = 1, FILEEXT = 2, PROGID = 3, COMCLASS = 4, }; pub const APPNAME = INSTALLSPECTYPE.APPNAME; pub const FILEEXT = INSTALLSPECTYPE.FILEEXT; pub const PROGID = INSTALLSPECTYPE.PROGID; pub const COMCLASS = INSTALLSPECTYPE.COMCLASS; pub const INSTALLSPEC = extern union { AppName: extern struct { Name: ?PWSTR, GPOId: Guid, }, FileExt: ?PWSTR, ProgId: ?PWSTR, COMClass: extern struct { Clsid: Guid, ClsCtx: u32, }, }; pub const INSTALLDATA = extern struct { Type: INSTALLSPECTYPE, Spec: INSTALLSPEC, }; pub const APPSTATE = enum(i32) { ABSENT = 0, ASSIGNED = 1, PUBLISHED = 2, }; pub const ABSENT = APPSTATE.ABSENT; pub const ASSIGNED = APPSTATE.ASSIGNED; pub const PUBLISHED = APPSTATE.PUBLISHED; pub const LOCALMANAGEDAPPLICATION = extern struct { pszDeploymentName: ?PWSTR, pszPolicyName: ?PWSTR, pszProductId: ?PWSTR, dwState: u32, }; pub const MANAGEDAPPLICATION = extern struct { pszPackageName: ?PWSTR, pszPublisher: ?PWSTR, dwVersionHi: u32, dwVersionLo: u32, dwRevision: u32, GpoId: Guid, pszPolicyName: ?PWSTR, ProductId: Guid, Language: u16, pszOwner: ?PWSTR, pszCompany: ?PWSTR, pszComments: ?PWSTR, pszContact: ?PWSTR, pszSupportUrl: ?PWSTR, dwPathType: u32, bInstalled: BOOL, }; pub const GROUP_POLICY_OBJECT_TYPE = enum(i32) { Local = 0, Remote = 1, DS = 2, LocalUser = 3, LocalGroup = 4, }; pub const GPOTypeLocal = GROUP_POLICY_OBJECT_TYPE.Local; pub const GPOTypeRemote = GROUP_POLICY_OBJECT_TYPE.Remote; pub const GPOTypeDS = GROUP_POLICY_OBJECT_TYPE.DS; pub const GPOTypeLocalUser = GROUP_POLICY_OBJECT_TYPE.LocalUser; pub const GPOTypeLocalGroup = GROUP_POLICY_OBJECT_TYPE.LocalGroup; pub const GROUP_POLICY_HINT_TYPE = enum(i32) { Unknown = 0, Machine = 1, Site = 2, Domain = 3, OrganizationalUnit = 4, }; pub const GPHintUnknown = GROUP_POLICY_HINT_TYPE.Unknown; pub const GPHintMachine = GROUP_POLICY_HINT_TYPE.Machine; pub const GPHintSite = GROUP_POLICY_HINT_TYPE.Site; pub const GPHintDomain = GROUP_POLICY_HINT_TYPE.Domain; pub const GPHintOrganizationalUnit = GROUP_POLICY_HINT_TYPE.OrganizationalUnit; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGPEInformation_Value = @import("../zig.zig").Guid.initString("8fc0b735-a0e1-11d1-a7d3-0000f87571e3"); pub const IID_IGPEInformation = &IID_IGPEInformation_Value; pub const IGPEInformation = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetName: fn( self: *const IGPEInformation, pszName: [*:0]u16, cchMaxLength: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDisplayName: fn( self: *const IGPEInformation, pszName: [*:0]u16, cchMaxLength: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRegistryKey: fn( self: *const IGPEInformation, dwSection: u32, hKey: ?*?HKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDSPath: fn( self: *const IGPEInformation, dwSection: u32, pszPath: [*:0]u16, cchMaxPath: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFileSysPath: fn( self: *const IGPEInformation, dwSection: u32, pszPath: [*:0]u16, cchMaxPath: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOptions: fn( self: *const IGPEInformation, dwOptions: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetType: fn( self: *const IGPEInformation, gpoType: ?*GROUP_POLICY_OBJECT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetHint: fn( self: *const IGPEInformation, gpHint: ?*GROUP_POLICY_HINT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PolicyChanged: fn( self: *const IGPEInformation, bMachine: BOOL, bAdd: BOOL, pGuidExtension: ?*Guid, pGuidSnapin: ?*Guid, ) 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 IGPEInformation_GetName(self: *const T, pszName: [*:0]u16, cchMaxLength: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPEInformation.VTable, self.vtable).GetName(@ptrCast(*const IGPEInformation, self), pszName, cchMaxLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPEInformation_GetDisplayName(self: *const T, pszName: [*:0]u16, cchMaxLength: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPEInformation.VTable, self.vtable).GetDisplayName(@ptrCast(*const IGPEInformation, self), pszName, cchMaxLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPEInformation_GetRegistryKey(self: *const T, dwSection: u32, hKey: ?*?HKEY) callconv(.Inline) HRESULT { return @ptrCast(*const IGPEInformation.VTable, self.vtable).GetRegistryKey(@ptrCast(*const IGPEInformation, self), dwSection, hKey); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPEInformation_GetDSPath(self: *const T, dwSection: u32, pszPath: [*:0]u16, cchMaxPath: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPEInformation.VTable, self.vtable).GetDSPath(@ptrCast(*const IGPEInformation, self), dwSection, pszPath, cchMaxPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPEInformation_GetFileSysPath(self: *const T, dwSection: u32, pszPath: [*:0]u16, cchMaxPath: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPEInformation.VTable, self.vtable).GetFileSysPath(@ptrCast(*const IGPEInformation, self), dwSection, pszPath, cchMaxPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPEInformation_GetOptions(self: *const T, dwOptions: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IGPEInformation.VTable, self.vtable).GetOptions(@ptrCast(*const IGPEInformation, self), dwOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPEInformation_GetType(self: *const T, gpoType: ?*GROUP_POLICY_OBJECT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IGPEInformation.VTable, self.vtable).GetType(@ptrCast(*const IGPEInformation, self), gpoType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPEInformation_GetHint(self: *const T, gpHint: ?*GROUP_POLICY_HINT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IGPEInformation.VTable, self.vtable).GetHint(@ptrCast(*const IGPEInformation, self), gpHint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGPEInformation_PolicyChanged(self: *const T, bMachine: BOOL, bAdd: BOOL, pGuidExtension: ?*Guid, pGuidSnapin: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IGPEInformation.VTable, self.vtable).PolicyChanged(@ptrCast(*const IGPEInformation, self), bMachine, bAdd, pGuidExtension, pGuidSnapin); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IGroupPolicyObject_Value = @import("../zig.zig").Guid.initString("ea502723-a23d-11d1-a7d3-0000f87571e3"); pub const IID_IGroupPolicyObject = &IID_IGroupPolicyObject_Value; pub const IGroupPolicyObject = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, New: fn( self: *const IGroupPolicyObject, pszDomainName: ?PWSTR, pszDisplayName: ?PWSTR, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenDSGPO: fn( self: *const IGroupPolicyObject, pszPath: ?PWSTR, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenLocalMachineGPO: fn( self: *const IGroupPolicyObject, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenRemoteMachineGPO: fn( self: *const IGroupPolicyObject, pszComputerName: ?PWSTR, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Save: fn( self: *const IGroupPolicyObject, bMachine: BOOL, bAdd: BOOL, pGuidExtension: ?*Guid, pGuid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Delete: fn( self: *const IGroupPolicyObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetName: fn( self: *const IGroupPolicyObject, pszName: [*:0]u16, cchMaxLength: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDisplayName: fn( self: *const IGroupPolicyObject, pszName: [*:0]u16, cchMaxLength: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDisplayName: fn( self: *const IGroupPolicyObject, pszName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPath: fn( self: *const IGroupPolicyObject, pszPath: [*:0]u16, cchMaxLength: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDSPath: fn( self: *const IGroupPolicyObject, dwSection: u32, pszPath: [*:0]u16, cchMaxPath: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFileSysPath: fn( self: *const IGroupPolicyObject, dwSection: u32, pszPath: [*:0]u16, cchMaxPath: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRegistryKey: fn( self: *const IGroupPolicyObject, dwSection: u32, hKey: ?*?HKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOptions: fn( self: *const IGroupPolicyObject, dwOptions: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOptions: fn( self: *const IGroupPolicyObject, dwOptions: u32, dwMask: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetType: fn( self: *const IGroupPolicyObject, gpoType: ?*GROUP_POLICY_OBJECT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMachineName: fn( self: *const IGroupPolicyObject, pszName: [*:0]u16, cchMaxLength: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPropertySheetPages: fn( self: *const IGroupPolicyObject, hPages: ?*?*?HPROPSHEETPAGE, uPageCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_New(self: *const T, pszDomainName: ?PWSTR, pszDisplayName: ?PWSTR, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).New(@ptrCast(*const IGroupPolicyObject, self), pszDomainName, pszDisplayName, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_OpenDSGPO(self: *const T, pszPath: ?PWSTR, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).OpenDSGPO(@ptrCast(*const IGroupPolicyObject, self), pszPath, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_OpenLocalMachineGPO(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).OpenLocalMachineGPO(@ptrCast(*const IGroupPolicyObject, self), dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_OpenRemoteMachineGPO(self: *const T, pszComputerName: ?PWSTR, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).OpenRemoteMachineGPO(@ptrCast(*const IGroupPolicyObject, self), pszComputerName, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_Save(self: *const T, bMachine: BOOL, bAdd: BOOL, pGuidExtension: ?*Guid, pGuid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).Save(@ptrCast(*const IGroupPolicyObject, self), bMachine, bAdd, pGuidExtension, pGuid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_Delete(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).Delete(@ptrCast(*const IGroupPolicyObject, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_GetName(self: *const T, pszName: [*:0]u16, cchMaxLength: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).GetName(@ptrCast(*const IGroupPolicyObject, self), pszName, cchMaxLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_GetDisplayName(self: *const T, pszName: [*:0]u16, cchMaxLength: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).GetDisplayName(@ptrCast(*const IGroupPolicyObject, self), pszName, cchMaxLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_SetDisplayName(self: *const T, pszName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).SetDisplayName(@ptrCast(*const IGroupPolicyObject, self), pszName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_GetPath(self: *const T, pszPath: [*:0]u16, cchMaxLength: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).GetPath(@ptrCast(*const IGroupPolicyObject, self), pszPath, cchMaxLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_GetDSPath(self: *const T, dwSection: u32, pszPath: [*:0]u16, cchMaxPath: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).GetDSPath(@ptrCast(*const IGroupPolicyObject, self), dwSection, pszPath, cchMaxPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_GetFileSysPath(self: *const T, dwSection: u32, pszPath: [*:0]u16, cchMaxPath: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).GetFileSysPath(@ptrCast(*const IGroupPolicyObject, self), dwSection, pszPath, cchMaxPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_GetRegistryKey(self: *const T, dwSection: u32, hKey: ?*?HKEY) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).GetRegistryKey(@ptrCast(*const IGroupPolicyObject, self), dwSection, hKey); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_GetOptions(self: *const T, dwOptions: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).GetOptions(@ptrCast(*const IGroupPolicyObject, self), dwOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_SetOptions(self: *const T, dwOptions: u32, dwMask: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).SetOptions(@ptrCast(*const IGroupPolicyObject, self), dwOptions, dwMask); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_GetType(self: *const T, gpoType: ?*GROUP_POLICY_OBJECT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).GetType(@ptrCast(*const IGroupPolicyObject, self), gpoType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_GetMachineName(self: *const T, pszName: [*:0]u16, cchMaxLength: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).GetMachineName(@ptrCast(*const IGroupPolicyObject, self), pszName, cchMaxLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGroupPolicyObject_GetPropertySheetPages(self: *const T, hPages: ?*?*?HPROPSHEETPAGE, uPageCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IGroupPolicyObject.VTable, self.vtable).GetPropertySheetPages(@ptrCast(*const IGroupPolicyObject, self), hPages, uPageCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IRSOPInformation_Value = @import("../zig.zig").Guid.initString("9a5a81b5-d9c7-49ef-9d11-ddf50968c48d"); pub const IID_IRSOPInformation = &IID_IRSOPInformation_Value; pub const IRSOPInformation = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetNamespace: fn( self: *const IRSOPInformation, dwSection: u32, pszName: [*:0]u16, cchMaxLength: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFlags: fn( self: *const IRSOPInformation, pdwFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEventLogEntryText: fn( self: *const IRSOPInformation, pszEventSource: ?PWSTR, pszEventLogName: ?PWSTR, pszEventTime: ?PWSTR, dwEventID: u32, ppszText: ?*?PWSTR, ) 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 IRSOPInformation_GetNamespace(self: *const T, dwSection: u32, pszName: [*:0]u16, cchMaxLength: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IRSOPInformation.VTable, self.vtable).GetNamespace(@ptrCast(*const IRSOPInformation, self), dwSection, pszName, cchMaxLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRSOPInformation_GetFlags(self: *const T, pdwFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IRSOPInformation.VTable, self.vtable).GetFlags(@ptrCast(*const IRSOPInformation, self), pdwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRSOPInformation_GetEventLogEntryText(self: *const T, pszEventSource: ?PWSTR, pszEventLogName: ?PWSTR, pszEventTime: ?PWSTR, dwEventID: u32, ppszText: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IRSOPInformation.VTable, self.vtable).GetEventLogEntryText(@ptrCast(*const IRSOPInformation, self), pszEventSource, pszEventLogName, pszEventTime, dwEventID, ppszText); } };} pub usingnamespace MethodMixin(@This()); }; pub const GPOBROWSEINFO = extern struct { dwSize: u32, dwFlags: u32, hwndOwner: ?HWND, lpTitle: ?PWSTR, lpInitialOU: ?PWSTR, lpDSPath: ?PWSTR, dwDSPathSize: u32, lpName: ?PWSTR, dwNameSize: u32, gpoType: GROUP_POLICY_OBJECT_TYPE, gpoHint: GROUP_POLICY_HINT_TYPE, }; //-------------------------------------------------------------------------------- // Section: Functions (32) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn RefreshPolicy( bMachine: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn RefreshPolicyEx( bMachine: BOOL, dwOptions: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn EnterCriticalPolicySection( bMachine: BOOL, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn LeaveCriticalPolicySection( hSection: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn RegisterGPNotification( hEvent: ?HANDLE, bMachine: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn UnregisterGPNotification( hEvent: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn GetGPOListA( hToken: ?HANDLE, lpName: ?[*:0]const u8, lpHostName: ?[*:0]const u8, lpComputerName: ?[*:0]const u8, dwFlags: u32, pGPOList: ?*?*GROUP_POLICY_OBJECTA, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn GetGPOListW( hToken: ?HANDLE, lpName: ?[*:0]const u16, lpHostName: ?[*:0]const u16, lpComputerName: ?[*:0]const u16, dwFlags: u32, pGPOList: ?*?*GROUP_POLICY_OBJECTW, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn FreeGPOListA( pGPOList: ?*GROUP_POLICY_OBJECTA, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn FreeGPOListW( pGPOList: ?*GROUP_POLICY_OBJECTW, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn GetAppliedGPOListA( dwFlags: u32, pMachineName: ?[*:0]const u8, pSidUser: ?PSID, pGuidExtension: ?*Guid, ppGPOList: ?*?*GROUP_POLICY_OBJECTA, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn GetAppliedGPOListW( dwFlags: u32, pMachineName: ?[*:0]const u16, pSidUser: ?PSID, pGuidExtension: ?*Guid, ppGPOList: ?*?*GROUP_POLICY_OBJECTW, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn ProcessGroupPolicyCompleted( extensionId: ?*Guid, pAsyncHandle: usize, dwStatus: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn ProcessGroupPolicyCompletedEx( extensionId: ?*Guid, pAsyncHandle: usize, dwStatus: u32, RsopStatus: HRESULT, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn RsopAccessCheckByType( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, pPrincipalSelfSid: ?PSID, pRsopToken: ?*anyopaque, dwDesiredAccessMask: u32, pObjectTypeList: ?[*]OBJECT_TYPE_LIST, ObjectTypeListLength: u32, pGenericMapping: ?*GENERIC_MAPPING, // TODO: what to do with BytesParamIndex 8? pPrivilegeSet: ?*PRIVILEGE_SET, pdwPrivilegeSetLength: ?*u32, pdwGrantedAccessMask: ?*u32, pbAccessStatus: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn RsopFileAccessCheck( pszFileName: ?PWSTR, pRsopToken: ?*anyopaque, dwDesiredAccessMask: u32, pdwGrantedAccessMask: ?*u32, pbAccessStatus: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn RsopSetPolicySettingStatus( dwFlags: u32, pServices: ?*IWbemServices, pSettingInstance: ?*IWbemClassObject, nInfo: u32, pStatus: [*]POLICYSETTINGSTATUSINFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USERENV" fn RsopResetPolicySettingStatus( dwFlags: u32, pServices: ?*IWbemServices, pSettingInstance: ?*IWbemClassObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "USERENV" fn GenerateGPNotification( bMachine: BOOL, lpwszMgmtProduct: ?[*:0]const u16, dwMgmtProductOptions: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn InstallApplication( pInstallInfo: ?*INSTALLDATA, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn UninstallApplication( ProductCode: ?PWSTR, dwStatus: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "ADVAPI32" fn CommandLineFromMsiDescriptor( Descriptor: ?PWSTR, CommandLine: [*:0]u16, CommandLineLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn GetManagedApplications( pCategory: ?*Guid, dwQueryFlags: u32, dwInfoLevel: u32, pdwApps: ?*u32, prgManagedApps: ?*?*MANAGEDAPPLICATION, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn GetLocalManagedApplications( bUserApps: BOOL, pdwApps: ?*u32, prgLocalApps: ?*?*LOCALMANAGEDAPPLICATION, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "ADVAPI32" fn GetLocalManagedApplicationData( ProductCode: ?PWSTR, DisplayName: ?*?PWSTR, SupportUrl: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn GetManagedApplicationCategories( dwReserved: u32, pAppCategory: ?*APPCATEGORYINFOLIST, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "GPEDIT" fn CreateGPOLink( lpGPO: ?PWSTR, lpContainer: ?PWSTR, fHighPriority: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "GPEDIT" fn DeleteGPOLink( lpGPO: ?PWSTR, lpContainer: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "GPEDIT" fn DeleteAllGPOLinks( lpContainer: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "GPEDIT" fn BrowseForGPO( lpBrowseInfo: ?*GPOBROWSEINFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "GPEDIT" fn ImportRSoPData( lpNameSpace: ?PWSTR, lpFileName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "GPEDIT" fn ExportRSoPData( lpNameSpace: ?PWSTR, lpFileName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (4) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const GROUP_POLICY_OBJECT = thismodule.GROUP_POLICY_OBJECTA; pub const GetGPOList = thismodule.GetGPOListA; pub const FreeGPOList = thismodule.FreeGPOListA; pub const GetAppliedGPOList = thismodule.GetAppliedGPOListA; }, .wide => struct { pub const GROUP_POLICY_OBJECT = thismodule.GROUP_POLICY_OBJECTW; pub const GetGPOList = thismodule.GetGPOListW; pub const FreeGPOList = thismodule.FreeGPOListW; pub const GetAppliedGPOList = thismodule.GetAppliedGPOListW; }, .unspecified => if (@import("builtin").is_test) struct { pub const GROUP_POLICY_OBJECT = *opaque{}; pub const GetGPOList = *opaque{}; pub const FreeGPOList = *opaque{}; pub const GetAppliedGPOList = *opaque{}; } else struct { pub const GROUP_POLICY_OBJECT = @compileError("'GROUP_POLICY_OBJECT' requires that UNICODE be set to true or false in the root module"); pub const GetGPOList = @compileError("'GetGPOList' requires that UNICODE be set to true or false in the root module"); pub const FreeGPOList = @compileError("'FreeGPOList' requires that UNICODE be set to true or false in the root module"); pub const GetAppliedGPOList = @compileError("'GetAppliedGPOList' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (26) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const APPCATEGORYINFOLIST = @import("../ui/shell.zig").APPCATEGORYINFOLIST; const BOOL = @import("../foundation.zig").BOOL; const BSTR = @import("../foundation.zig").BSTR; const CHAR = @import("../foundation.zig").CHAR; const GENERIC_MAPPING = @import("../security.zig").GENERIC_MAPPING; const HANDLE = @import("../foundation.zig").HANDLE; const HKEY = @import("../system/registry.zig").HKEY; const HPROPSHEETPAGE = @import("../ui/controls.zig").HPROPSHEETPAGE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IDispatch = @import("../system/com.zig").IDispatch; const IEnumVARIANT = @import("../system/ole.zig").IEnumVARIANT; const IUnknown = @import("../system/com.zig").IUnknown; const IWbemClassObject = @import("../system/wmi.zig").IWbemClassObject; const IWbemServices = @import("../system/wmi.zig").IWbemServices; const LPARAM = @import("../foundation.zig").LPARAM; const OBJECT_TYPE_LIST = @import("../security.zig").OBJECT_TYPE_LIST; const PRIVILEGE_SET = @import("../security.zig").PRIVILEGE_SET; const PSID = @import("../foundation.zig").PSID; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const SAFEARRAY = @import("../system/com.zig").SAFEARRAY; const SECURITY_DESCRIPTOR = @import("../security.zig").SECURITY_DESCRIPTOR; const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME; const VARIANT = @import("../system/com.zig").VARIANT; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFNSTATUSMESSAGECALLBACK")) { _ = PFNSTATUSMESSAGECALLBACK; } if (@hasDecl(@This(), "PFNPROCESSGROUPPOLICY")) { _ = PFNPROCESSGROUPPOLICY; } if (@hasDecl(@This(), "PFNPROCESSGROUPPOLICYEX")) { _ = PFNPROCESSGROUPPOLICYEX; } if (@hasDecl(@This(), "PFNGENERATEGROUPPOLICY")) { _ = PFNGENERATEGROUPPOLICY; } @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/group_policy.zig
const std = @import("std"); const utility = @import("utility.zig"); // Import modules to reduce file size // usingnamespace @import("value.zig"); /// A compiled piece of code, provides the building blocks for /// an environment. Note that a compile unit must be instantiated /// into an environment to be executed. pub const CompileUnit = @This(); /// Description of a script function. pub const Function = struct { name: []const u8, entryPoint: u32, localCount: u16, }; /// A mapping of which code portion belongs to which /// line in the source code. /// Lines are valid from offset until the next available symbol. pub const DebugSymbol = struct { /// Offset of the symbol from the start of the compiled code. offset: u32, /// The line number, starting at 1. sourceLine: u32, /// The offset into the line, starting at 1. sourceColumn: u16, }; arena: std.heap.ArenaAllocator, /// Freeform file structure comment. This usually contains the file name of the compile file. comment: []const u8, /// Number of global (persistent) variables stored in the environment globalCount: u16, /// Number of temporary (local) variables in the global scope. temporaryCount: u16, /// The compiled binary code. code: []u8, /// Array of function definitions functions: []const Function, /// Sorted array of debug symbols debugSymbols: []const DebugSymbol, /// Loads a compile unit from a data stream. pub fn loadFromStream(allocator: std.mem.Allocator, stream: anytype) !CompileUnit { // var inStream = file.getInStream(); // var stream = &inStream.stream; var header: [8]u8 = undefined; stream.readNoEof(&header) catch |err| switch (err) { error.EndOfStream => return error.InvalidFormat, // file is too short! else => return err, }; if (!std.mem.eql(u8, &header, "LoLa\xB9\x40\x80\x5A")) return error.InvalidFormat; const version = try stream.readIntLittle(u32); if (version != 1) return error.UnsupportedVersion; var comment: [256]u8 = undefined; try stream.readNoEof(&comment); var unit = CompileUnit{ .arena = std.heap.ArenaAllocator.init(allocator), .globalCount = undefined, .temporaryCount = undefined, .code = undefined, .functions = undefined, .debugSymbols = undefined, .comment = undefined, }; errdefer unit.arena.deinit(); unit.comment = try unit.arena.allocator().dupe(u8, utility.clampFixedString(&comment)); unit.globalCount = try stream.readIntLittle(u16); unit.temporaryCount = try stream.readIntLittle(u16); const functionCount = try stream.readIntLittle(u16); const codeSize = try stream.readIntLittle(u32); const numSymbols = try stream.readIntLittle(u32); if (functionCount > codeSize or numSymbols > codeSize) { // It is not reasonable to have multiple functions per // byte of code. // The same is valid for debug symbols. return error.CorruptedData; } const functions = try unit.arena.allocator().alloc(Function, functionCount); const code = try unit.arena.allocator().alloc(u8, codeSize); const debugSymbols = try unit.arena.allocator().alloc(DebugSymbol, numSymbols); for (functions) |*fun| { var name: [128]u8 = undefined; try stream.readNoEof(&name); const entryPoint = try stream.readIntLittle(u32); const localCount = try stream.readIntLittle(u16); fun.* = Function{ .name = try unit.arena.allocator().dupe(u8, utility.clampFixedString(&name)), .entryPoint = entryPoint, .localCount = localCount, }; } unit.functions = functions; try stream.readNoEof(code); unit.code = code; for (debugSymbols) |*sym| { const offset = try stream.readIntLittle(u32); const sourceLine = try stream.readIntLittle(u32); const sourceColumn = try stream.readIntLittle(u16); sym.* = DebugSymbol{ .offset = offset, .sourceLine = sourceLine, .sourceColumn = sourceColumn, }; } std.sort.sort(DebugSymbol, debugSymbols, {}, struct { fn lessThan(context: void, lhs: DebugSymbol, rhs: DebugSymbol) bool { _ = context; return lhs.offset < rhs.offset; } }.lessThan); unit.debugSymbols = debugSymbols; return unit; } /// Saves a compile unit to a data stream. pub fn saveToStream(self: CompileUnit, stream: anytype) !void { try stream.writeAll("LoLa\xB9\x40\x80\x5A"); try stream.writeIntLittle(u32, 1); try stream.writeAll(self.comment); try stream.writeByteNTimes(0, 256 - self.comment.len); try stream.writeIntLittle(u16, self.globalCount); try stream.writeIntLittle(u16, self.temporaryCount); try stream.writeIntLittle(u16, @intCast(u16, self.functions.len)); try stream.writeIntLittle(u32, @intCast(u32, self.code.len)); try stream.writeIntLittle(u32, @intCast(u32, self.debugSymbols.len)); for (self.functions) |fun| { try stream.writeAll(fun.name); try stream.writeByteNTimes(0, 128 - fun.name.len); try stream.writeIntNative(u32, fun.entryPoint); try stream.writeIntNative(u16, fun.localCount); } try stream.writeAll(self.code); for (self.debugSymbols) |sym| { try stream.writeIntNative(u32, sym.offset); try stream.writeIntNative(u32, sym.sourceLine); try stream.writeIntNative(u16, sym.sourceColumn); } } /// Searches for a debug symbol that preceeds the given address. /// Function assumes that CompileUnit.debugSymbols is sorted /// front-to-back by offset. pub fn lookUp(self: CompileUnit, offset: u32) ?DebugSymbol { if (offset >= self.code.len) return null; var result: ?DebugSymbol = null; for (self.debugSymbols) |sym| { if (sym.offset > offset) break; result = sym; } return result; } pub fn deinit(self: CompileUnit) void { self.arena.deinit(); } const serializedCompileUnit = "" // SoT ++ "LoLa\xB9\x40\x80\x5A" // Header ++ "\x01\x00\x00\x00" // Version ++ "Made with NativeLola.zig!" ++ ("\x00" ** (256 - 25)) // Comment ++ "\x03\x00" // globalCount ++ "\x55\x11" // temporaryCount ++ "\x02\x00" // functionCount ++ "\x05\x00\x00\x00" // codeSize ++ "\x03\x00\x00\x00" // numSymbols ++ "Function1" ++ ("\x00" ** (128 - 9)) // Name ++ "\x00\x00\x00\x00" // entryPoint ++ "\x01\x00" // localCount ++ "Function2" ++ ("\x00" ** (128 - 9)) // Name ++ "\x10\x10\x00\x00" // entryPoint ++ "\x02\x00" // localCount ++ "Hello" // code ++ "\x01\x00\x00\x00" ++ "\x01\x00\x00\x00" ++ "\x01\x00" // dbgSym1 ++ "\x02\x00\x00\x00" ++ "\x02\x00\x00\x00" ++ "\x04\x00" // dbgSym2 ++ "\x04\x00\x00\x00" ++ "\x03\x00\x00\x00" ++ "\x08\x00" // dbgSym3 ; test "CompileUnit I/O" { var sliceInStream = std.io.fixedBufferStream(serializedCompileUnit); const cu = try CompileUnit.loadFromStream(std.testing.allocator, sliceInStream.reader()); defer cu.deinit(); std.debug.assert(std.mem.eql(u8, cu.comment, "Made with NativeLola.zig!")); std.debug.assert(cu.globalCount == 3); std.debug.assert(cu.temporaryCount == 0x1155); std.debug.assert(std.mem.eql(u8, cu.code, "Hello")); std.debug.assert(cu.functions.len == 2); std.debug.assert(cu.debugSymbols.len == 3); std.debug.assert(std.mem.eql(u8, cu.functions[0].name, "Function1")); std.debug.assert(cu.functions[0].entryPoint == 0x00000000); std.debug.assert(cu.functions[0].localCount == 1); std.debug.assert(std.mem.eql(u8, cu.functions[1].name, "Function2")); std.debug.assert(cu.functions[1].entryPoint == 0x00001010); std.debug.assert(cu.functions[1].localCount == 2); std.debug.assert(cu.debugSymbols[0].offset == 1); std.debug.assert(cu.debugSymbols[0].sourceLine == 1); std.debug.assert(cu.debugSymbols[0].sourceColumn == 1); std.debug.assert(cu.debugSymbols[1].offset == 2); std.debug.assert(cu.debugSymbols[1].sourceLine == 2); std.debug.assert(cu.debugSymbols[1].sourceColumn == 4); std.debug.assert(cu.debugSymbols[2].offset == 4); std.debug.assert(cu.debugSymbols[2].sourceLine == 3); std.debug.assert(cu.debugSymbols[2].sourceColumn == 8); var storage: [serializedCompileUnit.len]u8 = undefined; var sliceOutStream = std.io.fixedBufferStream(&storage); try cu.saveToStream(sliceOutStream.writer()); std.debug.assert(sliceOutStream.getWritten().len == serializedCompileUnit.len); std.debug.assert(std.mem.eql(u8, sliceOutStream.getWritten(), serializedCompileUnit)); } test "CompileUnit.lookUp" { var sliceInStream = std.io.fixedBufferStream(serializedCompileUnit); const cu = try CompileUnit.loadFromStream(std.testing.allocator, sliceInStream.reader()); defer cu.deinit(); std.debug.assert(cu.lookUp(0) == null); // no debug symbol before 1 std.debug.assert(cu.lookUp(1).?.sourceLine == 1); std.debug.assert(cu.lookUp(2).?.sourceLine == 2); std.debug.assert(cu.lookUp(3).?.sourceLine == 2); std.debug.assert(cu.lookUp(4).?.sourceLine == 3); std.debug.assert(cu.lookUp(5) == null); // no debug symbol after end-of-code }
src/library/common/CompileUnit.zig
const std = @import("std"); usingnamespace @import("common.zig"); usingnamespace @import("job.zig"); usingnamespace @import("location.zig"); usingnamespace @import("lexer.zig"); usingnamespace @import("ast.zig"); usingnamespace @import("parser.zig"); usingnamespace @import("error_handler.zig"); usingnamespace @import("types.zig"); usingnamespace @import("symbol.zig"); usingnamespace @import("code_formatter.zig"); usingnamespace @import("compiler.zig"); usingnamespace @import("code_runner.zig"); usingnamespace @import("dot_printer.zig"); usingnamespace @import("ring_buffer.zig"); const log = std.log.scoped(.TypeChecker); pub const TypeListener = struct { const Self = @This(); notifyFn: fn (self: *Self, typ: *const Type) void, pub fn notify(self: *Self, typ: *const Type) void { return self.notifyFn(self, typ); } }; pub const TypeChecker = struct { compiler: *Compiler, typeRegistry: *TypeRegistry, errorReporter: *ErrorReporter, errorMsgBuffer: std.ArrayList(u8), codeRunner: *CodeRunner, globalScope: *SymbolTable, currentScope: *SymbolTable, currentFunction: ?*Ast = null, const Context = struct { injected: ?*Ast = null, expected: ?*const Type = null, typeListener: ?*TypeListener = null, }; const Self = @This(); pub fn init(compiler: *Compiler, codeRunner: *CodeRunner) !Self { return Self{ .compiler = compiler, .typeRegistry = &compiler.typeRegistry, .codeRunner = codeRunner, .globalScope = compiler.globalScope, .currentScope = compiler.globalScope, .errorReporter = compiler.errorReporter, .errorMsgBuffer = std.ArrayList(u8).init(compiler.allocator), }; } pub fn deinit(self: *Self) void { self.errorMsgBuffer.deinit(); } pub fn reportError(self: *Self, location: *const Location, comptime format: []const u8, args: anytype) void { self.errorMsgBuffer.resize(0) catch unreachable; std.fmt.format(self.errorMsgBuffer.writer(), format, args) catch {}; self.compiler.errorReporter.report(self.errorMsgBuffer.items, location); } fn wasError(self: *Self, ast: *Ast, check: *Ast) bool { if (check.typ.is(.Error)) { ast.typ = check.typ; return true; } return false; } pub fn pushEnv(self: *Self) anyerror!*SymbolTable { var env = try self.compiler.constantsAllocator.allocator.create(SymbolTable); env.* = SymbolTable.init( self.currentScope, &self.compiler.constantsAllocator.allocator, &self.compiler.constantsAllocator.allocator, ); self.currentScope = env; return env; } pub fn popEnv(self: *Self) void { self.currentScope = self.currentScope.parent.?; } fn typesDontMatch(self: *Self, expected: *const Type, given: *Ast) !bool { if (expected == given.typ) { return false; } return true; } pub fn compileAst(self: *Self, _ast: *Ast, ctx: Context) anyerror!void { switch (_ast.spec) { .Block => try self.compileBlock(_ast, ctx), .Call => try self.compileCall(_ast, ctx), .Identifier => try self.compileIdentifier(_ast, ctx), .Int => try self.compileInt(_ast, ctx), .Pipe => try self.compilePipe(_ast, ctx), .ConstDecl => try self.compileConstDecl(_ast, ctx), .VarDecl => try self.compileVarDecl(_ast, ctx), else => { const UnionTagType = @typeInfo(AstSpec).Union.tag_type.?; log.debug("compileAst({s}) Not implemented", .{@tagName(@as(UnionTagType, _ast.spec))}); return error.NotImplemented; }, } } fn compileBlock(self: *Self, ast: *Ast, ctx: Context) anyerror!void { const block = &ast.spec.Block; //std.log.debug("compileBlock()", .{}); ast.typ = try self.typeRegistry.getVoidType(); var subEnv = try self.pushEnv(); defer self.popEnv(); for (block.body.items) |expr| { try self.compileAst(expr, .{}); if (self.wasError(ast, expr)) { return; } ast.typ = expr.typ; } } fn compileCall(self: *Self, ast: *Ast, ctx: Context) anyerror!void { //std.log.debug("compileCall()", .{}); const call = &ast.spec.Call; switch (call.func.spec) { .Identifier => |*id| { if (id.name[0] == '@') { if (std.mem.eql(u8, id.name, "@print")) { try self.compileCallPrint(ast, ctx); return; } else if (std.mem.eql(u8, id.name, "@then")) { try self.compileCallThen(ast, ctx); return; } else if (std.mem.eql(u8, id.name, "@repeat")) { try self.compileCallRepeat(ast, ctx); return; } else if (std.mem.eql(u8, id.name, "@fn")) { try self.compileCallFn(ast, ctx); return; } else if (std.mem.eql(u8, id.name, "@return")) { try self.compileCallReturn(ast, ctx); return; } else if (id.name[0] == '@') { self.reportError(&ast.location, "Unknown compiler function '{s}'", .{id.name}); ast.typ = try self.typeRegistry.getErrorType(); return; } } }, else => {}, } try self.compileAst(call.func, .{}); if (self.wasError(ast, call.func)) { return; } switch (call.func.typ.kind) { .Function => |func| try self.compileRegularFunctionCall(ast, call.func.typ, ctx), else => { self.reportError(&call.func.location, "Invalid type for call exression: {}", .{call.func.typ}); ast.typ = try self.typeRegistry.getErrorType(); return error.NotImplemented; }, } } fn compileRegularFunctionCall(self: *Self, ast: *Ast, funcType: *const Type, ctx: Context) anyerror!void { var call = &ast.spec.Call; var func = &funcType.kind.Function; ast.typ = func.returnType; // Check arguments. if (call.args.items.len != func.params.items.len) { self.reportError(&ast.location, "Wrong number of arguments. Expected {}, got {}.", .{ func.params.items.len, call.args.items.len }); ast.typ = try self.typeRegistry.getErrorType(); return; } var i: usize = 0; while (i < call.args.items.len) : (i += 1) { const paramType = func.params.items[i]; const arg = call.args.items[i]; try self.compileAst(arg, .{ .expected = paramType }); if (self.wasError(ast, arg)) { return; } std.log.debug("Param: {}, arg: {}.", .{ paramType, arg.typ }); std.log.debug("Param: {}, arg: {}.", .{ &paramType, &arg.typ }); // @todo: Check if arg has correct type. if (try self.typesDontMatch(paramType, arg)) { self.reportError(&arg.location, "Argument type does not match parameter type. Expected {}, got {}.", .{ paramType, arg.typ }); ast.typ = try self.typeRegistry.getErrorType(); return; } } } fn compileCallPrint(self: *Self, ast: *Ast, ctx: Context) anyerror!void { const call = &ast.spec.Call; //std.log.debug("compileCallPrint()", .{}); for (call.args.items) |arg| { try self.compileAst(arg, .{}); if (self.wasError(ast, arg)) { return; } } ast.typ = try self.typeRegistry.getVoidType(); } fn compileCallThen(self: *Self, ast: *Ast, ctx: Context) anyerror!void { const call = &ast.spec.Call; //std.log.debug("compileCallThen()", .{}); if (ctx.injected == null and call.args.items.len != 2) { self.reportError(&ast.location, "Missing condition for @then(). Hint: Use the pipe operator (->)", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } // Add injected expression as first argument so we have a pointer for running this ast. if (ctx.injected != null) { try call.args.insert(0, ctx.injected.?); } if (call.args.items.len != 2) { self.reportError(&ast.location, "Wrong number of arguments for @then(). Expected 2, got {}.", .{call.args.items.len}); ast.typ = try self.typeRegistry.getErrorType(); return; } const condition = call.args.items[0]; // compile and check condition try self.compileAst(condition, .{}); if (self.wasError(ast, condition)) { return; } if (!condition.typ.is(.Bool)) { self.reportError(&ast.location, "Condition for @then() is not a bool but '{}'", .{condition.typ}); ast.typ = try self.typeRegistry.getErrorType(); return; } // compile body try self.compileAst(call.args.items[1], .{}); if (self.wasError(ast, call.args.items[1])) { return; } ast.typ = try self.typeRegistry.getVoidType(); } fn compileCallRepeat(self: *Self, ast: *Ast, ctx: Context) anyerror!void { const call = &ast.spec.Call; //std.log.debug("compileCallRepeat()", .{}); if (ctx.injected == null) { self.reportError(&ast.location, "Missing condition for @repeat(). Hint: Use the pipe operator (->)", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } // compile and check condition try self.compileAst(ctx.injected.?, .{}); if (self.wasError(ast, ctx.injected.?)) { return; } if (ctx.injected.?.typ.is(.Bool)) { // ok } else if (ctx.injected.?.typ.is(.Int)) { // ok } else { self.reportError(&ast.location, "Condition for @repeat() is not a bool or int but '{}'", .{ctx.injected.?.typ}); ast.typ = try self.typeRegistry.getErrorType(); return; } // check number of arguments if (call.args.items.len != 1) { self.reportError(&ast.location, "Wrong number of arguments for @repeat(): expected exactly one argument but found {}", .{call.args.items.len}); ast.typ = try self.typeRegistry.getErrorType(); return; } // compile body try self.compileAst(call.args.items[0], .{}); if (self.wasError(ast, call.args.items[0])) { return; } // Add injected expression as last argument so we have a pointer for running this ast. try call.args.append(ctx.injected.?); ast.typ = try self.typeRegistry.getVoidType(); } fn compileCallFn(self: *Self, ast: *Ast, ctx: Context) anyerror!void { const call = &ast.spec.Call; //std.log.debug("compileCallFn()", .{}); if (ctx.injected != null) { self.reportError(&ast.location, "Can't inject into function.", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } var signature: ?*Ast = null; var body: ?*Ast = null; if (call.args.items.len > 2) { self.reportError(&ast.location, "Too many arguments for function declaration.", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } if (call.args.items.len == 1) { var temp = call.args.items[0]; if (temp.is(.Pipe)) { signature = call.args.pop(); } else { body = call.args.pop(); } } else if (call.args.items.len == 2) { body = call.args.pop(); signature = call.args.pop(); } if (body == null) { self.reportError(&ast.location, "Extern function declarations not implemented yet.", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } var returnType = try self.typeRegistry.getVoidType(); var paramTypes = try self.typeRegistry.allocTypeArray(0); var argsScope = try self.pushEnv(); defer self.popEnv(); if (signature) |sig| { if (!sig.is(.Pipe)) { self.reportError(&sig.location, "Function parameters must be of this pattern: (arg1: T1, arg2: T2, ...) -> T0", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } var paramsAst = sig.spec.Pipe.left; var returnTypeAst = sig.spec.Pipe.right; if (!paramsAst.is(.Tuple)) { self.reportError(&sig.location, "Function parameters must be of this pattern: (arg1: T1, arg2: T2, ...) -> T0", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } var paramsTuple = &paramsAst.spec.Tuple; // Compile parameters. var argOffset: usize = 0; for (paramsTuple.values.items) |param| { // Make sure param is a declaration. if (!param.is(.VarDecl)) { self.reportError(&param.location, "Function parameter must be a declaration.", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } var paramDecl = &param.spec.VarDecl; // Make sure pattern is an identifier. if (!paramDecl.pattern.is(.Identifier)) { self.reportError(&param.location, "Parameter pattern must be an identifier.", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } var paramName = &paramDecl.pattern.spec.Identifier; // Get type of parameter. try self.compileAst(paramDecl.typ.?, .{}); if (self.wasError(ast, paramDecl.typ.?)) { return; } if (!paramDecl.typ.?.typ.is(.Type)) { self.reportError(&param.location, "Function parameter type is not a type: {}", .{paramDecl.typ.?.typ}); ast.typ = try self.typeRegistry.getErrorType(); return; } try self.codeRunner.runAst(paramDecl.typ.?); const paramType = try self.codeRunner.pop(*const Type); try paramTypes.append(paramType); if (try argsScope.define(paramName.name)) |sym| sym.kind = .{ .Argument = .{ .decl = param, .typ = paramType, .offset = argOffset, } } else { self.reportError(&sig.location, "Parameter with name '{s}' already exists.", .{paramName.name}); ast.typ = try self.typeRegistry.getErrorType(); return; } argOffset = std.mem.alignForward(argOffset + paramType.size, paramType.alignment); } // Compile return type. try self.compileAst(returnTypeAst, .{}); if (self.wasError(ast, returnTypeAst)) { return; } if (!returnTypeAst.typ.is(.Type)) { self.reportError(&sig.location, "Function return type is not a type: {}", .{returnTypeAst.typ}); ast.typ = try self.typeRegistry.getErrorType(); return; } try self.codeRunner.runAst(returnTypeAst); returnType = try self.codeRunner.pop(*const Type); } ast.typ = try self.typeRegistry.getFunctionType(paramTypes, returnType); if (ctx.typeListener) |listener| { listener.notify(ast.typ); } // call.args change type of ast to Function and use call.args for the actual args. var args = call.args; ast.spec = .{ .Function = .{ .args = args, .body = body.?, } }; const oldCurrentFunction = self.currentFunction; self.currentFunction = ast; defer self.currentFunction = oldCurrentFunction; try self.compileAst(body.?, .{}); } fn compileCallReturn(self: *Self, ast: *Ast, ctx: Context) anyerror!void { const call = &ast.spec.Call; //std.log.debug("compileCallFn()", .{}); const function = self.currentFunction orelse { self.reportError(&ast.location, "Can't return outside of function.", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; }; var returnValue: ?*Ast = null; if (ctx.injected != null) { returnValue = ctx.injected; if (call.args.items.len > 0) { self.reportError(&ast.location, "Too many arguments to @return().", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } } else { if (call.args.items.len > 1) { self.reportError(&ast.location, "Too many arguments to @return().", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } else if (call.args.items.len == 1) { returnValue = call.args.items[0]; } } const functionType = &function.typ.kind.Function; ast.spec = .{ .Return = .{ .value = returnValue, } }; if (returnValue) |value| { if (functionType.returnType == try self.typeRegistry.getVoidType()) { self.reportError(&ast.location, "Can't return value in void function.", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } try self.compileAst(value, .{ .expected = functionType.returnType }); } else { if (functionType.returnType != try self.typeRegistry.getVoidType()) { self.reportError(&ast.location, "Missing return value.", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } } ast.typ = try self.typeRegistry.getVoidType(); } fn compileIdentifier(self: *Self, ast: *Ast, ctx: Context) anyerror!void { const id = &ast.spec.Identifier; //std.log.debug("compileIdentifier() {s}", .{id.name}); if (std.mem.eql(u8, id.name, "true")) { ast.typ = try self.typeRegistry.getBoolType(1); return; } else if (std.mem.eql(u8, id.name, "false")) { ast.typ = try self.typeRegistry.getBoolType(1); return; } if (try self.currentScope.get(id.name, &ast.location)) |sym| { id.symbol = sym; // Wait until symbol kind is set. { var condition = struct { condition: FiberWaitCondition = .{ .evalFn = eval, .reportErrorFn = reportError, }, symbol: *Symbol, location: *Location, pub fn eval(condition: *FiberWaitCondition) bool { const s = @fieldParentPtr(@This(), "condition", condition); return !s.symbol.is(.NotSet); } pub fn reportError(condition: *FiberWaitCondition, compiler: *Compiler) void { const s = @fieldParentPtr(@This(), "condition", condition); compiler.reportError(s.location, "Unknown kind of symbol: {s}", .{s.symbol.name}); } }{ .symbol = sym, .location = &ast.location, }; try Coroutine.current().getUserData().?.waitUntil(&condition.condition); } switch (sym.kind) { .Argument => |*arg| { ast.typ = arg.typ; }, .Constant => |*gv| { ast.typ = gv.typ; }, .GlobalVariable => |*gv| { ast.typ = gv.typ; }, .NativeFunction => |*nf| { ast.typ = nf.typ; }, .Type => ast.typ = try self.typeRegistry.getTypeType(), else => return error.NotImplemented, } } else { self.reportError(&ast.location, "Unknown symbol '{s}'", .{id.name}); ast.typ = try self.typeRegistry.getErrorType(); return; } } fn compileInt(self: *Self, ast: *Ast, ctx: Context) anyerror!void { const int = &ast.spec.Int; //std.log.debug("compileInt() {}", .{int.value}); if (ctx.expected) |expected| switch (expected.kind) { .Int => { // @todo: Make sure the value fits in this size. ast.typ = expected; }, else => ast.typ = try self.typeRegistry.getIntType(8, false, null), } else { ast.typ = try self.typeRegistry.getIntType(8, false, null); } } fn compilePipe(self: *Self, ast: *Ast, ctx: Context) anyerror!void { const pipe = &ast.spec.Pipe; //std.log.debug("compilePipe()", .{}); if (ctx.injected) |_| { self.reportError(&ast.location, "Can't inject expressions into the pipe operator (->)", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } try self.compileAst(pipe.right, .{ .injected = pipe.left }); ast.typ = pipe.right.typ; } fn compileConstDecl(self: *Self, ast: *Ast, ctx: Context) anyerror!void { const decl = &ast.spec.ConstDecl; //std.log.debug("compileConstDecl()", .{}); if (ctx.injected) |_| { self.reportError(&ast.location, "Can't inject expressions into constant declaration", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } var varType: ?*const Type = null; var varName: String = ""; switch (decl.pattern.spec) { .Identifier => |*id| { varName = id.name; }, else => { self.reportError(&decl.pattern.location, "Unsupported pattern in variable declaration.", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; }, } if (decl.typ) |typ| { try self.compileAst(typ, .{}); if (self.wasError(ast, typ)) { return; } if (!typ.typ.is(.Type)) { self.reportError(&typ.location, "Expected type, found '{any}'", .{typ.typ}); ast.typ = try self.typeRegistry.getErrorType(); return; } try self.codeRunner.runAst(typ); varType = try self.codeRunner.pop(*const Type); } var sym = if (try self.currentScope.define(varName)) |sym| sym else { self.reportError(&decl.pattern.location, "A symbol with name '{s}' already exists in the current scope", .{varName}); ast.typ = try self.typeRegistry.getErrorType(); return; }; // Register type set listener. var onTypeSet = struct { listener: TypeListener = .{ .notifyFn = notify, }, ast: *Ast, symbol: *Symbol, pub fn notify(listener: *TypeListener, typ: *const Type) void { const s = @fieldParentPtr(@This(), "listener", listener); s.symbol.kind = .{ .Constant = .{ .decl = s.ast, .typ = typ, .value = null, } }; } }{ .ast = ast, .symbol = sym, }; try self.compileAst(decl.value, .{ .expected = varType, .typeListener = &onTypeSet.listener }); if (self.wasError(ast, decl.value)) { return; } varType = decl.value.typ; std.debug.assert(varType != null); try self.codeRunner.runAst(decl.value); var value = try self.compiler.constantsAllocator.allocator.alloc(u8, varType.?.size); try self.codeRunner.popInto(value); if (sym.is(.NotSet)) { sym.kind = .{ .Constant = .{ .decl = ast, .typ = varType.?, .value = value, } }; } else { sym.kind.Constant.value = value; } decl.symbol = sym; ast.typ = try self.typeRegistry.getVoidType(); } fn compileVarDecl(self: *Self, ast: *Ast, ctx: Context) anyerror!void { const decl = &ast.spec.VarDecl; //std.log.debug("compileVarDecl()", .{}); if (ctx.injected) |_| { self.reportError(&ast.location, "Can't inject expressions into variable declaration", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; } var varType: ?*const Type = null; var varName: String = ""; switch (decl.pattern.spec) { .Identifier => |*id| { varName = id.name; }, else => { self.reportError(&decl.pattern.location, "Unsupported pattern in variable declaration.", .{}); ast.typ = try self.typeRegistry.getErrorType(); return; }, } if (decl.typ) |typ| { try self.compileAst(typ, .{}); if (self.wasError(ast, typ)) { return; } if (!typ.typ.is(.Type)) { self.reportError(&typ.location, "Expected type, found '{any}'", .{typ.typ}); ast.typ = try self.typeRegistry.getErrorType(); return; } try self.codeRunner.runAst(typ); varType = try self.codeRunner.pop(*const Type); } if (decl.value) |value| { try self.compileAst(value, .{}); if (self.wasError(ast, value)) { return; } varType = value.typ; } std.debug.assert(varType != null); var sym = if (try self.currentScope.define(varName)) |sym| sym else { self.reportError(&decl.pattern.location, "A symbol with name '{s}' already exists in the current scope", .{varName}); ast.typ = try self.typeRegistry.getErrorType(); return; }; sym.kind = .{ .GlobalVariable = .{ .decl = ast, .typ = varType.?, } }; decl.symbol = sym; ast.typ = try self.typeRegistry.getVoidType(); } };
src/type_checker.zig
const std = @import("std"); /// Frame timing values. pub const Time = struct { /// Time elapsed since the last frame. delta_time: u64 = 0, /// Time elapsed since the last frame ignoring the time speed multiplier. delta_real_time: u64 = 0, /// Rate at which `State::fixed_update` is called. fixed_time: u64 = 16_666_666, /// The total number of frames that have been played in this session. frame_number: u64 = 0, ///Time elapsed since game start, ignoring the speed multipler. absolute_real_time: u64 = 0, ///Time elapsed since game start, taking the speed multiplier into account. absolute_time: u64 = 0, ///Time multiplier. Affects returned delta_time and absolute_time. time_scale: f32 = 1.0, /// Fixed timestep accumulator. fixed_time_accumulator: u64 = 0, /// Sets delta_time to the given `Duration`. /// Updates the struct to reflect the changes of this frame. /// This should be called before using step_fixed_update. pub fn advance_frame(self: *@This(), time_diff: u64) void { self.delta_time = @floatToInt(u64, @intToFloat(f64, time_diff) * self.time_scale); self.delta_real_time = time_diff; self.frame_number += 1; self.absolute_time += self.delta_time; self.absolute_real_time += self.delta_real_time; self.fixed_time_accumulator += self.delta_real_time; } /// Checks to see if we should perform another fixed update iteration, and if so, returns true /// and reduces the accumulator. pub fn step_fixed_update(self: *@This()) bool { if (self.fixed_time_accumulator >= self.fixed_time) { self.fixed_time_accumulator -= self.fixed_time; return true; } return false; } }; fn approx_zero(v: u64) bool { //return v >= -0.000001 and v <= 0.000001; return v == 0; } // Test that fixed_update methods accumulate and return correctly // Test confirms that with a fixed update of 120fps, we run fixed update twice with the timer // Runs at 10 times game speed, which shouldn't affect fixed updates test "Fixed update 120 fps" { var time = Time{}; time.fixed_time = std.time.ns_per_s / 120; time.time_scale = 10.0; const step = std.time.ns_per_s / 60; var fixed_count = @as(u32, 0); var iter_count = @as(u32, 0); while (iter_count < 60) { time.advance_frame(step); while (time.step_fixed_update()) { fixed_count += 1; } iter_count += 1; } try std.testing.expectEqual(fixed_count, 120); } // Test that fixed_update methods accumulate and return correctly // Test confirms that with a fixed update every 1 second, it runs every 1 second only test "Fixed update 1 sec" { var time = Time{}; time.fixed_time = std.time.ns_per_s; const step = std.time.ns_per_s / 60; var fixed_count = @as(u32, 0); var iter_count = @as(u32, 0); while (iter_count < 130) { // Run two seconds time.advance_frame(step); while (time.step_fixed_update()) { fixed_count += 1; } iter_count += 1; } try std.testing.expectEqual(fixed_count, 2); } test "All getters" { var time = Time{}; time.time_scale = 2.0; time.fixed_time = std.time.ns_per_s / 120; const step = std.time.ns_per_s / 60; time.advance_frame(step); try std.testing.expectEqual(time.time_scale, 2.0); try std.testing.expect(approx_zero(time.delta_time - step * 2)); try std.testing.expect(approx_zero(time.delta_real_time - step)); try std.testing.expect(approx_zero(time.absolute_time - step * 2)); try std.testing.expect(approx_zero(time.absolute_real_time - step)); try std.testing.expectEqual(time.frame_number, 1); try std.testing.expectEqual(time.time_scale, 2.0); try std.testing.expectEqual(time.fixed_time, std.time.ns_per_s / 120); time.advance_frame(step); try std.testing.expectEqual(time.time_scale, 2.0); try std.testing.expect(approx_zero(time.delta_time - step * 2)); try std.testing.expect(approx_zero(time.delta_real_time - step)); try std.testing.expect(approx_zero(time.absolute_time - step * 4)); try std.testing.expect(approx_zero(time.absolute_real_time - step * 2)); try std.testing.expectEqual(time.frame_number, 2); try std.testing.expectEqual(time.time_scale, 2.0); try std.testing.expectEqual(time.fixed_time, std.time.ns_per_s / 120); }
src/time.zig
const std = @import("std"); usingnamespace @import("imgui"); const upaya = @import("upaya"); const ts = @import("../tilescript.zig"); const colors = @import("../colors.zig"); const processor = @import("../rule_processor.zig"); const object_editor = @import("object_editor.zig"); var dragged_obj_index: ?usize = null; var drag_type: enum { move, link } = .move; pub fn drawWindow(state: *ts.AppState) void { // only process map data when it changes if (state.map_data_dirty) { processor.generateProcessedMap(state); processor.generateOutputMap(state); state.map_data_dirty = false; } if (igBegin("Output Map", null, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) { draw(state); } igEnd(); } fn draw(state: *ts.AppState) void { const origin = ogGetCursorScreenPos(); const map_size = state.mapSize(); ogAddRectFilled(igGetWindowDrawList(), origin, map_size, colors.colorRgb(0, 0, 0)); _ = ogInvisibleButton("##output-map-button", map_size, ImGuiButtonFlags_None); var y: usize = 0; while (y < state.map.h) : (y += 1) { var x: usize = 0; while (x < state.map.w) : (x += 1) { var tile = state.final_map_data[x + y * state.map.w]; if (tile == 0) continue; if (state.prefs.show_animations) { if (state.map.tryGetAnimation(tile - 1)) |anim| { if (anim.tiles.len > 0) { const sec_per_frame = @intToFloat(f32, anim.rate) / 1000; const iter_duration = sec_per_frame * @intToFloat(f32, anim.tiles.len); const elapsed = @mod(@intToFloat(f32, @divTrunc(std.time.milliTimestamp(), 1000)), iter_duration); const frame = upaya.math.ifloor(usize, elapsed / sec_per_frame); tile = anim.tiles.items[frame] + 1; } else { continue; } } } const offset_x = @intToFloat(f32, x) * state.map_rect_size; const offset_y = @intToFloat(f32, y) * state.map_rect_size; var tl = ImVec2{ .x = origin.x + offset_x, .y = origin.y + offset_y }; drawTile(state, tl, tile - 1); } } // draw objects if (state.prefs.show_objects) { for (state.map.objects.items) |obj, i| { const tl = ImVec2{ .x = origin.x + @intToFloat(f32, obj.x) * state.map_rect_size, .y = origin.y + @intToFloat(f32, obj.y) * state.map_rect_size }; const color = if (dragged_obj_index != null and dragged_obj_index.? == i) colors.object_selected else colors.object; ogAddQuad(igGetWindowDrawList(), tl, state.map_rect_size, color, 1); for (obj.props.items) |prop| { switch (prop.value) { .link => |linked_id| { const half_rect = @divTrunc(state.map_rect_size, 2); const linked_obj = state.map.getObjectWithId(linked_id); // offset the line from the center of our tile var tl_offset = tl; tl_offset.x += half_rect; tl_offset.y += half_rect; const other = ImVec2{ .x = origin.x + half_rect + @intToFloat(f32, linked_obj.x) * state.map_rect_size, .y = origin.y + half_rect + @intToFloat(f32, linked_obj.y) * state.map_rect_size }; ogImDrawList_AddLine(igGetWindowDrawList(), tl_offset, other, colors.object_link, 1); }, else => {}, } } } } if (igIsItemHovered(ImGuiHoveredFlags_None)) { handleInput(state, origin); } else { dragged_obj_index = null; } } /// returns the index of the object under the mouse or null fn objectIndexUnderMouse(state: *ts.AppState, origin: ImVec2) ?usize { var tile = ts.tileIndexUnderMouse(@floatToInt(usize, state.map_rect_size), origin); for (state.map.objects.items) |obj, i| { if (obj.x == tile.x and obj.y == tile.y) { return i; } } return null; } fn handleInput(state: *ts.AppState, origin: ImVec2) void { // scrolling via drag with alt key down if (igIsMouseDragging(ImGuiMouseButton_Left, 0) and (igGetIO().KeyAlt or igGetIO().KeySuper)) { var scroll_delta = ogGetMouseDragDelta(0, 0); igSetScrollXFloat(igGetScrollX() - scroll_delta.x); igSetScrollYFloat(igGetScrollY() - scroll_delta.y); igResetMouseDragDelta(ImGuiMouseButton_Left); return; } if (!state.object_edit_mode) { return; } if (igIsMouseClicked(ImGuiMouseButton_Left, false) or igIsMouseClicked(ImGuiMouseButton_Right, false)) { // figure out if we clicked on any of our objects var tile = ts.tileIndexUnderMouse(@floatToInt(usize, state.map_rect_size), origin); for (state.map.objects.items) |obj, i| { if (obj.x == tile.x and obj.y == tile.y) { dragged_obj_index = i; object_editor.setSelectedObject(i); @import("objects.zig").setSelectedObject(i); drag_type = if (igIsMouseClicked(ImGuiMouseButton_Left, false)) .move else .link; break; } } } else if (dragged_obj_index != null) { if (drag_type == .move) { if (igIsMouseDragging(ImGuiMouseButton_Left, 0)) { var tile = ts.tileIndexUnderMouse(@floatToInt(usize, state.map_rect_size), origin); var obj = &state.map.objects.items[dragged_obj_index.?]; obj.x = tile.x; obj.y = tile.y; } else if (igIsMouseReleased(ImGuiMouseButton_Left)) { dragged_obj_index = null; } } else if (drag_type == .link) { if (igIsMouseDragging(ImGuiMouseButton_Right, 0)) { // highlight the drop target if we have one if (objectIndexUnderMouse(state, origin)) |index| { if (index != dragged_obj_index.?) { const obj = state.map.objects.items[index]; const tl = ImVec2{ .x = origin.x - 2 + @intToFloat(f32, obj.x) * state.map_rect_size, .y = origin.y - 2 + @intToFloat(f32, obj.y) * state.map_rect_size }; ogAddQuad(igGetWindowDrawList(), tl, state.map_rect_size + 4, igColorConvertFloat4ToU32(igGetStyle().Colors[ImGuiCol_DragDropTarget]), 2); } } ogImDrawList_AddLine(igGetWindowDrawList(), igGetIO().MouseClickedPos[1], igGetIO().MousePos, colors.object_drag_link, 2); } else if (igIsMouseReleased(ImGuiMouseButton_Right)) { if (objectIndexUnderMouse(state, origin)) |index| { if (index != dragged_obj_index.?) { var obj = &state.map.objects.items[dragged_obj_index.?]; obj.addProp(.{ .link = state.map.objects.items[index].id }); var prop = &obj.props.items[obj.props.items.len - 1]; std.mem.copy(u8, &prop.name, "link"); } } dragged_obj_index = null; } } } } fn drawTile(state: *ts.AppState, tl: ImVec2, tile: usize) void { var br = tl; br.x += @intToFloat(f32, state.map.tile_size * state.prefs.tile_size_multiplier); br.y += @intToFloat(f32, state.map.tile_size * state.prefs.tile_size_multiplier); const rect = ts.uvsForTile(state, tile); const uv0 = ImVec2{ .x = rect.x, .y = rect.y }; const uv1 = ImVec2{ .x = rect.x + rect.width, .y = rect.y + rect.height }; ogImDrawList_AddImage(igGetWindowDrawList(), state.texture.imTextureID(), tl, br, uv0, uv1, 0xffffffff); }
tilescript/windows/output_map.zig
const std = @import("std"); const Builder = std.build.Builder; const builtin = @import("builtin"); pub fn build(b: *Builder) void { // Each tutorial stage, its source file, and description const targets = [_]Target{ .{ .name = "base_code", .src = "src/00_base_code.zig", .description = "Base Code" }, .{ .name = "instance_creation", .src = "src/01_instance_creation.zig", .description = "Instance Creation" }, }; // Build all targets for (targets) |target| { target.build(b); } } const Target = struct { name: []const u8, src: []const u8, description: []const u8, pub fn build(self: Target, b: *Builder) void { var exe = b.addExecutable(self.name, self.src); exe.setBuildMode(b.standardReleaseOptions()); // OS stuff exe.linkLibC(); switch (builtin.os) { .windows => { exe.linkSystemLibrary("kernel32"); exe.linkSystemLibrary("user32"); exe.linkSystemLibrary("shell32"); exe.linkSystemLibrary("gdi32"); // Vcpkg Install exe.addIncludeDir("C:\\Users\\charlie\\src\\github.com\\Microsoft\\vcpkg\\installed\\x64-windows-static\\include\\"); exe.addLibPath("C:\\Users\\charlie\\src\\github.com\\Microsoft\\vcpkg\\installed\\x64-windows-static\\lib\\"); // Vulkan Install exe.addIncludeDir("C:\\VulkanSDK\\1.1.130.0\\Include\\"); exe.addLibPath("C:\\VulkanSDK\\1.1.130.0\\Lib\\"); }, else => {}, } // GLFW exe.linkSystemLibrary("glfw3"); // Vulkan exe.linkSystemLibrary("vulkan-1"); // STB // exe.addCSourceFile("deps/stb_image/src/stb_image_impl.c", &[_][]const u8{"-std=c99"}); // exe.addIncludeDir("deps/stb_image/include"); b.default_step.dependOn(&exe.step); b.step(self.name, self.description).dependOn(&exe.run().step); } };
build.zig
const std = @import("std"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; const params = @import("params.zig"); const hblock = @import("hblock.zig"); const FreeSpanList = hblock.FreeSpanList(STMHeap); const FreeSpanLists = hblock.FreeSpanLists(STMHeap); const Hyperblock = hblock.Hyperblock(STMHeap); const HyperblockList = hblock.HyperblockList(STMHeap); //===========================================================================// const STMHeap = struct { free_span_lists: FreeSpanLists, hyperblocks: HyperblockList, pub fn init(child_allocator: *Allocator) !*STMHeap { var self = try child_allocator.createOne(STMHeap); self.free_span_lists.init(); self.hyperblocks.init(); return self; } pub fn deinit(self: *this, child_allocator: *Allocator) void { self.hyperblocks.deinit(child_allocator); self.free_span_lists.deinit(); child_allocator.destroy(self); } pub fn alloc(self: *this, size: usize, child_allocator: *Allocator) ![]u8 { assert(size <= params.allocated_span_max_size); const num_chunks = Hyperblock.numChunksForSize(size); assert(num_chunks >= 1); assert(num_chunks <= params.allocated_span_max_num_chunks); // Look for an existing free span large enough for this allocation. // TODO: make this search loop a method of FreeSpanLists for (self.free_span_lists.lists[(num_chunks - 1)..]) |*list| { if (list.head()) |free_span| { return free_span.hyperblock.allocFrom( free_span, size, &self.free_span_lists); } } // If there are no free spans large enough, then allocate a new // hyperblock, and then allocate from that. var hyperblock = try Hyperblock.init(self, &self.hyperblocks, &self.free_span_lists, child_allocator); var free_span = self.free_span_lists.lastList().head() orelse unreachable; return hyperblock.allocFrom(free_span, size, &self.free_span_lists); } pub fn free(self: *this, old_mem: []u8, child_allocator: *Allocator) void { assert(old_mem.len <= params.allocated_span_max_size); if (Hyperblock.allocSpanHyperblockPtr(old_mem)) |hyperblock| { assert(hyperblock.header.magic_number == params.hyperblock_magic_number); hyperblock.free(old_mem, &self.free_span_lists); } else { child_allocator.freeFn(child_allocator, old_mem); } } }; //===========================================================================// const STMAllocator = struct { pub allocator: Allocator, child_allocator: *Allocator, heap: *STMHeap, pub fn init(child_allocator: *Allocator) !STMAllocator { return STMAllocator{ .allocator = Allocator{ .allocFn = alloc, .reallocFn = realloc, .freeFn = free, }, .child_allocator = child_allocator, .heap = try STMHeap.init(child_allocator), }; } pub fn deinit(self: *this) void { self.heap.deinit(self.child_allocator); } fn alloc(allocator: *Allocator, size: usize, alignment: u29) Allocator.Error![]u8 { const self = @fieldParentPtr(STMAllocator, "allocator", allocator); if (size > params.allocated_span_max_size) { return try self.child_allocator.allocFn(self.child_allocator, size, alignment); } assert(alignment <= params.chunk_size); return try self.heap.alloc(size, self.child_allocator); } fn realloc(allocator: *Allocator, old_mem: []u8, new_size: usize, alignment: u29) Allocator.Error![]u8 { @panic("STMAllocator.realloc is not yet implemented"); // TODO } fn free(allocator: *Allocator, old_mem: []u8) void { const self = @fieldParentPtr(STMAllocator, "allocator", allocator); if (old_mem.len > params.allocated_span_max_size) { self.child_allocator.freeFn(self.child_allocator, old_mem); } else { self.heap.free(old_mem, self.child_allocator); } } }; //===========================================================================// test "STMAllocator alloc and free" { var direct = std.heap.DirectAllocator.init(); var stm = try STMAllocator.init(&direct.allocator); defer stm.deinit(); var slice = try stm.allocator.alloc(u8, 1500); defer stm.allocator.free(slice); assert(slice.len == 1500); } //===========================================================================//
src/ziegfried/stmheap.zig
const std = @import("std"); const expect = std.testing.expect; const print = std.debug.print; const heap = std.heap; const Bitmap = @import("roaring.zig").Bitmap; const allocForFrozen = @import("roaring.zig").allocForFrozen; pub fn main() void { } test "create + free" { var b = try Bitmap.create(); b.free(); } test "createWithCapacity + free" { var b = try Bitmap.createWithCapacity(100); b.free(); } test "add, remove" { var b = try Bitmap.create(); b.add(6); b.add(7); try expect(b.contains(6)); try expect(b.contains(7)); b.remove(6); try expect(!b.contains(6)); b.free(); } test "and, or" { var a = try Bitmap.create(); defer a.free(); a.add(7); var b = try Bitmap.create(); defer b.free(); b.add(2); b.add(7); var andResult = try a._and(b); defer andResult.free(); try expect(andResult.contains(7)); try expect(andResult.cardinality() == 1); var orResult = try a._or(b); defer orResult.free(); try expect(orResult.contains(2)); try expect(orResult.contains(7)); try expect(orResult.cardinality() == 2); } test "or many" { var bitmaps : [3]*const Bitmap = undefined; bitmaps[0] = try Bitmap.fromRange(1, 20, 1); bitmaps[1] = try Bitmap.fromRange(101, 120, 1); bitmaps[2] = try Bitmap.fromRange(1001, 1020, 1); const ret = try Bitmap._orMany(bitmaps[0..]); try expect(ret.contains(2)); try expect(ret.contains(102)); try expect(ret.contains(1002)); } test "iterator" { var a = try Bitmap.create(); defer a.free(); a.add(7); a.add(17); a.add(27); a.add(37); var it = a.iterator(); //while (it.hasValue()) { //print("iterator: {}\n", .{ it.currentValue() }); //_ = it.next(); //} try expect(it.hasValue()); try expect(it.currentValue() == 7); try expect(it.next()); try expect(it.hasValue()); try expect(it.currentValue() == 17); try expect(it.next()); try expect(it.hasValue()); try expect(it.currentValue() == 27); try expect(it.next()); try expect(it.hasValue()); try expect(it.currentValue() == 37); try expect(!it.next()); try expect(!it.hasValue()); //// Let's try starting somewhere else and working backwards it = a.iterator(); _ = it.moveEqualOrLarger(16); try expect(it.hasValue()); try expect(it.currentValue() == 17); try expect(it.previous()); try expect(it.hasValue()); try expect(it.currentValue() == 7); try expect(!it.previous()); try expect(!it.hasValue()); } test "frozen" { var a = try Bitmap.create(); defer a.free(); a.add(7); a.add(17); a.add(27); a.add(37); const len = a.frozenSizeInBytes(); var buf = try allocForFrozen(heap.page_allocator, len); a.frozenSerialize(buf); const b = try Bitmap.frozenView(buf[0..]); try expect(a.eql(b)); } test "portable serialize/deserialize" { var a = try Bitmap.fromRange(0, 10, 1); defer a.free(); var buf : [1024]u8 = undefined; const neededBytes = a.portableSizeInBytes(); try expect(neededBytes < buf.len); try expect(neededBytes == a.portableSerialize(buf[0..])); const b = try Bitmap.portableDeserializeSafe(buf[0..]); defer b.free(); try expect(a.eql(b)); } test "lazy bitwise" { var a = try Bitmap.fromRange(0, 10, 1); defer a.free(); var b = try Bitmap.fromRange(5, 15, 1); defer b.free(); var c = try a._orLazy(b, false); c.repairAfterLazy(); try expect(c.eql(try Bitmap.fromRange(0, 15, 1))); c._xorLazyInPlace(b); c.repairAfterLazy(); try expect(c.eql(try Bitmap.fromRange(0, 5, 1))); } test "select, rank" { var a = try Bitmap.fromRange(1, 10, 1); defer a.free(); var third : u32 = 0; try expect(a.select(2, &third)); // rank counting starts at 0 try expect(third == 3); try expect(a.rank(3) == 3); } test "_andnot" { var a = try Bitmap.fromRange(0, 10, 1); defer a.free(); var b = try Bitmap.fromRange(5, 15, 1); defer b.free(); var res = try a._andnot(b); try expect(res.eql(try Bitmap.fromRange(0, 5, 1))); } test "min & max" { var a = try Bitmap.fromRange(0, 10, 1); defer a.free(); try expect(0 == a.minimum()); try expect(9 == a.maximum()); } test "catch 'em all" { var a = try Bitmap.create(); defer a.free(); var b = try Bitmap.createWithCapacity(100); defer b.free(); var c = try Bitmap.fromRange(10, 20, 2); defer c.free(); var vals = [_]u32{ 6, 2, 4 }; var d = try Bitmap.fromSlice(vals[0..]); defer d.free(); try expect(d.getCopyOnWrite() == false); d.setCopyOnWrite(true); try expect(d.getCopyOnWrite() == true); var e = try d.copy(); defer e.free(); _ = e.overwrite(c); a.add(17); b.addMany(vals[0..]); try expect(b.addChecked(13)); try expect(!b.addChecked(13)); b.addRangeClosed(20, 30); b.addRange(100, 200); b.remove(100); try expect(!b.removeChecked(200)); try expect(b.removeChecked(199)); b.removeMany(vals[0..]); b.removeRange(110, 120); b.removeRangeClosed(0, 1000); b.clear(); try expect(!b.contains(100)); try expect(c.contains(12)); try expect(!c.containsRange(10, 20)); try expect(b.empty()); (try a._and(b)).free(); a._andInPlace(b); _ = a._andCardinality(b); _ = a.intersect(b); _ = a.jaccardIndex(b); (try a._or(b)).free(); a._orInPlace(b); (try Bitmap._orMany(&[_]*Bitmap{b, c, d})).free(); (try Bitmap._orManyHeap(&[_]*Bitmap{b, c, d})).free(); _ = a._orCardinality(b); (try a._xor(b)).free(); a._xorInPlace(b); _ = a._xorCardinality(b); (try Bitmap._xorMany(&[_]*Bitmap{b, c, d})).free(); (try a._andnot(b)).free(); a._andnotInPlace(b); _ = a._andnotCardinality(b); (try a.flip(0, 10)).free(); a.flipInPlace(0, 10); (try a._orLazy(b, false)).free(); a._orLazyInPlace(b, false); (try a._xorLazy(b)).free(); a._xorLazyInPlace(b); a.repairAfterLazy(); var buf: [1024]u8 align(32) = undefined; try expect(c.sizeInBytes() <= buf.len); var len = c.serialize(buf[0..]); var cPrime = try Bitmap.deserialize(buf[0..len]); cPrime.free(); try expect(c.portableSizeInBytes() <= buf.len); len = c.portableSerialize(buf[0..]); cPrime = try Bitmap.portableDeserialize(buf[0..len]); cPrime.free(); cPrime = try Bitmap.portableDeserializeSafe(buf[0..len]); cPrime.free(); try expect(Bitmap.portableDeserializeSize(buf[0..]) < buf.len); len = c.frozenSizeInBytes(); try expect(len < buf.len); c.frozenSerialize(buf[0..]); var view : *const Bitmap = try Bitmap.frozenView(buf[0..len]); try expect(c.eql(view)); var f = try Bitmap.fromRange(10, 50, 1); defer f.free(); var g = try Bitmap.fromRange(20, 40, 1); defer g.free(); try expect(g.isSubset(f)); try expect(g.isStrictSubset(f)); _ = a.cardinality(); _ = a.cardinalityRange(0, 100); _ = a.minimum(); _ = a.maximum(); var el: u32 = 0; _ = a.select(3, &el); _ = a.rank(3); a.printfDescribe(); a.printf(); _ = a.removeRunCompression(); _ = a.runOptimize(); _ = a.shrinkToFit(); var it = c.iterator(); while (it.hasValue()) { _ = it.currentValue(); _ = it.next(); _ = it.previous(); _ = it.next(); } _ = it.moveEqualOrLarger(10); _ = it.read(vals[0..]); }
src/test.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const print = std.debug.print; const data = @embedFile("../inputs/day16.txt"); pub fn main() anyerror!void { var gpa_impl = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa_impl.deinit(); const gpa = gpa_impl.allocator(); return main_with_allocator(gpa); } pub fn main_with_allocator(allocator: Allocator) anyerror!void { const packet = try Packet.parse_str(allocator, std.mem.trimRight(u8, data, "\n")); defer packet.deinit(); print("Part 1: {d}\n", .{packet.version_sum()}); print("Part 2: {d}\n", .{packet.value()}); } const BitReader = std.io.BitReader(.Big, std.io.FixedBufferStream([]u8).Reader); fn bit_offset(bit_reader: BitReader) usize { const byte_offset = bit_reader.forward_reader.context.pos; const extra_bits = 8 - @as(usize, bit_reader.bit_count); return byte_offset * 8 + extra_bits; } const Payload = union { literal_value: u64, operator: []Packet, }; const PacketType = enum(u3) { sum = 0, product = 1, minimum = 2, maximum = 3, literal = 4, greater_than = 5, less_than = 6, equal_to = 7, }; const Packet = struct { const Self = @This(); allocator: Allocator, version: u3, id: PacketType, payload: Payload, fn deinit(self: Self) void { switch (self.id) { .literal => {}, else => { for (self.payload.operator) |packet| { packet.deinit(); } self.allocator.free(self.payload.operator); }, } } fn parse_str(allocator: Allocator, hex_input: []const u8) !Self { var input = try dehex(allocator, hex_input); defer allocator.free(input); var fixed_buf_reader = std.io.fixedBufferStream(input); var bit_reader: BitReader = std.io.bitReader(.Big, fixed_buf_reader.reader()); return try Self.parse(allocator, &bit_reader); } fn parse(allocator: Allocator, bit_reader: *BitReader) anyerror!Self { const version = try bit_reader.readBitsNoEof(u3, 3); const id = @intToEnum(PacketType, try bit_reader.readBitsNoEof(u3, 3)); var payload: Payload = undefined; switch (id) { .literal => { var literal_value: u64 = 0; var more = true; while (more) { const nibble = try bit_reader.readBitsNoEof(u5, 5); literal_value = (literal_value << 4) | (nibble & 0xF); more = (nibble >> 4) == 1; } payload = Payload{ .literal_value = literal_value }; }, else => { const length_type = try bit_reader.readBitsNoEof(u1, 1); var packets = std.ArrayList(Packet).init(allocator); switch (length_type) { 0 => { const length_bits = try bit_reader.readBitsNoEof(u15, 15); const start_offset = bit_offset(bit_reader.*); while (bit_offset(bit_reader.*) < start_offset + length_bits) { try packets.append(try Packet.parse(allocator, bit_reader)); } }, 1 => { var length_count = try bit_reader.readBitsNoEof(u11, 11); while (length_count > 0) : (length_count -= 1) { try packets.append(try Packet.parse(allocator, bit_reader)); } }, } payload = Payload{ .operator = packets.toOwnedSlice() }; }, } return Self{ .allocator = allocator, .version = version, .id = id, .payload = payload, }; } fn version_sum(self: Self) usize { var sum = @as(usize, self.version); switch (self.id) { .literal => {}, else => for (self.payload.operator) |packet| { sum += packet.version_sum(); }, } return sum; } fn value(self: Self) u64 { switch (self.id) { .sum => { var sum: u64 = 0; for (self.payload.operator) |packet| { sum += packet.value(); } return sum; }, .product => { var product: u64 = 1; for (self.payload.operator) |packet| { product *= packet.value(); } return product; }, .minimum => { var minimum: u64 = std.math.maxInt(u64); for (self.payload.operator) |packet| { minimum = std.math.min(minimum, packet.value()); } return minimum; }, .maximum => { var maximum: u64 = 0; for (self.payload.operator) |packet| { maximum = std.math.max(maximum, packet.value()); } return maximum; }, .literal => { return self.payload.literal_value; }, .greater_than => { const a = self.payload.operator[0].value(); const b = self.payload.operator[1].value(); return if (a > b) 1 else 0; }, .less_than => { const a = self.payload.operator[0].value(); const b = self.payload.operator[1].value(); return if (a < b) 1 else 0; }, .equal_to => { const a = self.payload.operator[0].value(); const b = self.payload.operator[1].value(); return if (a == b) 1 else 0; }, } } }; fn dehex(allocator: Allocator, hex_input: []const u8) ![]u8 { var input = try std.ArrayList(u8).initCapacity(allocator, (hex_input.len + 1) / 2); errdefer input.deinit(); for (hex_input) |c, i| { const x = try std.fmt.charToDigit(c, 16); if (i % 2 == 0) { try input.append(x << 4); } else { input.items[input.items.len - 1] |= x; } } return input.toOwnedSlice(); } test "bits example 1" { const input = "D2FE28"; const allocator = std.testing.allocator; const packet = try Packet.parse_str(allocator, input); defer packet.deinit(); try std.testing.expectEqual(@as(u3, 6), packet.version); try std.testing.expectEqual(@as(u3, 4), @enumToInt(packet.id)); try std.testing.expectEqual(@as(u64, 2021), packet.payload.literal_value); } test "bits example 2" { const input = "38006F45291200"; const allocator = std.testing.allocator; const packet = try Packet.parse_str(allocator, input); defer packet.deinit(); try std.testing.expectEqual(@as(u3, 1), packet.version); try std.testing.expectEqual(@as(u3, 6), @enumToInt(packet.id)); try std.testing.expectEqual(@as(u64, 10), packet.payload.operator[0].payload.literal_value); try std.testing.expectEqual(@as(u64, 20), packet.payload.operator[1].payload.literal_value); } test "bits example 3" { const input = "EE00D40C823060"; const allocator = std.testing.allocator; const packet = try Packet.parse_str(allocator, input); defer packet.deinit(); try std.testing.expectEqual(@as(u3, 7), packet.version); try std.testing.expectEqual(@as(u3, 3), @enumToInt(packet.id)); try std.testing.expectEqual(@as(u64, 1), packet.payload.operator[0].payload.literal_value); try std.testing.expectEqual(@as(u64, 2), packet.payload.operator[1].payload.literal_value); try std.testing.expectEqual(@as(u64, 3), packet.payload.operator[2].payload.literal_value); } test "version sums" { const allocator = std.testing.allocator; const a = try Packet.parse_str(allocator, "8A004A801A8002F478"); defer a.deinit(); try std.testing.expectEqual(@as(usize, 16), a.version_sum()); const b = try Packet.parse_str(allocator, "620080001611562C8802118E34"); defer b.deinit(); try std.testing.expectEqual(@as(usize, 12), b.version_sum()); } test "values" { const allocator = std.testing.allocator; const a = try Packet.parse_str(allocator, "C200B40A82"); defer a.deinit(); try std.testing.expectEqual(@as(u64, 3), a.value()); const b = try Packet.parse_str(allocator, "04005AC33890"); defer b.deinit(); try std.testing.expectEqual(@as(u64, 54), b.value()); const c = try Packet.parse_str(allocator, "880086C3E88112"); defer c.deinit(); try std.testing.expectEqual(@as(u64, 7), c.value()); const d = try Packet.parse_str(allocator, "CE00C43D881120"); defer d.deinit(); try std.testing.expectEqual(@as(u64, 9), d.value()); const e = try Packet.parse_str(allocator, "D8005AC2A8F0"); defer e.deinit(); try std.testing.expectEqual(@as(u64, 1), e.value()); const f = try Packet.parse_str(allocator, "F600BC2D8F"); defer f.deinit(); try std.testing.expectEqual(@as(u64, 0), f.value()); const g = try Packet.parse_str(allocator, "9C005AC2F8F0"); defer g.deinit(); try std.testing.expectEqual(@as(u64, 0), g.value()); const h = try Packet.parse_str(allocator, "9C0141080250320F1802104A08"); defer h.deinit(); try std.testing.expectEqual(@as(u64, 1), h.value()); }
src/day16.zig
// Code lengths for fixed Huffman coding of litlen and dist symbols. pub const fixed_litlen_lengths: [288]u8 = print_fixed_litlen_lengths(); pub const fixed_dist_lengths: [32]u8 = [_]u8{5} ** 32; fn print_fixed_litlen_lengths() [288]u8 { var ret: [288]u8 = undefined; // RFC 1951, 3.2.6 for (ret) |_, i| { if (i <= 143) { ret[i] = 8; continue; } if (i <= 255) { ret[i] = 9; continue; } if (i <= 279) { ret[i] = 7; continue; } if (i <= 287) { ret[i] = 8; continue; } } return ret; } // RFC 1951, 3.2.5 const litlen_t = struct { litlen: u16, base_len: u16, ebits: u16, }; fn litlen_base_tbl() [29]litlen_t { return [_]litlen_t{ litlen_t{ .litlen = 257, .base_len = 3, .ebits = 0 }, litlen_t{ .litlen = 258, .base_len = 4, .ebits = 0 }, litlen_t{ .litlen = 259, .base_len = 5, .ebits = 0 }, litlen_t{ .litlen = 260, .base_len = 6, .ebits = 0 }, litlen_t{ .litlen = 261, .base_len = 7, .ebits = 0 }, litlen_t{ .litlen = 262, .base_len = 8, .ebits = 0 }, litlen_t{ .litlen = 263, .base_len = 9, .ebits = 0 }, litlen_t{ .litlen = 264, .base_len = 10, .ebits = 0 }, litlen_t{ .litlen = 265, .base_len = 11, .ebits = 1 }, litlen_t{ .litlen = 266, .base_len = 13, .ebits = 1 }, litlen_t{ .litlen = 267, .base_len = 15, .ebits = 1 }, litlen_t{ .litlen = 268, .base_len = 17, .ebits = 1 }, litlen_t{ .litlen = 269, .base_len = 19, .ebits = 2 }, litlen_t{ .litlen = 270, .base_len = 23, .ebits = 2 }, litlen_t{ .litlen = 271, .base_len = 27, .ebits = 2 }, litlen_t{ .litlen = 272, .base_len = 31, .ebits = 2 }, litlen_t{ .litlen = 273, .base_len = 35, .ebits = 3 }, litlen_t{ .litlen = 274, .base_len = 43, .ebits = 3 }, litlen_t{ .litlen = 275, .base_len = 51, .ebits = 3 }, litlen_t{ .litlen = 276, .base_len = 59, .ebits = 3 }, litlen_t{ .litlen = 277, .base_len = 67, .ebits = 4 }, litlen_t{ .litlen = 278, .base_len = 83, .ebits = 4 }, litlen_t{ .litlen = 279, .base_len = 99, .ebits = 4 }, litlen_t{ .litlen = 280, .base_len = 115, .ebits = 4 }, litlen_t{ .litlen = 281, .base_len = 131, .ebits = 5 }, litlen_t{ .litlen = 282, .base_len = 163, .ebits = 5 }, litlen_t{ .litlen = 283, .base_len = 195, .ebits = 5 }, litlen_t{ .litlen = 284, .base_len = 227, .ebits = 5 }, litlen_t{ .litlen = 285, .base_len = 258, .ebits = 0 }, }; } // Table of litlen symbol values minus 257 with corresponding base length // and number of extra bits. const litlen_tbl_t = struct { base_len: u16 = 9, ebits: u16 = 7, }; pub const litlen_tbl: [29]litlen_tbl_t = print_litlen_tbl(); fn print_litlen_tbl() [29]litlen_tbl_t { var table: [29]litlen_tbl_t = undefined; const litlen_table: [29]litlen_t = litlen_base_tbl(); for (litlen_table) |ll, i| { table[i].base_len = ll.base_len; table[i].ebits = ll.ebits; } return table; } // Mapping from length (3--258) to litlen symbol (257--285). pub const len2litlen: [259]u16 = print_len2litlen(); fn print_len2litlen() [259]u16 { var i: usize = 0; var len: usize = 0; var table: [259]u16 = undefined; const litlen_table: [29]litlen_t = litlen_base_tbl(); // Lengths 0, 1, 2 are not valid. table[0] = 0xffff; table[1] = 0xffff; table[2] = 0xffff; i = 0; len = 3; while (len <= 258) : (len += 1) { if (len == litlen_table[i + 1].base_len) { i += 1; } table[len] = litlen_table[i].litlen; } return table; } // Table of dist symbol values with corresponding base distance and number of // extra bits. // RFC 1951, 3.2.5 const dist_tbl_t = struct { base_dist: u16, ebits: u16, }; pub const dist_tbl: [30]dist_tbl_t = [_]dist_tbl_t{ dist_tbl_t{ .base_dist = 1, .ebits = 0 }, dist_tbl_t{ .base_dist = 2, .ebits = 0 }, dist_tbl_t{ .base_dist = 3, .ebits = 0 }, dist_tbl_t{ .base_dist = 4, .ebits = 0 }, dist_tbl_t{ .base_dist = 5, .ebits = 1 }, dist_tbl_t{ .base_dist = 7, .ebits = 1 }, dist_tbl_t{ .base_dist = 9, .ebits = 2 }, dist_tbl_t{ .base_dist = 13, .ebits = 2 }, dist_tbl_t{ .base_dist = 17, .ebits = 3 }, dist_tbl_t{ .base_dist = 25, .ebits = 3 }, dist_tbl_t{ .base_dist = 33, .ebits = 4 }, dist_tbl_t{ .base_dist = 49, .ebits = 4 }, dist_tbl_t{ .base_dist = 65, .ebits = 5 }, dist_tbl_t{ .base_dist = 97, .ebits = 5 }, dist_tbl_t{ .base_dist = 129, .ebits = 6 }, dist_tbl_t{ .base_dist = 193, .ebits = 6 }, dist_tbl_t{ .base_dist = 257, .ebits = 7 }, dist_tbl_t{ .base_dist = 385, .ebits = 7 }, dist_tbl_t{ .base_dist = 513, .ebits = 8 }, dist_tbl_t{ .base_dist = 769, .ebits = 8 }, dist_tbl_t{ .base_dist = 1025, .ebits = 9 }, dist_tbl_t{ .base_dist = 1537, .ebits = 9 }, dist_tbl_t{ .base_dist = 2049, .ebits = 10 }, dist_tbl_t{ .base_dist = 3073, .ebits = 10 }, dist_tbl_t{ .base_dist = 4097, .ebits = 11 }, dist_tbl_t{ .base_dist = 6145, .ebits = 11 }, dist_tbl_t{ .base_dist = 8193, .ebits = 12 }, dist_tbl_t{ .base_dist = 12289, .ebits = 12 }, dist_tbl_t{ .base_dist = 16385, .ebits = 13 }, dist_tbl_t{ .base_dist = 24577, .ebits = 13 }, }; pub const distance2dist_lo: [256]u8 = print_distance2dist()[0]; pub const distance2dist_hi: [256]u8 = print_distance2dist()[1]; fn print_distance2dist() [2][256]u8 { @setEvalBranchQuota(147_700); var ret: [2][256]u8 = undefined; var low: [256]u8 = undefined; var high: [256]u8 = undefined; var dist: u8 = 0; var distance: usize = 0; // For each distance. distance = 1; while (distance <= 32768) : (distance += 1) { // Find the corresponding dist code. dist = 29; while (dist_tbl[dist].base_dist > distance) { dist -= 1; } if (distance <= 256) { low[(distance - 1)] = dist; } else { high[(distance - 1) >> 7] = dist; } } high[0] = 0xff; // invalid high[1] = 0xff; // invalid ret[0] = low; ret[1] = high; return ret; }
src/tables.zig
const pc_keyboard = @import("../../pc_keyboard.zig"); const us104 = @import("us104.zig"); pub fn mapKeycode(keycode: pc_keyboard.KeyCode, modifiers: pc_keyboard.Modifiers, handle_ctrl: pc_keyboard.HandleControl) pc_keyboard.DecodedKey { const map_to_unicode = handle_ctrl == .MapLettersToUnicode; switch (keycode) { .Minus => { if (modifiers.isShifted()) { return .{ .Unicode = "{" }; } else { return .{ .Unicode = "[" }; } }, .Equals => { if (modifiers.isShifted()) { return .{ .Unicode = "}" }; } else { return .{ .Unicode = "]" }; } }, .Q => { if (modifiers.isShifted()) { return .{ .Unicode = "\"" }; } else { return .{ .Unicode = "'" }; } }, .W => { if (modifiers.isShifted()) { return .{ .Unicode = "<" }; } else { return .{ .Unicode = "," }; } }, .E => { if (modifiers.isShifted()) { return .{ .Unicode = ">" }; } else { return .{ .Unicode = "." }; } }, .R => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0010}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "P" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "p" }; } }, .T => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0019}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "Y" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "y" }; } }, .Y => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0006}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "F" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "f" }; } }, .U => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0007}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "G" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "g" }; } }, .I => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0003}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "C" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "c" }; } }, .O => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0012}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "R" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "r" }; } }, .P => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{000C}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "L" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "l" }; } }, .BracketSquareLeft => { if (modifiers.isShifted()) { return .{ .Unicode = "?" }; } else { return .{ .Unicode = "/" }; } }, .BracketSquareRight => { if (modifiers.isShifted()) { return .{ .Unicode = "+" }; } else { return .{ .Unicode = "=" }; } }, .S => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{000F}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "O" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "o" }; } }, .D => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0005}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "E" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "e" }; } }, .F => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0015}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "U" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "u" }; } }, .G => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0009}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "I" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "i" }; } }, .H => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0004}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "D" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "d" }; } }, .J => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0008}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "H" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "h" }; } }, .K => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0014}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "T" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "t" }; } }, .L => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{000E}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "N" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "n" }; } }, .SemiColon => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0013}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "S" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "s" }; } }, .Quote => { if (modifiers.isShifted()) { return .{ .Unicode = "_" }; } else { return .{ .Unicode = "-" }; } }, .Z => { if (modifiers.isShifted()) { return .{ .Unicode = ":" }; } else { return .{ .Unicode = ";" }; } }, .X => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0011}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "Q" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "q" }; } }, .C => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{000A}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "J" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "j" }; } }, .V => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{000B}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "K" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "k" }; } }, .B => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0018}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "X" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "x" }; } }, .N => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0002}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "B" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "b" }; } }, .Comma => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0017}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "W" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "w" }; } }, .Fullstop => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{0016}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "V" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "v" }; } }, .Slash => { if (map_to_unicode and modifiers.isCtrl()) { return pc_keyboard.DecodedKey{ .Unicode = "\u{001A}" }; } else if (modifiers.isCaps()) { return pc_keyboard.DecodedKey{ .Unicode = "Z" }; } else { return pc_keyboard.DecodedKey{ .Unicode = "z" }; } }, else => return us104.mapKeycode(keycode, modifiers, handle_ctrl), } } comptime { @import("std").testing.refAllDecls(@This()); }
src/keycode/layouts/dvorak104.zig
const std = @import("std"); const use_test_input = false; const filename = if (use_test_input) "day-3_test-input" else "day-3_real-input"; const sample_count = if (use_test_input) 12 else 1000; const sample_length = if (use_test_input) 5 else 12; pub fn main() !void { std.debug.print("--- Day 3 ---\n", .{}); const cwd = std.fs.cwd(); const file = try cwd.openFile(filename, .{}); defer file.close(); var file_text: [sample_count * (sample_length + 1) + 1]u8 = undefined; _ = try file.readAll(file_text[0..]); const samples = getSamples(file_text[0..]); try powerConsumption(samples[0..]); try lifeSupportRating(samples[0..]); } fn getSamples(file_text: []const u8) [sample_count][]const u8 { var samples: [sample_count][]const u8 = undefined; var sample_index: usize = 0; while (sample_index < sample_count):(sample_index += 1) { const start = sample_index * (sample_length + 1); const end = start + sample_length; samples[sample_index] = file_text[start..end]; } return samples; } fn powerConsumption(samples: []const []const u8) !void { var one_counts = [_]u32{0} ** sample_length; for (samples) |sample| { for (sample) |char, i| { if (char == '1') { one_counts[i] += 1; } } } var gamma_string: [sample_length]u8 = undefined; var epsilon_string: [sample_length]u8 = undefined; for (one_counts) |count, i| { gamma_string[i] = if (count > sample_count / 2) '1' else '0'; epsilon_string[i] = if (count > sample_count / 2) '0' else '1'; } const gamma = try std.fmt.parseInt(u32, gamma_string[0..], 2); const epsilon = try std.fmt.parseInt(u32, epsilon_string[0..], 2); const power_consumption = gamma * epsilon; std.debug.print("power consumption is {d}\n", .{ power_consumption }); } fn lifeSupportRating(samples: []const []const u8) !void { var oxygen_buffer: [64 * sample_count]u8 = undefined; var oxygen_allocator = std.heap.FixedBufferAllocator.init(oxygen_buffer[0..]); var oxygen_candidates = try std.ArrayList([]const u8).initCapacity(oxygen_allocator.allocator(), sample_count); var co2_buffer: [64 * sample_count]u8 = undefined; var co2_allocator = std.heap.FixedBufferAllocator.init(co2_buffer[0..]); var co2_candidates = try std.ArrayList([]const u8).initCapacity(co2_allocator.allocator(), sample_count); for (samples) |sample| { oxygen_candidates.appendAssumeCapacity(sample); co2_candidates.appendAssumeCapacity(sample); } var digit_index: usize = 0; while (digit_index < sample_length):(digit_index += 1) { if (oxygen_candidates.items.len > 1) { var one_count: u32 = 0; for (oxygen_candidates.items) |candidate| { if (candidate[digit_index] == '1') { one_count += 1; } } const zero_count = oxygen_candidates.items.len - one_count; const needs_one = one_count >= zero_count; var i: usize = oxygen_candidates.items.len - 1; while (true) { const candidate = oxygen_candidates.items[i]; if (needs_one != (candidate[digit_index] == '1')) { _ = oxygen_candidates.swapRemove(i); } if (i == 0) { break; } i -= 1; } } if (co2_candidates.items.len > 1) { var one_count: u32 = 0; for (co2_candidates.items) |candidate| { if (candidate[digit_index] == '1') { one_count += 1; } } const zero_count = co2_candidates.items.len - one_count; const needs_one = one_count < zero_count; var i: usize = co2_candidates.items.len - 1; while (true) { const candidate = co2_candidates.items[i]; if (needs_one != (candidate[digit_index] == '1')) { _ = co2_candidates.swapRemove(i); } if (i == 0) { break; } i -= 1; } } if (oxygen_candidates.items.len <= 1 and co2_candidates.items.len <= 1) { break; } } std.debug.assert(oxygen_candidates.items.len == 1); std.debug.assert(co2_candidates.items.len == 1); const oxygen = try std.fmt.parseInt(u32, oxygen_candidates.items[0], 2); const co2 = try std.fmt.parseInt(u32, co2_candidates.items[0], 2); const life_support_rating = oxygen * co2; std.debug.print("life support rating is {d}\n", .{ life_support_rating }); }
day-3.zig